| 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 "CheckExprLifetime.h" |
| 14 | #include "TreeTransform.h" |
| 15 | #include "UsedDeclVisitor.h" |
| 16 | #include "clang/AST/ASTConsumer.h" |
| 17 | #include "clang/AST/ASTContext.h" |
| 18 | #include "clang/AST/ASTDiagnostic.h" |
| 19 | #include "clang/AST/ASTLambda.h" |
| 20 | #include "clang/AST/ASTMutationListener.h" |
| 21 | #include "clang/AST/CXXInheritance.h" |
| 22 | #include "clang/AST/Decl.h" |
| 23 | #include "clang/AST/DeclObjC.h" |
| 24 | #include "clang/AST/DeclTemplate.h" |
| 25 | #include "clang/AST/DynamicRecursiveASTVisitor.h" |
| 26 | #include "clang/AST/EvaluatedExprVisitor.h" |
| 27 | #include "clang/AST/Expr.h" |
| 28 | #include "clang/AST/ExprCXX.h" |
| 29 | #include "clang/AST/ExprObjC.h" |
| 30 | #include "clang/AST/MangleNumberingContext.h" |
| 31 | #include "clang/AST/OperationKinds.h" |
| 32 | #include "clang/AST/Type.h" |
| 33 | #include "clang/AST/TypeLoc.h" |
| 34 | #include "clang/Basic/Builtins.h" |
| 35 | #include "clang/Basic/DiagnosticSema.h" |
| 36 | #include "clang/Basic/PartialDiagnostic.h" |
| 37 | #include "clang/Basic/SourceManager.h" |
| 38 | #include "clang/Basic/Specifiers.h" |
| 39 | #include "clang/Basic/TargetInfo.h" |
| 40 | #include "clang/Basic/TypeTraits.h" |
| 41 | #include "clang/Lex/LiteralSupport.h" |
| 42 | #include "clang/Lex/Preprocessor.h" |
| 43 | #include "clang/Sema/AnalysisBasedWarnings.h" |
| 44 | #include "clang/Sema/DeclSpec.h" |
| 45 | #include "clang/Sema/DelayedDiagnostic.h" |
| 46 | #include "clang/Sema/Designator.h" |
| 47 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
| 48 | #include "clang/Sema/Initialization.h" |
| 49 | #include "clang/Sema/Lookup.h" |
| 50 | #include "clang/Sema/Overload.h" |
| 51 | #include "clang/Sema/ParsedTemplate.h" |
| 52 | #include "clang/Sema/Scope.h" |
| 53 | #include "clang/Sema/ScopeInfo.h" |
| 54 | #include "clang/Sema/SemaARM.h" |
| 55 | #include "clang/Sema/SemaCUDA.h" |
| 56 | #include "clang/Sema/SemaFixItUtils.h" |
| 57 | #include "clang/Sema/SemaHLSL.h" |
| 58 | #include "clang/Sema/SemaObjC.h" |
| 59 | #include "clang/Sema/SemaOpenMP.h" |
| 60 | #include "clang/Sema/SemaPseudoObject.h" |
| 61 | #include "clang/Sema/Template.h" |
| 62 | #include "llvm/ADT/STLExtras.h" |
| 63 | #include "llvm/ADT/StringExtras.h" |
| 64 | #include "llvm/Support/ConvertUTF.h" |
| 65 | #include "llvm/Support/SaveAndRestore.h" |
| 66 | #include "llvm/Support/TimeProfiler.h" |
| 67 | #include "llvm/Support/TypeSize.h" |
| 68 | #include <optional> |
| 69 | |
| 70 | using namespace clang; |
| 71 | using namespace sema; |
| 72 | |
| 73 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { |
| 74 | // See if this is an auto-typed variable whose initializer we are parsing. |
| 75 | if (ParsingInitForAutoVars.count(Ptr: D)) |
| 76 | return false; |
| 77 | |
| 78 | // See if this is a deleted function. |
| 79 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) { |
| 80 | if (FD->isDeleted()) |
| 81 | return false; |
| 82 | |
| 83 | // If the function has a deduced return type, and we can't deduce it, |
| 84 | // then we can't use it either. |
| 85 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && |
| 86 | DeduceReturnType(FD, Loc: SourceLocation(), /*Diagnose*/ false)) |
| 87 | return false; |
| 88 | |
| 89 | // See if this is an aligned allocation/deallocation function that is |
| 90 | // unavailable. |
| 91 | if (TreatUnavailableAsInvalid && |
| 92 | isUnavailableAlignedAllocationFunction(FD: *FD)) |
| 93 | return false; |
| 94 | } |
| 95 | |
| 96 | // See if this function is unavailable. |
| 97 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && |
| 98 | cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable) |
| 99 | return false; |
| 100 | |
| 101 | if (isa<UnresolvedUsingIfExistsDecl>(Val: D)) |
| 102 | return false; |
| 103 | |
| 104 | return true; |
| 105 | } |
| 106 | |
| 107 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { |
| 108 | // Warn if this is used but marked unused. |
| 109 | if (const auto *A = D->getAttr<UnusedAttr>()) { |
| 110 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) |
| 111 | // should diagnose them. |
| 112 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && |
| 113 | A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) { |
| 114 | const Decl *DC = cast_or_null<Decl>(Val: S.ObjC().getCurObjCLexicalContext()); |
| 115 | if (DC && !DC->hasAttr<UnusedAttr>()) |
| 116 | S.Diag(Loc, DiagID: diag::warn_used_but_marked_unused) << D; |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { |
| 122 | assert(Decl && Decl->isDeleted()); |
| 123 | |
| 124 | if (Decl->isDefaulted()) { |
| 125 | // If the method was explicitly defaulted, point at that declaration. |
| 126 | if (!Decl->isImplicit()) |
| 127 | Diag(Loc: Decl->getLocation(), DiagID: diag::note_implicitly_deleted); |
| 128 | |
| 129 | // Try to diagnose why this special member function was implicitly |
| 130 | // deleted. This might fail, if that reason no longer applies. |
| 131 | DiagnoseDeletedDefaultedFunction(FD: Decl); |
| 132 | return; |
| 133 | } |
| 134 | |
| 135 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl); |
| 136 | if (Ctor && Ctor->isInheritingConstructor()) |
| 137 | return NoteDeletedInheritingConstructor(CD: Ctor); |
| 138 | |
| 139 | Diag(Loc: Decl->getLocation(), DiagID: diag::note_availability_specified_here) |
| 140 | << Decl << 1; |
| 141 | } |
| 142 | |
| 143 | /// Determine whether a FunctionDecl was ever declared with an |
| 144 | /// explicit storage class. |
| 145 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { |
| 146 | for (auto *I : D->redecls()) { |
| 147 | if (I->getStorageClass() != SC_None) |
| 148 | return true; |
| 149 | } |
| 150 | return false; |
| 151 | } |
| 152 | |
| 153 | /// Check whether we're in an extern inline function and referring to a |
| 154 | /// variable or function with internal linkage (C11 6.7.4p3). |
| 155 | /// |
| 156 | /// This is only a warning because we used to silently accept this code, but |
| 157 | /// in many cases it will not behave correctly. This is not enabled in C++ mode |
| 158 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) |
| 159 | /// and so while there may still be user mistakes, most of the time we can't |
| 160 | /// prove that there are errors. |
| 161 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, |
| 162 | const NamedDecl *D, |
| 163 | SourceLocation Loc) { |
| 164 | // This is disabled under C++; there are too many ways for this to fire in |
| 165 | // contexts where the warning is a false positive, or where it is technically |
| 166 | // correct but benign. |
| 167 | if (S.getLangOpts().CPlusPlus) |
| 168 | return; |
| 169 | |
| 170 | // Check if this is an inlined function or method. |
| 171 | FunctionDecl *Current = S.getCurFunctionDecl(); |
| 172 | if (!Current) |
| 173 | return; |
| 174 | if (!Current->isInlined()) |
| 175 | return; |
| 176 | if (!Current->isExternallyVisible()) |
| 177 | return; |
| 178 | |
| 179 | // Check if the decl has internal linkage. |
| 180 | if (D->getFormalLinkage() != Linkage::Internal) |
| 181 | return; |
| 182 | |
| 183 | // Downgrade from ExtWarn to Extension if |
| 184 | // (1) the supposedly external inline function is in the main file, |
| 185 | // and probably won't be included anywhere else. |
| 186 | // (2) the thing we're referencing is a pure function. |
| 187 | // (3) the thing we're referencing is another inline function. |
| 188 | // This last can give us false negatives, but it's better than warning on |
| 189 | // wrappers for simple C library functions. |
| 190 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(Val: D); |
| 191 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); |
| 192 | if (!DowngradeWarning && UsedFn) |
| 193 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); |
| 194 | |
| 195 | S.Diag(Loc, DiagID: DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet |
| 196 | : diag::ext_internal_in_extern_inline) |
| 197 | << /*IsVar=*/!UsedFn << D; |
| 198 | |
| 199 | S.MaybeSuggestAddingStaticToDecl(D: Current); |
| 200 | |
| 201 | S.Diag(Loc: D->getCanonicalDecl()->getLocation(), DiagID: diag::note_entity_declared_at) |
| 202 | << D; |
| 203 | } |
| 204 | |
| 205 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { |
| 206 | const FunctionDecl *First = Cur->getFirstDecl(); |
| 207 | |
| 208 | // Suggest "static" on the function, if possible. |
| 209 | if (!hasAnyExplicitStorageClass(D: First)) { |
| 210 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); |
| 211 | Diag(Loc: DeclBegin, DiagID: diag::note_convert_inline_to_static) |
| 212 | << Cur << FixItHint::CreateInsertion(InsertionLoc: DeclBegin, Code: "static " ); |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, |
| 217 | const ObjCInterfaceDecl *UnknownObjCClass, |
| 218 | bool ObjCPropertyAccess, |
| 219 | bool AvoidPartialAvailabilityChecks, |
| 220 | ObjCInterfaceDecl *ClassReceiver, |
| 221 | bool SkipTrailingRequiresClause) { |
| 222 | SourceLocation Loc = Locs.front(); |
| 223 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(Val: D)) { |
| 224 | // If there were any diagnostics suppressed by template argument deduction, |
| 225 | // emit them now. |
| 226 | auto Pos = SuppressedDiagnostics.find(Val: D->getCanonicalDecl()); |
| 227 | if (Pos != SuppressedDiagnostics.end()) { |
| 228 | for (const auto &[DiagLoc, PD] : Pos->second) { |
| 229 | DiagnosticBuilder Builder(Diags.Report(Loc: DiagLoc, DiagID: PD.getDiagID())); |
| 230 | PD.Emit(DB: Builder); |
| 231 | } |
| 232 | // Clear out the list of suppressed diagnostics, so that we don't emit |
| 233 | // them again for this specialization. However, we don't obsolete this |
| 234 | // entry from the table, because we want to avoid ever emitting these |
| 235 | // diagnostics again. |
| 236 | Pos->second.clear(); |
| 237 | } |
| 238 | |
| 239 | // C++ [basic.start.main]p3: |
| 240 | // The function 'main' shall not be used within a program. |
| 241 | if (cast<FunctionDecl>(Val: D)->isMain()) |
| 242 | Diag(Loc, DiagID: diag::ext_main_used); |
| 243 | |
| 244 | diagnoseUnavailableAlignedAllocation(FD: *cast<FunctionDecl>(Val: D), Loc); |
| 245 | } |
| 246 | |
| 247 | // See if this is an auto-typed variable whose initializer we are parsing. |
| 248 | if (ParsingInitForAutoVars.count(Ptr: D)) { |
| 249 | if (isa<BindingDecl>(Val: D)) { |
| 250 | Diag(Loc, DiagID: diag::err_binding_cannot_appear_in_own_initializer) |
| 251 | << D->getDeclName(); |
| 252 | } else { |
| 253 | Diag(Loc, DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer) |
| 254 | << diag::ParsingInitFor::Var << D->getDeclName() |
| 255 | << cast<VarDecl>(Val: D)->getType(); |
| 256 | } |
| 257 | return true; |
| 258 | } |
| 259 | |
| 260 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) { |
| 261 | // See if this is a deleted function. |
| 262 | if (FD->isDeleted()) { |
| 263 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD); |
| 264 | if (Ctor && Ctor->isInheritingConstructor()) |
| 265 | Diag(Loc, DiagID: diag::err_deleted_inherited_ctor_use) |
| 266 | << Ctor->getParent() |
| 267 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); |
| 268 | else { |
| 269 | StringLiteral *Msg = FD->getDeletedMessage(); |
| 270 | Diag(Loc, DiagID: diag::err_deleted_function_use) |
| 271 | << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef()); |
| 272 | } |
| 273 | NoteDeletedFunction(Decl: FD); |
| 274 | return true; |
| 275 | } |
| 276 | |
| 277 | // [expr.prim.id]p4 |
| 278 | // A program that refers explicitly or implicitly to a function with a |
| 279 | // trailing requires-clause whose constraint-expression is not satisfied, |
| 280 | // other than to declare it, is ill-formed. [...] |
| 281 | // |
| 282 | // See if this is a function with constraints that need to be satisfied. |
| 283 | // Check this before deducing the return type, as it might instantiate the |
| 284 | // definition. |
| 285 | if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) { |
| 286 | ConstraintSatisfaction Satisfaction; |
| 287 | if (CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc, |
| 288 | /*ForOverloadResolution*/ true)) |
| 289 | // A diagnostic will have already been generated (non-constant |
| 290 | // constraint expression, for example) |
| 291 | return true; |
| 292 | if (!Satisfaction.IsSatisfied) { |
| 293 | Diag(Loc, |
| 294 | DiagID: diag::err_reference_to_function_with_unsatisfied_constraints) |
| 295 | << D; |
| 296 | DiagnoseUnsatisfiedConstraint(Satisfaction); |
| 297 | return true; |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | // If the function has a deduced return type, and we can't deduce it, |
| 302 | // then we can't use it either. |
| 303 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && |
| 304 | DeduceReturnType(FD, Loc)) |
| 305 | return true; |
| 306 | |
| 307 | if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, Callee: FD)) |
| 308 | return true; |
| 309 | |
| 310 | } |
| 311 | |
| 312 | if (auto *Concept = dyn_cast<ConceptDecl>(Val: D); |
| 313 | Concept && CheckConceptUseInDefinition(Concept, Loc)) |
| 314 | return true; |
| 315 | |
| 316 | if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) { |
| 317 | // Lambdas are only default-constructible or assignable in C++2a onwards. |
| 318 | if (MD->getParent()->isLambda() && |
| 319 | ((isa<CXXConstructorDecl>(Val: MD) && |
| 320 | cast<CXXConstructorDecl>(Val: MD)->isDefaultConstructor()) || |
| 321 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { |
| 322 | Diag(Loc, DiagID: diag::warn_cxx17_compat_lambda_def_ctor_assign) |
| 323 | << !isa<CXXConstructorDecl>(Val: MD); |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | auto getReferencedObjCProp = [](const NamedDecl *D) -> |
| 328 | const ObjCPropertyDecl * { |
| 329 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) |
| 330 | return MD->findPropertyDecl(); |
| 331 | return nullptr; |
| 332 | }; |
| 333 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { |
| 334 | if (diagnoseArgIndependentDiagnoseIfAttrs(ND: ObjCPDecl, Loc)) |
| 335 | return true; |
| 336 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(ND: D, Loc)) { |
| 337 | return true; |
| 338 | } |
| 339 | |
| 340 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions |
| 341 | // Only the variables omp_in and omp_out are allowed in the combiner. |
| 342 | // Only the variables omp_priv and omp_orig are allowed in the |
| 343 | // initializer-clause. |
| 344 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: CurContext); |
| 345 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && |
| 346 | isa<VarDecl>(Val: D)) { |
| 347 | Diag(Loc, DiagID: diag::err_omp_wrong_var_in_declare_reduction) |
| 348 | << getCurFunction()->HasOMPDeclareReductionCombiner; |
| 349 | Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D; |
| 350 | return true; |
| 351 | } |
| 352 | |
| 353 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions |
| 354 | // List-items in map clauses on this construct may only refer to the declared |
| 355 | // variable var and entities that could be referenced by a procedure defined |
| 356 | // at the same location. |
| 357 | // [OpenMP 5.2] Also allow iterator declared variables. |
| 358 | if (LangOpts.OpenMP && isa<VarDecl>(Val: D) && |
| 359 | !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) { |
| 360 | Diag(Loc, DiagID: diag::err_omp_declare_mapper_wrong_var) |
| 361 | << OpenMP().getOpenMPDeclareMapperVarName(); |
| 362 | Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D; |
| 363 | return true; |
| 364 | } |
| 365 | |
| 366 | if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: D)) { |
| 367 | Diag(Loc, DiagID: diag::err_use_of_empty_using_if_exists); |
| 368 | Diag(Loc: EmptyD->getLocation(), DiagID: diag::note_empty_using_if_exists_here); |
| 369 | return true; |
| 370 | } |
| 371 | |
| 372 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, |
| 373 | AvoidPartialAvailabilityChecks, ClassReceiver); |
| 374 | |
| 375 | DiagnoseUnusedOfDecl(S&: *this, D, Loc); |
| 376 | |
| 377 | diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc); |
| 378 | |
| 379 | if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) { |
| 380 | if (getLangOpts().getFPEvalMethod() != |
| 381 | LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine && |
| 382 | PP.getLastFPEvalPragmaLocation().isValid() && |
| 383 | PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod()) |
| 384 | Diag(Loc: D->getLocation(), |
| 385 | DiagID: diag::err_type_available_only_in_default_eval_method) |
| 386 | << D->getName(); |
| 387 | } |
| 388 | |
| 389 | if (auto *VD = dyn_cast<ValueDecl>(Val: D)) |
| 390 | checkTypeSupport(Ty: VD->getType(), Loc, D: VD); |
| 391 | |
| 392 | if (LangOpts.SYCLIsDevice || |
| 393 | (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) { |
| 394 | if (!Context.getTargetInfo().isTLSSupported()) |
| 395 | if (const auto *VD = dyn_cast<VarDecl>(Val: D)) |
| 396 | if (VD->getTLSKind() != VarDecl::TLS_None) |
| 397 | targetDiag(Loc: *Locs.begin(), DiagID: diag::err_thread_unsupported); |
| 398 | } |
| 399 | |
| 400 | return false; |
| 401 | } |
| 402 | |
| 403 | void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, |
| 404 | ArrayRef<Expr *> Args) { |
| 405 | const SentinelAttr *Attr = D->getAttr<SentinelAttr>(); |
| 406 | if (!Attr) |
| 407 | return; |
| 408 | |
| 409 | // The number of formal parameters of the declaration. |
| 410 | unsigned NumFormalParams; |
| 411 | |
| 412 | // The kind of declaration. This is also an index into a %select in |
| 413 | // the diagnostic. |
| 414 | enum { CK_Function, CK_Method, CK_Block } CalleeKind; |
| 415 | |
| 416 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) { |
| 417 | NumFormalParams = MD->param_size(); |
| 418 | CalleeKind = CK_Method; |
| 419 | } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
| 420 | NumFormalParams = FD->param_size(); |
| 421 | CalleeKind = CK_Function; |
| 422 | } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) { |
| 423 | QualType Ty = VD->getType(); |
| 424 | const FunctionType *Fn = nullptr; |
| 425 | if (const auto *PtrTy = Ty->getAs<PointerType>()) { |
| 426 | Fn = PtrTy->getPointeeType()->getAs<FunctionType>(); |
| 427 | if (!Fn) |
| 428 | return; |
| 429 | CalleeKind = CK_Function; |
| 430 | } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) { |
| 431 | Fn = PtrTy->getPointeeType()->castAs<FunctionType>(); |
| 432 | CalleeKind = CK_Block; |
| 433 | } else { |
| 434 | return; |
| 435 | } |
| 436 | |
| 437 | if (const auto *proto = dyn_cast<FunctionProtoType>(Val: Fn)) |
| 438 | NumFormalParams = proto->getNumParams(); |
| 439 | else |
| 440 | NumFormalParams = 0; |
| 441 | } else { |
| 442 | return; |
| 443 | } |
| 444 | |
| 445 | // "NullPos" is the number of formal parameters at the end which |
| 446 | // effectively count as part of the variadic arguments. This is |
| 447 | // useful if you would prefer to not have *any* formal parameters, |
| 448 | // but the language forces you to have at least one. |
| 449 | unsigned NullPos = Attr->getNullPos(); |
| 450 | assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel" ); |
| 451 | NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos); |
| 452 | |
| 453 | // The number of arguments which should follow the sentinel. |
| 454 | unsigned NumArgsAfterSentinel = Attr->getSentinel(); |
| 455 | |
| 456 | // If there aren't enough arguments for all the formal parameters, |
| 457 | // the sentinel, and the args after the sentinel, complain. |
| 458 | if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) { |
| 459 | Diag(Loc, DiagID: diag::warn_not_enough_argument) << D->getDeclName(); |
| 460 | Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here) << int(CalleeKind); |
| 461 | return; |
| 462 | } |
| 463 | |
| 464 | // Otherwise, find the sentinel expression. |
| 465 | const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1]; |
| 466 | if (!SentinelExpr) |
| 467 | return; |
| 468 | if (SentinelExpr->isValueDependent()) |
| 469 | return; |
| 470 | if (Context.isSentinelNullExpr(E: SentinelExpr)) |
| 471 | return; |
| 472 | |
| 473 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', |
| 474 | // or 'NULL' if those are actually defined in the context. Only use |
| 475 | // 'nil' for ObjC methods, where it's much more likely that the |
| 476 | // variadic arguments form a list of object pointers. |
| 477 | SourceLocation MissingNilLoc = getLocForEndOfToken(Loc: SentinelExpr->getEndLoc()); |
| 478 | std::string NullValue; |
| 479 | if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil" )) |
| 480 | NullValue = "nil" ; |
| 481 | else if (getLangOpts().CPlusPlus11) |
| 482 | NullValue = "nullptr" ; |
| 483 | else if (PP.isMacroDefined(Id: "NULL" )) |
| 484 | NullValue = "NULL" ; |
| 485 | else |
| 486 | NullValue = "(void*) 0" ; |
| 487 | |
| 488 | if (MissingNilLoc.isInvalid()) |
| 489 | Diag(Loc, DiagID: diag::warn_missing_sentinel) << int(CalleeKind); |
| 490 | else |
| 491 | Diag(Loc: MissingNilLoc, DiagID: diag::warn_missing_sentinel) |
| 492 | << int(CalleeKind) |
| 493 | << FixItHint::CreateInsertion(InsertionLoc: MissingNilLoc, Code: ", " + NullValue); |
| 494 | Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here) |
| 495 | << int(CalleeKind) << Attr->getRange(); |
| 496 | } |
| 497 | |
| 498 | SourceRange Sema::getExprRange(Expr *E) const { |
| 499 | return E ? E->getSourceRange() : SourceRange(); |
| 500 | } |
| 501 | |
| 502 | //===----------------------------------------------------------------------===// |
| 503 | // Standard Promotions and Conversions |
| 504 | //===----------------------------------------------------------------------===// |
| 505 | |
| 506 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). |
| 507 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { |
| 508 | // Handle any placeholder expressions which made it here. |
| 509 | if (E->hasPlaceholderType()) { |
| 510 | ExprResult result = CheckPlaceholderExpr(E); |
| 511 | if (result.isInvalid()) return ExprError(); |
| 512 | E = result.get(); |
| 513 | } |
| 514 | |
| 515 | QualType Ty = E->getType(); |
| 516 | assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type" ); |
| 517 | |
| 518 | if (Ty->isFunctionType()) { |
| 519 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts())) |
| 520 | if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl())) |
| 521 | if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc())) |
| 522 | return ExprError(); |
| 523 | |
| 524 | E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty), |
| 525 | CK: CK_FunctionToPointerDecay).get(); |
| 526 | } else if (Ty->isArrayType()) { |
| 527 | // In C90 mode, arrays only promote to pointers if the array expression is |
| 528 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has |
| 529 | // type 'array of type' is converted to an expression that has type 'pointer |
| 530 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression |
| 531 | // that has type 'array of type' ...". The relevant change is "an lvalue" |
| 532 | // (C90) to "an expression" (C99). |
| 533 | // |
| 534 | // C++ 4.2p1: |
| 535 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of |
| 536 | // T" can be converted to an rvalue of type "pointer to T". |
| 537 | // |
| 538 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { |
| 539 | ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty), |
| 540 | CK: CK_ArrayToPointerDecay); |
| 541 | if (Res.isInvalid()) |
| 542 | return ExprError(); |
| 543 | E = Res.get(); |
| 544 | } |
| 545 | } |
| 546 | return E; |
| 547 | } |
| 548 | |
| 549 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { |
| 550 | // Check to see if we are dereferencing a null pointer. If so, |
| 551 | // and if not volatile-qualified, this is undefined behavior that the |
| 552 | // optimizer will delete, so warn about it. People sometimes try to use this |
| 553 | // to get a deterministic trap and are surprised by clang's behavior. This |
| 554 | // only handles the pattern "*null", which is a very syntactic check. |
| 555 | const auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts()); |
| 556 | if (UO && UO->getOpcode() == UO_Deref && |
| 557 | UO->getSubExpr()->getType()->isPointerType()) { |
| 558 | const LangAS AS = |
| 559 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); |
| 560 | if ((!isTargetAddressSpace(AS) || |
| 561 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && |
| 562 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( |
| 563 | Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) && |
| 564 | !UO->getType().isVolatileQualified()) { |
| 565 | S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO, |
| 566 | PD: S.PDiag(DiagID: diag::warn_indirection_through_null) |
| 567 | << UO->getSubExpr()->getSourceRange()); |
| 568 | S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO, |
| 569 | PD: S.PDiag(DiagID: diag::note_indirection_through_null)); |
| 570 | } |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, |
| 575 | SourceLocation AssignLoc, |
| 576 | const Expr* RHS) { |
| 577 | const ObjCIvarDecl *IV = OIRE->getDecl(); |
| 578 | if (!IV) |
| 579 | return; |
| 580 | |
| 581 | DeclarationName MemberName = IV->getDeclName(); |
| 582 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); |
| 583 | if (!Member || !Member->isStr(Str: "isa" )) |
| 584 | return; |
| 585 | |
| 586 | const Expr *Base = OIRE->getBase(); |
| 587 | QualType BaseType = Base->getType(); |
| 588 | if (OIRE->isArrow()) |
| 589 | BaseType = BaseType->getPointeeType(); |
| 590 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) |
| 591 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { |
| 592 | ObjCInterfaceDecl *ClassDeclared = nullptr; |
| 593 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared); |
| 594 | if (!ClassDeclared->getSuperClass() |
| 595 | && (*ClassDeclared->ivar_begin()) == IV) { |
| 596 | if (RHS) { |
| 597 | NamedDecl *ObjectSetClass = |
| 598 | S.LookupSingleName(S: S.TUScope, |
| 599 | Name: &S.Context.Idents.get(Name: "object_setClass" ), |
| 600 | Loc: SourceLocation(), NameKind: S.LookupOrdinaryName); |
| 601 | if (ObjectSetClass) { |
| 602 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc()); |
| 603 | S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_assign) |
| 604 | << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(), |
| 605 | Code: "object_setClass(" ) |
| 606 | << FixItHint::CreateReplacement( |
| 607 | RemoveRange: SourceRange(OIRE->getOpLoc(), AssignLoc), Code: "," ) |
| 608 | << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")" ); |
| 609 | } |
| 610 | else |
| 611 | S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_assign); |
| 612 | } else { |
| 613 | NamedDecl *ObjectGetClass = |
| 614 | S.LookupSingleName(S: S.TUScope, |
| 615 | Name: &S.Context.Idents.get(Name: "object_getClass" ), |
| 616 | Loc: SourceLocation(), NameKind: S.LookupOrdinaryName); |
| 617 | if (ObjectGetClass) |
| 618 | S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_use) |
| 619 | << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(), |
| 620 | Code: "object_getClass(" ) |
| 621 | << FixItHint::CreateReplacement( |
| 622 | RemoveRange: SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), Code: ")" ); |
| 623 | else |
| 624 | S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_use); |
| 625 | } |
| 626 | S.Diag(Loc: IV->getLocation(), DiagID: diag::note_ivar_decl); |
| 627 | } |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { |
| 632 | // Handle any placeholder expressions which made it here. |
| 633 | if (E->hasPlaceholderType()) { |
| 634 | ExprResult result = CheckPlaceholderExpr(E); |
| 635 | if (result.isInvalid()) return ExprError(); |
| 636 | E = result.get(); |
| 637 | } |
| 638 | |
| 639 | // C++ [conv.lval]p1: |
| 640 | // A glvalue of a non-function, non-array type T can be |
| 641 | // converted to a prvalue. |
| 642 | if (!E->isGLValue()) return E; |
| 643 | |
| 644 | QualType T = E->getType(); |
| 645 | assert(!T.isNull() && "r-value conversion on typeless expression?" ); |
| 646 | |
| 647 | // lvalue-to-rvalue conversion cannot be applied to types that decay to |
| 648 | // pointers (i.e. function or array types). |
| 649 | if (T->canDecayToPointerType()) |
| 650 | return E; |
| 651 | |
| 652 | // We don't want to throw lvalue-to-rvalue casts on top of |
| 653 | // expressions of certain types in C++. |
| 654 | if (getLangOpts().CPlusPlus) { |
| 655 | if (T == Context.OverloadTy || T->isRecordType() || |
| 656 | (T->isDependentType() && !T->isAnyPointerType() && |
| 657 | !T->isMemberPointerType())) |
| 658 | return E; |
| 659 | } |
| 660 | |
| 661 | // The C standard is actually really unclear on this point, and |
| 662 | // DR106 tells us what the result should be but not why. It's |
| 663 | // generally best to say that void types just doesn't undergo |
| 664 | // lvalue-to-rvalue at all. Note that expressions of unqualified |
| 665 | // 'void' type are never l-values, but qualified void can be. |
| 666 | if (T->isVoidType()) |
| 667 | return E; |
| 668 | |
| 669 | // OpenCL usually rejects direct accesses to values of 'half' type. |
| 670 | if (getLangOpts().OpenCL && |
| 671 | !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16" , LO: getLangOpts()) && |
| 672 | T->isHalfType()) { |
| 673 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_half_load_store) |
| 674 | << 0 << T; |
| 675 | return ExprError(); |
| 676 | } |
| 677 | |
| 678 | CheckForNullPointerDereference(S&: *this, E); |
| 679 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) { |
| 680 | NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope, |
| 681 | Name: &Context.Idents.get(Name: "object_getClass" ), |
| 682 | Loc: SourceLocation(), NameKind: LookupOrdinaryName); |
| 683 | if (ObjectGetClass) |
| 684 | Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use) |
| 685 | << FixItHint::CreateInsertion(InsertionLoc: OISA->getBeginLoc(), Code: "object_getClass(" ) |
| 686 | << FixItHint::CreateReplacement( |
| 687 | RemoveRange: SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), Code: ")" ); |
| 688 | else |
| 689 | Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use); |
| 690 | } |
| 691 | else if (const ObjCIvarRefExpr *OIRE = |
| 692 | dyn_cast<ObjCIvarRefExpr>(Val: E->IgnoreParenCasts())) |
| 693 | DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: nullptr); |
| 694 | |
| 695 | // C++ [conv.lval]p1: |
| 696 | // [...] If T is a non-class type, the type of the prvalue is the |
| 697 | // cv-unqualified version of T. Otherwise, the type of the |
| 698 | // rvalue is T. |
| 699 | // |
| 700 | // C99 6.3.2.1p2: |
| 701 | // If the lvalue has qualified type, the value has the unqualified |
| 702 | // version of the type of the lvalue; otherwise, the value has the |
| 703 | // type of the lvalue. |
| 704 | if (T.hasQualifiers()) |
| 705 | T = T.getUnqualifiedType(); |
| 706 | |
| 707 | // Under the MS ABI, lock down the inheritance model now. |
| 708 | if (T->isMemberPointerType() && |
| 709 | Context.getTargetInfo().getCXXABI().isMicrosoft()) |
| 710 | (void)isCompleteType(Loc: E->getExprLoc(), T); |
| 711 | |
| 712 | ExprResult Res = CheckLValueToRValueConversionOperand(E); |
| 713 | if (Res.isInvalid()) |
| 714 | return Res; |
| 715 | E = Res.get(); |
| 716 | |
| 717 | // Loading a __weak object implicitly retains the value, so we need a cleanup to |
| 718 | // balance that. |
| 719 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) |
| 720 | Cleanup.setExprNeedsCleanups(true); |
| 721 | |
| 722 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) |
| 723 | Cleanup.setExprNeedsCleanups(true); |
| 724 | |
| 725 | if (!BoundsSafetyCheckUseOfCountAttrPtr(E: Res.get())) |
| 726 | return ExprError(); |
| 727 | |
| 728 | // C++ [conv.lval]p3: |
| 729 | // If T is cv std::nullptr_t, the result is a null pointer constant. |
| 730 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; |
| 731 | Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue, |
| 732 | FPO: CurFPFeatureOverrides()); |
| 733 | |
| 734 | // C11 6.3.2.1p2: |
| 735 | // ... if the lvalue has atomic type, the value has the non-atomic version |
| 736 | // of the type of the lvalue ... |
| 737 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { |
| 738 | T = Atomic->getValueType().getUnqualifiedType(); |
| 739 | Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(), |
| 740 | BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
| 741 | } |
| 742 | |
| 743 | return Res; |
| 744 | } |
| 745 | |
| 746 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { |
| 747 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); |
| 748 | if (Res.isInvalid()) |
| 749 | return ExprError(); |
| 750 | Res = DefaultLvalueConversion(E: Res.get()); |
| 751 | if (Res.isInvalid()) |
| 752 | return ExprError(); |
| 753 | return Res; |
| 754 | } |
| 755 | |
| 756 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { |
| 757 | QualType Ty = E->getType(); |
| 758 | ExprResult Res = E; |
| 759 | // Only do implicit cast for a function type, but not for a pointer |
| 760 | // to function type. |
| 761 | if (Ty->isFunctionType()) { |
| 762 | Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty), |
| 763 | CK: CK_FunctionToPointerDecay); |
| 764 | if (Res.isInvalid()) |
| 765 | return ExprError(); |
| 766 | } |
| 767 | Res = DefaultLvalueConversion(E: Res.get()); |
| 768 | if (Res.isInvalid()) |
| 769 | return ExprError(); |
| 770 | return Res.get(); |
| 771 | } |
| 772 | |
| 773 | /// UsualUnaryFPConversions - Promotes floating-point types according to the |
| 774 | /// current language semantics. |
| 775 | ExprResult Sema::UsualUnaryFPConversions(Expr *E) { |
| 776 | QualType Ty = E->getType(); |
| 777 | assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type" ); |
| 778 | |
| 779 | LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); |
| 780 | if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() && |
| 781 | (getLangOpts().getFPEvalMethod() != |
| 782 | LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine || |
| 783 | PP.getLastFPEvalPragmaLocation().isValid())) { |
| 784 | switch (EvalMethod) { |
| 785 | default: |
| 786 | llvm_unreachable("Unrecognized float evaluation method" ); |
| 787 | break; |
| 788 | case LangOptions::FEM_UnsetOnCommandLine: |
| 789 | llvm_unreachable("Float evaluation method should be set by now" ); |
| 790 | break; |
| 791 | case LangOptions::FEM_Double: |
| 792 | if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0) |
| 793 | // Widen the expression to double. |
| 794 | return Ty->isComplexType() |
| 795 | ? ImpCastExprToType(E, |
| 796 | Type: Context.getComplexType(T: Context.DoubleTy), |
| 797 | CK: CK_FloatingComplexCast) |
| 798 | : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast); |
| 799 | break; |
| 800 | case LangOptions::FEM_Extended: |
| 801 | if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0) |
| 802 | // Widen the expression to long double. |
| 803 | return Ty->isComplexType() |
| 804 | ? ImpCastExprToType( |
| 805 | E, Type: Context.getComplexType(T: Context.LongDoubleTy), |
| 806 | CK: CK_FloatingComplexCast) |
| 807 | : ImpCastExprToType(E, Type: Context.LongDoubleTy, |
| 808 | CK: CK_FloatingCast); |
| 809 | break; |
| 810 | } |
| 811 | } |
| 812 | |
| 813 | // Half FP have to be promoted to float unless it is natively supported |
| 814 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) |
| 815 | return ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast); |
| 816 | |
| 817 | return E; |
| 818 | } |
| 819 | |
| 820 | /// UsualUnaryConversions - Performs various conversions that are common to most |
| 821 | /// operators (C99 6.3). The conversions of array and function types are |
| 822 | /// sometimes suppressed. For example, the array->pointer conversion doesn't |
| 823 | /// apply if the array is an argument to the sizeof or address (&) operators. |
| 824 | /// In these instances, this routine should *not* be called. |
| 825 | ExprResult Sema::UsualUnaryConversions(Expr *E) { |
| 826 | // First, convert to an r-value. |
| 827 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); |
| 828 | if (Res.isInvalid()) |
| 829 | return ExprError(); |
| 830 | |
| 831 | // Promote floating-point types. |
| 832 | Res = UsualUnaryFPConversions(E: Res.get()); |
| 833 | if (Res.isInvalid()) |
| 834 | return ExprError(); |
| 835 | E = Res.get(); |
| 836 | |
| 837 | QualType Ty = E->getType(); |
| 838 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type" ); |
| 839 | |
| 840 | // Try to perform integral promotions if the object has a theoretically |
| 841 | // promotable type. |
| 842 | if (Ty->isIntegralOrUnscopedEnumerationType()) { |
| 843 | // C99 6.3.1.1p2: |
| 844 | // |
| 845 | // The following may be used in an expression wherever an int or |
| 846 | // unsigned int may be used: |
| 847 | // - an object or expression with an integer type whose integer |
| 848 | // conversion rank is less than or equal to the rank of int |
| 849 | // and unsigned int. |
| 850 | // - A bit-field of type _Bool, int, signed int, or unsigned int. |
| 851 | // |
| 852 | // If an int can represent all values of the original type, the |
| 853 | // value is converted to an int; otherwise, it is converted to an |
| 854 | // unsigned int. These are called the integer promotions. All |
| 855 | // other types are unchanged by the integer promotions. |
| 856 | |
| 857 | QualType PTy = Context.isPromotableBitField(E); |
| 858 | if (!PTy.isNull()) { |
| 859 | E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get(); |
| 860 | return E; |
| 861 | } |
| 862 | if (Context.isPromotableIntegerType(T: Ty)) { |
| 863 | QualType PT = Context.getPromotedIntegerType(PromotableType: Ty); |
| 864 | E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get(); |
| 865 | return E; |
| 866 | } |
| 867 | } |
| 868 | return E; |
| 869 | } |
| 870 | |
| 871 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that |
| 872 | /// do not have a prototype. Arguments that have type float or __fp16 |
| 873 | /// are promoted to double. All other argument types are converted by |
| 874 | /// UsualUnaryConversions(). |
| 875 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { |
| 876 | QualType Ty = E->getType(); |
| 877 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type" ); |
| 878 | |
| 879 | ExprResult Res = UsualUnaryConversions(E); |
| 880 | if (Res.isInvalid()) |
| 881 | return ExprError(); |
| 882 | E = Res.get(); |
| 883 | |
| 884 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) |
| 885 | // promote to double. |
| 886 | // Note that default argument promotion applies only to float (and |
| 887 | // half/fp16); it does not apply to _Float16. |
| 888 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); |
| 889 | if (BTy && (BTy->getKind() == BuiltinType::Half || |
| 890 | BTy->getKind() == BuiltinType::Float)) { |
| 891 | if (getLangOpts().OpenCL && |
| 892 | !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64" , LO: getLangOpts())) { |
| 893 | if (BTy->getKind() == BuiltinType::Half) { |
| 894 | E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get(); |
| 895 | } |
| 896 | } else { |
| 897 | E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get(); |
| 898 | } |
| 899 | } |
| 900 | if (BTy && |
| 901 | getLangOpts().getExtendIntArgs() == |
| 902 | LangOptions::ExtendArgsKind::ExtendTo64 && |
| 903 | Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && |
| 904 | Context.getTypeSizeInChars(T: BTy) < |
| 905 | Context.getTypeSizeInChars(T: Context.LongLongTy)) { |
| 906 | E = (Ty->isUnsignedIntegerType()) |
| 907 | ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast) |
| 908 | .get() |
| 909 | : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get(); |
| 910 | assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && |
| 911 | "Unexpected typesize for LongLongTy" ); |
| 912 | } |
| 913 | |
| 914 | // C++ performs lvalue-to-rvalue conversion as a default argument |
| 915 | // promotion, even on class types, but note: |
| 916 | // C++11 [conv.lval]p2: |
| 917 | // When an lvalue-to-rvalue conversion occurs in an unevaluated |
| 918 | // operand or a subexpression thereof the value contained in the |
| 919 | // referenced object is not accessed. Otherwise, if the glvalue |
| 920 | // has a class type, the conversion copy-initializes a temporary |
| 921 | // of type T from the glvalue and the result of the conversion |
| 922 | // is a prvalue for the temporary. |
| 923 | // FIXME: add some way to gate this entire thing for correctness in |
| 924 | // potentially potentially evaluated contexts. |
| 925 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { |
| 926 | ExprResult Temp = PerformCopyInitialization( |
| 927 | Entity: InitializedEntity::InitializeTemporary(Type: E->getType()), |
| 928 | EqualLoc: E->getExprLoc(), Init: E); |
| 929 | if (Temp.isInvalid()) |
| 930 | return ExprError(); |
| 931 | E = Temp.get(); |
| 932 | } |
| 933 | |
| 934 | // C++ [expr.call]p7, per CWG722: |
| 935 | // An argument that has (possibly cv-qualified) type std::nullptr_t is |
| 936 | // converted to void* ([conv.ptr]). |
| 937 | // (This does not apply to C23 nullptr) |
| 938 | if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType()) |
| 939 | E = ImpCastExprToType(E, Type: Context.VoidPtrTy, CK: CK_NullToPointer).get(); |
| 940 | |
| 941 | return E; |
| 942 | } |
| 943 | |
| 944 | VarArgKind Sema::isValidVarArgType(const QualType &Ty) { |
| 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 null pointer conversion, array-to-pointer |
| 952 | // decay and function-to-pointer decay, the only such type in C++ is cv |
| 953 | // void. This also handles initializer lists as variadic arguments. |
| 954 | if (Ty->isVoidType()) |
| 955 | return VarArgKind::Invalid; |
| 956 | |
| 957 | if (Ty->isObjCObjectType()) |
| 958 | return VarArgKind::Invalid; |
| 959 | return VarArgKind::Valid; |
| 960 | } |
| 961 | |
| 962 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) |
| 963 | return VarArgKind::Invalid; |
| 964 | |
| 965 | if (Context.getTargetInfo().getTriple().isWasm() && |
| 966 | Ty.isWebAssemblyReferenceType()) { |
| 967 | return VarArgKind::Invalid; |
| 968 | } |
| 969 | |
| 970 | if (Ty.isCXX98PODType(Context)) |
| 971 | return VarArgKind::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. |
| 978 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) |
| 979 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) |
| 980 | if (!Record->hasNonTrivialCopyConstructor() && |
| 981 | !Record->hasNonTrivialMoveConstructor() && |
| 982 | !Record->hasNonTrivialDestructor()) |
| 983 | return VarArgKind::ValidInCXX11; |
| 984 | |
| 985 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) |
| 986 | return VarArgKind::Valid; |
| 987 | |
| 988 | if (Ty->isObjCObjectType()) |
| 989 | return VarArgKind::Invalid; |
| 990 | |
| 991 | if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>()) |
| 992 | return VarArgKind::Valid; |
| 993 | |
| 994 | if (getLangOpts().MSVCCompat) |
| 995 | return VarArgKind::MSVCUndefined; |
| 996 | |
| 997 | if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>()) |
| 998 | return VarArgKind::Valid; |
| 999 | |
| 1000 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're |
| 1001 | // permitted to reject them. We should consider doing so. |
| 1002 | return VarArgKind::Undefined; |
| 1003 | } |
| 1004 | |
| 1005 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { |
| 1006 | // Don't allow one to pass an Objective-C interface to a vararg. |
| 1007 | const QualType &Ty = E->getType(); |
| 1008 | VarArgKind VAK = isValidVarArgType(Ty); |
| 1009 | |
| 1010 | // Complain about passing non-POD types through varargs. |
| 1011 | switch (VAK) { |
| 1012 | case VarArgKind::ValidInCXX11: |
| 1013 | DiagRuntimeBehavior( |
| 1014 | Loc: E->getBeginLoc(), Statement: nullptr, |
| 1015 | PD: PDiag(DiagID: diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); |
| 1016 | [[fallthrough]]; |
| 1017 | case VarArgKind::Valid: |
| 1018 | if (Ty->isRecordType()) { |
| 1019 | // This is unlikely to be what the user intended. If the class has a |
| 1020 | // 'c_str' member function, the user probably meant to call that. |
| 1021 | DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr, |
| 1022 | PD: PDiag(DiagID: diag::warn_pass_class_arg_to_vararg) |
| 1023 | << Ty << CT << hasCStrMethod(E) << ".c_str()" ); |
| 1024 | } |
| 1025 | break; |
| 1026 | |
| 1027 | case VarArgKind::Undefined: |
| 1028 | case VarArgKind::MSVCUndefined: |
| 1029 | DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr, |
| 1030 | PD: PDiag(DiagID: diag::warn_cannot_pass_non_pod_arg_to_vararg) |
| 1031 | << getLangOpts().CPlusPlus11 << Ty << CT); |
| 1032 | break; |
| 1033 | |
| 1034 | case VarArgKind::Invalid: |
| 1035 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) |
| 1036 | Diag(Loc: E->getBeginLoc(), |
| 1037 | DiagID: diag::err_cannot_pass_non_trivial_c_struct_to_vararg) |
| 1038 | << Ty << CT; |
| 1039 | else if (Ty->isObjCObjectType()) |
| 1040 | DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr, |
| 1041 | PD: PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg) |
| 1042 | << Ty << CT); |
| 1043 | else |
| 1044 | Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg) |
| 1045 | << isa<InitListExpr>(Val: E) << Ty << CT; |
| 1046 | break; |
| 1047 | } |
| 1048 | } |
| 1049 | |
| 1050 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, |
| 1051 | FunctionDecl *FDecl) { |
| 1052 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { |
| 1053 | // Strip the unbridged-cast placeholder expression off, if applicable. |
| 1054 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && |
| 1055 | (CT == VariadicCallType::Method || |
| 1056 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { |
| 1057 | E = ObjC().stripARCUnbridgedCast(e: E); |
| 1058 | |
| 1059 | // Otherwise, do normal placeholder checking. |
| 1060 | } else { |
| 1061 | ExprResult ExprRes = CheckPlaceholderExpr(E); |
| 1062 | if (ExprRes.isInvalid()) |
| 1063 | return ExprError(); |
| 1064 | E = ExprRes.get(); |
| 1065 | } |
| 1066 | } |
| 1067 | |
| 1068 | ExprResult ExprRes = DefaultArgumentPromotion(E); |
| 1069 | if (ExprRes.isInvalid()) |
| 1070 | return ExprError(); |
| 1071 | |
| 1072 | // Copy blocks to the heap. |
| 1073 | if (ExprRes.get()->getType()->isBlockPointerType()) |
| 1074 | maybeExtendBlockObject(E&: ExprRes); |
| 1075 | |
| 1076 | E = ExprRes.get(); |
| 1077 | |
| 1078 | // Diagnostics regarding non-POD argument types are |
| 1079 | // emitted along with format string checking in Sema::CheckFunctionCall(). |
| 1080 | if (isValidVarArgType(Ty: E->getType()) == VarArgKind::Undefined) { |
| 1081 | // Turn this into a trap. |
| 1082 | CXXScopeSpec SS; |
| 1083 | SourceLocation TemplateKWLoc; |
| 1084 | UnqualifiedId Name; |
| 1085 | Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap" ), |
| 1086 | IdLoc: E->getBeginLoc()); |
| 1087 | ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name, |
| 1088 | /*HasTrailingLParen=*/true, |
| 1089 | /*IsAddressOfOperand=*/false); |
| 1090 | if (TrapFn.isInvalid()) |
| 1091 | return ExprError(); |
| 1092 | |
| 1093 | ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(), ArgExprs: {}, |
| 1094 | RParenLoc: E->getEndLoc()); |
| 1095 | if (Call.isInvalid()) |
| 1096 | return ExprError(); |
| 1097 | |
| 1098 | ExprResult Comma = |
| 1099 | ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E); |
| 1100 | if (Comma.isInvalid()) |
| 1101 | return ExprError(); |
| 1102 | return Comma.get(); |
| 1103 | } |
| 1104 | |
| 1105 | if (!getLangOpts().CPlusPlus && |
| 1106 | RequireCompleteType(Loc: E->getExprLoc(), T: E->getType(), |
| 1107 | DiagID: diag::err_call_incomplete_argument)) |
| 1108 | return ExprError(); |
| 1109 | |
| 1110 | return E; |
| 1111 | } |
| 1112 | |
| 1113 | /// Convert complex integers to complex floats and real integers to |
| 1114 | /// real floats as required for complex arithmetic. Helper function of |
| 1115 | /// UsualArithmeticConversions() |
| 1116 | /// |
| 1117 | /// \return false if the integer expression is an integer type and is |
| 1118 | /// successfully converted to the (complex) float type. |
| 1119 | static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, |
| 1120 | ExprResult &ComplexExpr, |
| 1121 | QualType IntTy, |
| 1122 | QualType ComplexTy, |
| 1123 | bool SkipCast) { |
| 1124 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; |
| 1125 | if (SkipCast) return false; |
| 1126 | if (IntTy->isIntegerType()) { |
| 1127 | QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType(); |
| 1128 | IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating); |
| 1129 | } else { |
| 1130 | assert(IntTy->isComplexIntegerType()); |
| 1131 | IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy, |
| 1132 | CK: CK_IntegralComplexToFloatingComplex); |
| 1133 | } |
| 1134 | return false; |
| 1135 | } |
| 1136 | |
| 1137 | // This handles complex/complex, complex/float, or float/complex. |
| 1138 | // When both operands are complex, the shorter operand is converted to the |
| 1139 | // type of the longer, and that is the type of the result. This corresponds |
| 1140 | // to what is done when combining two real floating-point operands. |
| 1141 | // The fun begins when size promotion occur across type domains. |
| 1142 | // From H&S 6.3.4: When one operand is complex and the other is a real |
| 1143 | // floating-point type, the less precise type is converted, within it's |
| 1144 | // real or complex domain, to the precision of the other type. For example, |
| 1145 | // when combining a "long double" with a "double _Complex", the |
| 1146 | // "double _Complex" is promoted to "long double _Complex". |
| 1147 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, |
| 1148 | QualType ShorterType, |
| 1149 | QualType LongerType, |
| 1150 | bool PromotePrecision) { |
| 1151 | bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType()); |
| 1152 | QualType Result = |
| 1153 | LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType); |
| 1154 | |
| 1155 | if (PromotePrecision) { |
| 1156 | if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) { |
| 1157 | Shorter = |
| 1158 | S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast); |
| 1159 | } else { |
| 1160 | if (LongerIsComplex) |
| 1161 | LongerType = LongerType->castAs<ComplexType>()->getElementType(); |
| 1162 | Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast); |
| 1163 | } |
| 1164 | } |
| 1165 | return Result; |
| 1166 | } |
| 1167 | |
| 1168 | /// Handle arithmetic conversion with complex types. Helper function of |
| 1169 | /// UsualArithmeticConversions() |
| 1170 | static QualType handleComplexConversion(Sema &S, ExprResult &LHS, |
| 1171 | ExprResult &RHS, QualType LHSType, |
| 1172 | QualType RHSType, bool IsCompAssign) { |
| 1173 | // Handle (complex) integer types. |
| 1174 | if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType, |
| 1175 | /*SkipCast=*/false)) |
| 1176 | return LHSType; |
| 1177 | if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType, |
| 1178 | /*SkipCast=*/IsCompAssign)) |
| 1179 | return RHSType; |
| 1180 | |
| 1181 | // Compute the rank of the two types, regardless of whether they are complex. |
| 1182 | int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType); |
| 1183 | if (Order < 0) |
| 1184 | // Promote the precision of the LHS if not an assignment. |
| 1185 | return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType, |
| 1186 | /*PromotePrecision=*/!IsCompAssign); |
| 1187 | // Promote the precision of the RHS unless it is already the same as the LHS. |
| 1188 | return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType, |
| 1189 | /*PromotePrecision=*/Order > 0); |
| 1190 | } |
| 1191 | |
| 1192 | /// Handle arithmetic conversion from integer to float. Helper function |
| 1193 | /// of UsualArithmeticConversions() |
| 1194 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, |
| 1195 | ExprResult &IntExpr, |
| 1196 | QualType FloatTy, QualType IntTy, |
| 1197 | bool ConvertFloat, bool ConvertInt) { |
| 1198 | if (IntTy->isIntegerType()) { |
| 1199 | if (ConvertInt) |
| 1200 | // Convert intExpr to the lhs floating point type. |
| 1201 | IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy, |
| 1202 | CK: CK_IntegralToFloating); |
| 1203 | return FloatTy; |
| 1204 | } |
| 1205 | |
| 1206 | // Convert both sides to the appropriate complex float. |
| 1207 | assert(IntTy->isComplexIntegerType()); |
| 1208 | QualType result = S.Context.getComplexType(T: FloatTy); |
| 1209 | |
| 1210 | // _Complex int -> _Complex float |
| 1211 | if (ConvertInt) |
| 1212 | IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result, |
| 1213 | CK: CK_IntegralComplexToFloatingComplex); |
| 1214 | |
| 1215 | // float -> _Complex float |
| 1216 | if (ConvertFloat) |
| 1217 | FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result, |
| 1218 | CK: CK_FloatingRealToComplex); |
| 1219 | |
| 1220 | return result; |
| 1221 | } |
| 1222 | |
| 1223 | /// Handle arithmethic conversion with floating point types. Helper |
| 1224 | /// function of UsualArithmeticConversions() |
| 1225 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, |
| 1226 | ExprResult &RHS, QualType LHSType, |
| 1227 | QualType RHSType, bool IsCompAssign) { |
| 1228 | bool LHSFloat = LHSType->isRealFloatingType(); |
| 1229 | bool RHSFloat = RHSType->isRealFloatingType(); |
| 1230 | |
| 1231 | // N1169 4.1.4: If one of the operands has a floating type and the other |
| 1232 | // operand has a fixed-point type, the fixed-point operand |
| 1233 | // is converted to the floating type [...] |
| 1234 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { |
| 1235 | if (LHSFloat) |
| 1236 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating); |
| 1237 | else if (!IsCompAssign) |
| 1238 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating); |
| 1239 | return LHSFloat ? LHSType : RHSType; |
| 1240 | } |
| 1241 | |
| 1242 | // If we have two real floating types, convert the smaller operand |
| 1243 | // to the bigger result. |
| 1244 | if (LHSFloat && RHSFloat) { |
| 1245 | int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType); |
| 1246 | if (order > 0) { |
| 1247 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast); |
| 1248 | return LHSType; |
| 1249 | } |
| 1250 | |
| 1251 | assert(order < 0 && "illegal float comparison" ); |
| 1252 | if (!IsCompAssign) |
| 1253 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast); |
| 1254 | return RHSType; |
| 1255 | } |
| 1256 | |
| 1257 | if (LHSFloat) { |
| 1258 | // Half FP has to be promoted to float unless it is natively supported |
| 1259 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) |
| 1260 | LHSType = S.Context.FloatTy; |
| 1261 | |
| 1262 | return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType, |
| 1263 | /*ConvertFloat=*/!IsCompAssign, |
| 1264 | /*ConvertInt=*/ true); |
| 1265 | } |
| 1266 | assert(RHSFloat); |
| 1267 | return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType, |
| 1268 | /*ConvertFloat=*/ true, |
| 1269 | /*ConvertInt=*/!IsCompAssign); |
| 1270 | } |
| 1271 | |
| 1272 | /// Diagnose attempts to convert between __float128, __ibm128 and |
| 1273 | /// long double if there is no support for such conversion. |
| 1274 | /// Helper function of UsualArithmeticConversions(). |
| 1275 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, |
| 1276 | QualType RHSType) { |
| 1277 | // No issue if either is not a floating point type. |
| 1278 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) |
| 1279 | return false; |
| 1280 | |
| 1281 | // No issue if both have the same 128-bit float semantics. |
| 1282 | auto *LHSComplex = LHSType->getAs<ComplexType>(); |
| 1283 | auto *RHSComplex = RHSType->getAs<ComplexType>(); |
| 1284 | |
| 1285 | QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; |
| 1286 | QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; |
| 1287 | |
| 1288 | const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem); |
| 1289 | const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem); |
| 1290 | |
| 1291 | if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || |
| 1292 | &RHSSem != &llvm::APFloat::IEEEquad()) && |
| 1293 | (&LHSSem != &llvm::APFloat::IEEEquad() || |
| 1294 | &RHSSem != &llvm::APFloat::PPCDoubleDouble())) |
| 1295 | return false; |
| 1296 | |
| 1297 | return true; |
| 1298 | } |
| 1299 | |
| 1300 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); |
| 1301 | |
| 1302 | namespace { |
| 1303 | /// These helper callbacks are placed in an anonymous namespace to |
| 1304 | /// permit their use as function template parameters. |
| 1305 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { |
| 1306 | return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast); |
| 1307 | } |
| 1308 | |
| 1309 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { |
| 1310 | return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType), |
| 1311 | CK: CK_IntegralComplexCast); |
| 1312 | } |
| 1313 | } |
| 1314 | |
| 1315 | /// Handle integer arithmetic conversions. Helper function of |
| 1316 | /// UsualArithmeticConversions() |
| 1317 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> |
| 1318 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, |
| 1319 | ExprResult &RHS, QualType LHSType, |
| 1320 | QualType RHSType, bool IsCompAssign) { |
| 1321 | // The rules for this case are in C99 6.3.1.8 |
| 1322 | int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType); |
| 1323 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); |
| 1324 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); |
| 1325 | if (LHSSigned == RHSSigned) { |
| 1326 | // Same signedness; use the higher-ranked type |
| 1327 | if (order >= 0) { |
| 1328 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); |
| 1329 | return LHSType; |
| 1330 | } else if (!IsCompAssign) |
| 1331 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); |
| 1332 | return RHSType; |
| 1333 | } else if (order != (LHSSigned ? 1 : -1)) { |
| 1334 | // The unsigned type has greater than or equal rank to the |
| 1335 | // signed type, so use the unsigned type |
| 1336 | if (RHSSigned) { |
| 1337 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); |
| 1338 | return LHSType; |
| 1339 | } else if (!IsCompAssign) |
| 1340 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); |
| 1341 | return RHSType; |
| 1342 | } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) { |
| 1343 | // The two types are different widths; if we are here, that |
| 1344 | // means the signed type is larger than the unsigned type, so |
| 1345 | // use the signed type. |
| 1346 | if (LHSSigned) { |
| 1347 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); |
| 1348 | return LHSType; |
| 1349 | } else if (!IsCompAssign) |
| 1350 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); |
| 1351 | return RHSType; |
| 1352 | } else { |
| 1353 | // The signed type is higher-ranked than the unsigned type, |
| 1354 | // but isn't actually any bigger (like unsigned int and long |
| 1355 | // on most 32-bit systems). Use the unsigned type corresponding |
| 1356 | // to the signed type. |
| 1357 | QualType result = |
| 1358 | S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType); |
| 1359 | RHS = (*doRHSCast)(S, RHS.get(), result); |
| 1360 | if (!IsCompAssign) |
| 1361 | LHS = (*doLHSCast)(S, LHS.get(), result); |
| 1362 | return result; |
| 1363 | } |
| 1364 | } |
| 1365 | |
| 1366 | /// Handle conversions with GCC complex int extension. Helper function |
| 1367 | /// of UsualArithmeticConversions() |
| 1368 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, |
| 1369 | ExprResult &RHS, QualType LHSType, |
| 1370 | QualType RHSType, |
| 1371 | bool IsCompAssign) { |
| 1372 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); |
| 1373 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); |
| 1374 | |
| 1375 | if (LHSComplexInt && RHSComplexInt) { |
| 1376 | QualType LHSEltType = LHSComplexInt->getElementType(); |
| 1377 | QualType RHSEltType = RHSComplexInt->getElementType(); |
| 1378 | QualType ScalarType = |
| 1379 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> |
| 1380 | (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign); |
| 1381 | |
| 1382 | return S.Context.getComplexType(T: ScalarType); |
| 1383 | } |
| 1384 | |
| 1385 | if (LHSComplexInt) { |
| 1386 | QualType LHSEltType = LHSComplexInt->getElementType(); |
| 1387 | QualType ScalarType = |
| 1388 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> |
| 1389 | (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign); |
| 1390 | QualType ComplexType = S.Context.getComplexType(T: ScalarType); |
| 1391 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType, |
| 1392 | CK: CK_IntegralRealToComplex); |
| 1393 | |
| 1394 | return ComplexType; |
| 1395 | } |
| 1396 | |
| 1397 | assert(RHSComplexInt); |
| 1398 | |
| 1399 | QualType RHSEltType = RHSComplexInt->getElementType(); |
| 1400 | QualType ScalarType = |
| 1401 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> |
| 1402 | (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign); |
| 1403 | QualType ComplexType = S.Context.getComplexType(T: ScalarType); |
| 1404 | |
| 1405 | if (!IsCompAssign) |
| 1406 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType, |
| 1407 | CK: CK_IntegralRealToComplex); |
| 1408 | return ComplexType; |
| 1409 | } |
| 1410 | |
| 1411 | /// Return the rank of a given fixed point or integer type. The value itself |
| 1412 | /// doesn't matter, but the values must be increasing with proper increasing |
| 1413 | /// rank as described in N1169 4.1.1. |
| 1414 | static unsigned GetFixedPointRank(QualType Ty) { |
| 1415 | const auto *BTy = Ty->getAs<BuiltinType>(); |
| 1416 | assert(BTy && "Expected a builtin type." ); |
| 1417 | |
| 1418 | switch (BTy->getKind()) { |
| 1419 | case BuiltinType::ShortFract: |
| 1420 | case BuiltinType::UShortFract: |
| 1421 | case BuiltinType::SatShortFract: |
| 1422 | case BuiltinType::SatUShortFract: |
| 1423 | return 1; |
| 1424 | case BuiltinType::Fract: |
| 1425 | case BuiltinType::UFract: |
| 1426 | case BuiltinType::SatFract: |
| 1427 | case BuiltinType::SatUFract: |
| 1428 | return 2; |
| 1429 | case BuiltinType::LongFract: |
| 1430 | case BuiltinType::ULongFract: |
| 1431 | case BuiltinType::SatLongFract: |
| 1432 | case BuiltinType::SatULongFract: |
| 1433 | return 3; |
| 1434 | case BuiltinType::ShortAccum: |
| 1435 | case BuiltinType::UShortAccum: |
| 1436 | case BuiltinType::SatShortAccum: |
| 1437 | case BuiltinType::SatUShortAccum: |
| 1438 | return 4; |
| 1439 | case BuiltinType::Accum: |
| 1440 | case BuiltinType::UAccum: |
| 1441 | case BuiltinType::SatAccum: |
| 1442 | case BuiltinType::SatUAccum: |
| 1443 | return 5; |
| 1444 | case BuiltinType::LongAccum: |
| 1445 | case BuiltinType::ULongAccum: |
| 1446 | case BuiltinType::SatLongAccum: |
| 1447 | case BuiltinType::SatULongAccum: |
| 1448 | return 6; |
| 1449 | default: |
| 1450 | if (BTy->isInteger()) |
| 1451 | return 0; |
| 1452 | llvm_unreachable("Unexpected fixed point or integer type" ); |
| 1453 | } |
| 1454 | } |
| 1455 | |
| 1456 | /// handleFixedPointConversion - Fixed point operations between fixed |
| 1457 | /// point types and integers or other fixed point types do not fall under |
| 1458 | /// usual arithmetic conversion since these conversions could result in loss |
| 1459 | /// of precsision (N1169 4.1.4). These operations should be calculated with |
| 1460 | /// the full precision of their result type (N1169 4.1.6.2.1). |
| 1461 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, |
| 1462 | QualType RHSTy) { |
| 1463 | assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && |
| 1464 | "Expected at least one of the operands to be a fixed point type" ); |
| 1465 | assert((LHSTy->isFixedPointOrIntegerType() || |
| 1466 | RHSTy->isFixedPointOrIntegerType()) && |
| 1467 | "Special fixed point arithmetic operation conversions are only " |
| 1468 | "applied to ints or other fixed point types" ); |
| 1469 | |
| 1470 | // If one operand has signed fixed-point type and the other operand has |
| 1471 | // unsigned fixed-point type, then the unsigned fixed-point operand is |
| 1472 | // converted to its corresponding signed fixed-point type and the resulting |
| 1473 | // type is the type of the converted operand. |
| 1474 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) |
| 1475 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy); |
| 1476 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) |
| 1477 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy); |
| 1478 | |
| 1479 | // The result type is the type with the highest rank, whereby a fixed-point |
| 1480 | // conversion rank is always greater than an integer conversion rank; if the |
| 1481 | // type of either of the operands is a saturating fixedpoint type, the result |
| 1482 | // type shall be the saturating fixed-point type corresponding to the type |
| 1483 | // with the highest rank; the resulting value is converted (taking into |
| 1484 | // account rounding and overflow) to the precision of the resulting type. |
| 1485 | // Same ranks between signed and unsigned types are resolved earlier, so both |
| 1486 | // types are either signed or both unsigned at this point. |
| 1487 | unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy); |
| 1488 | unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy); |
| 1489 | |
| 1490 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; |
| 1491 | |
| 1492 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) |
| 1493 | ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy); |
| 1494 | |
| 1495 | return ResultTy; |
| 1496 | } |
| 1497 | |
| 1498 | /// Check that the usual arithmetic conversions can be performed on this pair of |
| 1499 | /// expressions that might be of enumeration type. |
| 1500 | void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, |
| 1501 | SourceLocation Loc, |
| 1502 | ArithConvKind ACK) { |
| 1503 | // C++2a [expr.arith.conv]p1: |
| 1504 | // If one operand is of enumeration type and the other operand is of a |
| 1505 | // different enumeration type or a floating-point type, this behavior is |
| 1506 | // deprecated ([depr.arith.conv.enum]). |
| 1507 | // |
| 1508 | // Warn on this in all language modes. Produce a deprecation warning in C++20. |
| 1509 | // Eventually we will presumably reject these cases (in C++23 onwards?). |
| 1510 | QualType L = LHS->getEnumCoercedType(Ctx: Context), |
| 1511 | R = RHS->getEnumCoercedType(Ctx: Context); |
| 1512 | bool LEnum = L->isUnscopedEnumerationType(), |
| 1513 | REnum = R->isUnscopedEnumerationType(); |
| 1514 | bool IsCompAssign = ACK == ArithConvKind::CompAssign; |
| 1515 | if ((!IsCompAssign && LEnum && R->isFloatingType()) || |
| 1516 | (REnum && L->isFloatingType())) { |
| 1517 | Diag(Loc, DiagID: getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26 |
| 1518 | : getLangOpts().CPlusPlus20 |
| 1519 | ? diag::warn_arith_conv_enum_float_cxx20 |
| 1520 | : diag::warn_arith_conv_enum_float) |
| 1521 | << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum |
| 1522 | << L << R; |
| 1523 | } else if (!IsCompAssign && LEnum && REnum && |
| 1524 | !Context.hasSameUnqualifiedType(T1: L, T2: R)) { |
| 1525 | unsigned DiagID; |
| 1526 | // In C++ 26, usual arithmetic conversions between 2 different enum types |
| 1527 | // are ill-formed. |
| 1528 | if (getLangOpts().CPlusPlus26) |
| 1529 | DiagID = diag::warn_conv_mixed_enum_types_cxx26; |
| 1530 | else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || |
| 1531 | !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { |
| 1532 | // If either enumeration type is unnamed, it's less likely that the |
| 1533 | // user cares about this, but this situation is still deprecated in |
| 1534 | // C++2a. Use a different warning group. |
| 1535 | DiagID = getLangOpts().CPlusPlus20 |
| 1536 | ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 |
| 1537 | : diag::warn_arith_conv_mixed_anon_enum_types; |
| 1538 | } else if (ACK == ArithConvKind::Conditional) { |
| 1539 | // Conditional expressions are separated out because they have |
| 1540 | // historically had a different warning flag. |
| 1541 | DiagID = getLangOpts().CPlusPlus20 |
| 1542 | ? diag::warn_conditional_mixed_enum_types_cxx20 |
| 1543 | : diag::warn_conditional_mixed_enum_types; |
| 1544 | } else if (ACK == ArithConvKind::Comparison) { |
| 1545 | // Comparison expressions are separated out because they have |
| 1546 | // historically had a different warning flag. |
| 1547 | DiagID = getLangOpts().CPlusPlus20 |
| 1548 | ? diag::warn_comparison_mixed_enum_types_cxx20 |
| 1549 | : diag::warn_comparison_mixed_enum_types; |
| 1550 | } else { |
| 1551 | DiagID = getLangOpts().CPlusPlus20 |
| 1552 | ? diag::warn_arith_conv_mixed_enum_types_cxx20 |
| 1553 | : diag::warn_arith_conv_mixed_enum_types; |
| 1554 | } |
| 1555 | Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() |
| 1556 | << (int)ACK << L << R; |
| 1557 | } |
| 1558 | } |
| 1559 | |
| 1560 | static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS, |
| 1561 | Expr *RHS, SourceLocation Loc, |
| 1562 | ArithConvKind ACK) { |
| 1563 | QualType LHSType = LHS->getType().getUnqualifiedType(); |
| 1564 | QualType RHSType = RHS->getType().getUnqualifiedType(); |
| 1565 | |
| 1566 | if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() || |
| 1567 | !RHSType->isUnicodeCharacterType()) |
| 1568 | return; |
| 1569 | |
| 1570 | if (ACK == ArithConvKind::Comparison) { |
| 1571 | if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType)) |
| 1572 | return; |
| 1573 | |
| 1574 | auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) { |
| 1575 | if (T->isChar8Type()) |
| 1576 | return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue()); |
| 1577 | if (T->isChar16Type()) |
| 1578 | return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue()); |
| 1579 | assert(T->isChar32Type()); |
| 1580 | return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue()); |
| 1581 | }; |
| 1582 | |
| 1583 | Expr::EvalResult LHSRes, RHSRes; |
| 1584 | bool LHSSuccess = LHS->EvaluateAsInt(Result&: LHSRes, Ctx: SemaRef.getASTContext(), |
| 1585 | AllowSideEffects: Expr::SE_AllowSideEffects, |
| 1586 | InConstantContext: SemaRef.isConstantEvaluatedContext()); |
| 1587 | bool RHSuccess = RHS->EvaluateAsInt(Result&: RHSRes, Ctx: SemaRef.getASTContext(), |
| 1588 | AllowSideEffects: Expr::SE_AllowSideEffects, |
| 1589 | InConstantContext: SemaRef.isConstantEvaluatedContext()); |
| 1590 | |
| 1591 | // Don't warn if the one known value is a representable |
| 1592 | // in the type of both expressions. |
| 1593 | if (LHSSuccess != RHSuccess) { |
| 1594 | Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes; |
| 1595 | if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) && |
| 1596 | IsSingleCodeUnitCP(RHSType, Res.Val.getInt())) |
| 1597 | return; |
| 1598 | } |
| 1599 | |
| 1600 | if (!LHSSuccess || !RHSuccess) { |
| 1601 | SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types) |
| 1602 | << LHS->getSourceRange() << RHS->getSourceRange() << LHSType |
| 1603 | << RHSType; |
| 1604 | return; |
| 1605 | } |
| 1606 | |
| 1607 | llvm::APSInt LHSValue(32); |
| 1608 | LHSValue = LHSRes.Val.getInt(); |
| 1609 | llvm::APSInt RHSValue(32); |
| 1610 | RHSValue = RHSRes.Val.getInt(); |
| 1611 | |
| 1612 | bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue); |
| 1613 | bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue); |
| 1614 | if (LHSSafe && RHSSafe) |
| 1615 | return; |
| 1616 | |
| 1617 | SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types_constant) |
| 1618 | << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType |
| 1619 | << FormatUTFCodeUnitAsCodepoint(Value: LHSValue.getExtValue(), T: LHSType) |
| 1620 | << FormatUTFCodeUnitAsCodepoint(Value: RHSValue.getExtValue(), T: RHSType); |
| 1621 | return; |
| 1622 | } |
| 1623 | |
| 1624 | if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType)) |
| 1625 | return; |
| 1626 | |
| 1627 | SemaRef.Diag(Loc, DiagID: diag::warn_arith_conv_mixed_unicode_types) |
| 1628 | << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType |
| 1629 | << RHSType; |
| 1630 | } |
| 1631 | |
| 1632 | /// UsualArithmeticConversions - Performs various conversions that are common to |
| 1633 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this |
| 1634 | /// routine returns the first non-arithmetic type found. The client is |
| 1635 | /// responsible for emitting appropriate error diagnostics. |
| 1636 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, |
| 1637 | SourceLocation Loc, |
| 1638 | ArithConvKind ACK) { |
| 1639 | |
| 1640 | checkEnumArithmeticConversions(LHS: LHS.get(), RHS: RHS.get(), Loc, ACK); |
| 1641 | |
| 1642 | CheckUnicodeArithmeticConversions(SemaRef&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK); |
| 1643 | |
| 1644 | if (ACK != ArithConvKind::CompAssign) { |
| 1645 | LHS = UsualUnaryConversions(E: LHS.get()); |
| 1646 | if (LHS.isInvalid()) |
| 1647 | return QualType(); |
| 1648 | } |
| 1649 | |
| 1650 | RHS = UsualUnaryConversions(E: RHS.get()); |
| 1651 | if (RHS.isInvalid()) |
| 1652 | return QualType(); |
| 1653 | |
| 1654 | // For conversion purposes, we ignore any qualifiers. |
| 1655 | // For example, "const float" and "float" are equivalent. |
| 1656 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); |
| 1657 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); |
| 1658 | |
| 1659 | // For conversion purposes, we ignore any atomic qualifier on the LHS. |
| 1660 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) |
| 1661 | LHSType = AtomicLHS->getValueType(); |
| 1662 | |
| 1663 | // If both types are identical, no conversion is needed. |
| 1664 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
| 1665 | return Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
| 1666 | |
| 1667 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. |
| 1668 | // The caller can deal with this (e.g. pointer + int). |
| 1669 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) |
| 1670 | return QualType(); |
| 1671 | |
| 1672 | // Apply unary and bitfield promotions to the LHS's type. |
| 1673 | QualType LHSUnpromotedType = LHSType; |
| 1674 | if (Context.isPromotableIntegerType(T: LHSType)) |
| 1675 | LHSType = Context.getPromotedIntegerType(PromotableType: LHSType); |
| 1676 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get()); |
| 1677 | if (!LHSBitfieldPromoteTy.isNull()) |
| 1678 | LHSType = LHSBitfieldPromoteTy; |
| 1679 | if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign) |
| 1680 | LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast); |
| 1681 | |
| 1682 | // If both types are identical, no conversion is needed. |
| 1683 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
| 1684 | return Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
| 1685 | |
| 1686 | // At this point, we have two different arithmetic types. |
| 1687 | |
| 1688 | // Diagnose attempts to convert between __ibm128, __float128 and long double |
| 1689 | // where such conversions currently can't be handled. |
| 1690 | if (unsupportedTypeConversion(S: *this, LHSType, RHSType)) |
| 1691 | return QualType(); |
| 1692 | |
| 1693 | // Handle complex types first (C99 6.3.1.8p1). |
| 1694 | if (LHSType->isComplexType() || RHSType->isComplexType()) |
| 1695 | return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType, |
| 1696 | IsCompAssign: ACK == ArithConvKind::CompAssign); |
| 1697 | |
| 1698 | // Now handle "real" floating types (i.e. float, double, long double). |
| 1699 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) |
| 1700 | return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType, |
| 1701 | IsCompAssign: ACK == ArithConvKind::CompAssign); |
| 1702 | |
| 1703 | // Handle GCC complex int extension. |
| 1704 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) |
| 1705 | return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType, |
| 1706 | IsCompAssign: ACK == ArithConvKind::CompAssign); |
| 1707 | |
| 1708 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) |
| 1709 | return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType); |
| 1710 | |
| 1711 | // Finally, we have two differing integer types. |
| 1712 | return handleIntegerConversion<doIntegralCast, doIntegralCast>( |
| 1713 | S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign); |
| 1714 | } |
| 1715 | |
| 1716 | //===----------------------------------------------------------------------===// |
| 1717 | // Semantic Analysis for various Expression Types |
| 1718 | //===----------------------------------------------------------------------===// |
| 1719 | |
| 1720 | |
| 1721 | ExprResult Sema::ActOnGenericSelectionExpr( |
| 1722 | SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, |
| 1723 | bool PredicateIsExpr, void *ControllingExprOrType, |
| 1724 | ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) { |
| 1725 | unsigned NumAssocs = ArgTypes.size(); |
| 1726 | assert(NumAssocs == ArgExprs.size()); |
| 1727 | |
| 1728 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; |
| 1729 | for (unsigned i = 0; i < NumAssocs; ++i) { |
| 1730 | if (ArgTypes[i]) |
| 1731 | (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]); |
| 1732 | else |
| 1733 | Types[i] = nullptr; |
| 1734 | } |
| 1735 | |
| 1736 | // If we have a controlling type, we need to convert it from a parsed type |
| 1737 | // into a semantic type and then pass that along. |
| 1738 | if (!PredicateIsExpr) { |
| 1739 | TypeSourceInfo *ControllingType; |
| 1740 | (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType), |
| 1741 | TInfo: &ControllingType); |
| 1742 | assert(ControllingType && "couldn't get the type out of the parser" ); |
| 1743 | ControllingExprOrType = ControllingType; |
| 1744 | } |
| 1745 | |
| 1746 | ExprResult ER = CreateGenericSelectionExpr( |
| 1747 | KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType, |
| 1748 | Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs); |
| 1749 | delete [] Types; |
| 1750 | return ER; |
| 1751 | } |
| 1752 | |
| 1753 | ExprResult Sema::CreateGenericSelectionExpr( |
| 1754 | SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, |
| 1755 | bool PredicateIsExpr, void *ControllingExprOrType, |
| 1756 | ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) { |
| 1757 | unsigned NumAssocs = Types.size(); |
| 1758 | assert(NumAssocs == Exprs.size()); |
| 1759 | assert(ControllingExprOrType && |
| 1760 | "Must have either a controlling expression or a controlling type" ); |
| 1761 | |
| 1762 | Expr *ControllingExpr = nullptr; |
| 1763 | TypeSourceInfo *ControllingType = nullptr; |
| 1764 | if (PredicateIsExpr) { |
| 1765 | // Decay and strip qualifiers for the controlling expression type, and |
| 1766 | // handle placeholder type replacement. See committee discussion from WG14 |
| 1767 | // DR423. |
| 1768 | EnterExpressionEvaluationContext Unevaluated( |
| 1769 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
| 1770 | ExprResult R = DefaultFunctionArrayLvalueConversion( |
| 1771 | E: reinterpret_cast<Expr *>(ControllingExprOrType)); |
| 1772 | if (R.isInvalid()) |
| 1773 | return ExprError(); |
| 1774 | ControllingExpr = R.get(); |
| 1775 | } else { |
| 1776 | // The extension form uses the type directly rather than converting it. |
| 1777 | ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType); |
| 1778 | if (!ControllingType) |
| 1779 | return ExprError(); |
| 1780 | } |
| 1781 | |
| 1782 | bool TypeErrorFound = false, |
| 1783 | IsResultDependent = ControllingExpr |
| 1784 | ? ControllingExpr->isTypeDependent() |
| 1785 | : ControllingType->getType()->isDependentType(), |
| 1786 | ContainsUnexpandedParameterPack = |
| 1787 | ControllingExpr |
| 1788 | ? ControllingExpr->containsUnexpandedParameterPack() |
| 1789 | : ControllingType->getType()->containsUnexpandedParameterPack(); |
| 1790 | |
| 1791 | // The controlling expression is an unevaluated operand, so side effects are |
| 1792 | // likely unintended. |
| 1793 | if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr && |
| 1794 | ControllingExpr->HasSideEffects(Ctx: Context, IncludePossibleEffects: false)) |
| 1795 | Diag(Loc: ControllingExpr->getExprLoc(), |
| 1796 | DiagID: diag::warn_side_effects_unevaluated_context); |
| 1797 | |
| 1798 | for (unsigned i = 0; i < NumAssocs; ++i) { |
| 1799 | if (Exprs[i]->containsUnexpandedParameterPack()) |
| 1800 | ContainsUnexpandedParameterPack = true; |
| 1801 | |
| 1802 | if (Types[i]) { |
| 1803 | if (Types[i]->getType()->containsUnexpandedParameterPack()) |
| 1804 | ContainsUnexpandedParameterPack = true; |
| 1805 | |
| 1806 | if (Types[i]->getType()->isDependentType()) { |
| 1807 | IsResultDependent = true; |
| 1808 | } else { |
| 1809 | // We relax the restriction on use of incomplete types and non-object |
| 1810 | // types with the type-based extension of _Generic. Allowing incomplete |
| 1811 | // objects means those can be used as "tags" for a type-safe way to map |
| 1812 | // to a value. Similarly, matching on function types rather than |
| 1813 | // function pointer types can be useful. However, the restriction on VM |
| 1814 | // types makes sense to retain as there are open questions about how |
| 1815 | // the selection can be made at compile time. |
| 1816 | // |
| 1817 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a |
| 1818 | // complete object type other than a variably modified type." |
| 1819 | // C2y removed the requirement that an expression form must |
| 1820 | // use a complete type, though it's still as-if the type has undergone |
| 1821 | // lvalue conversion. We support this as an extension in C23 and |
| 1822 | // earlier because GCC does so. |
| 1823 | unsigned D = 0; |
| 1824 | if (ControllingExpr && Types[i]->getType()->isIncompleteType()) |
| 1825 | D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete |
| 1826 | : diag::ext_assoc_type_incomplete; |
| 1827 | else if (ControllingExpr && !Types[i]->getType()->isObjectType()) |
| 1828 | D = diag::err_assoc_type_nonobject; |
| 1829 | else if (Types[i]->getType()->isVariablyModifiedType()) |
| 1830 | D = diag::err_assoc_type_variably_modified; |
| 1831 | else if (ControllingExpr) { |
| 1832 | // Because the controlling expression undergoes lvalue conversion, |
| 1833 | // array conversion, and function conversion, an association which is |
| 1834 | // of array type, function type, or is qualified can never be |
| 1835 | // reached. We will warn about this so users are less surprised by |
| 1836 | // the unreachable association. However, we don't have to handle |
| 1837 | // function types; that's not an object type, so it's handled above. |
| 1838 | // |
| 1839 | // The logic is somewhat different for C++ because C++ has different |
| 1840 | // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says, |
| 1841 | // If T is a non-class type, the type of the prvalue is the cv- |
| 1842 | // unqualified version of T. Otherwise, the type of the prvalue is T. |
| 1843 | // The result of these rules is that all qualified types in an |
| 1844 | // association in C are unreachable, and in C++, only qualified non- |
| 1845 | // class types are unreachable. |
| 1846 | // |
| 1847 | // NB: this does not apply when the first operand is a type rather |
| 1848 | // than an expression, because the type form does not undergo |
| 1849 | // conversion. |
| 1850 | unsigned Reason = 0; |
| 1851 | QualType QT = Types[i]->getType(); |
| 1852 | if (QT->isArrayType()) |
| 1853 | Reason = 1; |
| 1854 | else if (QT.hasQualifiers() && |
| 1855 | (!LangOpts.CPlusPlus || !QT->isRecordType())) |
| 1856 | Reason = 2; |
| 1857 | |
| 1858 | if (Reason) |
| 1859 | Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), |
| 1860 | DiagID: diag::warn_unreachable_association) |
| 1861 | << QT << (Reason - 1); |
| 1862 | } |
| 1863 | |
| 1864 | if (D != 0) { |
| 1865 | Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), DiagID: D) |
| 1866 | << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType(); |
| 1867 | if (getDiagnostics().getDiagnosticLevel( |
| 1868 | DiagID: D, Loc: Types[i]->getTypeLoc().getBeginLoc()) >= |
| 1869 | DiagnosticsEngine::Error) |
| 1870 | TypeErrorFound = true; |
| 1871 | } |
| 1872 | |
| 1873 | // C11 6.5.1.1p2 "No two generic associations in the same generic |
| 1874 | // selection shall specify compatible types." |
| 1875 | for (unsigned j = i+1; j < NumAssocs; ++j) |
| 1876 | if (Types[j] && !Types[j]->getType()->isDependentType() && |
| 1877 | Context.typesAreCompatible(T1: Types[i]->getType(), |
| 1878 | T2: Types[j]->getType())) { |
| 1879 | Diag(Loc: Types[j]->getTypeLoc().getBeginLoc(), |
| 1880 | DiagID: diag::err_assoc_compatible_types) |
| 1881 | << Types[j]->getTypeLoc().getSourceRange() |
| 1882 | << Types[j]->getType() |
| 1883 | << Types[i]->getType(); |
| 1884 | Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), |
| 1885 | DiagID: diag::note_compat_assoc) |
| 1886 | << Types[i]->getTypeLoc().getSourceRange() |
| 1887 | << Types[i]->getType(); |
| 1888 | TypeErrorFound = true; |
| 1889 | } |
| 1890 | } |
| 1891 | } |
| 1892 | } |
| 1893 | if (TypeErrorFound) |
| 1894 | return ExprError(); |
| 1895 | |
| 1896 | // If we determined that the generic selection is result-dependent, don't |
| 1897 | // try to compute the result expression. |
| 1898 | if (IsResultDependent) { |
| 1899 | if (ControllingExpr) |
| 1900 | return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr, |
| 1901 | AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc, |
| 1902 | ContainsUnexpandedParameterPack); |
| 1903 | return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, |
| 1904 | AssocExprs: Exprs, DefaultLoc, RParenLoc, |
| 1905 | ContainsUnexpandedParameterPack); |
| 1906 | } |
| 1907 | |
| 1908 | SmallVector<unsigned, 1> CompatIndices; |
| 1909 | unsigned DefaultIndex = -1U; |
| 1910 | // Look at the canonical type of the controlling expression in case it was a |
| 1911 | // deduced type like __auto_type. However, when issuing diagnostics, use the |
| 1912 | // type the user wrote in source rather than the canonical one. |
| 1913 | for (unsigned i = 0; i < NumAssocs; ++i) { |
| 1914 | if (!Types[i]) |
| 1915 | DefaultIndex = i; |
| 1916 | else if (ControllingExpr && |
| 1917 | Context.typesAreCompatible( |
| 1918 | T1: ControllingExpr->getType().getCanonicalType(), |
| 1919 | T2: Types[i]->getType())) |
| 1920 | CompatIndices.push_back(Elt: i); |
| 1921 | else if (ControllingType && |
| 1922 | Context.typesAreCompatible( |
| 1923 | T1: ControllingType->getType().getCanonicalType(), |
| 1924 | T2: Types[i]->getType())) |
| 1925 | CompatIndices.push_back(Elt: i); |
| 1926 | } |
| 1927 | |
| 1928 | auto GetControllingRangeAndType = [](Expr *ControllingExpr, |
| 1929 | TypeSourceInfo *ControllingType) { |
| 1930 | // We strip parens here because the controlling expression is typically |
| 1931 | // parenthesized in macro definitions. |
| 1932 | if (ControllingExpr) |
| 1933 | ControllingExpr = ControllingExpr->IgnoreParens(); |
| 1934 | |
| 1935 | SourceRange SR = ControllingExpr |
| 1936 | ? ControllingExpr->getSourceRange() |
| 1937 | : ControllingType->getTypeLoc().getSourceRange(); |
| 1938 | QualType QT = ControllingExpr ? ControllingExpr->getType() |
| 1939 | : ControllingType->getType(); |
| 1940 | |
| 1941 | return std::make_pair(x&: SR, y&: QT); |
| 1942 | }; |
| 1943 | |
| 1944 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have |
| 1945 | // type compatible with at most one of the types named in its generic |
| 1946 | // association list." |
| 1947 | if (CompatIndices.size() > 1) { |
| 1948 | auto P = GetControllingRangeAndType(ControllingExpr, ControllingType); |
| 1949 | SourceRange SR = P.first; |
| 1950 | Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_multi_match) |
| 1951 | << SR << P.second << (unsigned)CompatIndices.size(); |
| 1952 | for (unsigned I : CompatIndices) { |
| 1953 | Diag(Loc: Types[I]->getTypeLoc().getBeginLoc(), |
| 1954 | DiagID: diag::note_compat_assoc) |
| 1955 | << Types[I]->getTypeLoc().getSourceRange() |
| 1956 | << Types[I]->getType(); |
| 1957 | } |
| 1958 | return ExprError(); |
| 1959 | } |
| 1960 | |
| 1961 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, |
| 1962 | // its controlling expression shall have type compatible with exactly one of |
| 1963 | // the types named in its generic association list." |
| 1964 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { |
| 1965 | auto P = GetControllingRangeAndType(ControllingExpr, ControllingType); |
| 1966 | SourceRange SR = P.first; |
| 1967 | Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_no_match) << SR << P.second; |
| 1968 | return ExprError(); |
| 1969 | } |
| 1970 | |
| 1971 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a |
| 1972 | // type name that is compatible with the type of the controlling expression, |
| 1973 | // then the result expression of the generic selection is the expression |
| 1974 | // in that generic association. Otherwise, the result expression of the |
| 1975 | // generic selection is the expression in the default generic association." |
| 1976 | unsigned ResultIndex = |
| 1977 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; |
| 1978 | |
| 1979 | if (ControllingExpr) { |
| 1980 | return GenericSelectionExpr::Create( |
| 1981 | Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc, |
| 1982 | ContainsUnexpandedParameterPack, ResultIndex); |
| 1983 | } |
| 1984 | return GenericSelectionExpr::Create( |
| 1985 | Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc, |
| 1986 | ContainsUnexpandedParameterPack, ResultIndex); |
| 1987 | } |
| 1988 | |
| 1989 | static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) { |
| 1990 | switch (Kind) { |
| 1991 | default: |
| 1992 | llvm_unreachable("unexpected TokenKind" ); |
| 1993 | case tok::kw___func__: |
| 1994 | return PredefinedIdentKind::Func; // [C99 6.4.2.2] |
| 1995 | case tok::kw___FUNCTION__: |
| 1996 | return PredefinedIdentKind::Function; |
| 1997 | case tok::kw___FUNCDNAME__: |
| 1998 | return PredefinedIdentKind::FuncDName; // [MS] |
| 1999 | case tok::kw___FUNCSIG__: |
| 2000 | return PredefinedIdentKind::FuncSig; // [MS] |
| 2001 | case tok::kw_L__FUNCTION__: |
| 2002 | return PredefinedIdentKind::LFunction; // [MS] |
| 2003 | case tok::kw_L__FUNCSIG__: |
| 2004 | return PredefinedIdentKind::LFuncSig; // [MS] |
| 2005 | case tok::kw___PRETTY_FUNCTION__: |
| 2006 | return PredefinedIdentKind::PrettyFunction; // [GNU] |
| 2007 | } |
| 2008 | } |
| 2009 | |
| 2010 | /// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used |
| 2011 | /// to determine the value of a PredefinedExpr. This can be either a |
| 2012 | /// block, lambda, captured statement, function, otherwise a nullptr. |
| 2013 | static Decl *getPredefinedExprDecl(DeclContext *DC) { |
| 2014 | while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC)) |
| 2015 | DC = DC->getParent(); |
| 2016 | return cast_or_null<Decl>(Val: DC); |
| 2017 | } |
| 2018 | |
| 2019 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the |
| 2020 | /// location of the token and the offset of the ud-suffix within it. |
| 2021 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, |
| 2022 | unsigned Offset) { |
| 2023 | return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(), |
| 2024 | LangOpts: S.getLangOpts()); |
| 2025 | } |
| 2026 | |
| 2027 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up |
| 2028 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. |
| 2029 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, |
| 2030 | IdentifierInfo *UDSuffix, |
| 2031 | SourceLocation UDSuffixLoc, |
| 2032 | ArrayRef<Expr*> Args, |
| 2033 | SourceLocation LitEndLoc) { |
| 2034 | assert(Args.size() <= 2 && "too many arguments for literal operator" ); |
| 2035 | |
| 2036 | QualType ArgTy[2]; |
| 2037 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { |
| 2038 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); |
| 2039 | if (ArgTy[ArgIdx]->isArrayType()) |
| 2040 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]); |
| 2041 | } |
| 2042 | |
| 2043 | DeclarationName OpName = |
| 2044 | S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix); |
| 2045 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); |
| 2046 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); |
| 2047 | |
| 2048 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); |
| 2049 | if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()), |
| 2050 | /*AllowRaw*/ false, /*AllowTemplate*/ false, |
| 2051 | /*AllowStringTemplatePack*/ AllowStringTemplate: false, |
| 2052 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) |
| 2053 | return ExprError(); |
| 2054 | |
| 2055 | return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc); |
| 2056 | } |
| 2057 | |
| 2058 | ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) { |
| 2059 | // StringToks needs backing storage as it doesn't hold array elements itself |
| 2060 | std::vector<Token> ExpandedToks; |
| 2061 | if (getLangOpts().MicrosoftExt) |
| 2062 | StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks); |
| 2063 | |
| 2064 | StringLiteralParser Literal(StringToks, PP, |
| 2065 | StringLiteralEvalMethod::Unevaluated); |
| 2066 | if (Literal.hadError) |
| 2067 | return ExprError(); |
| 2068 | |
| 2069 | SmallVector<SourceLocation, 4> StringTokLocs; |
| 2070 | for (const Token &Tok : StringToks) |
| 2071 | StringTokLocs.push_back(Elt: Tok.getLocation()); |
| 2072 | |
| 2073 | StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(), |
| 2074 | Kind: StringLiteralKind::Unevaluated, |
| 2075 | Pascal: false, Ty: {}, Locs: StringTokLocs); |
| 2076 | |
| 2077 | if (!Literal.getUDSuffix().empty()) { |
| 2078 | SourceLocation UDSuffixLoc = |
| 2079 | getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()], |
| 2080 | Offset: Literal.getUDSuffixOffset()); |
| 2081 | return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl)); |
| 2082 | } |
| 2083 | |
| 2084 | return Lit; |
| 2085 | } |
| 2086 | |
| 2087 | std::vector<Token> |
| 2088 | Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) { |
| 2089 | // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function |
| 2090 | // local macros that expand to string literals that may be concatenated. |
| 2091 | // These macros are expanded here (in Sema), because StringLiteralParser |
| 2092 | // (in Lex) doesn't know the enclosing function (because it hasn't been |
| 2093 | // parsed yet). |
| 2094 | assert(getLangOpts().MicrosoftExt); |
| 2095 | |
| 2096 | // Note: Although function local macros are defined only inside functions, |
| 2097 | // we ensure a valid `CurrentDecl` even outside of a function. This allows |
| 2098 | // expansion of macros into empty string literals without additional checks. |
| 2099 | Decl *CurrentDecl = getPredefinedExprDecl(DC: CurContext); |
| 2100 | if (!CurrentDecl) |
| 2101 | CurrentDecl = Context.getTranslationUnitDecl(); |
| 2102 | |
| 2103 | std::vector<Token> ExpandedToks; |
| 2104 | ExpandedToks.reserve(n: Toks.size()); |
| 2105 | for (const Token &Tok : Toks) { |
| 2106 | if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) { |
| 2107 | assert(tok::isStringLiteral(Tok.getKind())); |
| 2108 | ExpandedToks.emplace_back(args: Tok); |
| 2109 | continue; |
| 2110 | } |
| 2111 | if (isa<TranslationUnitDecl>(Val: CurrentDecl)) |
| 2112 | Diag(Loc: Tok.getLocation(), DiagID: diag::ext_predef_outside_function); |
| 2113 | // Stringify predefined expression |
| 2114 | Diag(Loc: Tok.getLocation(), DiagID: diag::ext_string_literal_from_predefined) |
| 2115 | << Tok.getKind(); |
| 2116 | SmallString<64> Str; |
| 2117 | llvm::raw_svector_ostream OS(Str); |
| 2118 | Token &Exp = ExpandedToks.emplace_back(); |
| 2119 | Exp.startToken(); |
| 2120 | if (Tok.getKind() == tok::kw_L__FUNCTION__ || |
| 2121 | Tok.getKind() == tok::kw_L__FUNCSIG__) { |
| 2122 | OS << 'L'; |
| 2123 | Exp.setKind(tok::wide_string_literal); |
| 2124 | } else { |
| 2125 | Exp.setKind(tok::string_literal); |
| 2126 | } |
| 2127 | OS << '"' |
| 2128 | << Lexer::Stringify(Str: PredefinedExpr::ComputeName( |
| 2129 | IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl)) |
| 2130 | << '"'; |
| 2131 | PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc()); |
| 2132 | } |
| 2133 | return ExpandedToks; |
| 2134 | } |
| 2135 | |
| 2136 | ExprResult |
| 2137 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { |
| 2138 | assert(!StringToks.empty() && "Must have at least one string!" ); |
| 2139 | |
| 2140 | // StringToks needs backing storage as it doesn't hold array elements itself |
| 2141 | std::vector<Token> ExpandedToks; |
| 2142 | if (getLangOpts().MicrosoftExt) |
| 2143 | StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks); |
| 2144 | |
| 2145 | StringLiteralParser Literal(StringToks, PP); |
| 2146 | if (Literal.hadError) |
| 2147 | return ExprError(); |
| 2148 | |
| 2149 | SmallVector<SourceLocation, 4> StringTokLocs; |
| 2150 | for (const Token &Tok : StringToks) |
| 2151 | StringTokLocs.push_back(Elt: Tok.getLocation()); |
| 2152 | |
| 2153 | QualType CharTy = Context.CharTy; |
| 2154 | StringLiteralKind Kind = StringLiteralKind::Ordinary; |
| 2155 | if (Literal.isWide()) { |
| 2156 | CharTy = Context.getWideCharType(); |
| 2157 | Kind = StringLiteralKind::Wide; |
| 2158 | } else if (Literal.isUTF8()) { |
| 2159 | if (getLangOpts().Char8) |
| 2160 | CharTy = Context.Char8Ty; |
| 2161 | else if (getLangOpts().C23) |
| 2162 | CharTy = Context.UnsignedCharTy; |
| 2163 | Kind = StringLiteralKind::UTF8; |
| 2164 | } else if (Literal.isUTF16()) { |
| 2165 | CharTy = Context.Char16Ty; |
| 2166 | Kind = StringLiteralKind::UTF16; |
| 2167 | } else if (Literal.isUTF32()) { |
| 2168 | CharTy = Context.Char32Ty; |
| 2169 | Kind = StringLiteralKind::UTF32; |
| 2170 | } else if (Literal.isPascal()) { |
| 2171 | CharTy = Context.UnsignedCharTy; |
| 2172 | } |
| 2173 | |
| 2174 | // Warn on u8 string literals before C++20 and C23, whose type |
| 2175 | // was an array of char before but becomes an array of char8_t. |
| 2176 | // In C++20, it cannot be used where a pointer to char is expected. |
| 2177 | // In C23, it might have an unexpected value if char was signed. |
| 2178 | if (Kind == StringLiteralKind::UTF8 && |
| 2179 | (getLangOpts().CPlusPlus |
| 2180 | ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8 |
| 2181 | : !getLangOpts().C23)) { |
| 2182 | Diag(Loc: StringTokLocs.front(), DiagID: getLangOpts().CPlusPlus |
| 2183 | ? diag::warn_cxx20_compat_utf8_string |
| 2184 | : diag::warn_c23_compat_utf8_string); |
| 2185 | |
| 2186 | // Create removals for all 'u8' prefixes in the string literal(s). This |
| 2187 | // ensures C++20/C23 compatibility (but may change the program behavior when |
| 2188 | // built by non-Clang compilers for which the execution character set is |
| 2189 | // not always UTF-8). |
| 2190 | auto RemovalDiag = PDiag(DiagID: diag::note_cxx20_c23_compat_utf8_string_remove_u8); |
| 2191 | SourceLocation RemovalDiagLoc; |
| 2192 | for (const Token &Tok : StringToks) { |
| 2193 | if (Tok.getKind() == tok::utf8_string_literal) { |
| 2194 | if (RemovalDiagLoc.isInvalid()) |
| 2195 | RemovalDiagLoc = Tok.getLocation(); |
| 2196 | RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange( |
| 2197 | B: Tok.getLocation(), |
| 2198 | E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2, |
| 2199 | SM: getSourceManager(), LangOpts: getLangOpts()))); |
| 2200 | } |
| 2201 | } |
| 2202 | Diag(Loc: RemovalDiagLoc, PD: RemovalDiag); |
| 2203 | } |
| 2204 | |
| 2205 | QualType StrTy = |
| 2206 | Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars()); |
| 2207 | |
| 2208 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! |
| 2209 | StringLiteral *Lit = StringLiteral::Create( |
| 2210 | Ctx: Context, Str: Literal.GetString(), Kind, Pascal: Literal.Pascal, Ty: StrTy, Locs: StringTokLocs); |
| 2211 | if (Literal.getUDSuffix().empty()) |
| 2212 | return Lit; |
| 2213 | |
| 2214 | // We're building a user-defined literal. |
| 2215 | IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix()); |
| 2216 | SourceLocation UDSuffixLoc = |
| 2217 | getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()], |
| 2218 | Offset: Literal.getUDSuffixOffset()); |
| 2219 | |
| 2220 | // Make sure we're allowed user-defined literals here. |
| 2221 | if (!UDLScope) |
| 2222 | return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl)); |
| 2223 | |
| 2224 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form |
| 2225 | // operator "" X (str, len) |
| 2226 | QualType SizeType = Context.getSizeType(); |
| 2227 | |
| 2228 | DeclarationName OpName = |
| 2229 | Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix); |
| 2230 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); |
| 2231 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); |
| 2232 | |
| 2233 | QualType ArgTy[] = { |
| 2234 | Context.getArrayDecayedType(T: StrTy), SizeType |
| 2235 | }; |
| 2236 | |
| 2237 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); |
| 2238 | switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy, |
| 2239 | /*AllowRaw*/ false, /*AllowTemplate*/ true, |
| 2240 | /*AllowStringTemplatePack*/ AllowStringTemplate: true, |
| 2241 | /*DiagnoseMissing*/ true, StringLit: Lit)) { |
| 2242 | |
| 2243 | case LOLR_Cooked: { |
| 2244 | llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars()); |
| 2245 | IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType, |
| 2246 | l: StringTokLocs[0]); |
| 2247 | Expr *Args[] = { Lit, LenArg }; |
| 2248 | |
| 2249 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc: StringTokLocs.back()); |
| 2250 | } |
| 2251 | |
| 2252 | case LOLR_Template: { |
| 2253 | TemplateArgumentListInfo ExplicitArgs; |
| 2254 | TemplateArgument Arg(Lit, /*IsCanonical=*/false); |
| 2255 | TemplateArgumentLocInfo ArgInfo(Lit); |
| 2256 | ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo)); |
| 2257 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(), |
| 2258 | ExplicitTemplateArgs: &ExplicitArgs); |
| 2259 | } |
| 2260 | |
| 2261 | case LOLR_StringTemplatePack: { |
| 2262 | TemplateArgumentListInfo ExplicitArgs; |
| 2263 | |
| 2264 | unsigned CharBits = Context.getIntWidth(T: CharTy); |
| 2265 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); |
| 2266 | llvm::APSInt Value(CharBits, CharIsUnsigned); |
| 2267 | |
| 2268 | TemplateArgument TypeArg(CharTy); |
| 2269 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy)); |
| 2270 | ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo)); |
| 2271 | |
| 2272 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { |
| 2273 | Value = Lit->getCodeUnit(i: I); |
| 2274 | TemplateArgument Arg(Context, Value, CharTy); |
| 2275 | TemplateArgumentLocInfo ArgInfo; |
| 2276 | ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo)); |
| 2277 | } |
| 2278 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(), |
| 2279 | ExplicitTemplateArgs: &ExplicitArgs); |
| 2280 | } |
| 2281 | case LOLR_Raw: |
| 2282 | case LOLR_ErrorNoDiagnostic: |
| 2283 | llvm_unreachable("unexpected literal operator lookup result" ); |
| 2284 | case LOLR_Error: |
| 2285 | return ExprError(); |
| 2286 | } |
| 2287 | llvm_unreachable("unexpected literal operator lookup result" ); |
| 2288 | } |
| 2289 | |
| 2290 | DeclRefExpr * |
| 2291 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
| 2292 | SourceLocation Loc, |
| 2293 | const CXXScopeSpec *SS) { |
| 2294 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); |
| 2295 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); |
| 2296 | } |
| 2297 | |
| 2298 | DeclRefExpr * |
| 2299 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
| 2300 | const DeclarationNameInfo &NameInfo, |
| 2301 | const CXXScopeSpec *SS, NamedDecl *FoundD, |
| 2302 | SourceLocation TemplateKWLoc, |
| 2303 | const TemplateArgumentListInfo *TemplateArgs) { |
| 2304 | NestedNameSpecifierLoc NNS = |
| 2305 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); |
| 2306 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, |
| 2307 | TemplateArgs); |
| 2308 | } |
| 2309 | |
| 2310 | // CUDA/HIP: Check whether a captured reference variable is referencing a |
| 2311 | // host variable in a device or host device lambda. |
| 2312 | static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, |
| 2313 | VarDecl *VD) { |
| 2314 | if (!S.getLangOpts().CUDA || !VD->hasInit()) |
| 2315 | return false; |
| 2316 | assert(VD->getType()->isReferenceType()); |
| 2317 | |
| 2318 | // Check whether the reference variable is referencing a host variable. |
| 2319 | auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit()); |
| 2320 | if (!DRE) |
| 2321 | return false; |
| 2322 | auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
| 2323 | if (!Referee || !Referee->hasGlobalStorage() || |
| 2324 | Referee->hasAttr<CUDADeviceAttr>()) |
| 2325 | return false; |
| 2326 | |
| 2327 | // Check whether the current function is a device or host device lambda. |
| 2328 | // Check whether the reference variable is a capture by getDeclContext() |
| 2329 | // since refersToEnclosingVariableOrCapture() is not ready at this point. |
| 2330 | auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext); |
| 2331 | if (MD && MD->getParent()->isLambda() && |
| 2332 | MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && |
| 2333 | VD->getDeclContext() != MD) |
| 2334 | return true; |
| 2335 | |
| 2336 | return false; |
| 2337 | } |
| 2338 | |
| 2339 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { |
| 2340 | // A declaration named in an unevaluated operand never constitutes an odr-use. |
| 2341 | if (isUnevaluatedContext()) |
| 2342 | return NOUR_Unevaluated; |
| 2343 | |
| 2344 | // C++2a [basic.def.odr]p4: |
| 2345 | // A variable x whose name appears as a potentially-evaluated expression e |
| 2346 | // is odr-used by e unless [...] x is a reference that is usable in |
| 2347 | // constant expressions. |
| 2348 | // CUDA/HIP: |
| 2349 | // If a reference variable referencing a host variable is captured in a |
| 2350 | // device or host device lambda, the value of the referee must be copied |
| 2351 | // to the capture and the reference variable must be treated as odr-use |
| 2352 | // since the value of the referee is not known at compile time and must |
| 2353 | // be loaded from the captured. |
| 2354 | if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
| 2355 | if (VD->getType()->isReferenceType() && |
| 2356 | !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) && |
| 2357 | !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) && |
| 2358 | VD->isUsableInConstantExpressions(C: Context)) |
| 2359 | return NOUR_Constant; |
| 2360 | } |
| 2361 | |
| 2362 | // All remaining non-variable cases constitute an odr-use. For variables, we |
| 2363 | // need to wait and see how the expression is used. |
| 2364 | return NOUR_None; |
| 2365 | } |
| 2366 | |
| 2367 | DeclRefExpr * |
| 2368 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
| 2369 | const DeclarationNameInfo &NameInfo, |
| 2370 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, |
| 2371 | SourceLocation TemplateKWLoc, |
| 2372 | const TemplateArgumentListInfo *TemplateArgs) { |
| 2373 | bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) && |
| 2374 | NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc()); |
| 2375 | |
| 2376 | DeclRefExpr *E = DeclRefExpr::Create( |
| 2377 | Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty, |
| 2378 | VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D)); |
| 2379 | MarkDeclRefReferenced(E); |
| 2380 | |
| 2381 | // C++ [except.spec]p17: |
| 2382 | // An exception-specification is considered to be needed when: |
| 2383 | // - in an expression, the function is the unique lookup result or |
| 2384 | // the selected member of a set of overloaded functions. |
| 2385 | // |
| 2386 | // We delay doing this until after we've built the function reference and |
| 2387 | // marked it as used so that: |
| 2388 | // a) if the function is defaulted, we get errors from defining it before / |
| 2389 | // instead of errors from computing its exception specification, and |
| 2390 | // b) if the function is a defaulted comparison, we can use the body we |
| 2391 | // build when defining it as input to the exception specification |
| 2392 | // computation rather than computing a new body. |
| 2393 | if (const auto *FPT = Ty->getAs<FunctionProtoType>()) { |
| 2394 | if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) { |
| 2395 | if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT)) |
| 2396 | E->setType(Context.getQualifiedType(T: NewFPT, Qs: Ty.getQualifiers())); |
| 2397 | } |
| 2398 | } |
| 2399 | |
| 2400 | if (getLangOpts().ObjCWeak && isa<VarDecl>(Val: D) && |
| 2401 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && |
| 2402 | !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: E->getBeginLoc())) |
| 2403 | getCurFunction()->recordUseOfWeak(E); |
| 2404 | |
| 2405 | const auto *FD = dyn_cast<FieldDecl>(Val: D); |
| 2406 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D)) |
| 2407 | FD = IFD->getAnonField(); |
| 2408 | if (FD) { |
| 2409 | UnusedPrivateFields.remove(X: FD); |
| 2410 | // Just in case we're building an illegal pointer-to-member. |
| 2411 | if (FD->isBitField()) |
| 2412 | E->setObjectKind(OK_BitField); |
| 2413 | } |
| 2414 | |
| 2415 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier |
| 2416 | // designates a bit-field. |
| 2417 | if (const auto *BD = dyn_cast<BindingDecl>(Val: D)) |
| 2418 | if (const auto *BE = BD->getBinding()) |
| 2419 | E->setObjectKind(BE->getObjectKind()); |
| 2420 | |
| 2421 | return E; |
| 2422 | } |
| 2423 | |
| 2424 | void |
| 2425 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, |
| 2426 | TemplateArgumentListInfo &Buffer, |
| 2427 | DeclarationNameInfo &NameInfo, |
| 2428 | const TemplateArgumentListInfo *&TemplateArgs) { |
| 2429 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { |
| 2430 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); |
| 2431 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); |
| 2432 | |
| 2433 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), |
| 2434 | Id.TemplateId->NumArgs); |
| 2435 | translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer); |
| 2436 | |
| 2437 | TemplateName TName = Id.TemplateId->Template.get(); |
| 2438 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; |
| 2439 | NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc); |
| 2440 | TemplateArgs = &Buffer; |
| 2441 | } else { |
| 2442 | NameInfo = GetNameFromUnqualifiedId(Name: Id); |
| 2443 | TemplateArgs = nullptr; |
| 2444 | } |
| 2445 | } |
| 2446 | |
| 2447 | bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) { |
| 2448 | // During a default argument instantiation the CurContext points |
| 2449 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a |
| 2450 | // function parameter list, hence add an explicit check. |
| 2451 | bool isDefaultArgument = |
| 2452 | !CodeSynthesisContexts.empty() && |
| 2453 | CodeSynthesisContexts.back().Kind == |
| 2454 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; |
| 2455 | const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext); |
| 2456 | bool isInstance = CurMethod && CurMethod->isInstance() && |
| 2457 | R.getNamingClass() == CurMethod->getParent() && |
| 2458 | !isDefaultArgument; |
| 2459 | |
| 2460 | // There are two ways we can find a class-scope declaration during template |
| 2461 | // instantiation that we did not find in the template definition: if it is a |
| 2462 | // member of a dependent base class, or if it is declared after the point of |
| 2463 | // use in the same class. Distinguish these by comparing the class in which |
| 2464 | // the member was found to the naming class of the lookup. |
| 2465 | unsigned DiagID = diag::err_found_in_dependent_base; |
| 2466 | unsigned NoteID = diag::note_member_declared_at; |
| 2467 | if (R.getRepresentativeDecl()->getDeclContext()->Equals(DC: R.getNamingClass())) { |
| 2468 | DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class |
| 2469 | : diag::err_found_later_in_class; |
| 2470 | } else if (getLangOpts().MSVCCompat) { |
| 2471 | DiagID = diag::ext_found_in_dependent_base; |
| 2472 | NoteID = diag::note_dependent_member_use; |
| 2473 | } |
| 2474 | |
| 2475 | if (isInstance) { |
| 2476 | // Give a code modification hint to insert 'this->'. |
| 2477 | Diag(Loc: R.getNameLoc(), DiagID) |
| 2478 | << R.getLookupName() |
| 2479 | << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->" ); |
| 2480 | CheckCXXThisCapture(Loc: R.getNameLoc()); |
| 2481 | } else { |
| 2482 | // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming |
| 2483 | // they're not shadowed). |
| 2484 | Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName(); |
| 2485 | } |
| 2486 | |
| 2487 | for (const NamedDecl *D : R) |
| 2488 | Diag(Loc: D->getLocation(), DiagID: NoteID); |
| 2489 | |
| 2490 | // Return true if we are inside a default argument instantiation |
| 2491 | // and the found name refers to an instance member function, otherwise |
| 2492 | // the caller will try to create an implicit member call and this is wrong |
| 2493 | // for default arguments. |
| 2494 | // |
| 2495 | // FIXME: Is this special case necessary? We could allow the caller to |
| 2496 | // diagnose this. |
| 2497 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { |
| 2498 | Diag(Loc: R.getNameLoc(), DiagID: diag::err_member_call_without_object) << 0; |
| 2499 | return true; |
| 2500 | } |
| 2501 | |
| 2502 | // Tell the callee to try to recover. |
| 2503 | return false; |
| 2504 | } |
| 2505 | |
| 2506 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, |
| 2507 | CorrectionCandidateCallback &CCC, |
| 2508 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
| 2509 | ArrayRef<Expr *> Args, DeclContext *LookupCtx) { |
| 2510 | DeclarationName Name = R.getLookupName(); |
| 2511 | SourceRange NameRange = R.getLookupNameInfo().getSourceRange(); |
| 2512 | |
| 2513 | unsigned diagnostic = diag::err_undeclared_var_use; |
| 2514 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; |
| 2515 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || |
| 2516 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || |
| 2517 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { |
| 2518 | diagnostic = diag::err_undeclared_use; |
| 2519 | diagnostic_suggest = diag::err_undeclared_use_suggest; |
| 2520 | } |
| 2521 | |
| 2522 | // If the original lookup was an unqualified lookup, fake an |
| 2523 | // unqualified lookup. This is useful when (for example) the |
| 2524 | // original lookup would not have found something because it was a |
| 2525 | // dependent name. |
| 2526 | DeclContext *DC = |
| 2527 | LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr); |
| 2528 | while (DC) { |
| 2529 | if (isa<CXXRecordDecl>(Val: DC)) { |
| 2530 | if (ExplicitTemplateArgs) { |
| 2531 | if (LookupTemplateName( |
| 2532 | R, S, SS, ObjectType: Context.getRecordType(Decl: cast<CXXRecordDecl>(Val: DC)), |
| 2533 | /*EnteringContext*/ false, RequiredTemplate: TemplateNameIsRequired, |
| 2534 | /*RequiredTemplateKind*/ ATK: nullptr, /*AllowTypoCorrection*/ true)) |
| 2535 | return true; |
| 2536 | } else { |
| 2537 | LookupQualifiedName(R, LookupCtx: DC); |
| 2538 | } |
| 2539 | |
| 2540 | if (!R.empty()) { |
| 2541 | // Don't give errors about ambiguities in this lookup. |
| 2542 | R.suppressDiagnostics(); |
| 2543 | |
| 2544 | // If there's a best viable function among the results, only mention |
| 2545 | // that one in the notes. |
| 2546 | OverloadCandidateSet Candidates(R.getNameLoc(), |
| 2547 | OverloadCandidateSet::CSK_Normal); |
| 2548 | AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates); |
| 2549 | OverloadCandidateSet::iterator Best; |
| 2550 | if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) == |
| 2551 | OR_Success) { |
| 2552 | R.clear(); |
| 2553 | R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess()); |
| 2554 | R.resolveKind(); |
| 2555 | } |
| 2556 | |
| 2557 | return DiagnoseDependentMemberLookup(R); |
| 2558 | } |
| 2559 | |
| 2560 | R.clear(); |
| 2561 | } |
| 2562 | |
| 2563 | DC = DC->getLookupParent(); |
| 2564 | } |
| 2565 | |
| 2566 | // We didn't find anything, so try to correct for a typo. |
| 2567 | TypoCorrection Corrected; |
| 2568 | if (S && (Corrected = |
| 2569 | CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, |
| 2570 | CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx))) { |
| 2571 | std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts())); |
| 2572 | bool DroppedSpecifier = |
| 2573 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; |
| 2574 | R.setLookupName(Corrected.getCorrection()); |
| 2575 | |
| 2576 | bool AcceptableWithRecovery = false; |
| 2577 | bool AcceptableWithoutRecovery = false; |
| 2578 | NamedDecl *ND = Corrected.getFoundDecl(); |
| 2579 | if (ND) { |
| 2580 | if (Corrected.isOverloaded()) { |
| 2581 | OverloadCandidateSet OCS(R.getNameLoc(), |
| 2582 | OverloadCandidateSet::CSK_Normal); |
| 2583 | OverloadCandidateSet::iterator Best; |
| 2584 | for (NamedDecl *CD : Corrected) { |
| 2585 | if (FunctionTemplateDecl *FTD = |
| 2586 | dyn_cast<FunctionTemplateDecl>(Val: CD)) |
| 2587 | AddTemplateOverloadCandidate( |
| 2588 | FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: AS_none), ExplicitTemplateArgs, |
| 2589 | Args, CandidateSet&: OCS); |
| 2590 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD)) |
| 2591 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) |
| 2592 | AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), |
| 2593 | Args, CandidateSet&: OCS); |
| 2594 | } |
| 2595 | switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) { |
| 2596 | case OR_Success: |
| 2597 | ND = Best->FoundDecl; |
| 2598 | Corrected.setCorrectionDecl(ND); |
| 2599 | break; |
| 2600 | default: |
| 2601 | // FIXME: Arbitrarily pick the first declaration for the note. |
| 2602 | Corrected.setCorrectionDecl(ND); |
| 2603 | break; |
| 2604 | } |
| 2605 | } |
| 2606 | R.addDecl(D: ND); |
| 2607 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { |
| 2608 | CXXRecordDecl *Record = nullptr; |
| 2609 | if (Corrected.getCorrectionSpecifier()) { |
| 2610 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); |
| 2611 | Record = Ty->getAsCXXRecordDecl(); |
| 2612 | } |
| 2613 | if (!Record) |
| 2614 | Record = cast<CXXRecordDecl>( |
| 2615 | Val: ND->getDeclContext()->getRedeclContext()); |
| 2616 | R.setNamingClass(Record); |
| 2617 | } |
| 2618 | |
| 2619 | auto *UnderlyingND = ND->getUnderlyingDecl(); |
| 2620 | AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) || |
| 2621 | isa<FunctionTemplateDecl>(Val: UnderlyingND); |
| 2622 | // FIXME: If we ended up with a typo for a type name or |
| 2623 | // Objective-C class name, we're in trouble because the parser |
| 2624 | // is in the wrong place to recover. Suggest the typo |
| 2625 | // correction, but don't make it a fix-it since we're not going |
| 2626 | // to recover well anyway. |
| 2627 | AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) || |
| 2628 | getAsTypeTemplateDecl(D: UnderlyingND) || |
| 2629 | isa<ObjCInterfaceDecl>(Val: UnderlyingND); |
| 2630 | } else { |
| 2631 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it |
| 2632 | // because we aren't able to recover. |
| 2633 | AcceptableWithoutRecovery = true; |
| 2634 | } |
| 2635 | |
| 2636 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { |
| 2637 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() |
| 2638 | ? diag::note_implicit_param_decl |
| 2639 | : diag::note_previous_decl; |
| 2640 | if (SS.isEmpty()) |
| 2641 | diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name << NameRange, |
| 2642 | PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery); |
| 2643 | else |
| 2644 | diagnoseTypo(Correction: Corrected, |
| 2645 | TypoDiag: PDiag(DiagID: diag::err_no_member_suggest) |
| 2646 | << Name << computeDeclContext(SS, EnteringContext: false) |
| 2647 | << DroppedSpecifier << NameRange, |
| 2648 | PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery); |
| 2649 | |
| 2650 | // Tell the callee whether to try to recover. |
| 2651 | return !AcceptableWithRecovery; |
| 2652 | } |
| 2653 | } |
| 2654 | R.clear(); |
| 2655 | |
| 2656 | // Emit a special diagnostic for failed member lookups. |
| 2657 | // FIXME: computing the declaration context might fail here (?) |
| 2658 | if (!SS.isEmpty()) { |
| 2659 | Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member) |
| 2660 | << Name << computeDeclContext(SS, EnteringContext: false) << NameRange; |
| 2661 | return true; |
| 2662 | } |
| 2663 | |
| 2664 | // Give up, we can't recover. |
| 2665 | Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name << NameRange; |
| 2666 | return true; |
| 2667 | } |
| 2668 | |
| 2669 | /// In Microsoft mode, if we are inside a template class whose parent class has |
| 2670 | /// dependent base classes, and we can't resolve an unqualified identifier, then |
| 2671 | /// assume the identifier is a member of a dependent base class. We can only |
| 2672 | /// recover successfully in static methods, instance methods, and other contexts |
| 2673 | /// where 'this' is available. This doesn't precisely match MSVC's |
| 2674 | /// instantiation model, but it's close enough. |
| 2675 | static Expr * |
| 2676 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, |
| 2677 | DeclarationNameInfo &NameInfo, |
| 2678 | SourceLocation TemplateKWLoc, |
| 2679 | const TemplateArgumentListInfo *TemplateArgs) { |
| 2680 | // Only try to recover from lookup into dependent bases in static methods or |
| 2681 | // contexts where 'this' is available. |
| 2682 | QualType ThisType = S.getCurrentThisType(); |
| 2683 | const CXXRecordDecl *RD = nullptr; |
| 2684 | if (!ThisType.isNull()) |
| 2685 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); |
| 2686 | else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext)) |
| 2687 | RD = MD->getParent(); |
| 2688 | if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases()) |
| 2689 | return nullptr; |
| 2690 | |
| 2691 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' |
| 2692 | // is available, suggest inserting 'this->' as a fixit. |
| 2693 | SourceLocation Loc = NameInfo.getLoc(); |
| 2694 | auto DB = S.Diag(Loc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base); |
| 2695 | DB << NameInfo.getName() << RD; |
| 2696 | |
| 2697 | if (!ThisType.isNull()) { |
| 2698 | DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->" ); |
| 2699 | return CXXDependentScopeMemberExpr::Create( |
| 2700 | Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true, |
| 2701 | /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc, |
| 2702 | /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs); |
| 2703 | } |
| 2704 | |
| 2705 | // Synthesize a fake NNS that points to the derived class. This will |
| 2706 | // perform name lookup during template instantiation. |
| 2707 | CXXScopeSpec SS; |
| 2708 | auto *NNS = |
| 2709 | NestedNameSpecifier::Create(Context, Prefix: nullptr, T: RD->getTypeForDecl()); |
| 2710 | SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc)); |
| 2711 | return DependentScopeDeclRefExpr::Create( |
| 2712 | Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, |
| 2713 | TemplateArgs); |
| 2714 | } |
| 2715 | |
| 2716 | ExprResult |
| 2717 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, |
| 2718 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, |
| 2719 | bool HasTrailingLParen, bool IsAddressOfOperand, |
| 2720 | CorrectionCandidateCallback *CCC, |
| 2721 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { |
| 2722 | assert(!(IsAddressOfOperand && HasTrailingLParen) && |
| 2723 | "cannot be direct & operand and have a trailing lparen" ); |
| 2724 | if (SS.isInvalid()) |
| 2725 | return ExprError(); |
| 2726 | |
| 2727 | TemplateArgumentListInfo TemplateArgsBuffer; |
| 2728 | |
| 2729 | // Decompose the UnqualifiedId into the following data. |
| 2730 | DeclarationNameInfo NameInfo; |
| 2731 | const TemplateArgumentListInfo *TemplateArgs; |
| 2732 | DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs); |
| 2733 | |
| 2734 | DeclarationName Name = NameInfo.getName(); |
| 2735 | IdentifierInfo *II = Name.getAsIdentifierInfo(); |
| 2736 | SourceLocation NameLoc = NameInfo.getLoc(); |
| 2737 | |
| 2738 | if (II && II->isEditorPlaceholder()) { |
| 2739 | // FIXME: When typed placeholders are supported we can create a typed |
| 2740 | // placeholder expression node. |
| 2741 | return ExprError(); |
| 2742 | } |
| 2743 | |
| 2744 | // This specially handles arguments of attributes appertains to a type of C |
| 2745 | // struct field such that the name lookup within a struct finds the member |
| 2746 | // name, which is not the case for other contexts in C. |
| 2747 | if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) { |
| 2748 | // See if this is reference to a field of struct. |
| 2749 | LookupResult R(*this, NameInfo, LookupMemberName); |
| 2750 | // LookupName handles a name lookup from within anonymous struct. |
| 2751 | if (LookupName(R, S)) { |
| 2752 | if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) { |
| 2753 | QualType type = VD->getType().getNonReferenceType(); |
| 2754 | // This will eventually be translated into MemberExpr upon |
| 2755 | // the use of instantiated struct fields. |
| 2756 | return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc); |
| 2757 | } |
| 2758 | } |
| 2759 | } |
| 2760 | |
| 2761 | // Perform the required lookup. |
| 2762 | LookupResult R(*this, NameInfo, |
| 2763 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) |
| 2764 | ? LookupObjCImplicitSelfParam |
| 2765 | : LookupOrdinaryName); |
| 2766 | if (TemplateKWLoc.isValid() || TemplateArgs) { |
| 2767 | // Lookup the template name again to correctly establish the context in |
| 2768 | // which it was found. This is really unfortunate as we already did the |
| 2769 | // lookup to determine that it was a template name in the first place. If |
| 2770 | // this becomes a performance hit, we can work harder to preserve those |
| 2771 | // results until we get here but it's likely not worth it. |
| 2772 | AssumedTemplateKind AssumedTemplate; |
| 2773 | if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(), |
| 2774 | /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc, |
| 2775 | ATK: &AssumedTemplate)) |
| 2776 | return ExprError(); |
| 2777 | |
| 2778 | if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid()) |
| 2779 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, |
| 2780 | isAddressOfOperand: IsAddressOfOperand, TemplateArgs); |
| 2781 | } else { |
| 2782 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); |
| 2783 | LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(), |
| 2784 | /*AllowBuiltinCreation=*/!IvarLookupFollowUp); |
| 2785 | |
| 2786 | // If the result might be in a dependent base class, this is a dependent |
| 2787 | // id-expression. |
| 2788 | if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid()) |
| 2789 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, |
| 2790 | isAddressOfOperand: IsAddressOfOperand, TemplateArgs); |
| 2791 | |
| 2792 | // If this reference is in an Objective-C method, then we need to do |
| 2793 | // some special Objective-C lookup, too. |
| 2794 | if (IvarLookupFollowUp) { |
| 2795 | ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true)); |
| 2796 | if (E.isInvalid()) |
| 2797 | return ExprError(); |
| 2798 | |
| 2799 | if (Expr *Ex = E.getAs<Expr>()) |
| 2800 | return Ex; |
| 2801 | } |
| 2802 | } |
| 2803 | |
| 2804 | if (R.isAmbiguous()) |
| 2805 | return ExprError(); |
| 2806 | |
| 2807 | // This could be an implicitly declared function reference if the language |
| 2808 | // mode allows it as a feature. |
| 2809 | if (R.empty() && HasTrailingLParen && II && |
| 2810 | getLangOpts().implicitFunctionsAllowed()) { |
| 2811 | NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S); |
| 2812 | if (D) R.addDecl(D); |
| 2813 | } |
| 2814 | |
| 2815 | // Determine whether this name might be a candidate for |
| 2816 | // argument-dependent lookup. |
| 2817 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); |
| 2818 | |
| 2819 | if (R.empty() && !ADL) { |
| 2820 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { |
| 2821 | if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo, |
| 2822 | TemplateKWLoc, TemplateArgs)) |
| 2823 | return E; |
| 2824 | } |
| 2825 | |
| 2826 | // Don't diagnose an empty lookup for inline assembly. |
| 2827 | if (IsInlineAsmIdentifier) |
| 2828 | return ExprError(); |
| 2829 | |
| 2830 | // If this name wasn't predeclared and if this is not a function |
| 2831 | // call, diagnose the problem. |
| 2832 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() |
| 2833 | : nullptr); |
| 2834 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; |
| 2835 | assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && |
| 2836 | "Typo correction callback misconfigured" ); |
| 2837 | if (CCC) { |
| 2838 | // Make sure the callback knows what the typo being diagnosed is. |
| 2839 | CCC->setTypoName(II); |
| 2840 | if (SS.isValid()) |
| 2841 | CCC->setTypoNNS(SS.getScopeRep()); |
| 2842 | } |
| 2843 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for |
| 2844 | // a template name, but we happen to have always already looked up the name |
| 2845 | // before we get here if it must be a template name. |
| 2846 | if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr, |
| 2847 | Args: {}, LookupCtx: nullptr)) |
| 2848 | return ExprError(); |
| 2849 | |
| 2850 | assert(!R.empty() && |
| 2851 | "DiagnoseEmptyLookup returned false but added no results" ); |
| 2852 | |
| 2853 | // If we found an Objective-C instance variable, let |
| 2854 | // LookupInObjCMethod build the appropriate expression to |
| 2855 | // reference the ivar. |
| 2856 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { |
| 2857 | R.clear(); |
| 2858 | ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier())); |
| 2859 | // In a hopelessly buggy code, Objective-C instance variable |
| 2860 | // lookup fails and no expression will be built to reference it. |
| 2861 | if (!E.isInvalid() && !E.get()) |
| 2862 | return ExprError(); |
| 2863 | return E; |
| 2864 | } |
| 2865 | } |
| 2866 | |
| 2867 | // This is guaranteed from this point on. |
| 2868 | assert(!R.empty() || ADL); |
| 2869 | |
| 2870 | // Check whether this might be a C++ implicit instance member access. |
| 2871 | // C++ [class.mfct.non-static]p3: |
| 2872 | // When an id-expression that is not part of a class member access |
| 2873 | // syntax and not used to form a pointer to member is used in the |
| 2874 | // body of a non-static member function of class X, if name lookup |
| 2875 | // resolves the name in the id-expression to a non-static non-type |
| 2876 | // member of some class C, the id-expression is transformed into a |
| 2877 | // class member access expression using (*this) as the |
| 2878 | // postfix-expression to the left of the . operator. |
| 2879 | // |
| 2880 | // But we don't actually need to do this for '&' operands if R |
| 2881 | // resolved to a function or overloaded function set, because the |
| 2882 | // expression is ill-formed if it actually works out to be a |
| 2883 | // non-static member function: |
| 2884 | // |
| 2885 | // C++ [expr.ref]p4: |
| 2886 | // Otherwise, if E1.E2 refers to a non-static member function. . . |
| 2887 | // [t]he expression can be used only as the left-hand operand of a |
| 2888 | // member function call. |
| 2889 | // |
| 2890 | // There are other safeguards against such uses, but it's important |
| 2891 | // to get this right here so that we don't end up making a |
| 2892 | // spuriously dependent expression if we're inside a dependent |
| 2893 | // instance method. |
| 2894 | if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand)) |
| 2895 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, |
| 2896 | S); |
| 2897 | |
| 2898 | if (TemplateArgs || TemplateKWLoc.isValid()) { |
| 2899 | |
| 2900 | // In C++1y, if this is a variable template id, then check it |
| 2901 | // in BuildTemplateIdExpr(). |
| 2902 | // The single lookup result must be a variable template declaration. |
| 2903 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && |
| 2904 | Id.TemplateId->Kind == TNK_Var_template) { |
| 2905 | assert(R.getAsSingle<VarTemplateDecl>() && |
| 2906 | "There should only be one declaration found." ); |
| 2907 | } |
| 2908 | |
| 2909 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs); |
| 2910 | } |
| 2911 | |
| 2912 | return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL); |
| 2913 | } |
| 2914 | |
| 2915 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( |
| 2916 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, |
| 2917 | bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) { |
| 2918 | LookupResult R(*this, NameInfo, LookupOrdinaryName); |
| 2919 | LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType()); |
| 2920 | |
| 2921 | if (R.isAmbiguous()) |
| 2922 | return ExprError(); |
| 2923 | |
| 2924 | if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid()) |
| 2925 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), |
| 2926 | NameInfo, /*TemplateArgs=*/nullptr); |
| 2927 | |
| 2928 | if (R.empty()) { |
| 2929 | // Don't diagnose problems with invalid record decl, the secondary no_member |
| 2930 | // diagnostic during template instantiation is likely bogus, e.g. if a class |
| 2931 | // is invalid because it's derived from an invalid base class, then missing |
| 2932 | // members were likely supposed to be inherited. |
| 2933 | DeclContext *DC = computeDeclContext(SS); |
| 2934 | if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC)) |
| 2935 | if (CD->isInvalidDecl()) |
| 2936 | return ExprError(); |
| 2937 | Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member) |
| 2938 | << NameInfo.getName() << DC << SS.getRange(); |
| 2939 | return ExprError(); |
| 2940 | } |
| 2941 | |
| 2942 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { |
| 2943 | QualType Ty = Context.getTypeDeclType(Decl: TD); |
| 2944 | QualType ET = getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS, T: Ty); |
| 2945 | |
| 2946 | // Diagnose a missing typename if this resolved unambiguously to a type in |
| 2947 | // a dependent context. If we can recover with a type, downgrade this to |
| 2948 | // a warning in Microsoft compatibility mode. |
| 2949 | unsigned DiagID = diag::err_typename_missing; |
| 2950 | if (RecoveryTSI && getLangOpts().MSVCCompat) |
| 2951 | DiagID = diag::ext_typename_missing; |
| 2952 | SourceLocation Loc = SS.getBeginLoc(); |
| 2953 | auto D = Diag(Loc, DiagID); |
| 2954 | D << ET << SourceRange(Loc, NameInfo.getEndLoc()); |
| 2955 | |
| 2956 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE |
| 2957 | // context. |
| 2958 | if (!RecoveryTSI) |
| 2959 | return ExprError(); |
| 2960 | |
| 2961 | // Only issue the fixit if we're prepared to recover. |
| 2962 | D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename " ); |
| 2963 | |
| 2964 | // Recover by pretending this was an elaborated type. |
| 2965 | TypeLocBuilder TLB; |
| 2966 | TLB.pushTypeSpec(T: Ty).setNameLoc(NameInfo.getLoc()); |
| 2967 | |
| 2968 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(T: ET); |
| 2969 | QTL.setElaboratedKeywordLoc(SourceLocation()); |
| 2970 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| 2971 | |
| 2972 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET); |
| 2973 | |
| 2974 | return ExprEmpty(); |
| 2975 | } |
| 2976 | |
| 2977 | // If necessary, build an implicit class member access. |
| 2978 | if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand)) |
| 2979 | return BuildPossibleImplicitMemberExpr(SS, |
| 2980 | /*TemplateKWLoc=*/SourceLocation(), |
| 2981 | R, /*TemplateArgs=*/nullptr, |
| 2982 | /*S=*/nullptr); |
| 2983 | |
| 2984 | return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false); |
| 2985 | } |
| 2986 | |
| 2987 | ExprResult |
| 2988 | Sema::PerformObjectMemberConversion(Expr *From, |
| 2989 | NestedNameSpecifier *Qualifier, |
| 2990 | NamedDecl *FoundDecl, |
| 2991 | NamedDecl *Member) { |
| 2992 | const auto *RD = dyn_cast<CXXRecordDecl>(Val: Member->getDeclContext()); |
| 2993 | if (!RD) |
| 2994 | return From; |
| 2995 | |
| 2996 | QualType DestRecordType; |
| 2997 | QualType DestType; |
| 2998 | QualType FromRecordType; |
| 2999 | QualType FromType = From->getType(); |
| 3000 | bool PointerConversions = false; |
| 3001 | if (isa<FieldDecl>(Val: Member)) { |
| 3002 | DestRecordType = Context.getCanonicalType(T: Context.getTypeDeclType(Decl: RD)); |
| 3003 | auto FromPtrType = FromType->getAs<PointerType>(); |
| 3004 | DestRecordType = Context.getAddrSpaceQualType( |
| 3005 | T: DestRecordType, AddressSpace: FromPtrType |
| 3006 | ? FromType->getPointeeType().getAddressSpace() |
| 3007 | : FromType.getAddressSpace()); |
| 3008 | |
| 3009 | if (FromPtrType) { |
| 3010 | DestType = Context.getPointerType(T: DestRecordType); |
| 3011 | FromRecordType = FromPtrType->getPointeeType(); |
| 3012 | PointerConversions = true; |
| 3013 | } else { |
| 3014 | DestType = DestRecordType; |
| 3015 | FromRecordType = FromType; |
| 3016 | } |
| 3017 | } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) { |
| 3018 | if (!Method->isImplicitObjectMemberFunction()) |
| 3019 | return From; |
| 3020 | |
| 3021 | DestType = Method->getThisType().getNonReferenceType(); |
| 3022 | DestRecordType = Method->getFunctionObjectParameterType(); |
| 3023 | |
| 3024 | if (FromType->getAs<PointerType>()) { |
| 3025 | FromRecordType = FromType->getPointeeType(); |
| 3026 | PointerConversions = true; |
| 3027 | } else { |
| 3028 | FromRecordType = FromType; |
| 3029 | DestType = DestRecordType; |
| 3030 | } |
| 3031 | |
| 3032 | LangAS FromAS = FromRecordType.getAddressSpace(); |
| 3033 | LangAS DestAS = DestRecordType.getAddressSpace(); |
| 3034 | if (FromAS != DestAS) { |
| 3035 | QualType FromRecordTypeWithoutAS = |
| 3036 | Context.removeAddrSpaceQualType(T: FromRecordType); |
| 3037 | QualType FromTypeWithDestAS = |
| 3038 | Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS); |
| 3039 | if (PointerConversions) |
| 3040 | FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS); |
| 3041 | From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS, |
| 3042 | CK: CK_AddressSpaceConversion, VK: From->getValueKind()) |
| 3043 | .get(); |
| 3044 | } |
| 3045 | } else { |
| 3046 | // No conversion necessary. |
| 3047 | return From; |
| 3048 | } |
| 3049 | |
| 3050 | if (DestType->isDependentType() || FromType->isDependentType()) |
| 3051 | return From; |
| 3052 | |
| 3053 | // If the unqualified types are the same, no conversion is necessary. |
| 3054 | if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType)) |
| 3055 | return From; |
| 3056 | |
| 3057 | SourceRange FromRange = From->getSourceRange(); |
| 3058 | SourceLocation FromLoc = FromRange.getBegin(); |
| 3059 | |
| 3060 | ExprValueKind VK = From->getValueKind(); |
| 3061 | |
| 3062 | // C++ [class.member.lookup]p8: |
| 3063 | // [...] Ambiguities can often be resolved by qualifying a name with its |
| 3064 | // class name. |
| 3065 | // |
| 3066 | // If the member was a qualified name and the qualified referred to a |
| 3067 | // specific base subobject type, we'll cast to that intermediate type |
| 3068 | // first and then to the object in which the member is declared. That allows |
| 3069 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: |
| 3070 | // |
| 3071 | // class Base { public: int x; }; |
| 3072 | // class Derived1 : public Base { }; |
| 3073 | // class Derived2 : public Base { }; |
| 3074 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; |
| 3075 | // |
| 3076 | // void VeryDerived::f() { |
| 3077 | // x = 17; // error: ambiguous base subobjects |
| 3078 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 |
| 3079 | // } |
| 3080 | if (Qualifier && Qualifier->getAsType()) { |
| 3081 | QualType QType = QualType(Qualifier->getAsType(), 0); |
| 3082 | assert(QType->isRecordType() && "lookup done with non-record type" ); |
| 3083 | |
| 3084 | QualType QRecordType = QualType(QType->castAs<RecordType>(), 0); |
| 3085 | |
| 3086 | // In C++98, the qualifier type doesn't actually have to be a base |
| 3087 | // type of the object type, in which case we just ignore it. |
| 3088 | // Otherwise build the appropriate casts. |
| 3089 | if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) { |
| 3090 | CXXCastPath BasePath; |
| 3091 | if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType, |
| 3092 | Loc: FromLoc, Range: FromRange, BasePath: &BasePath)) |
| 3093 | return ExprError(); |
| 3094 | |
| 3095 | if (PointerConversions) |
| 3096 | QType = Context.getPointerType(T: QType); |
| 3097 | From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase, |
| 3098 | VK, BasePath: &BasePath).get(); |
| 3099 | |
| 3100 | FromType = QType; |
| 3101 | FromRecordType = QRecordType; |
| 3102 | |
| 3103 | // If the qualifier type was the same as the destination type, |
| 3104 | // we're done. |
| 3105 | if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType)) |
| 3106 | return From; |
| 3107 | } |
| 3108 | } |
| 3109 | |
| 3110 | CXXCastPath BasePath; |
| 3111 | if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType, |
| 3112 | Loc: FromLoc, Range: FromRange, BasePath: &BasePath, |
| 3113 | /*IgnoreAccess=*/true)) |
| 3114 | return ExprError(); |
| 3115 | |
| 3116 | // Propagate qualifiers to base subobjects as per: |
| 3117 | // C++ [basic.type.qualifier]p1.2: |
| 3118 | // A volatile object is [...] a subobject of a volatile object. |
| 3119 | Qualifiers FromTypeQuals = FromType.getQualifiers(); |
| 3120 | FromTypeQuals.setAddressSpace(DestType.getAddressSpace()); |
| 3121 | DestType = Context.getQualifiedType(T: DestType, Qs: FromTypeQuals); |
| 3122 | |
| 3123 | return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, VK, |
| 3124 | BasePath: &BasePath); |
| 3125 | } |
| 3126 | |
| 3127 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, |
| 3128 | const LookupResult &R, |
| 3129 | bool HasTrailingLParen) { |
| 3130 | // Only when used directly as the postfix-expression of a call. |
| 3131 | if (!HasTrailingLParen) |
| 3132 | return false; |
| 3133 | |
| 3134 | // Never if a scope specifier was provided. |
| 3135 | if (SS.isNotEmpty()) |
| 3136 | return false; |
| 3137 | |
| 3138 | // Only in C++ or ObjC++. |
| 3139 | if (!getLangOpts().CPlusPlus) |
| 3140 | return false; |
| 3141 | |
| 3142 | // Turn off ADL when we find certain kinds of declarations during |
| 3143 | // normal lookup: |
| 3144 | for (const NamedDecl *D : R) { |
| 3145 | // C++0x [basic.lookup.argdep]p3: |
| 3146 | // -- a declaration of a class member |
| 3147 | // Since using decls preserve this property, we check this on the |
| 3148 | // original decl. |
| 3149 | if (D->isCXXClassMember()) |
| 3150 | return false; |
| 3151 | |
| 3152 | // C++0x [basic.lookup.argdep]p3: |
| 3153 | // -- a block-scope function declaration that is not a |
| 3154 | // using-declaration |
| 3155 | // NOTE: we also trigger this for function templates (in fact, we |
| 3156 | // don't check the decl type at all, since all other decl types |
| 3157 | // turn off ADL anyway). |
| 3158 | if (isa<UsingShadowDecl>(Val: D)) |
| 3159 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
| 3160 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) |
| 3161 | return false; |
| 3162 | |
| 3163 | // C++0x [basic.lookup.argdep]p3: |
| 3164 | // -- a declaration that is neither a function or a function |
| 3165 | // template |
| 3166 | // And also for builtin functions. |
| 3167 | if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) { |
| 3168 | // But also builtin functions. |
| 3169 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) |
| 3170 | return false; |
| 3171 | } else if (!isa<FunctionTemplateDecl>(Val: D)) |
| 3172 | return false; |
| 3173 | } |
| 3174 | |
| 3175 | return true; |
| 3176 | } |
| 3177 | |
| 3178 | |
| 3179 | /// Diagnoses obvious problems with the use of the given declaration |
| 3180 | /// as an expression. This is only actually called for lookups that |
| 3181 | /// were not overloaded, and it doesn't promise that the declaration |
| 3182 | /// will in fact be used. |
| 3183 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, |
| 3184 | bool AcceptInvalid) { |
| 3185 | if (D->isInvalidDecl() && !AcceptInvalid) |
| 3186 | return true; |
| 3187 | |
| 3188 | if (isa<TypedefNameDecl>(Val: D)) { |
| 3189 | S.Diag(Loc, DiagID: diag::err_unexpected_typedef) << D->getDeclName(); |
| 3190 | return true; |
| 3191 | } |
| 3192 | |
| 3193 | if (isa<ObjCInterfaceDecl>(Val: D)) { |
| 3194 | S.Diag(Loc, DiagID: diag::err_unexpected_interface) << D->getDeclName(); |
| 3195 | return true; |
| 3196 | } |
| 3197 | |
| 3198 | if (isa<NamespaceDecl>(Val: D)) { |
| 3199 | S.Diag(Loc, DiagID: diag::err_unexpected_namespace) << D->getDeclName(); |
| 3200 | return true; |
| 3201 | } |
| 3202 | |
| 3203 | return false; |
| 3204 | } |
| 3205 | |
| 3206 | // Certain multiversion types should be treated as overloaded even when there is |
| 3207 | // only one result. |
| 3208 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { |
| 3209 | assert(R.isSingleResult() && "Expected only a single result" ); |
| 3210 | const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl()); |
| 3211 | return FD && |
| 3212 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); |
| 3213 | } |
| 3214 | |
| 3215 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, |
| 3216 | LookupResult &R, bool NeedsADL, |
| 3217 | bool AcceptInvalidDecl) { |
| 3218 | // If this is a single, fully-resolved result and we don't need ADL, |
| 3219 | // just build an ordinary singleton decl ref. |
| 3220 | if (!NeedsADL && R.isSingleResult() && |
| 3221 | !R.getAsSingle<FunctionTemplateDecl>() && |
| 3222 | !ShouldLookupResultBeMultiVersionOverload(R)) |
| 3223 | return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(), |
| 3224 | FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr, |
| 3225 | AcceptInvalidDecl); |
| 3226 | |
| 3227 | // We only need to check the declaration if there's exactly one |
| 3228 | // result, because in the overloaded case the results can only be |
| 3229 | // functions and function templates. |
| 3230 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && |
| 3231 | CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(), |
| 3232 | AcceptInvalid: AcceptInvalidDecl)) |
| 3233 | return ExprError(); |
| 3234 | |
| 3235 | // Otherwise, just build an unresolved lookup expression. Suppress |
| 3236 | // any lookup-related diagnostics; we'll hash these out later, when |
| 3237 | // we've picked a target. |
| 3238 | R.suppressDiagnostics(); |
| 3239 | |
| 3240 | UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create( |
| 3241 | Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context), |
| 3242 | NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(), |
| 3243 | /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false); |
| 3244 | |
| 3245 | return ULE; |
| 3246 | } |
| 3247 | |
| 3248 | static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, |
| 3249 | SourceLocation loc, |
| 3250 | ValueDecl *var); |
| 3251 | |
| 3252 | ExprResult Sema::BuildDeclarationNameExpr( |
| 3253 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, |
| 3254 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, |
| 3255 | bool AcceptInvalidDecl) { |
| 3256 | assert(D && "Cannot refer to a NULL declaration" ); |
| 3257 | assert(!isa<FunctionTemplateDecl>(D) && |
| 3258 | "Cannot refer unambiguously to a function template" ); |
| 3259 | |
| 3260 | SourceLocation Loc = NameInfo.getLoc(); |
| 3261 | if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) { |
| 3262 | // Recovery from invalid cases (e.g. D is an invalid Decl). |
| 3263 | // We use the dependent type for the RecoveryExpr to prevent bogus follow-up |
| 3264 | // diagnostics, as invalid decls use int as a fallback type. |
| 3265 | return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {}); |
| 3266 | } |
| 3267 | |
| 3268 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) { |
| 3269 | // Specifically diagnose references to class templates that are missing |
| 3270 | // a template argument list. |
| 3271 | diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc); |
| 3272 | return ExprError(); |
| 3273 | } |
| 3274 | |
| 3275 | // Make sure that we're referring to a value. |
| 3276 | if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) { |
| 3277 | Diag(Loc, DiagID: diag::err_ref_non_value) << D << SS.getRange(); |
| 3278 | Diag(Loc: D->getLocation(), DiagID: diag::note_declared_at); |
| 3279 | return ExprError(); |
| 3280 | } |
| 3281 | |
| 3282 | // Check whether this declaration can be used. Note that we suppress |
| 3283 | // this check when we're going to perform argument-dependent lookup |
| 3284 | // on this function name, because this might not be the function |
| 3285 | // that overload resolution actually selects. |
| 3286 | if (DiagnoseUseOfDecl(D, Locs: Loc)) |
| 3287 | return ExprError(); |
| 3288 | |
| 3289 | auto *VD = cast<ValueDecl>(Val: D); |
| 3290 | |
| 3291 | // Only create DeclRefExpr's for valid Decl's. |
| 3292 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) |
| 3293 | return ExprError(); |
| 3294 | |
| 3295 | // Handle members of anonymous structs and unions. If we got here, |
| 3296 | // and the reference is to a class member indirect field, then this |
| 3297 | // must be the subject of a pointer-to-member expression. |
| 3298 | if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD); |
| 3299 | IndirectField && !IndirectField->isCXXClassMember()) |
| 3300 | return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(), |
| 3301 | indirectField: IndirectField); |
| 3302 | |
| 3303 | QualType type = VD->getType(); |
| 3304 | if (type.isNull()) |
| 3305 | return ExprError(); |
| 3306 | ExprValueKind valueKind = VK_PRValue; |
| 3307 | |
| 3308 | // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of |
| 3309 | // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, |
| 3310 | // is expanded by some outer '...' in the context of the use. |
| 3311 | type = type.getNonPackExpansionType(); |
| 3312 | |
| 3313 | switch (D->getKind()) { |
| 3314 | // Ignore all the non-ValueDecl kinds. |
| 3315 | #define ABSTRACT_DECL(kind) |
| 3316 | #define VALUE(type, base) |
| 3317 | #define DECL(type, base) case Decl::type: |
| 3318 | #include "clang/AST/DeclNodes.inc" |
| 3319 | llvm_unreachable("invalid value decl kind" ); |
| 3320 | |
| 3321 | // These shouldn't make it here. |
| 3322 | case Decl::ObjCAtDefsField: |
| 3323 | llvm_unreachable("forming non-member reference to ivar?" ); |
| 3324 | |
| 3325 | // Enum constants are always r-values and never references. |
| 3326 | // Unresolved using declarations are dependent. |
| 3327 | case Decl::EnumConstant: |
| 3328 | case Decl::UnresolvedUsingValue: |
| 3329 | case Decl::OMPDeclareReduction: |
| 3330 | case Decl::OMPDeclareMapper: |
| 3331 | valueKind = VK_PRValue; |
| 3332 | break; |
| 3333 | |
| 3334 | // Fields and indirect fields that got here must be for |
| 3335 | // pointer-to-member expressions; we just call them l-values for |
| 3336 | // internal consistency, because this subexpression doesn't really |
| 3337 | // exist in the high-level semantics. |
| 3338 | case Decl::Field: |
| 3339 | case Decl::IndirectField: |
| 3340 | case Decl::ObjCIvar: |
| 3341 | assert((getLangOpts().CPlusPlus || isAttrContext()) && |
| 3342 | "building reference to field in C?" ); |
| 3343 | |
| 3344 | // These can't have reference type in well-formed programs, but |
| 3345 | // for internal consistency we do this anyway. |
| 3346 | type = type.getNonReferenceType(); |
| 3347 | valueKind = VK_LValue; |
| 3348 | break; |
| 3349 | |
| 3350 | // Non-type template parameters are either l-values or r-values |
| 3351 | // depending on the type. |
| 3352 | case Decl::NonTypeTemplateParm: { |
| 3353 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { |
| 3354 | type = reftype->getPointeeType(); |
| 3355 | valueKind = VK_LValue; // even if the parameter is an r-value reference |
| 3356 | break; |
| 3357 | } |
| 3358 | |
| 3359 | // [expr.prim.id.unqual]p2: |
| 3360 | // If the entity is a template parameter object for a template |
| 3361 | // parameter of type T, the type of the expression is const T. |
| 3362 | // [...] The expression is an lvalue if the entity is a [...] template |
| 3363 | // parameter object. |
| 3364 | if (type->isRecordType()) { |
| 3365 | type = type.getUnqualifiedType().withConst(); |
| 3366 | valueKind = VK_LValue; |
| 3367 | break; |
| 3368 | } |
| 3369 | |
| 3370 | // For non-references, we need to strip qualifiers just in case |
| 3371 | // the template parameter was declared as 'const int' or whatever. |
| 3372 | valueKind = VK_PRValue; |
| 3373 | type = type.getUnqualifiedType(); |
| 3374 | break; |
| 3375 | } |
| 3376 | |
| 3377 | case Decl::Var: |
| 3378 | case Decl::VarTemplateSpecialization: |
| 3379 | case Decl::VarTemplatePartialSpecialization: |
| 3380 | case Decl::Decomposition: |
| 3381 | case Decl::Binding: |
| 3382 | case Decl::OMPCapturedExpr: |
| 3383 | // In C, "extern void blah;" is valid and is an r-value. |
| 3384 | if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && |
| 3385 | type->isVoidType()) { |
| 3386 | valueKind = VK_PRValue; |
| 3387 | break; |
| 3388 | } |
| 3389 | [[fallthrough]]; |
| 3390 | |
| 3391 | case Decl::ImplicitParam: |
| 3392 | case Decl::ParmVar: { |
| 3393 | // These are always l-values. |
| 3394 | valueKind = VK_LValue; |
| 3395 | type = type.getNonReferenceType(); |
| 3396 | |
| 3397 | // FIXME: Does the addition of const really only apply in |
| 3398 | // potentially-evaluated contexts? Since the variable isn't actually |
| 3399 | // captured in an unevaluated context, it seems that the answer is no. |
| 3400 | if (!isUnevaluatedContext()) { |
| 3401 | QualType CapturedType = getCapturedDeclRefType(Var: cast<ValueDecl>(Val: VD), Loc); |
| 3402 | if (!CapturedType.isNull()) |
| 3403 | type = CapturedType; |
| 3404 | } |
| 3405 | break; |
| 3406 | } |
| 3407 | |
| 3408 | case Decl::Function: { |
| 3409 | if (unsigned BID = cast<FunctionDecl>(Val: VD)->getBuiltinID()) { |
| 3410 | if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) { |
| 3411 | type = Context.BuiltinFnTy; |
| 3412 | valueKind = VK_PRValue; |
| 3413 | break; |
| 3414 | } |
| 3415 | } |
| 3416 | |
| 3417 | const FunctionType *fty = type->castAs<FunctionType>(); |
| 3418 | |
| 3419 | // If we're referring to a function with an __unknown_anytype |
| 3420 | // result type, make the entire expression __unknown_anytype. |
| 3421 | if (fty->getReturnType() == Context.UnknownAnyTy) { |
| 3422 | type = Context.UnknownAnyTy; |
| 3423 | valueKind = VK_PRValue; |
| 3424 | break; |
| 3425 | } |
| 3426 | |
| 3427 | // Functions are l-values in C++. |
| 3428 | if (getLangOpts().CPlusPlus) { |
| 3429 | valueKind = VK_LValue; |
| 3430 | break; |
| 3431 | } |
| 3432 | |
| 3433 | // C99 DR 316 says that, if a function type comes from a |
| 3434 | // function definition (without a prototype), that type is only |
| 3435 | // used for checking compatibility. Therefore, when referencing |
| 3436 | // the function, we pretend that we don't have the full function |
| 3437 | // type. |
| 3438 | if (!cast<FunctionDecl>(Val: VD)->hasPrototype() && isa<FunctionProtoType>(Val: fty)) |
| 3439 | type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(), |
| 3440 | Info: fty->getExtInfo()); |
| 3441 | |
| 3442 | // Functions are r-values in C. |
| 3443 | valueKind = VK_PRValue; |
| 3444 | break; |
| 3445 | } |
| 3446 | |
| 3447 | case Decl::CXXDeductionGuide: |
| 3448 | llvm_unreachable("building reference to deduction guide" ); |
| 3449 | |
| 3450 | case Decl::MSProperty: |
| 3451 | case Decl::MSGuid: |
| 3452 | case Decl::TemplateParamObject: |
| 3453 | // FIXME: Should MSGuidDecl and template parameter objects be subject to |
| 3454 | // capture in OpenMP, or duplicated between host and device? |
| 3455 | valueKind = VK_LValue; |
| 3456 | break; |
| 3457 | |
| 3458 | case Decl::UnnamedGlobalConstant: |
| 3459 | valueKind = VK_LValue; |
| 3460 | break; |
| 3461 | |
| 3462 | case Decl::CXXMethod: |
| 3463 | // If we're referring to a method with an __unknown_anytype |
| 3464 | // result type, make the entire expression __unknown_anytype. |
| 3465 | // This should only be possible with a type written directly. |
| 3466 | if (const FunctionProtoType *proto = |
| 3467 | dyn_cast<FunctionProtoType>(Val: VD->getType())) |
| 3468 | if (proto->getReturnType() == Context.UnknownAnyTy) { |
| 3469 | type = Context.UnknownAnyTy; |
| 3470 | valueKind = VK_PRValue; |
| 3471 | break; |
| 3472 | } |
| 3473 | |
| 3474 | // C++ methods are l-values if static, r-values if non-static. |
| 3475 | if (cast<CXXMethodDecl>(Val: VD)->isStatic()) { |
| 3476 | valueKind = VK_LValue; |
| 3477 | break; |
| 3478 | } |
| 3479 | [[fallthrough]]; |
| 3480 | |
| 3481 | case Decl::CXXConversion: |
| 3482 | case Decl::CXXDestructor: |
| 3483 | case Decl::CXXConstructor: |
| 3484 | valueKind = VK_PRValue; |
| 3485 | break; |
| 3486 | } |
| 3487 | |
| 3488 | auto *E = |
| 3489 | BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD, |
| 3490 | /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs); |
| 3491 | // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We |
| 3492 | // wrap a DeclRefExpr referring to an invalid decl with a dependent-type |
| 3493 | // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus |
| 3494 | // diagnostics). |
| 3495 | if (VD->isInvalidDecl() && E) |
| 3496 | return CreateRecoveryExpr(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: {E}); |
| 3497 | return E; |
| 3498 | } |
| 3499 | |
| 3500 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, |
| 3501 | SmallString<32> &Target) { |
| 3502 | Target.resize(N: CharByteWidth * (Source.size() + 1)); |
| 3503 | char *ResultPtr = &Target[0]; |
| 3504 | const llvm::UTF8 *ErrorPtr; |
| 3505 | bool success = |
| 3506 | llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr); |
| 3507 | (void)success; |
| 3508 | assert(success); |
| 3509 | Target.resize(N: ResultPtr - &Target[0]); |
| 3510 | } |
| 3511 | |
| 3512 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, |
| 3513 | PredefinedIdentKind IK) { |
| 3514 | Decl *currentDecl = getPredefinedExprDecl(DC: CurContext); |
| 3515 | if (!currentDecl) { |
| 3516 | Diag(Loc, DiagID: diag::ext_predef_outside_function); |
| 3517 | currentDecl = Context.getTranslationUnitDecl(); |
| 3518 | } |
| 3519 | |
| 3520 | QualType ResTy; |
| 3521 | StringLiteral *SL = nullptr; |
| 3522 | if (cast<DeclContext>(Val: currentDecl)->isDependentContext()) |
| 3523 | ResTy = Context.DependentTy; |
| 3524 | else { |
| 3525 | // Pre-defined identifiers are of type char[x], where x is the length of |
| 3526 | // the string. |
| 3527 | bool ForceElaboratedPrinting = |
| 3528 | IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat; |
| 3529 | auto Str = |
| 3530 | PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting); |
| 3531 | unsigned Length = Str.length(); |
| 3532 | |
| 3533 | llvm::APInt LengthI(32, Length + 1); |
| 3534 | if (IK == PredefinedIdentKind::LFunction || |
| 3535 | IK == PredefinedIdentKind::LFuncSig) { |
| 3536 | ResTy = |
| 3537 | Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst()); |
| 3538 | SmallString<32> RawChars; |
| 3539 | ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(), |
| 3540 | Source: Str, Target&: RawChars); |
| 3541 | ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr, |
| 3542 | ASM: ArraySizeModifier::Normal, |
| 3543 | /*IndexTypeQuals*/ 0); |
| 3544 | SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide, |
| 3545 | /*Pascal*/ false, Ty: ResTy, Locs: Loc); |
| 3546 | } else { |
| 3547 | ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()); |
| 3548 | ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr, |
| 3549 | ASM: ArraySizeModifier::Normal, |
| 3550 | /*IndexTypeQuals*/ 0); |
| 3551 | SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary, |
| 3552 | /*Pascal*/ false, Ty: ResTy, Locs: Loc); |
| 3553 | } |
| 3554 | } |
| 3555 | |
| 3556 | return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt, |
| 3557 | SL); |
| 3558 | } |
| 3559 | |
| 3560 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { |
| 3561 | return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind)); |
| 3562 | } |
| 3563 | |
| 3564 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { |
| 3565 | SmallString<16> CharBuffer; |
| 3566 | bool Invalid = false; |
| 3567 | StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid); |
| 3568 | if (Invalid) |
| 3569 | return ExprError(); |
| 3570 | |
| 3571 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), |
| 3572 | PP, Tok.getKind()); |
| 3573 | if (Literal.hadError()) |
| 3574 | return ExprError(); |
| 3575 | |
| 3576 | QualType Ty; |
| 3577 | if (Literal.isWide()) |
| 3578 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. |
| 3579 | else if (Literal.isUTF8() && getLangOpts().C23) |
| 3580 | Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23 |
| 3581 | else if (Literal.isUTF8() && getLangOpts().Char8) |
| 3582 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. |
| 3583 | else if (Literal.isUTF16()) |
| 3584 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. |
| 3585 | else if (Literal.isUTF32()) |
| 3586 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. |
| 3587 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) |
| 3588 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. |
| 3589 | else |
| 3590 | Ty = Context.CharTy; // 'x' -> char in C++; |
| 3591 | // u8'x' -> char in C11-C17 and in C++ without char8_t. |
| 3592 | |
| 3593 | CharacterLiteralKind Kind = CharacterLiteralKind::Ascii; |
| 3594 | if (Literal.isWide()) |
| 3595 | Kind = CharacterLiteralKind::Wide; |
| 3596 | else if (Literal.isUTF16()) |
| 3597 | Kind = CharacterLiteralKind::UTF16; |
| 3598 | else if (Literal.isUTF32()) |
| 3599 | Kind = CharacterLiteralKind::UTF32; |
| 3600 | else if (Literal.isUTF8()) |
| 3601 | Kind = CharacterLiteralKind::UTF8; |
| 3602 | |
| 3603 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, |
| 3604 | Tok.getLocation()); |
| 3605 | |
| 3606 | if (Literal.getUDSuffix().empty()) |
| 3607 | return Lit; |
| 3608 | |
| 3609 | // We're building a user-defined literal. |
| 3610 | IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix()); |
| 3611 | SourceLocation UDSuffixLoc = |
| 3612 | getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset()); |
| 3613 | |
| 3614 | // Make sure we're allowed user-defined literals here. |
| 3615 | if (!UDLScope) |
| 3616 | return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_character_udl)); |
| 3617 | |
| 3618 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form |
| 3619 | // operator "" X (ch) |
| 3620 | return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc, |
| 3621 | Args: Lit, LitEndLoc: Tok.getLocation()); |
| 3622 | } |
| 3623 | |
| 3624 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) { |
| 3625 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); |
| 3626 | return IntegerLiteral::Create(C: Context, |
| 3627 | V: llvm::APInt(IntSize, Val, /*isSigned=*/true), |
| 3628 | type: Context.IntTy, l: Loc); |
| 3629 | } |
| 3630 | |
| 3631 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, |
| 3632 | QualType Ty, SourceLocation Loc) { |
| 3633 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty); |
| 3634 | |
| 3635 | using llvm::APFloat; |
| 3636 | APFloat Val(Format); |
| 3637 | |
| 3638 | llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode(); |
| 3639 | if (RM == llvm::RoundingMode::Dynamic) |
| 3640 | RM = llvm::RoundingMode::NearestTiesToEven; |
| 3641 | APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM); |
| 3642 | |
| 3643 | // Overflow is always an error, but underflow is only an error if |
| 3644 | // we underflowed to zero (APFloat reports denormals as underflow). |
| 3645 | if ((result & APFloat::opOverflow) || |
| 3646 | ((result & APFloat::opUnderflow) && Val.isZero())) { |
| 3647 | unsigned diagnostic; |
| 3648 | SmallString<20> buffer; |
| 3649 | if (result & APFloat::opOverflow) { |
| 3650 | diagnostic = diag::warn_float_overflow; |
| 3651 | APFloat::getLargest(Sem: Format).toString(Str&: buffer); |
| 3652 | } else { |
| 3653 | diagnostic = diag::warn_float_underflow; |
| 3654 | APFloat::getSmallest(Sem: Format).toString(Str&: buffer); |
| 3655 | } |
| 3656 | |
| 3657 | S.Diag(Loc, DiagID: diagnostic) << Ty << buffer.str(); |
| 3658 | } |
| 3659 | |
| 3660 | bool isExact = (result == APFloat::opOK); |
| 3661 | return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc); |
| 3662 | } |
| 3663 | |
| 3664 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) { |
| 3665 | assert(E && "Invalid expression" ); |
| 3666 | |
| 3667 | if (E->isValueDependent()) |
| 3668 | return false; |
| 3669 | |
| 3670 | QualType QT = E->getType(); |
| 3671 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { |
| 3672 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_pragma_loop_invalid_argument_type) << QT; |
| 3673 | return true; |
| 3674 | } |
| 3675 | |
| 3676 | llvm::APSInt ValueAPS; |
| 3677 | ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS); |
| 3678 | |
| 3679 | if (R.isInvalid()) |
| 3680 | return true; |
| 3681 | |
| 3682 | // GCC allows the value of unroll count to be 0. |
| 3683 | // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says |
| 3684 | // "The values of 0 and 1 block any unrolling of the loop." |
| 3685 | // The values doesn't have to be strictly positive in '#pragma GCC unroll' and |
| 3686 | // '#pragma unroll' cases. |
| 3687 | bool ValueIsPositive = |
| 3688 | AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive(); |
| 3689 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { |
| 3690 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_requires_positive_value) |
| 3691 | << toString(I: ValueAPS, Radix: 10) << ValueIsPositive; |
| 3692 | return true; |
| 3693 | } |
| 3694 | |
| 3695 | return false; |
| 3696 | } |
| 3697 | |
| 3698 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { |
| 3699 | // Fast path for a single digit (which is quite common). A single digit |
| 3700 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. |
| 3701 | if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) { |
| 3702 | const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); |
| 3703 | return ActOnIntegerConstant(Loc: Tok.getLocation(), Val); |
| 3704 | } |
| 3705 | |
| 3706 | SmallString<128> SpellingBuffer; |
| 3707 | // NumericLiteralParser wants to overread by one character. Add padding to |
| 3708 | // the buffer in case the token is copied to the buffer. If getSpelling() |
| 3709 | // returns a StringRef to the memory buffer, it should have a null char at |
| 3710 | // the EOF, so it is also safe. |
| 3711 | SpellingBuffer.resize(N: Tok.getLength() + 1); |
| 3712 | |
| 3713 | // Get the spelling of the token, which eliminates trigraphs, etc. |
| 3714 | bool Invalid = false; |
| 3715 | StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid); |
| 3716 | if (Invalid) |
| 3717 | return ExprError(); |
| 3718 | |
| 3719 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), |
| 3720 | PP.getSourceManager(), PP.getLangOpts(), |
| 3721 | PP.getTargetInfo(), PP.getDiagnostics()); |
| 3722 | if (Literal.hadError) |
| 3723 | return ExprError(); |
| 3724 | |
| 3725 | if (Literal.hasUDSuffix()) { |
| 3726 | // We're building a user-defined literal. |
| 3727 | const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix()); |
| 3728 | SourceLocation UDSuffixLoc = |
| 3729 | getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset()); |
| 3730 | |
| 3731 | // Make sure we're allowed user-defined literals here. |
| 3732 | if (!UDLScope) |
| 3733 | return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_numeric_udl)); |
| 3734 | |
| 3735 | QualType CookedTy; |
| 3736 | if (Literal.isFloatingLiteral()) { |
| 3737 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type |
| 3738 | // long double, the literal is treated as a call of the form |
| 3739 | // operator "" X (f L) |
| 3740 | CookedTy = Context.LongDoubleTy; |
| 3741 | } else { |
| 3742 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type |
| 3743 | // unsigned long long, the literal is treated as a call of the form |
| 3744 | // operator "" X (n ULL) |
| 3745 | CookedTy = Context.UnsignedLongLongTy; |
| 3746 | } |
| 3747 | |
| 3748 | DeclarationName OpName = |
| 3749 | Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix); |
| 3750 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); |
| 3751 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); |
| 3752 | |
| 3753 | SourceLocation TokLoc = Tok.getLocation(); |
| 3754 | |
| 3755 | // Perform literal operator lookup to determine if we're building a raw |
| 3756 | // literal or a cooked one. |
| 3757 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); |
| 3758 | switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy, |
| 3759 | /*AllowRaw*/ true, /*AllowTemplate*/ true, |
| 3760 | /*AllowStringTemplatePack*/ AllowStringTemplate: false, |
| 3761 | /*DiagnoseMissing*/ !Literal.isImaginary)) { |
| 3762 | case LOLR_ErrorNoDiagnostic: |
| 3763 | // Lookup failure for imaginary constants isn't fatal, there's still the |
| 3764 | // GNU extension producing _Complex types. |
| 3765 | break; |
| 3766 | case LOLR_Error: |
| 3767 | return ExprError(); |
| 3768 | case LOLR_Cooked: { |
| 3769 | Expr *Lit; |
| 3770 | if (Literal.isFloatingLiteral()) { |
| 3771 | Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation()); |
| 3772 | } else { |
| 3773 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); |
| 3774 | if (Literal.GetIntegerValue(Val&: ResultVal)) |
| 3775 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large) |
| 3776 | << /* Unsigned */ 1; |
| 3777 | Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy, |
| 3778 | l: Tok.getLocation()); |
| 3779 | } |
| 3780 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc); |
| 3781 | } |
| 3782 | |
| 3783 | case LOLR_Raw: { |
| 3784 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the |
| 3785 | // literal is treated as a call of the form |
| 3786 | // operator "" X ("n") |
| 3787 | unsigned Length = Literal.getUDSuffixOffset(); |
| 3788 | QualType StrTy = Context.getConstantArrayType( |
| 3789 | EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()), |
| 3790 | ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
| 3791 | Expr *Lit = |
| 3792 | StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length), |
| 3793 | Kind: StringLiteralKind::Ordinary, |
| 3794 | /*Pascal*/ false, Ty: StrTy, Locs: TokLoc); |
| 3795 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc); |
| 3796 | } |
| 3797 | |
| 3798 | case LOLR_Template: { |
| 3799 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator |
| 3800 | // template), L is treated as a call fo the form |
| 3801 | // operator "" X <'c1', 'c2', ... 'ck'>() |
| 3802 | // where n is the source character sequence c1 c2 ... ck. |
| 3803 | TemplateArgumentListInfo ExplicitArgs; |
| 3804 | unsigned CharBits = Context.getIntWidth(T: Context.CharTy); |
| 3805 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); |
| 3806 | llvm::APSInt Value(CharBits, CharIsUnsigned); |
| 3807 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { |
| 3808 | Value = TokSpelling[I]; |
| 3809 | TemplateArgument Arg(Context, Value, Context.CharTy); |
| 3810 | TemplateArgumentLocInfo ArgInfo; |
| 3811 | ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo)); |
| 3812 | } |
| 3813 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: TokLoc, ExplicitTemplateArgs: &ExplicitArgs); |
| 3814 | } |
| 3815 | case LOLR_StringTemplatePack: |
| 3816 | llvm_unreachable("unexpected literal operator lookup result" ); |
| 3817 | } |
| 3818 | } |
| 3819 | |
| 3820 | Expr *Res; |
| 3821 | |
| 3822 | if (Literal.isFixedPointLiteral()) { |
| 3823 | QualType Ty; |
| 3824 | |
| 3825 | if (Literal.isAccum) { |
| 3826 | if (Literal.isHalf) { |
| 3827 | Ty = Context.ShortAccumTy; |
| 3828 | } else if (Literal.isLong) { |
| 3829 | Ty = Context.LongAccumTy; |
| 3830 | } else { |
| 3831 | Ty = Context.AccumTy; |
| 3832 | } |
| 3833 | } else if (Literal.isFract) { |
| 3834 | if (Literal.isHalf) { |
| 3835 | Ty = Context.ShortFractTy; |
| 3836 | } else if (Literal.isLong) { |
| 3837 | Ty = Context.LongFractTy; |
| 3838 | } else { |
| 3839 | Ty = Context.FractTy; |
| 3840 | } |
| 3841 | } |
| 3842 | |
| 3843 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty); |
| 3844 | |
| 3845 | bool isSigned = !Literal.isUnsigned; |
| 3846 | unsigned scale = Context.getFixedPointScale(Ty); |
| 3847 | unsigned bit_width = Context.getTypeInfo(T: Ty).Width; |
| 3848 | |
| 3849 | llvm::APInt Val(bit_width, 0, isSigned); |
| 3850 | bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale); |
| 3851 | bool ValIsZero = Val.isZero() && !Overflowed; |
| 3852 | |
| 3853 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); |
| 3854 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) |
| 3855 | // Clause 6.4.4 - The value of a constant shall be in the range of |
| 3856 | // representable values for its type, with exception for constants of a |
| 3857 | // fract type with a value of exactly 1; such a constant shall denote |
| 3858 | // the maximal value for the type. |
| 3859 | --Val; |
| 3860 | else if (Val.ugt(RHS: MaxVal) || Overflowed) |
| 3861 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_too_large_for_fixed_point); |
| 3862 | |
| 3863 | Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty, |
| 3864 | l: Tok.getLocation(), Scale: scale); |
| 3865 | } else if (Literal.isFloatingLiteral()) { |
| 3866 | QualType Ty; |
| 3867 | if (Literal.isHalf){ |
| 3868 | if (getLangOpts().HLSL || |
| 3869 | getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16" , LO: getLangOpts())) |
| 3870 | Ty = Context.HalfTy; |
| 3871 | else { |
| 3872 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_half_const_requires_fp16); |
| 3873 | return ExprError(); |
| 3874 | } |
| 3875 | } else if (Literal.isFloat) |
| 3876 | Ty = Context.FloatTy; |
| 3877 | else if (Literal.isLong) |
| 3878 | Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy; |
| 3879 | else if (Literal.isFloat16) |
| 3880 | Ty = Context.Float16Ty; |
| 3881 | else if (Literal.isFloat128) |
| 3882 | Ty = Context.Float128Ty; |
| 3883 | else if (getLangOpts().HLSL) |
| 3884 | Ty = Context.FloatTy; |
| 3885 | else |
| 3886 | Ty = Context.DoubleTy; |
| 3887 | |
| 3888 | Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation()); |
| 3889 | |
| 3890 | if (Ty == Context.DoubleTy) { |
| 3891 | if (getLangOpts().SinglePrecisionConstants) { |
| 3892 | if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { |
| 3893 | Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get(); |
| 3894 | } |
| 3895 | } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( |
| 3896 | Ext: "cl_khr_fp64" , LO: getLangOpts())) { |
| 3897 | // Impose single-precision float type when cl_khr_fp64 is not enabled. |
| 3898 | Diag(Loc: Tok.getLocation(), DiagID: diag::warn_double_const_requires_fp64) |
| 3899 | << (getLangOpts().getOpenCLCompatibleVersion() >= 300); |
| 3900 | Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get(); |
| 3901 | } |
| 3902 | } |
| 3903 | } else if (!Literal.isIntegerLiteral()) { |
| 3904 | return ExprError(); |
| 3905 | } else { |
| 3906 | QualType Ty; |
| 3907 | |
| 3908 | // 'z/uz' literals are a C++23 feature. |
| 3909 | if (Literal.isSizeT) |
| 3910 | Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus |
| 3911 | ? getLangOpts().CPlusPlus23 |
| 3912 | ? diag::warn_cxx20_compat_size_t_suffix |
| 3913 | : diag::ext_cxx23_size_t_suffix |
| 3914 | : diag::err_cxx23_size_t_suffix); |
| 3915 | |
| 3916 | // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++, |
| 3917 | // but we do not currently support the suffix in C++ mode because it's not |
| 3918 | // entirely clear whether WG21 will prefer this suffix to return a library |
| 3919 | // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb' |
| 3920 | // literals are a C++ extension. |
| 3921 | if (Literal.isBitInt) |
| 3922 | PP.Diag(Loc: Tok.getLocation(), |
| 3923 | DiagID: getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix |
| 3924 | : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix |
| 3925 | : diag::ext_c23_bitint_suffix); |
| 3926 | |
| 3927 | // Get the value in the widest-possible width. What is "widest" depends on |
| 3928 | // whether the literal is a bit-precise integer or not. For a bit-precise |
| 3929 | // integer type, try to scan the source to determine how many bits are |
| 3930 | // needed to represent the value. This may seem a bit expensive, but trying |
| 3931 | // to get the integer value from an overly-wide APInt is *extremely* |
| 3932 | // expensive, so the naive approach of assuming |
| 3933 | // llvm::IntegerType::MAX_INT_BITS is a big performance hit. |
| 3934 | unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth(); |
| 3935 | if (Literal.isBitInt) |
| 3936 | BitsNeeded = llvm::APInt::getSufficientBitsNeeded( |
| 3937 | Str: Literal.getLiteralDigits(), Radix: Literal.getRadix()); |
| 3938 | if (Literal.MicrosoftInteger) { |
| 3939 | if (Literal.MicrosoftInteger == 128 && |
| 3940 | !Context.getTargetInfo().hasInt128Type()) |
| 3941 | PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large) |
| 3942 | << Literal.isUnsigned; |
| 3943 | BitsNeeded = Literal.MicrosoftInteger; |
| 3944 | } |
| 3945 | |
| 3946 | llvm::APInt ResultVal(BitsNeeded, 0); |
| 3947 | |
| 3948 | if (Literal.GetIntegerValue(Val&: ResultVal)) { |
| 3949 | // If this value didn't fit into uintmax_t, error and force to ull. |
| 3950 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large) |
| 3951 | << /* Unsigned */ 1; |
| 3952 | Ty = Context.UnsignedLongLongTy; |
| 3953 | assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && |
| 3954 | "long long is not intmax_t?" ); |
| 3955 | } else { |
| 3956 | // If this value fits into a ULL, try to figure out what else it fits into |
| 3957 | // according to the rules of C99 6.4.4.1p5. |
| 3958 | |
| 3959 | // Octal, Hexadecimal, and integers with a U suffix are allowed to |
| 3960 | // be an unsigned int. |
| 3961 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; |
| 3962 | |
| 3963 | // HLSL doesn't really have `long` or `long long`. We support the `ll` |
| 3964 | // suffix for portability of code with C++, but both `l` and `ll` are |
| 3965 | // 64-bit integer types, and we want the type of `1l` and `1ll` to be the |
| 3966 | // same. |
| 3967 | if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) { |
| 3968 | Literal.isLong = true; |
| 3969 | Literal.isLongLong = false; |
| 3970 | } |
| 3971 | |
| 3972 | // Check from smallest to largest, picking the smallest type we can. |
| 3973 | unsigned Width = 0; |
| 3974 | |
| 3975 | // Microsoft specific integer suffixes are explicitly sized. |
| 3976 | if (Literal.MicrosoftInteger) { |
| 3977 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { |
| 3978 | Width = 8; |
| 3979 | Ty = Context.CharTy; |
| 3980 | } else { |
| 3981 | Width = Literal.MicrosoftInteger; |
| 3982 | Ty = Context.getIntTypeForBitwidth(DestWidth: Width, |
| 3983 | /*Signed=*/!Literal.isUnsigned); |
| 3984 | } |
| 3985 | } |
| 3986 | |
| 3987 | // Bit-precise integer literals are automagically-sized based on the |
| 3988 | // width required by the literal. |
| 3989 | if (Literal.isBitInt) { |
| 3990 | // The signed version has one more bit for the sign value. There are no |
| 3991 | // zero-width bit-precise integers, even if the literal value is 0. |
| 3992 | Width = std::max(a: ResultVal.getActiveBits(), b: 1u) + |
| 3993 | (Literal.isUnsigned ? 0u : 1u); |
| 3994 | |
| 3995 | // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH, |
| 3996 | // and reset the type to the largest supported width. |
| 3997 | unsigned int MaxBitIntWidth = |
| 3998 | Context.getTargetInfo().getMaxBitIntWidth(); |
| 3999 | if (Width > MaxBitIntWidth) { |
| 4000 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large) |
| 4001 | << Literal.isUnsigned; |
| 4002 | Width = MaxBitIntWidth; |
| 4003 | } |
| 4004 | |
| 4005 | // Reset the result value to the smaller APInt and select the correct |
| 4006 | // type to be used. Note, we zext even for signed values because the |
| 4007 | // literal itself is always an unsigned value (a preceeding - is a |
| 4008 | // unary operator, not part of the literal). |
| 4009 | ResultVal = ResultVal.zextOrTrunc(width: Width); |
| 4010 | Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width); |
| 4011 | } |
| 4012 | |
| 4013 | // Check C++23 size_t literals. |
| 4014 | if (Literal.isSizeT) { |
| 4015 | assert(!Literal.MicrosoftInteger && |
| 4016 | "size_t literals can't be Microsoft literals" ); |
| 4017 | unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( |
| 4018 | T: Context.getTargetInfo().getSizeType()); |
| 4019 | |
| 4020 | // Does it fit in size_t? |
| 4021 | if (ResultVal.isIntN(N: SizeTSize)) { |
| 4022 | // Does it fit in ssize_t? |
| 4023 | if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) |
| 4024 | Ty = Context.getSignedSizeType(); |
| 4025 | else if (AllowUnsigned) |
| 4026 | Ty = Context.getSizeType(); |
| 4027 | Width = SizeTSize; |
| 4028 | } |
| 4029 | } |
| 4030 | |
| 4031 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && |
| 4032 | !Literal.isSizeT) { |
| 4033 | // Are int/unsigned possibilities? |
| 4034 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); |
| 4035 | |
| 4036 | // Does it fit in a unsigned int? |
| 4037 | if (ResultVal.isIntN(N: IntSize)) { |
| 4038 | // Does it fit in a signed int? |
| 4039 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) |
| 4040 | Ty = Context.IntTy; |
| 4041 | else if (AllowUnsigned) |
| 4042 | Ty = Context.UnsignedIntTy; |
| 4043 | Width = IntSize; |
| 4044 | } |
| 4045 | } |
| 4046 | |
| 4047 | // Are long/unsigned long possibilities? |
| 4048 | if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { |
| 4049 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); |
| 4050 | |
| 4051 | // Does it fit in a unsigned long? |
| 4052 | if (ResultVal.isIntN(N: LongSize)) { |
| 4053 | // Does it fit in a signed long? |
| 4054 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) |
| 4055 | Ty = Context.LongTy; |
| 4056 | else if (AllowUnsigned) |
| 4057 | Ty = Context.UnsignedLongTy; |
| 4058 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 |
| 4059 | // is compatible. |
| 4060 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { |
| 4061 | const unsigned LongLongSize = |
| 4062 | Context.getTargetInfo().getLongLongWidth(); |
| 4063 | Diag(Loc: Tok.getLocation(), |
| 4064 | DiagID: getLangOpts().CPlusPlus |
| 4065 | ? Literal.isLong |
| 4066 | ? diag::warn_old_implicitly_unsigned_long_cxx |
| 4067 | : /*C++98 UB*/ diag:: |
| 4068 | ext_old_implicitly_unsigned_long_cxx |
| 4069 | : diag::warn_old_implicitly_unsigned_long) |
| 4070 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 |
| 4071 | : /*will be ill-formed*/ 1); |
| 4072 | Ty = Context.UnsignedLongTy; |
| 4073 | } |
| 4074 | Width = LongSize; |
| 4075 | } |
| 4076 | } |
| 4077 | |
| 4078 | // Check long long if needed. |
| 4079 | if (Ty.isNull() && !Literal.isSizeT) { |
| 4080 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); |
| 4081 | |
| 4082 | // Does it fit in a unsigned long long? |
| 4083 | if (ResultVal.isIntN(N: LongLongSize)) { |
| 4084 | // Does it fit in a signed long long? |
| 4085 | // To be compatible with MSVC, hex integer literals ending with the |
| 4086 | // LL or i64 suffix are always signed in Microsoft mode. |
| 4087 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || |
| 4088 | (getLangOpts().MSVCCompat && Literal.isLongLong))) |
| 4089 | Ty = Context.LongLongTy; |
| 4090 | else if (AllowUnsigned) |
| 4091 | Ty = Context.UnsignedLongLongTy; |
| 4092 | Width = LongLongSize; |
| 4093 | |
| 4094 | // 'long long' is a C99 or C++11 feature, whether the literal |
| 4095 | // explicitly specified 'long long' or we needed the extra width. |
| 4096 | if (getLangOpts().CPlusPlus) |
| 4097 | Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus11 |
| 4098 | ? diag::warn_cxx98_compat_longlong |
| 4099 | : diag::ext_cxx11_longlong); |
| 4100 | else if (!getLangOpts().C99) |
| 4101 | Diag(Loc: Tok.getLocation(), DiagID: diag::ext_c99_longlong); |
| 4102 | } |
| 4103 | } |
| 4104 | |
| 4105 | // If we still couldn't decide a type, we either have 'size_t' literal |
| 4106 | // that is out of range, or a decimal literal that does not fit in a |
| 4107 | // signed long long and has no U suffix. |
| 4108 | if (Ty.isNull()) { |
| 4109 | if (Literal.isSizeT) |
| 4110 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_size_t_literal_too_large) |
| 4111 | << Literal.isUnsigned; |
| 4112 | else |
| 4113 | Diag(Loc: Tok.getLocation(), |
| 4114 | DiagID: diag::ext_integer_literal_too_large_for_signed); |
| 4115 | Ty = Context.UnsignedLongLongTy; |
| 4116 | Width = Context.getTargetInfo().getLongLongWidth(); |
| 4117 | } |
| 4118 | |
| 4119 | if (ResultVal.getBitWidth() != Width) |
| 4120 | ResultVal = ResultVal.trunc(width: Width); |
| 4121 | } |
| 4122 | Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation()); |
| 4123 | } |
| 4124 | |
| 4125 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. |
| 4126 | if (Literal.isImaginary) { |
| 4127 | Res = new (Context) ImaginaryLiteral(Res, |
| 4128 | Context.getComplexType(T: Res->getType())); |
| 4129 | |
| 4130 | // In C++, this is a GNU extension. In C, it's a C2y extension. |
| 4131 | unsigned DiagId; |
| 4132 | if (getLangOpts().CPlusPlus) |
| 4133 | DiagId = diag::ext_gnu_imaginary_constant; |
| 4134 | else if (getLangOpts().C2y) |
| 4135 | DiagId = diag::warn_c23_compat_imaginary_constant; |
| 4136 | else |
| 4137 | DiagId = diag::ext_c2y_imaginary_constant; |
| 4138 | Diag(Loc: Tok.getLocation(), DiagID: DiagId); |
| 4139 | } |
| 4140 | return Res; |
| 4141 | } |
| 4142 | |
| 4143 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { |
| 4144 | assert(E && "ActOnParenExpr() missing expr" ); |
| 4145 | QualType ExprTy = E->getType(); |
| 4146 | if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && |
| 4147 | !E->isLValue() && ExprTy->hasFloatingRepresentation()) |
| 4148 | return BuildBuiltinCallExpr(Loc: R, Id: Builtin::BI__arithmetic_fence, CallArgs: E); |
| 4149 | return new (Context) ParenExpr(L, R, E); |
| 4150 | } |
| 4151 | |
| 4152 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, |
| 4153 | SourceLocation Loc, |
| 4154 | SourceRange ArgRange) { |
| 4155 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in |
| 4156 | // scalar or vector data type argument..." |
| 4157 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic |
| 4158 | // type (C99 6.2.5p18) or void. |
| 4159 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { |
| 4160 | S.Diag(Loc, DiagID: diag::err_vecstep_non_scalar_vector_type) |
| 4161 | << T << ArgRange; |
| 4162 | return true; |
| 4163 | } |
| 4164 | |
| 4165 | assert((T->isVoidType() || !T->isIncompleteType()) && |
| 4166 | "Scalar types should always be complete" ); |
| 4167 | return false; |
| 4168 | } |
| 4169 | |
| 4170 | static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, |
| 4171 | SourceLocation Loc, |
| 4172 | SourceRange ArgRange) { |
| 4173 | // builtin_vectorelements supports both fixed-sized and scalable vectors. |
| 4174 | if (!T->isVectorType() && !T->isSizelessVectorType()) |
| 4175 | return S.Diag(Loc, DiagID: diag::err_builtin_non_vector_type) |
| 4176 | << "" |
| 4177 | << "__builtin_vectorelements" << T << ArgRange; |
| 4178 | |
| 4179 | return false; |
| 4180 | } |
| 4181 | |
| 4182 | static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, |
| 4183 | SourceLocation Loc, |
| 4184 | SourceRange ArgRange) { |
| 4185 | if (S.checkPointerAuthEnabled(Loc, Range: ArgRange)) |
| 4186 | return true; |
| 4187 | |
| 4188 | if (!T->isFunctionType() && !T->isFunctionPointerType() && |
| 4189 | !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) { |
| 4190 | S.Diag(Loc, DiagID: diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange; |
| 4191 | return true; |
| 4192 | } |
| 4193 | |
| 4194 | return false; |
| 4195 | } |
| 4196 | |
| 4197 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, |
| 4198 | SourceLocation Loc, |
| 4199 | SourceRange ArgRange, |
| 4200 | UnaryExprOrTypeTrait TraitKind) { |
| 4201 | // Invalid types must be hard errors for SFINAE in C++. |
| 4202 | if (S.LangOpts.CPlusPlus) |
| 4203 | return true; |
| 4204 | |
| 4205 | // C99 6.5.3.4p1: |
| 4206 | if (T->isFunctionType() && |
| 4207 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || |
| 4208 | TraitKind == UETT_PreferredAlignOf)) { |
| 4209 | // sizeof(function)/alignof(function) is allowed as an extension. |
| 4210 | S.Diag(Loc, DiagID: diag::ext_sizeof_alignof_function_type) |
| 4211 | << getTraitSpelling(T: TraitKind) << ArgRange; |
| 4212 | return false; |
| 4213 | } |
| 4214 | |
| 4215 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where |
| 4216 | // this is an error (OpenCL v1.1 s6.3.k) |
| 4217 | if (T->isVoidType()) { |
| 4218 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type |
| 4219 | : diag::ext_sizeof_alignof_void_type; |
| 4220 | S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange; |
| 4221 | return false; |
| 4222 | } |
| 4223 | |
| 4224 | return true; |
| 4225 | } |
| 4226 | |
| 4227 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, |
| 4228 | SourceLocation Loc, |
| 4229 | SourceRange ArgRange, |
| 4230 | UnaryExprOrTypeTrait TraitKind) { |
| 4231 | // Reject sizeof(interface) and sizeof(interface<proto>) if the |
| 4232 | // runtime doesn't allow it. |
| 4233 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { |
| 4234 | S.Diag(Loc, DiagID: diag::err_sizeof_nonfragile_interface) |
| 4235 | << T << (TraitKind == UETT_SizeOf) |
| 4236 | << ArgRange; |
| 4237 | return true; |
| 4238 | } |
| 4239 | |
| 4240 | return false; |
| 4241 | } |
| 4242 | |
| 4243 | /// Check whether E is a pointer from a decayed array type (the decayed |
| 4244 | /// pointer type is equal to T) and emit a warning if it is. |
| 4245 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, |
| 4246 | const Expr *E) { |
| 4247 | // Don't warn if the operation changed the type. |
| 4248 | if (T != E->getType()) |
| 4249 | return; |
| 4250 | |
| 4251 | // Now look for array decays. |
| 4252 | const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E); |
| 4253 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) |
| 4254 | return; |
| 4255 | |
| 4256 | S.Diag(Loc, DiagID: diag::warn_sizeof_array_decay) << ICE->getSourceRange() |
| 4257 | << ICE->getType() |
| 4258 | << ICE->getSubExpr()->getType(); |
| 4259 | } |
| 4260 | |
| 4261 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, |
| 4262 | UnaryExprOrTypeTrait ExprKind) { |
| 4263 | QualType ExprTy = E->getType(); |
| 4264 | assert(!ExprTy->isReferenceType()); |
| 4265 | |
| 4266 | bool IsUnevaluatedOperand = |
| 4267 | (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf || |
| 4268 | ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || |
| 4269 | ExprKind == UETT_VecStep || ExprKind == UETT_CountOf); |
| 4270 | if (IsUnevaluatedOperand) { |
| 4271 | ExprResult Result = CheckUnevaluatedOperand(E); |
| 4272 | if (Result.isInvalid()) |
| 4273 | return true; |
| 4274 | E = Result.get(); |
| 4275 | } |
| 4276 | |
| 4277 | // The operand for sizeof and alignof is in an unevaluated expression context, |
| 4278 | // so side effects could result in unintended consequences. |
| 4279 | // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes |
| 4280 | // used to build SFINAE gadgets. |
| 4281 | // FIXME: Should we consider instantiation-dependent operands to 'alignof'? |
| 4282 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && |
| 4283 | !E->isInstantiationDependent() && |
| 4284 | !E->getType()->isVariableArrayType() && |
| 4285 | E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false)) |
| 4286 | Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context); |
| 4287 | |
| 4288 | if (ExprKind == UETT_VecStep) |
| 4289 | return CheckVecStepTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(), |
| 4290 | ArgRange: E->getSourceRange()); |
| 4291 | |
| 4292 | if (ExprKind == UETT_VectorElements) |
| 4293 | return CheckVectorElementsTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(), |
| 4294 | ArgRange: E->getSourceRange()); |
| 4295 | |
| 4296 | // Explicitly list some types as extensions. |
| 4297 | if (!CheckExtensionTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(), |
| 4298 | ArgRange: E->getSourceRange(), TraitKind: ExprKind)) |
| 4299 | return false; |
| 4300 | |
| 4301 | // WebAssembly tables are always illegal operands to unary expressions and |
| 4302 | // type traits. |
| 4303 | if (Context.getTargetInfo().getTriple().isWasm() && |
| 4304 | E->getType()->isWebAssemblyTableType()) { |
| 4305 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_wasm_table_invalid_uett_operand) |
| 4306 | << getTraitSpelling(T: ExprKind); |
| 4307 | return true; |
| 4308 | } |
| 4309 | |
| 4310 | // 'alignof' applied to an expression only requires the base element type of |
| 4311 | // the expression to be complete. 'sizeof' requires the expression's type to |
| 4312 | // be complete (and will attempt to complete it if it's an array of unknown |
| 4313 | // bound). |
| 4314 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { |
| 4315 | if (RequireCompleteSizedType( |
| 4316 | Loc: E->getExprLoc(), T: Context.getBaseElementType(QT: E->getType()), |
| 4317 | DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type, |
| 4318 | Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange())) |
| 4319 | return true; |
| 4320 | } else { |
| 4321 | if (RequireCompleteSizedExprType( |
| 4322 | E, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type, |
| 4323 | Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange())) |
| 4324 | return true; |
| 4325 | } |
| 4326 | |
| 4327 | // Completing the expression's type may have changed it. |
| 4328 | ExprTy = E->getType(); |
| 4329 | assert(!ExprTy->isReferenceType()); |
| 4330 | |
| 4331 | if (ExprTy->isFunctionType()) { |
| 4332 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_function_type) |
| 4333 | << getTraitSpelling(T: ExprKind) << E->getSourceRange(); |
| 4334 | return true; |
| 4335 | } |
| 4336 | |
| 4337 | if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprTy, Loc: E->getExprLoc(), |
| 4338 | ArgRange: E->getSourceRange(), TraitKind: ExprKind)) |
| 4339 | return true; |
| 4340 | |
| 4341 | if (ExprKind == UETT_CountOf) { |
| 4342 | // The type has to be an array type. We already checked for incomplete |
| 4343 | // types above. |
| 4344 | QualType ExprType = E->IgnoreParens()->getType(); |
| 4345 | if (!ExprType->isArrayType()) { |
| 4346 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_countof_arg_not_array_type) << ExprType; |
| 4347 | return true; |
| 4348 | } |
| 4349 | // FIXME: warn on _Countof on an array parameter. Not warning on it |
| 4350 | // currently because there are papers in WG14 about array types which do |
| 4351 | // not decay that could impact this behavior, so we want to see if anything |
| 4352 | // changes here before coming up with a warning group for _Countof-related |
| 4353 | // diagnostics. |
| 4354 | } |
| 4355 | |
| 4356 | if (ExprKind == UETT_SizeOf) { |
| 4357 | if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) { |
| 4358 | if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) { |
| 4359 | QualType OType = PVD->getOriginalType(); |
| 4360 | QualType Type = PVD->getType(); |
| 4361 | if (Type->isPointerType() && OType->isArrayType()) { |
| 4362 | Diag(Loc: E->getExprLoc(), DiagID: diag::warn_sizeof_array_param) |
| 4363 | << Type << OType; |
| 4364 | Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at); |
| 4365 | } |
| 4366 | } |
| 4367 | } |
| 4368 | |
| 4369 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array |
| 4370 | // decays into a pointer and returns an unintended result. This is most |
| 4371 | // likely a typo for "sizeof(array) op x". |
| 4372 | if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) { |
| 4373 | warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(), |
| 4374 | E: BO->getLHS()); |
| 4375 | warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(), |
| 4376 | E: BO->getRHS()); |
| 4377 | } |
| 4378 | } |
| 4379 | |
| 4380 | return false; |
| 4381 | } |
| 4382 | |
| 4383 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { |
| 4384 | // Cannot know anything else if the expression is dependent. |
| 4385 | if (E->isTypeDependent()) |
| 4386 | return false; |
| 4387 | |
| 4388 | if (E->getObjectKind() == OK_BitField) { |
| 4389 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) |
| 4390 | << 1 << E->getSourceRange(); |
| 4391 | return true; |
| 4392 | } |
| 4393 | |
| 4394 | ValueDecl *D = nullptr; |
| 4395 | Expr *Inner = E->IgnoreParens(); |
| 4396 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) { |
| 4397 | D = DRE->getDecl(); |
| 4398 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) { |
| 4399 | D = ME->getMemberDecl(); |
| 4400 | } |
| 4401 | |
| 4402 | // If it's a field, require the containing struct to have a |
| 4403 | // complete definition so that we can compute the layout. |
| 4404 | // |
| 4405 | // This can happen in C++11 onwards, either by naming the member |
| 4406 | // in a way that is not transformed into a member access expression |
| 4407 | // (in an unevaluated operand, for instance), or by naming the member |
| 4408 | // in a trailing-return-type. |
| 4409 | // |
| 4410 | // For the record, since __alignof__ on expressions is a GCC |
| 4411 | // extension, GCC seems to permit this but always gives the |
| 4412 | // nonsensical answer 0. |
| 4413 | // |
| 4414 | // We don't really need the layout here --- we could instead just |
| 4415 | // directly check for all the appropriate alignment-lowing |
| 4416 | // attributes --- but that would require duplicating a lot of |
| 4417 | // logic that just isn't worth duplicating for such a marginal |
| 4418 | // use-case. |
| 4419 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) { |
| 4420 | // Fast path this check, since we at least know the record has a |
| 4421 | // definition if we can find a member of it. |
| 4422 | if (!FD->getParent()->isCompleteDefinition()) { |
| 4423 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_alignof_member_of_incomplete_type) |
| 4424 | << E->getSourceRange(); |
| 4425 | return true; |
| 4426 | } |
| 4427 | |
| 4428 | // Otherwise, if it's a field, and the field doesn't have |
| 4429 | // reference type, then it must have a complete type (or be a |
| 4430 | // flexible array member, which we explicitly want to |
| 4431 | // white-list anyway), which makes the following checks trivial. |
| 4432 | if (!FD->getType()->isReferenceType()) |
| 4433 | return false; |
| 4434 | } |
| 4435 | |
| 4436 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); |
| 4437 | } |
| 4438 | |
| 4439 | bool Sema::CheckVecStepExpr(Expr *E) { |
| 4440 | E = E->IgnoreParens(); |
| 4441 | |
| 4442 | // Cannot know anything else if the expression is dependent. |
| 4443 | if (E->isTypeDependent()) |
| 4444 | return false; |
| 4445 | |
| 4446 | return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep); |
| 4447 | } |
| 4448 | |
| 4449 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, |
| 4450 | CapturingScopeInfo *CSI) { |
| 4451 | assert(T->isVariablyModifiedType()); |
| 4452 | assert(CSI != nullptr); |
| 4453 | |
| 4454 | // We're going to walk down into the type and look for VLA expressions. |
| 4455 | do { |
| 4456 | const Type *Ty = T.getTypePtr(); |
| 4457 | switch (Ty->getTypeClass()) { |
| 4458 | #define TYPE(Class, Base) |
| 4459 | #define ABSTRACT_TYPE(Class, Base) |
| 4460 | #define NON_CANONICAL_TYPE(Class, Base) |
| 4461 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: |
| 4462 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) |
| 4463 | #include "clang/AST/TypeNodes.inc" |
| 4464 | T = QualType(); |
| 4465 | break; |
| 4466 | // These types are never variably-modified. |
| 4467 | case Type::Builtin: |
| 4468 | case Type::Complex: |
| 4469 | case Type::Vector: |
| 4470 | case Type::ExtVector: |
| 4471 | case Type::ConstantMatrix: |
| 4472 | case Type::Record: |
| 4473 | case Type::Enum: |
| 4474 | case Type::TemplateSpecialization: |
| 4475 | case Type::ObjCObject: |
| 4476 | case Type::ObjCInterface: |
| 4477 | case Type::ObjCObjectPointer: |
| 4478 | case Type::ObjCTypeParam: |
| 4479 | case Type::Pipe: |
| 4480 | case Type::BitInt: |
| 4481 | case Type::HLSLInlineSpirv: |
| 4482 | llvm_unreachable("type class is never variably-modified!" ); |
| 4483 | case Type::Elaborated: |
| 4484 | T = cast<ElaboratedType>(Val: Ty)->getNamedType(); |
| 4485 | break; |
| 4486 | case Type::Adjusted: |
| 4487 | T = cast<AdjustedType>(Val: Ty)->getOriginalType(); |
| 4488 | break; |
| 4489 | case Type::Decayed: |
| 4490 | T = cast<DecayedType>(Val: Ty)->getPointeeType(); |
| 4491 | break; |
| 4492 | case Type::ArrayParameter: |
| 4493 | T = cast<ArrayParameterType>(Val: Ty)->getElementType(); |
| 4494 | break; |
| 4495 | case Type::Pointer: |
| 4496 | T = cast<PointerType>(Val: Ty)->getPointeeType(); |
| 4497 | break; |
| 4498 | case Type::BlockPointer: |
| 4499 | T = cast<BlockPointerType>(Val: Ty)->getPointeeType(); |
| 4500 | break; |
| 4501 | case Type::LValueReference: |
| 4502 | case Type::RValueReference: |
| 4503 | T = cast<ReferenceType>(Val: Ty)->getPointeeType(); |
| 4504 | break; |
| 4505 | case Type::MemberPointer: |
| 4506 | T = cast<MemberPointerType>(Val: Ty)->getPointeeType(); |
| 4507 | break; |
| 4508 | case Type::ConstantArray: |
| 4509 | case Type::IncompleteArray: |
| 4510 | // Losing element qualification here is fine. |
| 4511 | T = cast<ArrayType>(Val: Ty)->getElementType(); |
| 4512 | break; |
| 4513 | case Type::VariableArray: { |
| 4514 | // Losing element qualification here is fine. |
| 4515 | const VariableArrayType *VAT = cast<VariableArrayType>(Val: Ty); |
| 4516 | |
| 4517 | // Unknown size indication requires no size computation. |
| 4518 | // Otherwise, evaluate and record it. |
| 4519 | auto Size = VAT->getSizeExpr(); |
| 4520 | if (Size && !CSI->isVLATypeCaptured(VAT) && |
| 4521 | (isa<CapturedRegionScopeInfo>(Val: CSI) || isa<LambdaScopeInfo>(Val: CSI))) |
| 4522 | CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType()); |
| 4523 | |
| 4524 | T = VAT->getElementType(); |
| 4525 | break; |
| 4526 | } |
| 4527 | case Type::FunctionProto: |
| 4528 | case Type::FunctionNoProto: |
| 4529 | T = cast<FunctionType>(Val: Ty)->getReturnType(); |
| 4530 | break; |
| 4531 | case Type::Paren: |
| 4532 | case Type::TypeOf: |
| 4533 | case Type::UnaryTransform: |
| 4534 | case Type::Attributed: |
| 4535 | case Type::BTFTagAttributed: |
| 4536 | case Type::HLSLAttributedResource: |
| 4537 | case Type::SubstTemplateTypeParm: |
| 4538 | case Type::MacroQualified: |
| 4539 | case Type::CountAttributed: |
| 4540 | // Keep walking after single level desugaring. |
| 4541 | T = T.getSingleStepDesugaredType(Context); |
| 4542 | break; |
| 4543 | case Type::Typedef: |
| 4544 | T = cast<TypedefType>(Val: Ty)->desugar(); |
| 4545 | break; |
| 4546 | case Type::Decltype: |
| 4547 | T = cast<DecltypeType>(Val: Ty)->desugar(); |
| 4548 | break; |
| 4549 | case Type::PackIndexing: |
| 4550 | T = cast<PackIndexingType>(Val: Ty)->desugar(); |
| 4551 | break; |
| 4552 | case Type::Using: |
| 4553 | T = cast<UsingType>(Val: Ty)->desugar(); |
| 4554 | break; |
| 4555 | case Type::Auto: |
| 4556 | case Type::DeducedTemplateSpecialization: |
| 4557 | T = cast<DeducedType>(Val: Ty)->getDeducedType(); |
| 4558 | break; |
| 4559 | case Type::TypeOfExpr: |
| 4560 | T = cast<TypeOfExprType>(Val: Ty)->getUnderlyingExpr()->getType(); |
| 4561 | break; |
| 4562 | case Type::Atomic: |
| 4563 | T = cast<AtomicType>(Val: Ty)->getValueType(); |
| 4564 | break; |
| 4565 | } |
| 4566 | } while (!T.isNull() && T->isVariablyModifiedType()); |
| 4567 | } |
| 4568 | |
| 4569 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, |
| 4570 | SourceLocation OpLoc, |
| 4571 | SourceRange ExprRange, |
| 4572 | UnaryExprOrTypeTrait ExprKind, |
| 4573 | StringRef KWName) { |
| 4574 | if (ExprType->isDependentType()) |
| 4575 | return false; |
| 4576 | |
| 4577 | // C++ [expr.sizeof]p2: |
| 4578 | // When applied to a reference or a reference type, the result |
| 4579 | // is the size of the referenced type. |
| 4580 | // C++11 [expr.alignof]p3: |
| 4581 | // When alignof is applied to a reference type, the result |
| 4582 | // shall be the alignment of the referenced type. |
| 4583 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) |
| 4584 | ExprType = Ref->getPointeeType(); |
| 4585 | |
| 4586 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: |
| 4587 | // When alignof or _Alignof is applied to an array type, the result |
| 4588 | // is the alignment of the element type. |
| 4589 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || |
| 4590 | ExprKind == UETT_OpenMPRequiredSimdAlign) { |
| 4591 | // If the trait is 'alignof' in C before C2y, the ability to apply the |
| 4592 | // trait to an incomplete array is an extension. |
| 4593 | if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus && |
| 4594 | ExprType->isIncompleteArrayType()) |
| 4595 | Diag(Loc: OpLoc, DiagID: getLangOpts().C2y |
| 4596 | ? diag::warn_c2y_compat_alignof_incomplete_array |
| 4597 | : diag::ext_c2y_alignof_incomplete_array); |
| 4598 | ExprType = Context.getBaseElementType(QT: ExprType); |
| 4599 | } |
| 4600 | |
| 4601 | if (ExprKind == UETT_VecStep) |
| 4602 | return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange); |
| 4603 | |
| 4604 | if (ExprKind == UETT_VectorElements) |
| 4605 | return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, |
| 4606 | ArgRange: ExprRange); |
| 4607 | |
| 4608 | if (ExprKind == UETT_PtrAuthTypeDiscriminator) |
| 4609 | return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc, |
| 4610 | ArgRange: ExprRange); |
| 4611 | |
| 4612 | // Explicitly list some types as extensions. |
| 4613 | if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange, |
| 4614 | TraitKind: ExprKind)) |
| 4615 | return false; |
| 4616 | |
| 4617 | if (RequireCompleteSizedType( |
| 4618 | Loc: OpLoc, T: ExprType, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type, |
| 4619 | Args: KWName, Args: ExprRange)) |
| 4620 | return true; |
| 4621 | |
| 4622 | if (ExprType->isFunctionType()) { |
| 4623 | Diag(Loc: OpLoc, DiagID: diag::err_sizeof_alignof_function_type) << KWName << ExprRange; |
| 4624 | return true; |
| 4625 | } |
| 4626 | |
| 4627 | if (ExprKind == UETT_CountOf) { |
| 4628 | // The type has to be an array type. We already checked for incomplete |
| 4629 | // types above. |
| 4630 | if (!ExprType->isArrayType()) { |
| 4631 | Diag(Loc: OpLoc, DiagID: diag::err_countof_arg_not_array_type) << ExprType; |
| 4632 | return true; |
| 4633 | } |
| 4634 | } |
| 4635 | |
| 4636 | // WebAssembly tables are always illegal operands to unary expressions and |
| 4637 | // type traits. |
| 4638 | if (Context.getTargetInfo().getTriple().isWasm() && |
| 4639 | ExprType->isWebAssemblyTableType()) { |
| 4640 | Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_invalid_uett_operand) |
| 4641 | << getTraitSpelling(T: ExprKind); |
| 4642 | return true; |
| 4643 | } |
| 4644 | |
| 4645 | if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange, |
| 4646 | TraitKind: ExprKind)) |
| 4647 | return true; |
| 4648 | |
| 4649 | if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) { |
| 4650 | if (auto *TT = ExprType->getAs<TypedefType>()) { |
| 4651 | for (auto I = FunctionScopes.rbegin(), |
| 4652 | E = std::prev(x: FunctionScopes.rend()); |
| 4653 | I != E; ++I) { |
| 4654 | auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I); |
| 4655 | if (CSI == nullptr) |
| 4656 | break; |
| 4657 | DeclContext *DC = nullptr; |
| 4658 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI)) |
| 4659 | DC = LSI->CallOperator; |
| 4660 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) |
| 4661 | DC = CRSI->TheCapturedDecl; |
| 4662 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) |
| 4663 | DC = BSI->TheDecl; |
| 4664 | if (DC) { |
| 4665 | if (DC->containsDecl(D: TT->getDecl())) |
| 4666 | break; |
| 4667 | captureVariablyModifiedType(Context, T: ExprType, CSI); |
| 4668 | } |
| 4669 | } |
| 4670 | } |
| 4671 | } |
| 4672 | |
| 4673 | return false; |
| 4674 | } |
| 4675 | |
| 4676 | ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, |
| 4677 | SourceLocation OpLoc, |
| 4678 | UnaryExprOrTypeTrait ExprKind, |
| 4679 | SourceRange R) { |
| 4680 | if (!TInfo) |
| 4681 | return ExprError(); |
| 4682 | |
| 4683 | QualType T = TInfo->getType(); |
| 4684 | |
| 4685 | if (!T->isDependentType() && |
| 4686 | CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind, |
| 4687 | KWName: getTraitSpelling(T: ExprKind))) |
| 4688 | return ExprError(); |
| 4689 | |
| 4690 | // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to |
| 4691 | // properly deal with VLAs in nested calls of sizeof and typeof. |
| 4692 | if (currentEvaluationContext().isUnevaluated() && |
| 4693 | currentEvaluationContext().InConditionallyConstantEvaluateContext && |
| 4694 | (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) && |
| 4695 | TInfo->getType()->isVariablyModifiedType()) |
| 4696 | TInfo = TransformToPotentiallyEvaluated(TInfo); |
| 4697 | |
| 4698 | // It's possible that the transformation above failed. |
| 4699 | if (!TInfo) |
| 4700 | return ExprError(); |
| 4701 | |
| 4702 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. |
| 4703 | return new (Context) UnaryExprOrTypeTraitExpr( |
| 4704 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); |
| 4705 | } |
| 4706 | |
| 4707 | ExprResult |
| 4708 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, |
| 4709 | UnaryExprOrTypeTrait ExprKind) { |
| 4710 | ExprResult PE = CheckPlaceholderExpr(E); |
| 4711 | if (PE.isInvalid()) |
| 4712 | return ExprError(); |
| 4713 | |
| 4714 | E = PE.get(); |
| 4715 | |
| 4716 | // Verify that the operand is valid. |
| 4717 | bool isInvalid = false; |
| 4718 | if (E->isTypeDependent()) { |
| 4719 | // Delay type-checking for type-dependent expressions. |
| 4720 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { |
| 4721 | isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind); |
| 4722 | } else if (ExprKind == UETT_VecStep) { |
| 4723 | isInvalid = CheckVecStepExpr(E); |
| 4724 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { |
| 4725 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_openmp_default_simd_align_expr); |
| 4726 | isInvalid = true; |
| 4727 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. |
| 4728 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) << 0; |
| 4729 | isInvalid = true; |
| 4730 | } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf || |
| 4731 | ExprKind == UETT_CountOf) { // FIXME: __datasizeof? |
| 4732 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind); |
| 4733 | } |
| 4734 | |
| 4735 | if (isInvalid) |
| 4736 | return ExprError(); |
| 4737 | |
| 4738 | if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) && |
| 4739 | E->getType()->isVariableArrayType()) { |
| 4740 | PE = TransformToPotentiallyEvaluated(E); |
| 4741 | if (PE.isInvalid()) return ExprError(); |
| 4742 | E = PE.get(); |
| 4743 | } |
| 4744 | |
| 4745 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. |
| 4746 | return new (Context) UnaryExprOrTypeTraitExpr( |
| 4747 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); |
| 4748 | } |
| 4749 | |
| 4750 | ExprResult |
| 4751 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, |
| 4752 | UnaryExprOrTypeTrait ExprKind, bool IsType, |
| 4753 | void *TyOrEx, SourceRange ArgRange) { |
| 4754 | // If error parsing type, ignore. |
| 4755 | if (!TyOrEx) return ExprError(); |
| 4756 | |
| 4757 | if (IsType) { |
| 4758 | TypeSourceInfo *TInfo; |
| 4759 | (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo); |
| 4760 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange); |
| 4761 | } |
| 4762 | |
| 4763 | Expr *ArgEx = (Expr *)TyOrEx; |
| 4764 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind); |
| 4765 | return Result; |
| 4766 | } |
| 4767 | |
| 4768 | bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, |
| 4769 | SourceLocation OpLoc, SourceRange R) { |
| 4770 | if (!TInfo) |
| 4771 | return true; |
| 4772 | return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R, |
| 4773 | ExprKind: UETT_AlignOf, KWName); |
| 4774 | } |
| 4775 | |
| 4776 | bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, |
| 4777 | SourceLocation OpLoc, SourceRange R) { |
| 4778 | TypeSourceInfo *TInfo; |
| 4779 | (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()), |
| 4780 | TInfo: &TInfo); |
| 4781 | return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R); |
| 4782 | } |
| 4783 | |
| 4784 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, |
| 4785 | bool IsReal) { |
| 4786 | if (V.get()->isTypeDependent()) |
| 4787 | return S.Context.DependentTy; |
| 4788 | |
| 4789 | // _Real and _Imag are only l-values for normal l-values. |
| 4790 | if (V.get()->getObjectKind() != OK_Ordinary) { |
| 4791 | V = S.DefaultLvalueConversion(E: V.get()); |
| 4792 | if (V.isInvalid()) |
| 4793 | return QualType(); |
| 4794 | } |
| 4795 | |
| 4796 | // These operators return the element type of a complex type. |
| 4797 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) |
| 4798 | return CT->getElementType(); |
| 4799 | |
| 4800 | // Otherwise they pass through real integer and floating point types here. |
| 4801 | if (V.get()->getType()->isArithmeticType()) |
| 4802 | return V.get()->getType(); |
| 4803 | |
| 4804 | // Test for placeholders. |
| 4805 | ExprResult PR = S.CheckPlaceholderExpr(E: V.get()); |
| 4806 | if (PR.isInvalid()) return QualType(); |
| 4807 | if (PR.get() != V.get()) { |
| 4808 | V = PR; |
| 4809 | return CheckRealImagOperand(S, V, Loc, IsReal); |
| 4810 | } |
| 4811 | |
| 4812 | // Reject anything else. |
| 4813 | S.Diag(Loc, DiagID: diag::err_realimag_invalid_type) << V.get()->getType() |
| 4814 | << (IsReal ? "__real" : "__imag" ); |
| 4815 | return QualType(); |
| 4816 | } |
| 4817 | |
| 4818 | |
| 4819 | |
| 4820 | ExprResult |
| 4821 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, |
| 4822 | tok::TokenKind Kind, Expr *Input) { |
| 4823 | UnaryOperatorKind Opc; |
| 4824 | switch (Kind) { |
| 4825 | default: llvm_unreachable("Unknown unary op!" ); |
| 4826 | case tok::plusplus: Opc = UO_PostInc; break; |
| 4827 | case tok::minusminus: Opc = UO_PostDec; break; |
| 4828 | } |
| 4829 | |
| 4830 | // Since this might is a postfix expression, get rid of ParenListExprs. |
| 4831 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input); |
| 4832 | if (Result.isInvalid()) return ExprError(); |
| 4833 | Input = Result.get(); |
| 4834 | |
| 4835 | return BuildUnaryOp(S, OpLoc, Opc, Input); |
| 4836 | } |
| 4837 | |
| 4838 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. |
| 4839 | /// |
| 4840 | /// \return true on error |
| 4841 | static bool checkArithmeticOnObjCPointer(Sema &S, |
| 4842 | SourceLocation opLoc, |
| 4843 | Expr *op) { |
| 4844 | assert(op->getType()->isObjCObjectPointerType()); |
| 4845 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && |
| 4846 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) |
| 4847 | return false; |
| 4848 | |
| 4849 | S.Diag(Loc: opLoc, DiagID: diag::err_arithmetic_nonfragile_interface) |
| 4850 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() |
| 4851 | << op->getSourceRange(); |
| 4852 | return true; |
| 4853 | } |
| 4854 | |
| 4855 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { |
| 4856 | auto *BaseNoParens = Base->IgnoreParens(); |
| 4857 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens)) |
| 4858 | return MSProp->getPropertyDecl()->getType()->isArrayType(); |
| 4859 | return isa<MSPropertySubscriptExpr>(Val: BaseNoParens); |
| 4860 | } |
| 4861 | |
| 4862 | // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. |
| 4863 | // Typically this is DependentTy, but can sometimes be more precise. |
| 4864 | // |
| 4865 | // There are cases when we could determine a non-dependent type: |
| 4866 | // - LHS and RHS may have non-dependent types despite being type-dependent |
| 4867 | // (e.g. unbounded array static members of the current instantiation) |
| 4868 | // - one may be a dependent-sized array with known element type |
| 4869 | // - one may be a dependent-typed valid index (enum in current instantiation) |
| 4870 | // |
| 4871 | // We *always* return a dependent type, in such cases it is DependentTy. |
| 4872 | // This avoids creating type-dependent expressions with non-dependent types. |
| 4873 | // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 |
| 4874 | static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, |
| 4875 | const ASTContext &Ctx) { |
| 4876 | assert(LHS->isTypeDependent() || RHS->isTypeDependent()); |
| 4877 | QualType LTy = LHS->getType(), RTy = RHS->getType(); |
| 4878 | QualType Result = Ctx.DependentTy; |
| 4879 | if (RTy->isIntegralOrUnscopedEnumerationType()) { |
| 4880 | if (const PointerType *PT = LTy->getAs<PointerType>()) |
| 4881 | Result = PT->getPointeeType(); |
| 4882 | else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) |
| 4883 | Result = AT->getElementType(); |
| 4884 | } else if (LTy->isIntegralOrUnscopedEnumerationType()) { |
| 4885 | if (const PointerType *PT = RTy->getAs<PointerType>()) |
| 4886 | Result = PT->getPointeeType(); |
| 4887 | else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) |
| 4888 | Result = AT->getElementType(); |
| 4889 | } |
| 4890 | // Ensure we return a dependent type. |
| 4891 | return Result->isDependentType() ? Result : Ctx.DependentTy; |
| 4892 | } |
| 4893 | |
| 4894 | ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, |
| 4895 | SourceLocation lbLoc, |
| 4896 | MultiExprArg ArgExprs, |
| 4897 | SourceLocation rbLoc) { |
| 4898 | |
| 4899 | if (base && !base->getType().isNull() && |
| 4900 | base->hasPlaceholderType(K: BuiltinType::ArraySection)) { |
| 4901 | auto *AS = cast<ArraySectionExpr>(Val: base); |
| 4902 | if (AS->isOMPArraySection()) |
| 4903 | return OpenMP().ActOnOMPArraySectionExpr( |
| 4904 | Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(), |
| 4905 | /*Length*/ nullptr, |
| 4906 | /*Stride=*/nullptr, RBLoc: rbLoc); |
| 4907 | |
| 4908 | return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), |
| 4909 | ColonLocFirst: SourceLocation(), /*Length*/ nullptr, |
| 4910 | RBLoc: rbLoc); |
| 4911 | } |
| 4912 | |
| 4913 | // Since this might be a postfix expression, get rid of ParenListExprs. |
| 4914 | if (isa<ParenListExpr>(Val: base)) { |
| 4915 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base); |
| 4916 | if (result.isInvalid()) |
| 4917 | return ExprError(); |
| 4918 | base = result.get(); |
| 4919 | } |
| 4920 | |
| 4921 | // Check if base and idx form a MatrixSubscriptExpr. |
| 4922 | // |
| 4923 | // Helper to check for comma expressions, which are not allowed as indices for |
| 4924 | // matrix subscript expressions. |
| 4925 | auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { |
| 4926 | if (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp()) { |
| 4927 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_matrix_subscript_comma) |
| 4928 | << SourceRange(base->getBeginLoc(), rbLoc); |
| 4929 | return true; |
| 4930 | } |
| 4931 | return false; |
| 4932 | }; |
| 4933 | // The matrix subscript operator ([][])is considered a single operator. |
| 4934 | // Separating the index expressions by parenthesis is not allowed. |
| 4935 | if (base && !base->getType().isNull() && |
| 4936 | base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) && |
| 4937 | !isa<MatrixSubscriptExpr>(Val: base)) { |
| 4938 | Diag(Loc: base->getExprLoc(), DiagID: diag::err_matrix_separate_incomplete_index) |
| 4939 | << SourceRange(base->getBeginLoc(), rbLoc); |
| 4940 | return ExprError(); |
| 4941 | } |
| 4942 | // If the base is a MatrixSubscriptExpr, try to create a new |
| 4943 | // MatrixSubscriptExpr. |
| 4944 | auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base); |
| 4945 | if (matSubscriptE) { |
| 4946 | assert(ArgExprs.size() == 1); |
| 4947 | if (CheckAndReportCommaError(ArgExprs.front())) |
| 4948 | return ExprError(); |
| 4949 | |
| 4950 | assert(matSubscriptE->isIncomplete() && |
| 4951 | "base has to be an incomplete matrix subscript" ); |
| 4952 | return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(), |
| 4953 | RowIdx: matSubscriptE->getRowIdx(), |
| 4954 | ColumnIdx: ArgExprs.front(), RBLoc: rbLoc); |
| 4955 | } |
| 4956 | if (base->getType()->isWebAssemblyTableType()) { |
| 4957 | Diag(Loc: base->getExprLoc(), DiagID: diag::err_wasm_table_art) |
| 4958 | << SourceRange(base->getBeginLoc(), rbLoc) << 3; |
| 4959 | return ExprError(); |
| 4960 | } |
| 4961 | |
| 4962 | CheckInvalidBuiltinCountedByRef(E: base, |
| 4963 | K: BuiltinCountedByRefKind::ArraySubscript); |
| 4964 | |
| 4965 | // Handle any non-overload placeholder types in the base and index |
| 4966 | // expressions. We can't handle overloads here because the other |
| 4967 | // operand might be an overloadable type, in which case the overload |
| 4968 | // resolution for the operator overload should get the first crack |
| 4969 | // at the overload. |
| 4970 | bool IsMSPropertySubscript = false; |
| 4971 | if (base->getType()->isNonOverloadPlaceholderType()) { |
| 4972 | IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base); |
| 4973 | if (!IsMSPropertySubscript) { |
| 4974 | ExprResult result = CheckPlaceholderExpr(E: base); |
| 4975 | if (result.isInvalid()) |
| 4976 | return ExprError(); |
| 4977 | base = result.get(); |
| 4978 | } |
| 4979 | } |
| 4980 | |
| 4981 | // If the base is a matrix type, try to create a new MatrixSubscriptExpr. |
| 4982 | if (base->getType()->isMatrixType()) { |
| 4983 | assert(ArgExprs.size() == 1); |
| 4984 | if (CheckAndReportCommaError(ArgExprs.front())) |
| 4985 | return ExprError(); |
| 4986 | |
| 4987 | return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr, |
| 4988 | RBLoc: rbLoc); |
| 4989 | } |
| 4990 | |
| 4991 | if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { |
| 4992 | Expr *idx = ArgExprs[0]; |
| 4993 | if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) || |
| 4994 | (isa<CXXOperatorCallExpr>(Val: idx) && |
| 4995 | cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) { |
| 4996 | Diag(Loc: idx->getExprLoc(), DiagID: diag::warn_deprecated_comma_subscript) |
| 4997 | << SourceRange(base->getBeginLoc(), rbLoc); |
| 4998 | } |
| 4999 | } |
| 5000 | |
| 5001 | if (ArgExprs.size() == 1 && |
| 5002 | ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { |
| 5003 | ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]); |
| 5004 | if (result.isInvalid()) |
| 5005 | return ExprError(); |
| 5006 | ArgExprs[0] = result.get(); |
| 5007 | } else { |
| 5008 | if (CheckArgsForPlaceholders(args: ArgExprs)) |
| 5009 | return ExprError(); |
| 5010 | } |
| 5011 | |
| 5012 | // Build an unanalyzed expression if either operand is type-dependent. |
| 5013 | if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && |
| 5014 | (base->isTypeDependent() || |
| 5015 | Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) && |
| 5016 | !isa<PackExpansionExpr>(Val: ArgExprs[0])) { |
| 5017 | return new (Context) ArraySubscriptExpr( |
| 5018 | base, ArgExprs.front(), |
| 5019 | getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()), |
| 5020 | VK_LValue, OK_Ordinary, rbLoc); |
| 5021 | } |
| 5022 | |
| 5023 | // MSDN, property (C++) |
| 5024 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx |
| 5025 | // This attribute can also be used in the declaration of an empty array in a |
| 5026 | // class or structure definition. For example: |
| 5027 | // __declspec(property(get=GetX, put=PutX)) int x[]; |
| 5028 | // The above statement indicates that x[] can be used with one or more array |
| 5029 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), |
| 5030 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); |
| 5031 | if (IsMSPropertySubscript) { |
| 5032 | assert(ArgExprs.size() == 1); |
| 5033 | // Build MS property subscript expression if base is MS property reference |
| 5034 | // or MS property subscript. |
| 5035 | return new (Context) |
| 5036 | MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, |
| 5037 | VK_LValue, OK_Ordinary, rbLoc); |
| 5038 | } |
| 5039 | |
| 5040 | // Use C++ overloaded-operator rules if either operand has record |
| 5041 | // type. The spec says to do this if either type is *overloadable*, |
| 5042 | // but enum types can't declare subscript operators or conversion |
| 5043 | // operators, so there's nothing interesting for overload resolution |
| 5044 | // to do if there aren't any record types involved. |
| 5045 | // |
| 5046 | // ObjC pointers have their own subscripting logic that is not tied |
| 5047 | // to overload resolution and so should not take this path. |
| 5048 | if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && |
| 5049 | ((base->getType()->isRecordType() || |
| 5050 | (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) || |
| 5051 | ArgExprs[0]->getType()->isRecordType())))) { |
| 5052 | return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs); |
| 5053 | } |
| 5054 | |
| 5055 | ExprResult Res = |
| 5056 | CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc); |
| 5057 | |
| 5058 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get())) |
| 5059 | CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get())); |
| 5060 | |
| 5061 | return Res; |
| 5062 | } |
| 5063 | |
| 5064 | ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { |
| 5065 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty); |
| 5066 | InitializationKind Kind = |
| 5067 | InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation()); |
| 5068 | InitializationSequence InitSeq(*this, Entity, Kind, E); |
| 5069 | return InitSeq.Perform(S&: *this, Entity, Kind, Args: E); |
| 5070 | } |
| 5071 | |
| 5072 | ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, |
| 5073 | Expr *ColumnIdx, |
| 5074 | SourceLocation RBLoc) { |
| 5075 | ExprResult BaseR = CheckPlaceholderExpr(E: Base); |
| 5076 | if (BaseR.isInvalid()) |
| 5077 | return BaseR; |
| 5078 | Base = BaseR.get(); |
| 5079 | |
| 5080 | ExprResult RowR = CheckPlaceholderExpr(E: RowIdx); |
| 5081 | if (RowR.isInvalid()) |
| 5082 | return RowR; |
| 5083 | RowIdx = RowR.get(); |
| 5084 | |
| 5085 | if (!ColumnIdx) |
| 5086 | return new (Context) MatrixSubscriptExpr( |
| 5087 | Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); |
| 5088 | |
| 5089 | // Build an unanalyzed expression if any of the operands is type-dependent. |
| 5090 | if (Base->isTypeDependent() || RowIdx->isTypeDependent() || |
| 5091 | ColumnIdx->isTypeDependent()) |
| 5092 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, |
| 5093 | Context.DependentTy, RBLoc); |
| 5094 | |
| 5095 | ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx); |
| 5096 | if (ColumnR.isInvalid()) |
| 5097 | return ColumnR; |
| 5098 | ColumnIdx = ColumnR.get(); |
| 5099 | |
| 5100 | // Check that IndexExpr is an integer expression. If it is a constant |
| 5101 | // expression, check that it is less than Dim (= the number of elements in the |
| 5102 | // corresponding dimension). |
| 5103 | auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, |
| 5104 | bool IsColumnIdx) -> Expr * { |
| 5105 | if (!IndexExpr->getType()->isIntegerType() && |
| 5106 | !IndexExpr->isTypeDependent()) { |
| 5107 | Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer) |
| 5108 | << IsColumnIdx; |
| 5109 | return nullptr; |
| 5110 | } |
| 5111 | |
| 5112 | if (std::optional<llvm::APSInt> Idx = |
| 5113 | IndexExpr->getIntegerConstantExpr(Ctx: Context)) { |
| 5114 | if ((*Idx < 0 || *Idx >= Dim)) { |
| 5115 | Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range) |
| 5116 | << IsColumnIdx << Dim; |
| 5117 | return nullptr; |
| 5118 | } |
| 5119 | } |
| 5120 | |
| 5121 | ExprResult ConvExpr = IndexExpr; |
| 5122 | assert(!ConvExpr.isInvalid() && |
| 5123 | "should be able to convert any integer type to size type" ); |
| 5124 | return ConvExpr.get(); |
| 5125 | }; |
| 5126 | |
| 5127 | auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); |
| 5128 | RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); |
| 5129 | ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); |
| 5130 | if (!RowIdx || !ColumnIdx) |
| 5131 | return ExprError(); |
| 5132 | |
| 5133 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, |
| 5134 | MTy->getElementType(), RBLoc); |
| 5135 | } |
| 5136 | |
| 5137 | void Sema::CheckAddressOfNoDeref(const Expr *E) { |
| 5138 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); |
| 5139 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); |
| 5140 | |
| 5141 | // For expressions like `&(*s).b`, the base is recorded and what should be |
| 5142 | // checked. |
| 5143 | const MemberExpr *Member = nullptr; |
| 5144 | while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow()) |
| 5145 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); |
| 5146 | |
| 5147 | LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr); |
| 5148 | } |
| 5149 | |
| 5150 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { |
| 5151 | if (isUnevaluatedContext()) |
| 5152 | return; |
| 5153 | |
| 5154 | QualType ResultTy = E->getType(); |
| 5155 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); |
| 5156 | |
| 5157 | // Bail if the element is an array since it is not memory access. |
| 5158 | if (isa<ArrayType>(Val: ResultTy)) |
| 5159 | return; |
| 5160 | |
| 5161 | if (ResultTy->hasAttr(AK: attr::NoDeref)) { |
| 5162 | LastRecord.PossibleDerefs.insert(Ptr: E); |
| 5163 | return; |
| 5164 | } |
| 5165 | |
| 5166 | // Check if the base type is a pointer to a member access of a struct |
| 5167 | // marked with noderef. |
| 5168 | const Expr *Base = E->getBase(); |
| 5169 | QualType BaseTy = Base->getType(); |
| 5170 | if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy))) |
| 5171 | // Not a pointer access |
| 5172 | return; |
| 5173 | |
| 5174 | const MemberExpr *Member = nullptr; |
| 5175 | while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) && |
| 5176 | Member->isArrow()) |
| 5177 | Base = Member->getBase(); |
| 5178 | |
| 5179 | if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) { |
| 5180 | if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref)) |
| 5181 | LastRecord.PossibleDerefs.insert(Ptr: E); |
| 5182 | } |
| 5183 | } |
| 5184 | |
| 5185 | ExprResult |
| 5186 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, |
| 5187 | Expr *Idx, SourceLocation RLoc) { |
| 5188 | Expr *LHSExp = Base; |
| 5189 | Expr *RHSExp = Idx; |
| 5190 | |
| 5191 | ExprValueKind VK = VK_LValue; |
| 5192 | ExprObjectKind OK = OK_Ordinary; |
| 5193 | |
| 5194 | // Per C++ core issue 1213, the result is an xvalue if either operand is |
| 5195 | // a non-lvalue array, and an lvalue otherwise. |
| 5196 | if (getLangOpts().CPlusPlus11) { |
| 5197 | for (auto *Op : {LHSExp, RHSExp}) { |
| 5198 | Op = Op->IgnoreImplicit(); |
| 5199 | if (Op->getType()->isArrayType() && !Op->isLValue()) |
| 5200 | VK = VK_XValue; |
| 5201 | } |
| 5202 | } |
| 5203 | |
| 5204 | // Perform default conversions. |
| 5205 | if (!LHSExp->getType()->isSubscriptableVectorType()) { |
| 5206 | ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp); |
| 5207 | if (Result.isInvalid()) |
| 5208 | return ExprError(); |
| 5209 | LHSExp = Result.get(); |
| 5210 | } |
| 5211 | ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp); |
| 5212 | if (Result.isInvalid()) |
| 5213 | return ExprError(); |
| 5214 | RHSExp = Result.get(); |
| 5215 | |
| 5216 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); |
| 5217 | |
| 5218 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent |
| 5219 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be |
| 5220 | // in the subscript position. As a result, we need to derive the array base |
| 5221 | // and index from the expression types. |
| 5222 | Expr *BaseExpr, *IndexExpr; |
| 5223 | QualType ResultType; |
| 5224 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { |
| 5225 | BaseExpr = LHSExp; |
| 5226 | IndexExpr = RHSExp; |
| 5227 | ResultType = |
| 5228 | getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext()); |
| 5229 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { |
| 5230 | BaseExpr = LHSExp; |
| 5231 | IndexExpr = RHSExp; |
| 5232 | ResultType = PTy->getPointeeType(); |
| 5233 | } else if (const ObjCObjectPointerType *PTy = |
| 5234 | LHSTy->getAs<ObjCObjectPointerType>()) { |
| 5235 | BaseExpr = LHSExp; |
| 5236 | IndexExpr = RHSExp; |
| 5237 | |
| 5238 | // Use custom logic if this should be the pseudo-object subscript |
| 5239 | // expression. |
| 5240 | if (!LangOpts.isSubscriptPointerArithmetic()) |
| 5241 | return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr, |
| 5242 | getterMethod: nullptr, setterMethod: nullptr); |
| 5243 | |
| 5244 | ResultType = PTy->getPointeeType(); |
| 5245 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { |
| 5246 | // Handle the uncommon case of "123[Ptr]". |
| 5247 | BaseExpr = RHSExp; |
| 5248 | IndexExpr = LHSExp; |
| 5249 | ResultType = PTy->getPointeeType(); |
| 5250 | } else if (const ObjCObjectPointerType *PTy = |
| 5251 | RHSTy->getAs<ObjCObjectPointerType>()) { |
| 5252 | // Handle the uncommon case of "123[Ptr]". |
| 5253 | BaseExpr = RHSExp; |
| 5254 | IndexExpr = LHSExp; |
| 5255 | ResultType = PTy->getPointeeType(); |
| 5256 | if (!LangOpts.isSubscriptPointerArithmetic()) { |
| 5257 | Diag(Loc: LLoc, DiagID: diag::err_subscript_nonfragile_interface) |
| 5258 | << ResultType << BaseExpr->getSourceRange(); |
| 5259 | return ExprError(); |
| 5260 | } |
| 5261 | } else if (LHSTy->isSubscriptableVectorType()) { |
| 5262 | if (LHSTy->isBuiltinType() && |
| 5263 | LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) { |
| 5264 | const BuiltinType *BTy = LHSTy->getAs<BuiltinType>(); |
| 5265 | if (BTy->isSVEBool()) |
| 5266 | return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_svbool_t) |
| 5267 | << LHSExp->getSourceRange() |
| 5268 | << RHSExp->getSourceRange()); |
| 5269 | ResultType = BTy->getSveEltType(Ctx: Context); |
| 5270 | } else { |
| 5271 | const VectorType *VTy = LHSTy->getAs<VectorType>(); |
| 5272 | ResultType = VTy->getElementType(); |
| 5273 | } |
| 5274 | BaseExpr = LHSExp; // vectors: V[123] |
| 5275 | IndexExpr = RHSExp; |
| 5276 | // We apply C++ DR1213 to vector subscripting too. |
| 5277 | if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { |
| 5278 | ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp); |
| 5279 | if (Materialized.isInvalid()) |
| 5280 | return ExprError(); |
| 5281 | LHSExp = Materialized.get(); |
| 5282 | } |
| 5283 | VK = LHSExp->getValueKind(); |
| 5284 | if (VK != VK_PRValue) |
| 5285 | OK = OK_VectorComponent; |
| 5286 | |
| 5287 | QualType BaseType = BaseExpr->getType(); |
| 5288 | Qualifiers BaseQuals = BaseType.getQualifiers(); |
| 5289 | Qualifiers MemberQuals = ResultType.getQualifiers(); |
| 5290 | Qualifiers Combined = BaseQuals + MemberQuals; |
| 5291 | if (Combined != MemberQuals) |
| 5292 | ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined); |
| 5293 | } else if (LHSTy->isArrayType()) { |
| 5294 | // If we see an array that wasn't promoted by |
| 5295 | // DefaultFunctionArrayLvalueConversion, it must be an array that |
| 5296 | // wasn't promoted because of the C90 rule that doesn't |
| 5297 | // allow promoting non-lvalue arrays. Warn, then |
| 5298 | // force the promotion here. |
| 5299 | Diag(Loc: LHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue) |
| 5300 | << LHSExp->getSourceRange(); |
| 5301 | LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy), |
| 5302 | CK: CK_ArrayToPointerDecay).get(); |
| 5303 | LHSTy = LHSExp->getType(); |
| 5304 | |
| 5305 | BaseExpr = LHSExp; |
| 5306 | IndexExpr = RHSExp; |
| 5307 | ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); |
| 5308 | } else if (RHSTy->isArrayType()) { |
| 5309 | // Same as previous, except for 123[f().a] case |
| 5310 | Diag(Loc: RHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue) |
| 5311 | << RHSExp->getSourceRange(); |
| 5312 | RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy), |
| 5313 | CK: CK_ArrayToPointerDecay).get(); |
| 5314 | RHSTy = RHSExp->getType(); |
| 5315 | |
| 5316 | BaseExpr = RHSExp; |
| 5317 | IndexExpr = LHSExp; |
| 5318 | ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); |
| 5319 | } else { |
| 5320 | return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_value) |
| 5321 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); |
| 5322 | } |
| 5323 | // C99 6.5.2.1p1 |
| 5324 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) |
| 5325 | return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_not_integer) |
| 5326 | << IndexExpr->getSourceRange()); |
| 5327 | |
| 5328 | if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) || |
| 5329 | IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) && |
| 5330 | !IndexExpr->isTypeDependent()) { |
| 5331 | std::optional<llvm::APSInt> IntegerContantExpr = |
| 5332 | IndexExpr->getIntegerConstantExpr(Ctx: getASTContext()); |
| 5333 | if (!IntegerContantExpr.has_value() || |
| 5334 | IntegerContantExpr.value().isNegative()) |
| 5335 | Diag(Loc: LLoc, DiagID: diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); |
| 5336 | } |
| 5337 | |
| 5338 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, |
| 5339 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object |
| 5340 | // type. Note that Functions are not objects, and that (in C99 parlance) |
| 5341 | // incomplete types are not object types. |
| 5342 | if (ResultType->isFunctionType()) { |
| 5343 | Diag(Loc: BaseExpr->getBeginLoc(), DiagID: diag::err_subscript_function_type) |
| 5344 | << ResultType << BaseExpr->getSourceRange(); |
| 5345 | return ExprError(); |
| 5346 | } |
| 5347 | |
| 5348 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { |
| 5349 | // GNU extension: subscripting on pointer to void |
| 5350 | Diag(Loc: LLoc, DiagID: diag::ext_gnu_subscript_void_type) |
| 5351 | << BaseExpr->getSourceRange(); |
| 5352 | |
| 5353 | // C forbids expressions of unqualified void type from being l-values. |
| 5354 | // See IsCForbiddenLValueType. |
| 5355 | if (!ResultType.hasQualifiers()) |
| 5356 | VK = VK_PRValue; |
| 5357 | } else if (!ResultType->isDependentType() && |
| 5358 | !ResultType.isWebAssemblyReferenceType() && |
| 5359 | RequireCompleteSizedType( |
| 5360 | Loc: LLoc, T: ResultType, |
| 5361 | DiagID: diag::err_subscript_incomplete_or_sizeless_type, Args: BaseExpr)) |
| 5362 | return ExprError(); |
| 5363 | |
| 5364 | assert(VK == VK_PRValue || LangOpts.CPlusPlus || |
| 5365 | !ResultType.isCForbiddenLValueType()); |
| 5366 | |
| 5367 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && |
| 5368 | FunctionScopes.size() > 1) { |
| 5369 | if (auto *TT = |
| 5370 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { |
| 5371 | for (auto I = FunctionScopes.rbegin(), |
| 5372 | E = std::prev(x: FunctionScopes.rend()); |
| 5373 | I != E; ++I) { |
| 5374 | auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I); |
| 5375 | if (CSI == nullptr) |
| 5376 | break; |
| 5377 | DeclContext *DC = nullptr; |
| 5378 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI)) |
| 5379 | DC = LSI->CallOperator; |
| 5380 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) |
| 5381 | DC = CRSI->TheCapturedDecl; |
| 5382 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) |
| 5383 | DC = BSI->TheDecl; |
| 5384 | if (DC) { |
| 5385 | if (DC->containsDecl(D: TT->getDecl())) |
| 5386 | break; |
| 5387 | captureVariablyModifiedType( |
| 5388 | Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI); |
| 5389 | } |
| 5390 | } |
| 5391 | } |
| 5392 | } |
| 5393 | |
| 5394 | return new (Context) |
| 5395 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); |
| 5396 | } |
| 5397 | |
| 5398 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, |
| 5399 | ParmVarDecl *Param, Expr *RewrittenInit, |
| 5400 | bool SkipImmediateInvocations) { |
| 5401 | if (Param->hasUnparsedDefaultArg()) { |
| 5402 | assert(!RewrittenInit && "Should not have a rewritten init expression yet" ); |
| 5403 | // If we've already cleared out the location for the default argument, |
| 5404 | // that means we're parsing it right now. |
| 5405 | if (!UnparsedDefaultArgLocs.count(Val: Param)) { |
| 5406 | Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) << FD; |
| 5407 | Diag(Loc: CallLoc, DiagID: diag::note_recursive_default_argument_used_here); |
| 5408 | Param->setInvalidDecl(); |
| 5409 | return true; |
| 5410 | } |
| 5411 | |
| 5412 | Diag(Loc: CallLoc, DiagID: diag::err_use_of_default_argument_to_function_declared_later) |
| 5413 | << FD << cast<CXXRecordDecl>(Val: FD->getDeclContext()); |
| 5414 | Diag(Loc: UnparsedDefaultArgLocs[Param], |
| 5415 | DiagID: diag::note_default_argument_declared_here); |
| 5416 | return true; |
| 5417 | } |
| 5418 | |
| 5419 | if (Param->hasUninstantiatedDefaultArg()) { |
| 5420 | assert(!RewrittenInit && "Should not have a rewitten init expression yet" ); |
| 5421 | if (InstantiateDefaultArgument(CallLoc, FD, Param)) |
| 5422 | return true; |
| 5423 | } |
| 5424 | |
| 5425 | Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit(); |
| 5426 | assert(Init && "default argument but no initializer?" ); |
| 5427 | |
| 5428 | // If the default expression creates temporaries, we need to |
| 5429 | // push them to the current stack of expression temporaries so they'll |
| 5430 | // be properly destroyed. |
| 5431 | // FIXME: We should really be rebuilding the default argument with new |
| 5432 | // bound temporaries; see the comment in PR5810. |
| 5433 | // We don't need to do that with block decls, though, because |
| 5434 | // blocks in default argument expression can never capture anything. |
| 5435 | if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Val: Init)) { |
| 5436 | // Set the "needs cleanups" bit regardless of whether there are |
| 5437 | // any explicit objects. |
| 5438 | Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects()); |
| 5439 | // Append all the objects to the cleanup list. Right now, this |
| 5440 | // should always be a no-op, because blocks in default argument |
| 5441 | // expressions should never be able to capture anything. |
| 5442 | assert(!InitWithCleanup->getNumObjects() && |
| 5443 | "default argument expression has capturing blocks?" ); |
| 5444 | } |
| 5445 | // C++ [expr.const]p15.1: |
| 5446 | // An expression or conversion is in an immediate function context if it is |
| 5447 | // potentially evaluated and [...] its innermost enclosing non-block scope |
| 5448 | // is a function parameter scope of an immediate function. |
| 5449 | EnterExpressionEvaluationContext EvalContext( |
| 5450 | *this, |
| 5451 | FD->isImmediateFunction() |
| 5452 | ? ExpressionEvaluationContext::ImmediateFunctionContext |
| 5453 | : ExpressionEvaluationContext::PotentiallyEvaluated, |
| 5454 | Param); |
| 5455 | ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer = |
| 5456 | SkipImmediateInvocations; |
| 5457 | runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] { |
| 5458 | MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true); |
| 5459 | }); |
| 5460 | return false; |
| 5461 | } |
| 5462 | |
| 5463 | struct ImmediateCallVisitor : DynamicRecursiveASTVisitor { |
| 5464 | const ASTContext &Context; |
| 5465 | ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) { |
| 5466 | ShouldVisitImplicitCode = true; |
| 5467 | } |
| 5468 | |
| 5469 | bool HasImmediateCalls = false; |
| 5470 | |
| 5471 | bool VisitCallExpr(CallExpr *E) override { |
| 5472 | if (const FunctionDecl *FD = E->getDirectCallee()) |
| 5473 | HasImmediateCalls |= FD->isImmediateFunction(); |
| 5474 | return DynamicRecursiveASTVisitor::VisitStmt(S: E); |
| 5475 | } |
| 5476 | |
| 5477 | bool VisitCXXConstructExpr(CXXConstructExpr *E) override { |
| 5478 | if (const FunctionDecl *FD = E->getConstructor()) |
| 5479 | HasImmediateCalls |= FD->isImmediateFunction(); |
| 5480 | return DynamicRecursiveASTVisitor::VisitStmt(S: E); |
| 5481 | } |
| 5482 | |
| 5483 | // SourceLocExpr are not immediate invocations |
| 5484 | // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr |
| 5485 | // need to be rebuilt so that they refer to the correct SourceLocation and |
| 5486 | // DeclContext. |
| 5487 | bool VisitSourceLocExpr(SourceLocExpr *E) override { |
| 5488 | HasImmediateCalls = true; |
| 5489 | return DynamicRecursiveASTVisitor::VisitStmt(S: E); |
| 5490 | } |
| 5491 | |
| 5492 | // A nested lambda might have parameters with immediate invocations |
| 5493 | // in their default arguments. |
| 5494 | // The compound statement is not visited (as it does not constitute a |
| 5495 | // subexpression). |
| 5496 | // FIXME: We should consider visiting and transforming captures |
| 5497 | // with init expressions. |
| 5498 | bool VisitLambdaExpr(LambdaExpr *E) override { |
| 5499 | return VisitCXXMethodDecl(D: E->getCallOperator()); |
| 5500 | } |
| 5501 | |
| 5502 | bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override { |
| 5503 | return TraverseStmt(S: E->getExpr()); |
| 5504 | } |
| 5505 | |
| 5506 | bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override { |
| 5507 | return TraverseStmt(S: E->getExpr()); |
| 5508 | } |
| 5509 | }; |
| 5510 | |
| 5511 | struct EnsureImmediateInvocationInDefaultArgs |
| 5512 | : TreeTransform<EnsureImmediateInvocationInDefaultArgs> { |
| 5513 | EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef) |
| 5514 | : TreeTransform(SemaRef) {} |
| 5515 | |
| 5516 | bool AlwaysRebuild() { return true; } |
| 5517 | |
| 5518 | // Lambda can only have immediate invocations in the default |
| 5519 | // args of their parameters, which is transformed upon calling the closure. |
| 5520 | // The body is not a subexpression, so we have nothing to do. |
| 5521 | // FIXME: Immediate calls in capture initializers should be transformed. |
| 5522 | ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; } |
| 5523 | ExprResult TransformBlockExpr(BlockExpr *E) { return E; } |
| 5524 | |
| 5525 | // Make sure we don't rebuild the this pointer as it would |
| 5526 | // cause it to incorrectly point it to the outermost class |
| 5527 | // in the case of nested struct initialization. |
| 5528 | ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; } |
| 5529 | |
| 5530 | // Rewrite to source location to refer to the context in which they are used. |
| 5531 | ExprResult TransformSourceLocExpr(SourceLocExpr *E) { |
| 5532 | DeclContext *DC = E->getParentContext(); |
| 5533 | if (DC == SemaRef.CurContext) |
| 5534 | return E; |
| 5535 | |
| 5536 | // FIXME: During instantiation, because the rebuild of defaults arguments |
| 5537 | // is not always done in the context of the template instantiator, |
| 5538 | // we run the risk of producing a dependent source location |
| 5539 | // that would never be rebuilt. |
| 5540 | // This usually happens during overload resolution, or in contexts |
| 5541 | // where the value of the source location does not matter. |
| 5542 | // However, we should find a better way to deal with source location |
| 5543 | // of function templates. |
| 5544 | if (!SemaRef.CurrentInstantiationScope || |
| 5545 | !SemaRef.CurContext->isDependentContext() || DC->isDependentContext()) |
| 5546 | DC = SemaRef.CurContext; |
| 5547 | |
| 5548 | return getDerived().RebuildSourceLocExpr( |
| 5549 | Kind: E->getIdentKind(), ResultTy: E->getType(), BuiltinLoc: E->getBeginLoc(), RPLoc: E->getEndLoc(), ParentContext: DC); |
| 5550 | } |
| 5551 | }; |
| 5552 | |
| 5553 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, |
| 5554 | FunctionDecl *FD, ParmVarDecl *Param, |
| 5555 | Expr *Init) { |
| 5556 | assert(Param->hasDefaultArg() && "can't build nonexistent default arg" ); |
| 5557 | |
| 5558 | bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer(); |
| 5559 | bool NeedRebuild = needsRebuildOfDefaultArgOrInit(); |
| 5560 | std::optional<ExpressionEvaluationContextRecord::InitializationContext> |
| 5561 | InitializationContext = |
| 5562 | OutermostDeclarationWithDelayedImmediateInvocations(); |
| 5563 | if (!InitializationContext.has_value()) |
| 5564 | InitializationContext.emplace(args&: CallLoc, args&: Param, args&: CurContext); |
| 5565 | |
| 5566 | if (!Init && !Param->hasUnparsedDefaultArg()) { |
| 5567 | // Mark that we are replacing a default argument first. |
| 5568 | // If we are instantiating a template we won't have to |
| 5569 | // retransform immediate calls. |
| 5570 | // C++ [expr.const]p15.1: |
| 5571 | // An expression or conversion is in an immediate function context if it |
| 5572 | // is potentially evaluated and [...] its innermost enclosing non-block |
| 5573 | // scope is a function parameter scope of an immediate function. |
| 5574 | EnterExpressionEvaluationContext EvalContext( |
| 5575 | *this, |
| 5576 | FD->isImmediateFunction() |
| 5577 | ? ExpressionEvaluationContext::ImmediateFunctionContext |
| 5578 | : ExpressionEvaluationContext::PotentiallyEvaluated, |
| 5579 | Param); |
| 5580 | |
| 5581 | if (Param->hasUninstantiatedDefaultArg()) { |
| 5582 | if (InstantiateDefaultArgument(CallLoc, FD, Param)) |
| 5583 | return ExprError(); |
| 5584 | } |
| 5585 | // CWG2631 |
| 5586 | // An immediate invocation that is not evaluated where it appears is |
| 5587 | // evaluated and checked for whether it is a constant expression at the |
| 5588 | // point where the enclosing initializer is used in a function call. |
| 5589 | ImmediateCallVisitor V(getASTContext()); |
| 5590 | if (!NestedDefaultChecking) |
| 5591 | V.TraverseDecl(D: Param); |
| 5592 | |
| 5593 | // Rewrite the call argument that was created from the corresponding |
| 5594 | // parameter's default argument. |
| 5595 | if (V.HasImmediateCalls || |
| 5596 | (NeedRebuild && isa_and_present<ExprWithCleanups>(Val: Param->getInit()))) { |
| 5597 | if (V.HasImmediateCalls) |
| 5598 | ExprEvalContexts.back().DelayedDefaultInitializationContext = { |
| 5599 | CallLoc, Param, CurContext}; |
| 5600 | // Pass down lifetime extending flag, and collect temporaries in |
| 5601 | // CreateMaterializeTemporaryExpr when we rewrite the call argument. |
| 5602 | currentEvaluationContext().InLifetimeExtendingContext = |
| 5603 | parentEvaluationContext().InLifetimeExtendingContext; |
| 5604 | EnsureImmediateInvocationInDefaultArgs Immediate(*this); |
| 5605 | ExprResult Res; |
| 5606 | runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] { |
| 5607 | Res = Immediate.TransformInitializer(Init: Param->getInit(), |
| 5608 | /*NotCopy=*/NotCopyInit: false); |
| 5609 | }); |
| 5610 | if (Res.isInvalid()) |
| 5611 | return ExprError(); |
| 5612 | Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(), |
| 5613 | EqualLoc: Res.get()->getBeginLoc()); |
| 5614 | if (Res.isInvalid()) |
| 5615 | return ExprError(); |
| 5616 | Init = Res.get(); |
| 5617 | } |
| 5618 | } |
| 5619 | |
| 5620 | if (CheckCXXDefaultArgExpr( |
| 5621 | CallLoc, FD, Param, RewrittenInit: Init, |
| 5622 | /*SkipImmediateInvocations=*/NestedDefaultChecking)) |
| 5623 | return ExprError(); |
| 5624 | |
| 5625 | return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param, |
| 5626 | RewrittenExpr: Init, UsedContext: InitializationContext->Context); |
| 5627 | } |
| 5628 | |
| 5629 | static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx, |
| 5630 | FieldDecl *Field) { |
| 5631 | if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field)) |
| 5632 | return Pattern; |
| 5633 | auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent()); |
| 5634 | CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); |
| 5635 | DeclContext::lookup_result Lookup = |
| 5636 | ClassPattern->lookup(Name: Field->getDeclName()); |
| 5637 | auto Rng = llvm::make_filter_range( |
| 5638 | Range&: Lookup, Pred: [](auto &&L) { return isa<FieldDecl>(*L); }); |
| 5639 | if (Rng.empty()) |
| 5640 | return nullptr; |
| 5641 | // FIXME: this breaks clang/test/Modules/pr28812.cpp |
| 5642 | // assert(std::distance(Rng.begin(), Rng.end()) <= 1 |
| 5643 | // && "Duplicated instantiation pattern for field decl"); |
| 5644 | return cast<FieldDecl>(Val: *Rng.begin()); |
| 5645 | } |
| 5646 | |
| 5647 | ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { |
| 5648 | assert(Field->hasInClassInitializer()); |
| 5649 | |
| 5650 | CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers()); |
| 5651 | |
| 5652 | auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent()); |
| 5653 | |
| 5654 | std::optional<ExpressionEvaluationContextRecord::InitializationContext> |
| 5655 | InitializationContext = |
| 5656 | OutermostDeclarationWithDelayedImmediateInvocations(); |
| 5657 | if (!InitializationContext.has_value()) |
| 5658 | InitializationContext.emplace(args&: Loc, args&: Field, args&: CurContext); |
| 5659 | |
| 5660 | Expr *Init = nullptr; |
| 5661 | |
| 5662 | bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer(); |
| 5663 | bool NeedRebuild = needsRebuildOfDefaultArgOrInit(); |
| 5664 | EnterExpressionEvaluationContext EvalContext( |
| 5665 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field); |
| 5666 | |
| 5667 | if (!Field->getInClassInitializer()) { |
| 5668 | // Maybe we haven't instantiated the in-class initializer. Go check the |
| 5669 | // pattern FieldDecl to see if it has one. |
| 5670 | if (isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) { |
| 5671 | FieldDecl *Pattern = |
| 5672 | FindFieldDeclInstantiationPattern(Ctx: getASTContext(), Field); |
| 5673 | assert(Pattern && "We must have set the Pattern!" ); |
| 5674 | if (!Pattern->hasInClassInitializer() || |
| 5675 | InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern, |
| 5676 | TemplateArgs: getTemplateInstantiationArgs(D: Field))) { |
| 5677 | Field->setInvalidDecl(); |
| 5678 | return ExprError(); |
| 5679 | } |
| 5680 | } |
| 5681 | } |
| 5682 | |
| 5683 | // CWG2631 |
| 5684 | // An immediate invocation that is not evaluated where it appears is |
| 5685 | // evaluated and checked for whether it is a constant expression at the |
| 5686 | // point where the enclosing initializer is used in a [...] a constructor |
| 5687 | // definition, or an aggregate initialization. |
| 5688 | ImmediateCallVisitor V(getASTContext()); |
| 5689 | if (!NestedDefaultChecking) |
| 5690 | V.TraverseDecl(D: Field); |
| 5691 | |
| 5692 | // CWG1815 |
| 5693 | // Support lifetime extension of temporary created by aggregate |
| 5694 | // initialization using a default member initializer. We should rebuild |
| 5695 | // the initializer in a lifetime extension context if the initializer |
| 5696 | // expression is an ExprWithCleanups. Then make sure the normal lifetime |
| 5697 | // extension code recurses into the default initializer and does lifetime |
| 5698 | // extension when warranted. |
| 5699 | bool ContainsAnyTemporaries = |
| 5700 | isa_and_present<ExprWithCleanups>(Val: Field->getInClassInitializer()); |
| 5701 | if (Field->getInClassInitializer() && |
| 5702 | !Field->getInClassInitializer()->containsErrors() && |
| 5703 | (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) { |
| 5704 | ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field, |
| 5705 | CurContext}; |
| 5706 | ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer = |
| 5707 | NestedDefaultChecking; |
| 5708 | // Pass down lifetime extending flag, and collect temporaries in |
| 5709 | // CreateMaterializeTemporaryExpr when we rewrite the call argument. |
| 5710 | currentEvaluationContext().InLifetimeExtendingContext = |
| 5711 | parentEvaluationContext().InLifetimeExtendingContext; |
| 5712 | EnsureImmediateInvocationInDefaultArgs Immediate(*this); |
| 5713 | ExprResult Res; |
| 5714 | runWithSufficientStackSpace(Loc, Fn: [&] { |
| 5715 | Res = Immediate.TransformInitializer(Init: Field->getInClassInitializer(), |
| 5716 | /*CXXDirectInit=*/NotCopyInit: false); |
| 5717 | }); |
| 5718 | if (!Res.isInvalid()) |
| 5719 | Res = ConvertMemberDefaultInitExpression(FD: Field, InitExpr: Res.get(), InitLoc: Loc); |
| 5720 | if (Res.isInvalid()) { |
| 5721 | Field->setInvalidDecl(); |
| 5722 | return ExprError(); |
| 5723 | } |
| 5724 | Init = Res.get(); |
| 5725 | } |
| 5726 | |
| 5727 | if (Field->getInClassInitializer()) { |
| 5728 | Expr *E = Init ? Init : Field->getInClassInitializer(); |
| 5729 | if (!NestedDefaultChecking) |
| 5730 | runWithSufficientStackSpace(Loc, Fn: [&] { |
| 5731 | MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false); |
| 5732 | }); |
| 5733 | if (isInLifetimeExtendingContext()) |
| 5734 | DiscardCleanupsInEvaluationContext(); |
| 5735 | // C++11 [class.base.init]p7: |
| 5736 | // The initialization of each base and member constitutes a |
| 5737 | // full-expression. |
| 5738 | ExprResult Res = ActOnFinishFullExpr(Expr: E, /*DiscardedValue=*/false); |
| 5739 | if (Res.isInvalid()) { |
| 5740 | Field->setInvalidDecl(); |
| 5741 | return ExprError(); |
| 5742 | } |
| 5743 | Init = Res.get(); |
| 5744 | |
| 5745 | return CXXDefaultInitExpr::Create(Ctx: Context, Loc: InitializationContext->Loc, |
| 5746 | Field, UsedContext: InitializationContext->Context, |
| 5747 | RewrittenInitExpr: Init); |
| 5748 | } |
| 5749 | |
| 5750 | // DR1351: |
| 5751 | // If the brace-or-equal-initializer of a non-static data member |
| 5752 | // invokes a defaulted default constructor of its class or of an |
| 5753 | // enclosing class in a potentially evaluated subexpression, the |
| 5754 | // program is ill-formed. |
| 5755 | // |
| 5756 | // This resolution is unworkable: the exception specification of the |
| 5757 | // default constructor can be needed in an unevaluated context, in |
| 5758 | // particular, in the operand of a noexcept-expression, and we can be |
| 5759 | // unable to compute an exception specification for an enclosed class. |
| 5760 | // |
| 5761 | // Any attempt to resolve the exception specification of a defaulted default |
| 5762 | // constructor before the initializer is lexically complete will ultimately |
| 5763 | // come here at which point we can diagnose it. |
| 5764 | RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); |
| 5765 | Diag(Loc, DiagID: diag::err_default_member_initializer_not_yet_parsed) |
| 5766 | << OutermostClass << Field; |
| 5767 | Diag(Loc: Field->getEndLoc(), |
| 5768 | DiagID: diag::note_default_member_initializer_not_yet_parsed); |
| 5769 | // Recover by marking the field invalid, unless we're in a SFINAE context. |
| 5770 | if (!isSFINAEContext()) |
| 5771 | Field->setInvalidDecl(); |
| 5772 | return ExprError(); |
| 5773 | } |
| 5774 | |
| 5775 | VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl, |
| 5776 | const FunctionProtoType *Proto, |
| 5777 | Expr *Fn) { |
| 5778 | if (Proto && Proto->isVariadic()) { |
| 5779 | if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl)) |
| 5780 | return VariadicCallType::Constructor; |
| 5781 | else if (Fn && Fn->getType()->isBlockPointerType()) |
| 5782 | return VariadicCallType::Block; |
| 5783 | else if (FDecl) { |
| 5784 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl)) |
| 5785 | if (Method->isInstance()) |
| 5786 | return VariadicCallType::Method; |
| 5787 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) |
| 5788 | return VariadicCallType::Method; |
| 5789 | return VariadicCallType::Function; |
| 5790 | } |
| 5791 | return VariadicCallType::DoesNotApply; |
| 5792 | } |
| 5793 | |
| 5794 | namespace { |
| 5795 | class FunctionCallCCC final : public FunctionCallFilterCCC { |
| 5796 | public: |
| 5797 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, |
| 5798 | unsigned NumArgs, MemberExpr *ME) |
| 5799 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), |
| 5800 | FunctionName(FuncName) {} |
| 5801 | |
| 5802 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
| 5803 | if (!candidate.getCorrectionSpecifier() || |
| 5804 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { |
| 5805 | return false; |
| 5806 | } |
| 5807 | |
| 5808 | return FunctionCallFilterCCC::ValidateCandidate(candidate); |
| 5809 | } |
| 5810 | |
| 5811 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
| 5812 | return std::make_unique<FunctionCallCCC>(args&: *this); |
| 5813 | } |
| 5814 | |
| 5815 | private: |
| 5816 | const IdentifierInfo *const FunctionName; |
| 5817 | }; |
| 5818 | } |
| 5819 | |
| 5820 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, |
| 5821 | FunctionDecl *FDecl, |
| 5822 | ArrayRef<Expr *> Args) { |
| 5823 | MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn); |
| 5824 | DeclarationName FuncName = FDecl->getDeclName(); |
| 5825 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); |
| 5826 | |
| 5827 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); |
| 5828 | if (TypoCorrection Corrected = S.CorrectTypo( |
| 5829 | Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName, |
| 5830 | S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC, |
| 5831 | Mode: CorrectTypoKind::ErrorRecovery)) { |
| 5832 | if (NamedDecl *ND = Corrected.getFoundDecl()) { |
| 5833 | if (Corrected.isOverloaded()) { |
| 5834 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); |
| 5835 | OverloadCandidateSet::iterator Best; |
| 5836 | for (NamedDecl *CD : Corrected) { |
| 5837 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD)) |
| 5838 | S.AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), Args, |
| 5839 | CandidateSet&: OCS); |
| 5840 | } |
| 5841 | switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) { |
| 5842 | case OR_Success: |
| 5843 | ND = Best->FoundDecl; |
| 5844 | Corrected.setCorrectionDecl(ND); |
| 5845 | break; |
| 5846 | default: |
| 5847 | break; |
| 5848 | } |
| 5849 | } |
| 5850 | ND = ND->getUnderlyingDecl(); |
| 5851 | if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND)) |
| 5852 | return Corrected; |
| 5853 | } |
| 5854 | } |
| 5855 | return TypoCorrection(); |
| 5856 | } |
| 5857 | |
| 5858 | // [C++26][[expr.unary.op]/p4 |
| 5859 | // A pointer to member is only formed when an explicit & |
| 5860 | // is used and its operand is a qualified-id not enclosed in parentheses. |
| 5861 | static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) { |
| 5862 | if (!isa<ParenExpr>(Val: Fn)) |
| 5863 | return false; |
| 5864 | |
| 5865 | Fn = Fn->IgnoreParens(); |
| 5866 | |
| 5867 | auto *UO = dyn_cast<UnaryOperator>(Val: Fn); |
| 5868 | if (!UO || UO->getOpcode() != clang::UO_AddrOf) |
| 5869 | return false; |
| 5870 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) { |
| 5871 | return DRE->hasQualifier(); |
| 5872 | } |
| 5873 | if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens())) |
| 5874 | return OVL->getQualifier(); |
| 5875 | return false; |
| 5876 | } |
| 5877 | |
| 5878 | bool |
| 5879 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, |
| 5880 | FunctionDecl *FDecl, |
| 5881 | const FunctionProtoType *Proto, |
| 5882 | ArrayRef<Expr *> Args, |
| 5883 | SourceLocation RParenLoc, |
| 5884 | bool IsExecConfig) { |
| 5885 | // Bail out early if calling a builtin with custom typechecking. |
| 5886 | if (FDecl) |
| 5887 | if (unsigned ID = FDecl->getBuiltinID()) |
| 5888 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) |
| 5889 | return false; |
| 5890 | |
| 5891 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by |
| 5892 | // assignment, to the types of the corresponding parameter, ... |
| 5893 | |
| 5894 | bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn); |
| 5895 | bool HasExplicitObjectParameter = |
| 5896 | !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter(); |
| 5897 | unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0; |
| 5898 | unsigned NumParams = Proto->getNumParams(); |
| 5899 | bool Invalid = false; |
| 5900 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; |
| 5901 | unsigned FnKind = Fn->getType()->isBlockPointerType() |
| 5902 | ? 1 /* block */ |
| 5903 | : (IsExecConfig ? 3 /* kernel function (exec config) */ |
| 5904 | : 0 /* function */); |
| 5905 | |
| 5906 | // If too few arguments are available (and we don't have default |
| 5907 | // arguments for the remaining parameters), don't make the call. |
| 5908 | if (Args.size() < NumParams) { |
| 5909 | if (Args.size() < MinArgs) { |
| 5910 | TypoCorrection TC; |
| 5911 | if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) { |
| 5912 | unsigned diag_id = |
| 5913 | MinArgs == NumParams && !Proto->isVariadic() |
| 5914 | ? diag::err_typecheck_call_too_few_args_suggest |
| 5915 | : diag::err_typecheck_call_too_few_args_at_least_suggest; |
| 5916 | diagnoseTypo( |
| 5917 | Correction: TC, TypoDiag: PDiag(DiagID: diag_id) |
| 5918 | << FnKind << MinArgs - ExplicitObjectParameterOffset |
| 5919 | << static_cast<unsigned>(Args.size()) - |
| 5920 | ExplicitObjectParameterOffset |
| 5921 | << HasExplicitObjectParameter << TC.getCorrectionRange()); |
| 5922 | } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl && |
| 5923 | FDecl->getParamDecl(i: ExplicitObjectParameterOffset) |
| 5924 | ->getDeclName()) |
| 5925 | Diag(Loc: RParenLoc, |
| 5926 | DiagID: MinArgs == NumParams && !Proto->isVariadic() |
| 5927 | ? diag::err_typecheck_call_too_few_args_one |
| 5928 | : diag::err_typecheck_call_too_few_args_at_least_one) |
| 5929 | << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset) |
| 5930 | << HasExplicitObjectParameter << Fn->getSourceRange(); |
| 5931 | else |
| 5932 | Diag(Loc: RParenLoc, DiagID: MinArgs == NumParams && !Proto->isVariadic() |
| 5933 | ? diag::err_typecheck_call_too_few_args |
| 5934 | : diag::err_typecheck_call_too_few_args_at_least) |
| 5935 | << FnKind << MinArgs - ExplicitObjectParameterOffset |
| 5936 | << static_cast<unsigned>(Args.size()) - |
| 5937 | ExplicitObjectParameterOffset |
| 5938 | << HasExplicitObjectParameter << Fn->getSourceRange(); |
| 5939 | |
| 5940 | // Emit the location of the prototype. |
| 5941 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) |
| 5942 | Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) |
| 5943 | << FDecl << FDecl->getParametersSourceRange(); |
| 5944 | |
| 5945 | return true; |
| 5946 | } |
| 5947 | // We reserve space for the default arguments when we create |
| 5948 | // the call expression, before calling ConvertArgumentsForCall. |
| 5949 | assert((Call->getNumArgs() == NumParams) && |
| 5950 | "We should have reserved space for the default arguments before!" ); |
| 5951 | } |
| 5952 | |
| 5953 | // If too many are passed and not variadic, error on the extras and drop |
| 5954 | // them. |
| 5955 | if (Args.size() > NumParams) { |
| 5956 | if (!Proto->isVariadic()) { |
| 5957 | TypoCorrection TC; |
| 5958 | if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) { |
| 5959 | unsigned diag_id = |
| 5960 | MinArgs == NumParams && !Proto->isVariadic() |
| 5961 | ? diag::err_typecheck_call_too_many_args_suggest |
| 5962 | : diag::err_typecheck_call_too_many_args_at_most_suggest; |
| 5963 | diagnoseTypo( |
| 5964 | Correction: TC, TypoDiag: PDiag(DiagID: diag_id) |
| 5965 | << FnKind << NumParams - ExplicitObjectParameterOffset |
| 5966 | << static_cast<unsigned>(Args.size()) - |
| 5967 | ExplicitObjectParameterOffset |
| 5968 | << HasExplicitObjectParameter << TC.getCorrectionRange()); |
| 5969 | } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl && |
| 5970 | FDecl->getParamDecl(i: ExplicitObjectParameterOffset) |
| 5971 | ->getDeclName()) |
| 5972 | Diag(Loc: Args[NumParams]->getBeginLoc(), |
| 5973 | DiagID: MinArgs == NumParams |
| 5974 | ? diag::err_typecheck_call_too_many_args_one |
| 5975 | : diag::err_typecheck_call_too_many_args_at_most_one) |
| 5976 | << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset) |
| 5977 | << static_cast<unsigned>(Args.size()) - |
| 5978 | ExplicitObjectParameterOffset |
| 5979 | << HasExplicitObjectParameter << Fn->getSourceRange() |
| 5980 | << SourceRange(Args[NumParams]->getBeginLoc(), |
| 5981 | Args.back()->getEndLoc()); |
| 5982 | else |
| 5983 | Diag(Loc: Args[NumParams]->getBeginLoc(), |
| 5984 | DiagID: MinArgs == NumParams |
| 5985 | ? diag::err_typecheck_call_too_many_args |
| 5986 | : diag::err_typecheck_call_too_many_args_at_most) |
| 5987 | << FnKind << NumParams - ExplicitObjectParameterOffset |
| 5988 | << static_cast<unsigned>(Args.size()) - |
| 5989 | ExplicitObjectParameterOffset |
| 5990 | << HasExplicitObjectParameter << Fn->getSourceRange() |
| 5991 | << SourceRange(Args[NumParams]->getBeginLoc(), |
| 5992 | Args.back()->getEndLoc()); |
| 5993 | |
| 5994 | // Emit the location of the prototype. |
| 5995 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) |
| 5996 | Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) |
| 5997 | << FDecl << FDecl->getParametersSourceRange(); |
| 5998 | |
| 5999 | // This deletes the extra arguments. |
| 6000 | Call->shrinkNumArgs(NewNumArgs: NumParams); |
| 6001 | return true; |
| 6002 | } |
| 6003 | } |
| 6004 | SmallVector<Expr *, 8> AllArgs; |
| 6005 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); |
| 6006 | |
| 6007 | Invalid = GatherArgumentsForCall(CallLoc: Call->getExprLoc(), FDecl, Proto, FirstParam: 0, Args, |
| 6008 | AllArgs, CallType); |
| 6009 | if (Invalid) |
| 6010 | return true; |
| 6011 | unsigned TotalNumArgs = AllArgs.size(); |
| 6012 | for (unsigned i = 0; i < TotalNumArgs; ++i) |
| 6013 | Call->setArg(Arg: i, ArgExpr: AllArgs[i]); |
| 6014 | |
| 6015 | Call->computeDependence(); |
| 6016 | return false; |
| 6017 | } |
| 6018 | |
| 6019 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, |
| 6020 | const FunctionProtoType *Proto, |
| 6021 | unsigned FirstParam, ArrayRef<Expr *> Args, |
| 6022 | SmallVectorImpl<Expr *> &AllArgs, |
| 6023 | VariadicCallType CallType, bool AllowExplicit, |
| 6024 | bool IsListInitialization) { |
| 6025 | unsigned NumParams = Proto->getNumParams(); |
| 6026 | bool Invalid = false; |
| 6027 | size_t ArgIx = 0; |
| 6028 | // Continue to check argument types (even if we have too few/many args). |
| 6029 | for (unsigned i = FirstParam; i < NumParams; i++) { |
| 6030 | QualType ProtoArgType = Proto->getParamType(i); |
| 6031 | |
| 6032 | Expr *Arg; |
| 6033 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; |
| 6034 | if (ArgIx < Args.size()) { |
| 6035 | Arg = Args[ArgIx++]; |
| 6036 | |
| 6037 | if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: ProtoArgType, |
| 6038 | DiagID: diag::err_call_incomplete_argument, Args: Arg)) |
| 6039 | return true; |
| 6040 | |
| 6041 | // Strip the unbridged-cast placeholder expression off, if applicable. |
| 6042 | bool CFAudited = false; |
| 6043 | if (Arg->getType() == Context.ARCUnbridgedCastTy && |
| 6044 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && |
| 6045 | (!Param || !Param->hasAttr<CFConsumedAttr>())) |
| 6046 | Arg = ObjC().stripARCUnbridgedCast(e: Arg); |
| 6047 | else if (getLangOpts().ObjCAutoRefCount && |
| 6048 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && |
| 6049 | (!Param || !Param->hasAttr<CFConsumedAttr>())) |
| 6050 | CFAudited = true; |
| 6051 | |
| 6052 | if (Proto->getExtParameterInfo(I: i).isNoEscape() && |
| 6053 | ProtoArgType->isBlockPointerType()) |
| 6054 | if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context))) |
| 6055 | BE->getBlockDecl()->setDoesNotEscape(); |
| 6056 | if ((Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLOut || |
| 6057 | Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLInOut)) { |
| 6058 | ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg); |
| 6059 | if (ArgExpr.isInvalid()) |
| 6060 | return true; |
| 6061 | Arg = ArgExpr.getAs<Expr>(); |
| 6062 | } |
| 6063 | |
| 6064 | InitializedEntity Entity = |
| 6065 | Param ? InitializedEntity::InitializeParameter(Context, Parm: Param, |
| 6066 | Type: ProtoArgType) |
| 6067 | : InitializedEntity::InitializeParameter( |
| 6068 | Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i)); |
| 6069 | |
| 6070 | // Remember that parameter belongs to a CF audited API. |
| 6071 | if (CFAudited) |
| 6072 | Entity.setParameterCFAudited(); |
| 6073 | |
| 6074 | ExprResult ArgE = PerformCopyInitialization( |
| 6075 | Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit); |
| 6076 | if (ArgE.isInvalid()) |
| 6077 | return true; |
| 6078 | |
| 6079 | Arg = ArgE.getAs<Expr>(); |
| 6080 | } else { |
| 6081 | assert(Param && "can't use default arguments without a known callee" ); |
| 6082 | |
| 6083 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param); |
| 6084 | if (ArgExpr.isInvalid()) |
| 6085 | return true; |
| 6086 | |
| 6087 | Arg = ArgExpr.getAs<Expr>(); |
| 6088 | } |
| 6089 | |
| 6090 | // Check for array bounds violations for each argument to the call. This |
| 6091 | // check only triggers warnings when the argument isn't a more complex Expr |
| 6092 | // with its own checking, such as a BinaryOperator. |
| 6093 | CheckArrayAccess(E: Arg); |
| 6094 | |
| 6095 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). |
| 6096 | CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg); |
| 6097 | |
| 6098 | AllArgs.push_back(Elt: Arg); |
| 6099 | } |
| 6100 | |
| 6101 | // If this is a variadic call, handle args passed through "...". |
| 6102 | if (CallType != VariadicCallType::DoesNotApply) { |
| 6103 | // Assume that extern "C" functions with variadic arguments that |
| 6104 | // return __unknown_anytype aren't *really* variadic. |
| 6105 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && |
| 6106 | FDecl->isExternC()) { |
| 6107 | for (Expr *A : Args.slice(N: ArgIx)) { |
| 6108 | QualType paramType; // ignored |
| 6109 | ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType); |
| 6110 | Invalid |= arg.isInvalid(); |
| 6111 | AllArgs.push_back(Elt: arg.get()); |
| 6112 | } |
| 6113 | |
| 6114 | // Otherwise do argument promotion, (C99 6.5.2.2p7). |
| 6115 | } else { |
| 6116 | for (Expr *A : Args.slice(N: ArgIx)) { |
| 6117 | ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl); |
| 6118 | Invalid |= Arg.isInvalid(); |
| 6119 | AllArgs.push_back(Elt: Arg.get()); |
| 6120 | } |
| 6121 | } |
| 6122 | |
| 6123 | // Check for array bounds violations. |
| 6124 | for (Expr *A : Args.slice(N: ArgIx)) |
| 6125 | CheckArrayAccess(E: A); |
| 6126 | } |
| 6127 | return Invalid; |
| 6128 | } |
| 6129 | |
| 6130 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { |
| 6131 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); |
| 6132 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) |
| 6133 | TL = DTL.getOriginalLoc(); |
| 6134 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) |
| 6135 | S.Diag(Loc: PVD->getLocation(), DiagID: diag::note_callee_static_array) |
| 6136 | << ATL.getLocalSourceRange(); |
| 6137 | } |
| 6138 | |
| 6139 | void |
| 6140 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, |
| 6141 | ParmVarDecl *Param, |
| 6142 | const Expr *ArgExpr) { |
| 6143 | // Static array parameters are not supported in C++. |
| 6144 | if (!Param || getLangOpts().CPlusPlus) |
| 6145 | return; |
| 6146 | |
| 6147 | QualType OrigTy = Param->getOriginalType(); |
| 6148 | |
| 6149 | const ArrayType *AT = Context.getAsArrayType(T: OrigTy); |
| 6150 | if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static) |
| 6151 | return; |
| 6152 | |
| 6153 | if (ArgExpr->isNullPointerConstant(Ctx&: Context, |
| 6154 | NPC: Expr::NPC_NeverValueDependent)) { |
| 6155 | Diag(Loc: CallLoc, DiagID: diag::warn_null_arg) << ArgExpr->getSourceRange(); |
| 6156 | DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param); |
| 6157 | return; |
| 6158 | } |
| 6159 | |
| 6160 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT); |
| 6161 | if (!CAT) |
| 6162 | return; |
| 6163 | |
| 6164 | const ConstantArrayType *ArgCAT = |
| 6165 | Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType()); |
| 6166 | if (!ArgCAT) |
| 6167 | return; |
| 6168 | |
| 6169 | if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(), |
| 6170 | T2: ArgCAT->getElementType())) { |
| 6171 | if (ArgCAT->getSize().ult(RHS: CAT->getSize())) { |
| 6172 | Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small) |
| 6173 | << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize() |
| 6174 | << (unsigned)CAT->getZExtSize() << 0; |
| 6175 | DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param); |
| 6176 | } |
| 6177 | return; |
| 6178 | } |
| 6179 | |
| 6180 | std::optional<CharUnits> ArgSize = |
| 6181 | getASTContext().getTypeSizeInCharsIfKnown(Ty: ArgCAT); |
| 6182 | std::optional<CharUnits> ParmSize = |
| 6183 | getASTContext().getTypeSizeInCharsIfKnown(Ty: CAT); |
| 6184 | if (ArgSize && ParmSize && *ArgSize < *ParmSize) { |
| 6185 | Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small) |
| 6186 | << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() |
| 6187 | << (unsigned)ParmSize->getQuantity() << 1; |
| 6188 | DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param); |
| 6189 | } |
| 6190 | } |
| 6191 | |
| 6192 | /// Given a function expression of unknown-any type, try to rebuild it |
| 6193 | /// to have a function type. |
| 6194 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); |
| 6195 | |
| 6196 | /// Is the given type a placeholder that we need to lower out |
| 6197 | /// immediately during argument processing? |
| 6198 | static bool isPlaceholderToRemoveAsArg(QualType type) { |
| 6199 | // Placeholders are never sugared. |
| 6200 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type); |
| 6201 | if (!placeholder) return false; |
| 6202 | |
| 6203 | switch (placeholder->getKind()) { |
| 6204 | // Ignore all the non-placeholder types. |
| 6205 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
| 6206 | case BuiltinType::Id: |
| 6207 | #include "clang/Basic/OpenCLImageTypes.def" |
| 6208 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
| 6209 | case BuiltinType::Id: |
| 6210 | #include "clang/Basic/OpenCLExtensionTypes.def" |
| 6211 | // In practice we'll never use this, since all SVE types are sugared |
| 6212 | // via TypedefTypes rather than exposed directly as BuiltinTypes. |
| 6213 | #define SVE_TYPE(Name, Id, SingletonId) \ |
| 6214 | case BuiltinType::Id: |
| 6215 | #include "clang/Basic/AArch64ACLETypes.def" |
| 6216 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ |
| 6217 | case BuiltinType::Id: |
| 6218 | #include "clang/Basic/PPCTypes.def" |
| 6219 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
| 6220 | #include "clang/Basic/RISCVVTypes.def" |
| 6221 | #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
| 6222 | #include "clang/Basic/WebAssemblyReferenceTypes.def" |
| 6223 | #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id: |
| 6224 | #include "clang/Basic/AMDGPUTypes.def" |
| 6225 | #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
| 6226 | #include "clang/Basic/HLSLIntangibleTypes.def" |
| 6227 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) |
| 6228 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: |
| 6229 | #include "clang/AST/BuiltinTypes.def" |
| 6230 | return false; |
| 6231 | |
| 6232 | case BuiltinType::UnresolvedTemplate: |
| 6233 | // We cannot lower out overload sets; they might validly be resolved |
| 6234 | // by the call machinery. |
| 6235 | case BuiltinType::Overload: |
| 6236 | return false; |
| 6237 | |
| 6238 | // Unbridged casts in ARC can be handled in some call positions and |
| 6239 | // should be left in place. |
| 6240 | case BuiltinType::ARCUnbridgedCast: |
| 6241 | return false; |
| 6242 | |
| 6243 | // Pseudo-objects should be converted as soon as possible. |
| 6244 | case BuiltinType::PseudoObject: |
| 6245 | return true; |
| 6246 | |
| 6247 | // The debugger mode could theoretically but currently does not try |
| 6248 | // to resolve unknown-typed arguments based on known parameter types. |
| 6249 | case BuiltinType::UnknownAny: |
| 6250 | return true; |
| 6251 | |
| 6252 | // These are always invalid as call arguments and should be reported. |
| 6253 | case BuiltinType::BoundMember: |
| 6254 | case BuiltinType::BuiltinFn: |
| 6255 | case BuiltinType::IncompleteMatrixIdx: |
| 6256 | case BuiltinType::ArraySection: |
| 6257 | case BuiltinType::OMPArrayShaping: |
| 6258 | case BuiltinType::OMPIterator: |
| 6259 | return true; |
| 6260 | |
| 6261 | } |
| 6262 | llvm_unreachable("bad builtin type kind" ); |
| 6263 | } |
| 6264 | |
| 6265 | bool Sema::CheckArgsForPlaceholders(MultiExprArg args) { |
| 6266 | // Apply this processing to all the arguments at once instead of |
| 6267 | // dying at the first failure. |
| 6268 | bool hasInvalid = false; |
| 6269 | for (size_t i = 0, e = args.size(); i != e; i++) { |
| 6270 | if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) { |
| 6271 | ExprResult result = CheckPlaceholderExpr(E: args[i]); |
| 6272 | if (result.isInvalid()) hasInvalid = true; |
| 6273 | else args[i] = result.get(); |
| 6274 | } |
| 6275 | } |
| 6276 | return hasInvalid; |
| 6277 | } |
| 6278 | |
| 6279 | /// If a builtin function has a pointer argument with no explicit address |
| 6280 | /// space, then it should be able to accept a pointer to any address |
| 6281 | /// space as input. In order to do this, we need to replace the |
| 6282 | /// standard builtin declaration with one that uses the same address space |
| 6283 | /// as the call. |
| 6284 | /// |
| 6285 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. |
| 6286 | /// it does not contain any pointer arguments without |
| 6287 | /// an address space qualifer. Otherwise the rewritten |
| 6288 | /// FunctionDecl is returned. |
| 6289 | /// TODO: Handle pointer return types. |
| 6290 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, |
| 6291 | FunctionDecl *FDecl, |
| 6292 | MultiExprArg ArgExprs) { |
| 6293 | |
| 6294 | QualType DeclType = FDecl->getType(); |
| 6295 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType); |
| 6296 | |
| 6297 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT || |
| 6298 | ArgExprs.size() < FT->getNumParams()) |
| 6299 | return nullptr; |
| 6300 | |
| 6301 | bool NeedsNewDecl = false; |
| 6302 | unsigned i = 0; |
| 6303 | SmallVector<QualType, 8> OverloadParams; |
| 6304 | |
| 6305 | for (QualType ParamType : FT->param_types()) { |
| 6306 | |
| 6307 | // Convert array arguments to pointer to simplify type lookup. |
| 6308 | ExprResult ArgRes = |
| 6309 | Sema->DefaultFunctionArrayLvalueConversion(E: ArgExprs[i++]); |
| 6310 | if (ArgRes.isInvalid()) |
| 6311 | return nullptr; |
| 6312 | Expr *Arg = ArgRes.get(); |
| 6313 | QualType ArgType = Arg->getType(); |
| 6314 | if (!ParamType->isPointerType() || |
| 6315 | ParamType->getPointeeType().hasAddressSpace() || |
| 6316 | !ArgType->isPointerType() || |
| 6317 | !ArgType->getPointeeType().hasAddressSpace() || |
| 6318 | isPtrSizeAddressSpace(AS: ArgType->getPointeeType().getAddressSpace())) { |
| 6319 | OverloadParams.push_back(Elt: ParamType); |
| 6320 | continue; |
| 6321 | } |
| 6322 | |
| 6323 | QualType PointeeType = ParamType->getPointeeType(); |
| 6324 | NeedsNewDecl = true; |
| 6325 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); |
| 6326 | |
| 6327 | PointeeType = Context.getAddrSpaceQualType(T: PointeeType, AddressSpace: AS); |
| 6328 | OverloadParams.push_back(Elt: Context.getPointerType(T: PointeeType)); |
| 6329 | } |
| 6330 | |
| 6331 | if (!NeedsNewDecl) |
| 6332 | return nullptr; |
| 6333 | |
| 6334 | FunctionProtoType::ExtProtoInfo EPI; |
| 6335 | EPI.Variadic = FT->isVariadic(); |
| 6336 | QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(), |
| 6337 | Args: OverloadParams, EPI); |
| 6338 | DeclContext *Parent = FDecl->getParent(); |
| 6339 | FunctionDecl *OverloadDecl = FunctionDecl::Create( |
| 6340 | C&: Context, DC: Parent, StartLoc: FDecl->getLocation(), NLoc: FDecl->getLocation(), |
| 6341 | N: FDecl->getIdentifier(), T: OverloadTy, |
| 6342 | /*TInfo=*/nullptr, SC: SC_Extern, UsesFPIntrin: Sema->getCurFPFeatures().isFPConstrained(), |
| 6343 | isInlineSpecified: false, |
| 6344 | /*hasPrototype=*/hasWrittenPrototype: true); |
| 6345 | SmallVector<ParmVarDecl*, 16> Params; |
| 6346 | FT = cast<FunctionProtoType>(Val&: OverloadTy); |
| 6347 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { |
| 6348 | QualType ParamType = FT->getParamType(i); |
| 6349 | ParmVarDecl *Parm = |
| 6350 | ParmVarDecl::Create(C&: Context, DC: OverloadDecl, StartLoc: SourceLocation(), |
| 6351 | IdLoc: SourceLocation(), Id: nullptr, T: ParamType, |
| 6352 | /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr); |
| 6353 | Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i); |
| 6354 | Params.push_back(Elt: Parm); |
| 6355 | } |
| 6356 | OverloadDecl->setParams(Params); |
| 6357 | // We cannot merge host/device attributes of redeclarations. They have to |
| 6358 | // be consistent when created. |
| 6359 | if (Sema->LangOpts.CUDA) { |
| 6360 | if (FDecl->hasAttr<CUDAHostAttr>()) |
| 6361 | OverloadDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context)); |
| 6362 | if (FDecl->hasAttr<CUDADeviceAttr>()) |
| 6363 | OverloadDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context)); |
| 6364 | } |
| 6365 | Sema->mergeDeclAttributes(New: OverloadDecl, Old: FDecl); |
| 6366 | return OverloadDecl; |
| 6367 | } |
| 6368 | |
| 6369 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, |
| 6370 | FunctionDecl *Callee, |
| 6371 | MultiExprArg ArgExprs) { |
| 6372 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and |
| 6373 | // similar attributes) really don't like it when functions are called with an |
| 6374 | // invalid number of args. |
| 6375 | if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(), |
| 6376 | /*PartialOverloading=*/false) && |
| 6377 | !Callee->isVariadic()) |
| 6378 | return; |
| 6379 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) |
| 6380 | return; |
| 6381 | |
| 6382 | if (const EnableIfAttr *Attr = |
| 6383 | S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) { |
| 6384 | S.Diag(Loc: Fn->getBeginLoc(), |
| 6385 | DiagID: isa<CXXMethodDecl>(Val: Callee) |
| 6386 | ? diag::err_ovl_no_viable_member_function_in_call |
| 6387 | : diag::err_ovl_no_viable_function_in_call) |
| 6388 | << Callee << Callee->getSourceRange(); |
| 6389 | S.Diag(Loc: Callee->getLocation(), |
| 6390 | DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr) |
| 6391 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); |
| 6392 | return; |
| 6393 | } |
| 6394 | } |
| 6395 | |
| 6396 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( |
| 6397 | const UnresolvedMemberExpr *const UME, Sema &S) { |
| 6398 | |
| 6399 | const auto GetFunctionLevelDCIfCXXClass = |
| 6400 | [](Sema &S) -> const CXXRecordDecl * { |
| 6401 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); |
| 6402 | if (!DC || !DC->getParent()) |
| 6403 | return nullptr; |
| 6404 | |
| 6405 | // If the call to some member function was made from within a member |
| 6406 | // function body 'M' return return 'M's parent. |
| 6407 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC)) |
| 6408 | return MD->getParent()->getCanonicalDecl(); |
| 6409 | // else the call was made from within a default member initializer of a |
| 6410 | // class, so return the class. |
| 6411 | if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) |
| 6412 | return RD->getCanonicalDecl(); |
| 6413 | return nullptr; |
| 6414 | }; |
| 6415 | // If our DeclContext is neither a member function nor a class (in the |
| 6416 | // case of a lambda in a default member initializer), we can't have an |
| 6417 | // enclosing 'this'. |
| 6418 | |
| 6419 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); |
| 6420 | if (!CurParentClass) |
| 6421 | return false; |
| 6422 | |
| 6423 | // The naming class for implicit member functions call is the class in which |
| 6424 | // name lookup starts. |
| 6425 | const CXXRecordDecl *const NamingClass = |
| 6426 | UME->getNamingClass()->getCanonicalDecl(); |
| 6427 | assert(NamingClass && "Must have naming class even for implicit access" ); |
| 6428 | |
| 6429 | // If the unresolved member functions were found in a 'naming class' that is |
| 6430 | // related (either the same or derived from) to the class that contains the |
| 6431 | // member function that itself contained the implicit member access. |
| 6432 | |
| 6433 | return CurParentClass == NamingClass || |
| 6434 | CurParentClass->isDerivedFrom(Base: NamingClass); |
| 6435 | } |
| 6436 | |
| 6437 | static void |
| 6438 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( |
| 6439 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { |
| 6440 | |
| 6441 | if (!UME) |
| 6442 | return; |
| 6443 | |
| 6444 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); |
| 6445 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't |
| 6446 | // already been captured, or if this is an implicit member function call (if |
| 6447 | // it isn't, an attempt to capture 'this' should already have been made). |
| 6448 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || |
| 6449 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) |
| 6450 | return; |
| 6451 | |
| 6452 | // Check if the naming class in which the unresolved members were found is |
| 6453 | // related (same as or is a base of) to the enclosing class. |
| 6454 | |
| 6455 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) |
| 6456 | return; |
| 6457 | |
| 6458 | |
| 6459 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); |
| 6460 | // If the enclosing function is not dependent, then this lambda is |
| 6461 | // capture ready, so if we can capture this, do so. |
| 6462 | if (!EnclosingFunctionCtx->isDependentContext()) { |
| 6463 | // If the current lambda and all enclosing lambdas can capture 'this' - |
| 6464 | // then go ahead and capture 'this' (since our unresolved overload set |
| 6465 | // contains at least one non-static member function). |
| 6466 | if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false)) |
| 6467 | S.CheckCXXThisCapture(Loc: CallLoc); |
| 6468 | } else if (S.CurContext->isDependentContext()) { |
| 6469 | // ... since this is an implicit member reference, that might potentially |
| 6470 | // involve a 'this' capture, mark 'this' for potential capture in |
| 6471 | // enclosing lambdas. |
| 6472 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) |
| 6473 | CurLSI->addPotentialThisCapture(Loc: CallLoc); |
| 6474 | } |
| 6475 | } |
| 6476 | |
| 6477 | // Once a call is fully resolved, warn for unqualified calls to specific |
| 6478 | // C++ standard functions, like move and forward. |
| 6479 | static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, |
| 6480 | const CallExpr *Call) { |
| 6481 | // We are only checking unary move and forward so exit early here. |
| 6482 | if (Call->getNumArgs() != 1) |
| 6483 | return; |
| 6484 | |
| 6485 | const Expr *E = Call->getCallee()->IgnoreParenImpCasts(); |
| 6486 | if (!E || isa<UnresolvedLookupExpr>(Val: E)) |
| 6487 | return; |
| 6488 | const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E); |
| 6489 | if (!DRE || !DRE->getLocation().isValid()) |
| 6490 | return; |
| 6491 | |
| 6492 | if (DRE->getQualifier()) |
| 6493 | return; |
| 6494 | |
| 6495 | const FunctionDecl *FD = Call->getDirectCallee(); |
| 6496 | if (!FD) |
| 6497 | return; |
| 6498 | |
| 6499 | // Only warn for some functions deemed more frequent or problematic. |
| 6500 | unsigned BuiltinID = FD->getBuiltinID(); |
| 6501 | if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward) |
| 6502 | return; |
| 6503 | |
| 6504 | S.Diag(Loc: DRE->getLocation(), DiagID: diag::warn_unqualified_call_to_std_cast_function) |
| 6505 | << FD->getQualifiedNameAsString() |
| 6506 | << FixItHint::CreateInsertion(InsertionLoc: DRE->getLocation(), Code: "std::" ); |
| 6507 | } |
| 6508 | |
| 6509 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, |
| 6510 | MultiExprArg ArgExprs, SourceLocation RParenLoc, |
| 6511 | Expr *ExecConfig) { |
| 6512 | ExprResult Call = |
| 6513 | BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, |
| 6514 | /*IsExecConfig=*/false, /*AllowRecovery=*/true); |
| 6515 | if (Call.isInvalid()) |
| 6516 | return Call; |
| 6517 | |
| 6518 | // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier |
| 6519 | // language modes. |
| 6520 | if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn); |
| 6521 | ULE && ULE->hasExplicitTemplateArgs() && |
| 6522 | ULE->decls_begin() == ULE->decls_end()) { |
| 6523 | DiagCompat(Loc: Fn->getExprLoc(), CompatDiagId: diag_compat::adl_only_template_id) |
| 6524 | << ULE->getName(); |
| 6525 | } |
| 6526 | |
| 6527 | if (LangOpts.OpenMP) |
| 6528 | Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, |
| 6529 | ExecConfig); |
| 6530 | if (LangOpts.CPlusPlus) { |
| 6531 | if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get())) |
| 6532 | DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE); |
| 6533 | |
| 6534 | // If we previously found that the id-expression of this call refers to a |
| 6535 | // consteval function but the call is dependent, we should not treat is an |
| 6536 | // an invalid immediate call. |
| 6537 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens()); |
| 6538 | DRE && Call.get()->isValueDependent()) { |
| 6539 | currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE); |
| 6540 | } |
| 6541 | } |
| 6542 | return Call; |
| 6543 | } |
| 6544 | |
| 6545 | // Any type that could be used to form a callable expression |
| 6546 | static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) { |
| 6547 | QualType T = E->getType(); |
| 6548 | if (T->isDependentType()) |
| 6549 | return true; |
| 6550 | |
| 6551 | if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy || |
| 6552 | T == Context.BuiltinFnTy || T == Context.OverloadTy || |
| 6553 | T->isFunctionType() || T->isFunctionReferenceType() || |
| 6554 | T->isMemberFunctionPointerType() || T->isFunctionPointerType() || |
| 6555 | T->isBlockPointerType() || T->isRecordType()) |
| 6556 | return true; |
| 6557 | |
| 6558 | return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr, |
| 6559 | OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(Val: E); |
| 6560 | } |
| 6561 | |
| 6562 | ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, |
| 6563 | MultiExprArg ArgExprs, SourceLocation RParenLoc, |
| 6564 | Expr *ExecConfig, bool IsExecConfig, |
| 6565 | bool AllowRecovery) { |
| 6566 | // Since this might be a postfix expression, get rid of ParenListExprs. |
| 6567 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn); |
| 6568 | if (Result.isInvalid()) return ExprError(); |
| 6569 | Fn = Result.get(); |
| 6570 | |
| 6571 | if (CheckArgsForPlaceholders(args: ArgExprs)) |
| 6572 | return ExprError(); |
| 6573 | |
| 6574 | // The result of __builtin_counted_by_ref cannot be used as a function |
| 6575 | // argument. It allows leaking and modification of bounds safety information. |
| 6576 | for (const Expr *Arg : ArgExprs) |
| 6577 | if (CheckInvalidBuiltinCountedByRef(E: Arg, |
| 6578 | K: BuiltinCountedByRefKind::FunctionArg)) |
| 6579 | return ExprError(); |
| 6580 | |
| 6581 | if (getLangOpts().CPlusPlus) { |
| 6582 | // If this is a pseudo-destructor expression, build the call immediately. |
| 6583 | if (isa<CXXPseudoDestructorExpr>(Val: Fn)) { |
| 6584 | if (!ArgExprs.empty()) { |
| 6585 | // Pseudo-destructor calls should not have any arguments. |
| 6586 | Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_pseudo_dtor_call_with_args) |
| 6587 | << FixItHint::CreateRemoval( |
| 6588 | RemoveRange: SourceRange(ArgExprs.front()->getBeginLoc(), |
| 6589 | ArgExprs.back()->getEndLoc())); |
| 6590 | } |
| 6591 | |
| 6592 | return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy, |
| 6593 | VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
| 6594 | } |
| 6595 | if (Fn->getType() == Context.PseudoObjectTy) { |
| 6596 | ExprResult result = CheckPlaceholderExpr(E: Fn); |
| 6597 | if (result.isInvalid()) return ExprError(); |
| 6598 | Fn = result.get(); |
| 6599 | } |
| 6600 | |
| 6601 | // Determine whether this is a dependent call inside a C++ template, |
| 6602 | // in which case we won't do any semantic analysis now. |
| 6603 | if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) { |
| 6604 | if (ExecConfig) { |
| 6605 | return CUDAKernelCallExpr::Create(Ctx: Context, Fn, |
| 6606 | Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs, |
| 6607 | Ty: Context.DependentTy, VK: VK_PRValue, |
| 6608 | RP: RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
| 6609 | } else { |
| 6610 | |
| 6611 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( |
| 6612 | S&: *this, UME: dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()), |
| 6613 | CallLoc: Fn->getBeginLoc()); |
| 6614 | |
| 6615 | // If the type of the function itself is not dependent |
| 6616 | // check that it is a reasonable as a function, as type deduction |
| 6617 | // later assume the CallExpr has a sensible TYPE. |
| 6618 | if (!MayBeFunctionType(Context, E: Fn)) |
| 6619 | return ExprError( |
| 6620 | Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function) |
| 6621 | << Fn->getType() << Fn->getSourceRange()); |
| 6622 | |
| 6623 | return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy, |
| 6624 | VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
| 6625 | } |
| 6626 | } |
| 6627 | |
| 6628 | // Determine whether this is a call to an object (C++ [over.call.object]). |
| 6629 | if (Fn->getType()->isRecordType()) |
| 6630 | return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs, |
| 6631 | RParenLoc); |
| 6632 | |
| 6633 | if (Fn->getType() == Context.UnknownAnyTy) { |
| 6634 | ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn); |
| 6635 | if (result.isInvalid()) return ExprError(); |
| 6636 | Fn = result.get(); |
| 6637 | } |
| 6638 | |
| 6639 | if (Fn->getType() == Context.BoundMemberTy) { |
| 6640 | return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs, |
| 6641 | RParenLoc, ExecConfig, IsExecConfig, |
| 6642 | AllowRecovery); |
| 6643 | } |
| 6644 | } |
| 6645 | |
| 6646 | // Check for overloaded calls. This can happen even in C due to extensions. |
| 6647 | if (Fn->getType() == Context.OverloadTy) { |
| 6648 | OverloadExpr::FindResult find = OverloadExpr::find(E: Fn); |
| 6649 | |
| 6650 | // We aren't supposed to apply this logic if there's an '&' involved. |
| 6651 | if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) { |
| 6652 | if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) |
| 6653 | return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy, |
| 6654 | VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
| 6655 | OverloadExpr *ovl = find.Expression; |
| 6656 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl)) |
| 6657 | return BuildOverloadedCallExpr( |
| 6658 | S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig, |
| 6659 | /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand); |
| 6660 | return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs, |
| 6661 | RParenLoc, ExecConfig, IsExecConfig, |
| 6662 | AllowRecovery); |
| 6663 | } |
| 6664 | } |
| 6665 | |
| 6666 | // If we're directly calling a function, get the appropriate declaration. |
| 6667 | if (Fn->getType() == Context.UnknownAnyTy) { |
| 6668 | ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn); |
| 6669 | if (result.isInvalid()) return ExprError(); |
| 6670 | Fn = result.get(); |
| 6671 | } |
| 6672 | |
| 6673 | Expr *NakedFn = Fn->IgnoreParens(); |
| 6674 | |
| 6675 | bool CallingNDeclIndirectly = false; |
| 6676 | NamedDecl *NDecl = nullptr; |
| 6677 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) { |
| 6678 | if (UnOp->getOpcode() == UO_AddrOf) { |
| 6679 | CallingNDeclIndirectly = true; |
| 6680 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); |
| 6681 | } |
| 6682 | } |
| 6683 | |
| 6684 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) { |
| 6685 | NDecl = DRE->getDecl(); |
| 6686 | |
| 6687 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl); |
| 6688 | if (FDecl && FDecl->getBuiltinID()) { |
| 6689 | // Rewrite the function decl for this builtin by replacing parameters |
| 6690 | // with no explicit address space with the address space of the arguments |
| 6691 | // in ArgExprs. |
| 6692 | if ((FDecl = |
| 6693 | rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) { |
| 6694 | NDecl = FDecl; |
| 6695 | Fn = DeclRefExpr::Create( |
| 6696 | Context, QualifierLoc: FDecl->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: FDecl, RefersToEnclosingVariableOrCapture: false, |
| 6697 | NameLoc: SourceLocation(), T: FDecl->getType(), VK: Fn->getValueKind(), FoundD: FDecl, |
| 6698 | TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse()); |
| 6699 | } |
| 6700 | } |
| 6701 | } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn)) |
| 6702 | NDecl = ME->getMemberDecl(); |
| 6703 | |
| 6704 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) { |
| 6705 | if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( |
| 6706 | Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc())) |
| 6707 | return ExprError(); |
| 6708 | |
| 6709 | checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs); |
| 6710 | |
| 6711 | // If this expression is a call to a builtin function in HIP device |
| 6712 | // compilation, allow a pointer-type argument to default address space to be |
| 6713 | // passed as a pointer-type parameter to a non-default address space. |
| 6714 | // If Arg is declared in the default address space and Param is declared |
| 6715 | // in a non-default address space, perform an implicit address space cast to |
| 6716 | // the parameter type. |
| 6717 | if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && |
| 6718 | FD->getBuiltinID()) { |
| 6719 | for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size(); |
| 6720 | ++Idx) { |
| 6721 | ParmVarDecl *Param = FD->getParamDecl(i: Idx); |
| 6722 | if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || |
| 6723 | !ArgExprs[Idx]->getType()->isPointerType()) |
| 6724 | continue; |
| 6725 | |
| 6726 | auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); |
| 6727 | auto ArgTy = ArgExprs[Idx]->getType(); |
| 6728 | auto ArgPtTy = ArgTy->getPointeeType(); |
| 6729 | auto ArgAS = ArgPtTy.getAddressSpace(); |
| 6730 | |
| 6731 | // Add address space cast if target address spaces are different |
| 6732 | bool NeedImplicitASC = |
| 6733 | ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. |
| 6734 | ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS |
| 6735 | // or from specific AS which has target AS matching that of Param. |
| 6736 | getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS)); |
| 6737 | if (!NeedImplicitASC) |
| 6738 | continue; |
| 6739 | |
| 6740 | // First, ensure that the Arg is an RValue. |
| 6741 | if (ArgExprs[Idx]->isGLValue()) { |
| 6742 | ArgExprs[Idx] = ImplicitCastExpr::Create( |
| 6743 | Context, T: ArgExprs[Idx]->getType(), Kind: CK_NoOp, Operand: ArgExprs[Idx], |
| 6744 | BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
| 6745 | } |
| 6746 | |
| 6747 | // Construct a new arg type with address space of Param |
| 6748 | Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); |
| 6749 | ArgPtQuals.setAddressSpace(ParamAS); |
| 6750 | auto NewArgPtTy = |
| 6751 | Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals); |
| 6752 | auto NewArgTy = |
| 6753 | Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy), |
| 6754 | Qs: ArgTy.getQualifiers()); |
| 6755 | |
| 6756 | // Finally perform an implicit address space cast |
| 6757 | ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy, |
| 6758 | CK: CK_AddressSpaceConversion) |
| 6759 | .get(); |
| 6760 | } |
| 6761 | } |
| 6762 | } |
| 6763 | |
| 6764 | if (Context.isDependenceAllowed() && |
| 6765 | (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) { |
| 6766 | assert(!getLangOpts().CPlusPlus); |
| 6767 | assert((Fn->containsErrors() || |
| 6768 | llvm::any_of(ArgExprs, |
| 6769 | [](clang::Expr *E) { return E->containsErrors(); })) && |
| 6770 | "should only occur in error-recovery path." ); |
| 6771 | return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy, |
| 6772 | VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
| 6773 | } |
| 6774 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc, |
| 6775 | Config: ExecConfig, IsExecConfig); |
| 6776 | } |
| 6777 | |
| 6778 | Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, |
| 6779 | MultiExprArg CallArgs) { |
| 6780 | std::string Name = Context.BuiltinInfo.getName(ID: Id); |
| 6781 | LookupResult R(*this, &Context.Idents.get(Name), Loc, |
| 6782 | Sema::LookupOrdinaryName); |
| 6783 | LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true); |
| 6784 | |
| 6785 | auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); |
| 6786 | assert(BuiltInDecl && "failed to find builtin declaration" ); |
| 6787 | |
| 6788 | ExprResult DeclRef = |
| 6789 | BuildDeclRefExpr(D: BuiltInDecl, Ty: BuiltInDecl->getType(), VK: VK_LValue, Loc); |
| 6790 | assert(DeclRef.isUsable() && "Builtin reference cannot fail" ); |
| 6791 | |
| 6792 | ExprResult Call = |
| 6793 | BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc); |
| 6794 | |
| 6795 | assert(!Call.isInvalid() && "Call to builtin cannot fail!" ); |
| 6796 | return Call.get(); |
| 6797 | } |
| 6798 | |
| 6799 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, |
| 6800 | SourceLocation BuiltinLoc, |
| 6801 | SourceLocation RParenLoc) { |
| 6802 | QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy); |
| 6803 | return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc); |
| 6804 | } |
| 6805 | |
| 6806 | ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, |
| 6807 | SourceLocation BuiltinLoc, |
| 6808 | SourceLocation RParenLoc) { |
| 6809 | ExprValueKind VK = VK_PRValue; |
| 6810 | ExprObjectKind OK = OK_Ordinary; |
| 6811 | QualType SrcTy = E->getType(); |
| 6812 | if (!SrcTy->isDependentType() && |
| 6813 | Context.getTypeSize(T: DestTy) != Context.getTypeSize(T: SrcTy)) |
| 6814 | return ExprError( |
| 6815 | Diag(Loc: BuiltinLoc, DiagID: diag::err_invalid_astype_of_different_size) |
| 6816 | << DestTy << SrcTy << E->getSourceRange()); |
| 6817 | return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); |
| 6818 | } |
| 6819 | |
| 6820 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, |
| 6821 | SourceLocation BuiltinLoc, |
| 6822 | SourceLocation RParenLoc) { |
| 6823 | TypeSourceInfo *TInfo; |
| 6824 | GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo); |
| 6825 | return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); |
| 6826 | } |
| 6827 | |
| 6828 | ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, |
| 6829 | SourceLocation LParenLoc, |
| 6830 | ArrayRef<Expr *> Args, |
| 6831 | SourceLocation RParenLoc, Expr *Config, |
| 6832 | bool IsExecConfig, ADLCallKind UsesADL) { |
| 6833 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl); |
| 6834 | unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); |
| 6835 | |
| 6836 | // Functions with 'interrupt' attribute cannot be called directly. |
| 6837 | if (FDecl) { |
| 6838 | if (FDecl->hasAttr<AnyX86InterruptAttr>()) { |
| 6839 | Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_anyx86_interrupt_called); |
| 6840 | return ExprError(); |
| 6841 | } |
| 6842 | if (FDecl->hasAttr<ARMInterruptAttr>()) { |
| 6843 | Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_arm_interrupt_called); |
| 6844 | return ExprError(); |
| 6845 | } |
| 6846 | } |
| 6847 | |
| 6848 | // X86 interrupt handlers may only call routines with attribute |
| 6849 | // no_caller_saved_registers since there is no efficient way to |
| 6850 | // save and restore the non-GPR state. |
| 6851 | if (auto *Caller = getCurFunctionDecl()) { |
| 6852 | if (Caller->hasAttr<AnyX86InterruptAttr>() || |
| 6853 | Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) { |
| 6854 | const TargetInfo &TI = Context.getTargetInfo(); |
| 6855 | bool HasNonGPRRegisters = |
| 6856 | TI.hasFeature(Feature: "sse" ) || TI.hasFeature(Feature: "x87" ) || TI.hasFeature(Feature: "mmx" ); |
| 6857 | if (HasNonGPRRegisters && |
| 6858 | (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) { |
| 6859 | Diag(Loc: Fn->getExprLoc(), DiagID: diag::warn_anyx86_excessive_regsave) |
| 6860 | << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1); |
| 6861 | if (FDecl) |
| 6862 | Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) << FDecl; |
| 6863 | } |
| 6864 | } |
| 6865 | } |
| 6866 | |
| 6867 | // Promote the function operand. |
| 6868 | // We special-case function promotion here because we only allow promoting |
| 6869 | // builtin functions to function pointers in the callee of a call. |
| 6870 | ExprResult Result; |
| 6871 | QualType ResultTy; |
| 6872 | if (BuiltinID && |
| 6873 | Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) { |
| 6874 | // Extract the return type from the (builtin) function pointer type. |
| 6875 | // FIXME Several builtins still have setType in |
| 6876 | // Sema::CheckBuiltinFunctionCall. One should review their definitions in |
| 6877 | // Builtins.td to ensure they are correct before removing setType calls. |
| 6878 | QualType FnPtrTy = Context.getPointerType(T: FDecl->getType()); |
| 6879 | Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get(); |
| 6880 | ResultTy = FDecl->getCallResultType(); |
| 6881 | } else { |
| 6882 | Result = CallExprUnaryConversions(E: Fn); |
| 6883 | ResultTy = Context.BoolTy; |
| 6884 | } |
| 6885 | if (Result.isInvalid()) |
| 6886 | return ExprError(); |
| 6887 | Fn = Result.get(); |
| 6888 | |
| 6889 | // Check for a valid function type, but only if it is not a builtin which |
| 6890 | // requires custom type checking. These will be handled by |
| 6891 | // CheckBuiltinFunctionCall below just after creation of the call expression. |
| 6892 | const FunctionType *FuncT = nullptr; |
| 6893 | if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) { |
| 6894 | retry: |
| 6895 | if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { |
| 6896 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall |
| 6897 | // have type pointer to function". |
| 6898 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); |
| 6899 | if (!FuncT) |
| 6900 | return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function) |
| 6901 | << Fn->getType() << Fn->getSourceRange()); |
| 6902 | } else if (const BlockPointerType *BPT = |
| 6903 | Fn->getType()->getAs<BlockPointerType>()) { |
| 6904 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); |
| 6905 | } else { |
| 6906 | // Handle calls to expressions of unknown-any type. |
| 6907 | if (Fn->getType() == Context.UnknownAnyTy) { |
| 6908 | ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn); |
| 6909 | if (rewrite.isInvalid()) |
| 6910 | return ExprError(); |
| 6911 | Fn = rewrite.get(); |
| 6912 | goto retry; |
| 6913 | } |
| 6914 | |
| 6915 | return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function) |
| 6916 | << Fn->getType() << Fn->getSourceRange()); |
| 6917 | } |
| 6918 | } |
| 6919 | |
| 6920 | // Get the number of parameters in the function prototype, if any. |
| 6921 | // We will allocate space for max(Args.size(), NumParams) arguments |
| 6922 | // in the call expression. |
| 6923 | const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT); |
| 6924 | unsigned NumParams = Proto ? Proto->getNumParams() : 0; |
| 6925 | |
| 6926 | CallExpr *TheCall; |
| 6927 | if (Config) { |
| 6928 | assert(UsesADL == ADLCallKind::NotADL && |
| 6929 | "CUDAKernelCallExpr should not use ADL" ); |
| 6930 | TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config), |
| 6931 | Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc, |
| 6932 | FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams); |
| 6933 | } else { |
| 6934 | TheCall = |
| 6935 | CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc, |
| 6936 | FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL); |
| 6937 | } |
| 6938 | |
| 6939 | // Bail out early if calling a builtin with custom type checking. |
| 6940 | if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) { |
| 6941 | ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); |
| 6942 | if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID)) |
| 6943 | E = CheckForImmediateInvocation(E, Decl: FDecl); |
| 6944 | return E; |
| 6945 | } |
| 6946 | |
| 6947 | if (getLangOpts().CUDA) { |
| 6948 | if (Config) { |
| 6949 | // CUDA: Kernel calls must be to global functions |
| 6950 | if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) |
| 6951 | return ExprError(Diag(Loc: LParenLoc,DiagID: diag::err_kern_call_not_global_function) |
| 6952 | << FDecl << Fn->getSourceRange()); |
| 6953 | |
| 6954 | // CUDA: Kernel function must have 'void' return type |
| 6955 | if (!FuncT->getReturnType()->isVoidType() && |
| 6956 | !FuncT->getReturnType()->getAs<AutoType>() && |
| 6957 | !FuncT->getReturnType()->isInstantiationDependentType()) |
| 6958 | return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_kern_type_not_void_return) |
| 6959 | << Fn->getType() << Fn->getSourceRange()); |
| 6960 | } else { |
| 6961 | // CUDA: Calls to global functions must be configured |
| 6962 | if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) |
| 6963 | return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_global_call_not_config) |
| 6964 | << FDecl << Fn->getSourceRange()); |
| 6965 | } |
| 6966 | } |
| 6967 | |
| 6968 | // Check for a valid return type |
| 6969 | if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall, |
| 6970 | FD: FDecl)) |
| 6971 | return ExprError(); |
| 6972 | |
| 6973 | // We know the result type of the call, set it. |
| 6974 | TheCall->setType(FuncT->getCallResultType(Context)); |
| 6975 | TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType())); |
| 6976 | |
| 6977 | // WebAssembly tables can't be used as arguments. |
| 6978 | if (Context.getTargetInfo().getTriple().isWasm()) { |
| 6979 | for (const Expr *Arg : Args) { |
| 6980 | if (Arg && Arg->getType()->isWebAssemblyTableType()) { |
| 6981 | return ExprError(Diag(Loc: Arg->getExprLoc(), |
| 6982 | DiagID: diag::err_wasm_table_as_function_parameter)); |
| 6983 | } |
| 6984 | } |
| 6985 | } |
| 6986 | |
| 6987 | if (Proto) { |
| 6988 | if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc, |
| 6989 | IsExecConfig)) |
| 6990 | return ExprError(); |
| 6991 | } else { |
| 6992 | assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!" ); |
| 6993 | |
| 6994 | if (FDecl) { |
| 6995 | // Check if we have too few/too many template arguments, based |
| 6996 | // on our knowledge of the function definition. |
| 6997 | const FunctionDecl *Def = nullptr; |
| 6998 | if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) { |
| 6999 | Proto = Def->getType()->getAs<FunctionProtoType>(); |
| 7000 | if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) |
| 7001 | Diag(Loc: RParenLoc, DiagID: diag::warn_call_wrong_number_of_arguments) |
| 7002 | << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); |
| 7003 | } |
| 7004 | |
| 7005 | // If the function we're calling isn't a function prototype, but we have |
| 7006 | // a function prototype from a prior declaratiom, use that prototype. |
| 7007 | if (!FDecl->hasPrototype()) |
| 7008 | Proto = FDecl->getType()->getAs<FunctionProtoType>(); |
| 7009 | } |
| 7010 | |
| 7011 | // If we still haven't found a prototype to use but there are arguments to |
| 7012 | // the call, diagnose this as calling a function without a prototype. |
| 7013 | // However, if we found a function declaration, check to see if |
| 7014 | // -Wdeprecated-non-prototype was disabled where the function was declared. |
| 7015 | // If so, we will silence the diagnostic here on the assumption that this |
| 7016 | // interface is intentional and the user knows what they're doing. We will |
| 7017 | // also silence the diagnostic if there is a function declaration but it |
| 7018 | // was implicitly defined (the user already gets diagnostics about the |
| 7019 | // creation of the implicit function declaration, so the additional warning |
| 7020 | // is not helpful). |
| 7021 | if (!Proto && !Args.empty() && |
| 7022 | (!FDecl || (!FDecl->isImplicit() && |
| 7023 | !Diags.isIgnored(DiagID: diag::warn_strict_uses_without_prototype, |
| 7024 | Loc: FDecl->getLocation())))) |
| 7025 | Diag(Loc: LParenLoc, DiagID: diag::warn_strict_uses_without_prototype) |
| 7026 | << (FDecl != nullptr) << FDecl; |
| 7027 | |
| 7028 | // Promote the arguments (C99 6.5.2.2p6). |
| 7029 | for (unsigned i = 0, e = Args.size(); i != e; i++) { |
| 7030 | Expr *Arg = Args[i]; |
| 7031 | |
| 7032 | if (Proto && i < Proto->getNumParams()) { |
| 7033 | InitializedEntity Entity = InitializedEntity::InitializeParameter( |
| 7034 | Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i)); |
| 7035 | ExprResult ArgE = |
| 7036 | PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg); |
| 7037 | if (ArgE.isInvalid()) |
| 7038 | return true; |
| 7039 | |
| 7040 | Arg = ArgE.getAs<Expr>(); |
| 7041 | |
| 7042 | } else { |
| 7043 | ExprResult ArgE = DefaultArgumentPromotion(E: Arg); |
| 7044 | |
| 7045 | if (ArgE.isInvalid()) |
| 7046 | return true; |
| 7047 | |
| 7048 | Arg = ArgE.getAs<Expr>(); |
| 7049 | } |
| 7050 | |
| 7051 | if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: Arg->getType(), |
| 7052 | DiagID: diag::err_call_incomplete_argument, Args: Arg)) |
| 7053 | return ExprError(); |
| 7054 | |
| 7055 | TheCall->setArg(Arg: i, ArgExpr: Arg); |
| 7056 | } |
| 7057 | TheCall->computeDependence(); |
| 7058 | } |
| 7059 | |
| 7060 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl)) |
| 7061 | if (Method->isImplicitObjectMemberFunction()) |
| 7062 | return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_member_call_without_object) |
| 7063 | << Fn->getSourceRange() << 0); |
| 7064 | |
| 7065 | // Check for sentinels |
| 7066 | if (NDecl) |
| 7067 | DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args); |
| 7068 | |
| 7069 | // Warn for unions passing across security boundary (CMSE). |
| 7070 | if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { |
| 7071 | for (unsigned i = 0, e = Args.size(); i != e; i++) { |
| 7072 | if (const auto *RT = |
| 7073 | dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) { |
| 7074 | if (RT->getDecl()->isOrContainsUnion()) |
| 7075 | Diag(Loc: Args[i]->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union) |
| 7076 | << 0 << i; |
| 7077 | } |
| 7078 | } |
| 7079 | } |
| 7080 | |
| 7081 | // Do special checking on direct calls to functions. |
| 7082 | if (FDecl) { |
| 7083 | if (CheckFunctionCall(FDecl, TheCall, Proto)) |
| 7084 | return ExprError(); |
| 7085 | |
| 7086 | checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall); |
| 7087 | |
| 7088 | if (BuiltinID) |
| 7089 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); |
| 7090 | } else if (NDecl) { |
| 7091 | if (CheckPointerCall(NDecl, TheCall, Proto)) |
| 7092 | return ExprError(); |
| 7093 | } else { |
| 7094 | if (CheckOtherCall(TheCall, Proto)) |
| 7095 | return ExprError(); |
| 7096 | } |
| 7097 | |
| 7098 | return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FDecl); |
| 7099 | } |
| 7100 | |
| 7101 | ExprResult |
| 7102 | Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, |
| 7103 | SourceLocation RParenLoc, Expr *InitExpr) { |
| 7104 | assert(Ty && "ActOnCompoundLiteral(): missing type" ); |
| 7105 | assert(InitExpr && "ActOnCompoundLiteral(): missing expression" ); |
| 7106 | |
| 7107 | TypeSourceInfo *TInfo; |
| 7108 | QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo); |
| 7109 | if (!TInfo) |
| 7110 | TInfo = Context.getTrivialTypeSourceInfo(T: literalType); |
| 7111 | |
| 7112 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr); |
| 7113 | } |
| 7114 | |
| 7115 | ExprResult |
| 7116 | Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, |
| 7117 | SourceLocation RParenLoc, Expr *LiteralExpr) { |
| 7118 | QualType literalType = TInfo->getType(); |
| 7119 | |
| 7120 | if (literalType->isArrayType()) { |
| 7121 | if (RequireCompleteSizedType( |
| 7122 | Loc: LParenLoc, T: Context.getBaseElementType(QT: literalType), |
| 7123 | DiagID: diag::err_array_incomplete_or_sizeless_type, |
| 7124 | Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) |
| 7125 | return ExprError(); |
| 7126 | if (literalType->isVariableArrayType()) { |
| 7127 | // C23 6.7.10p4: An entity of variable length array type shall not be |
| 7128 | // initialized except by an empty initializer. |
| 7129 | // |
| 7130 | // The C extension warnings are issued from ParseBraceInitializer() and |
| 7131 | // do not need to be issued here. However, we continue to issue an error |
| 7132 | // in the case there are initializers or we are compiling C++. We allow |
| 7133 | // use of VLAs in C++, but it's not clear we want to allow {} to zero |
| 7134 | // init a VLA in C++ in all cases (such as with non-trivial constructors). |
| 7135 | // FIXME: should we allow this construct in C++ when it makes sense to do |
| 7136 | // so? |
| 7137 | // |
| 7138 | // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name |
| 7139 | // shall specify an object type or an array of unknown size, but not a |
| 7140 | // variable length array type. This seems odd, as it allows 'int a[size] = |
| 7141 | // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard |
| 7142 | // says, this is what's implemented here for C (except for the extension |
| 7143 | // that permits constant foldable size arrays) |
| 7144 | |
| 7145 | auto diagID = LangOpts.CPlusPlus |
| 7146 | ? diag::err_variable_object_no_init |
| 7147 | : diag::err_compound_literal_with_vla_type; |
| 7148 | if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc, |
| 7149 | FailedFoldDiagID: diagID)) |
| 7150 | return ExprError(); |
| 7151 | } |
| 7152 | } else if (!literalType->isDependentType() && |
| 7153 | RequireCompleteType(Loc: LParenLoc, T: literalType, |
| 7154 | DiagID: diag::err_typecheck_decl_incomplete_type, |
| 7155 | Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) |
| 7156 | return ExprError(); |
| 7157 | |
| 7158 | InitializedEntity Entity |
| 7159 | = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo); |
| 7160 | InitializationKind Kind |
| 7161 | = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc, |
| 7162 | TypeRange: SourceRange(LParenLoc, RParenLoc), |
| 7163 | /*InitList=*/true); |
| 7164 | InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); |
| 7165 | ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr, |
| 7166 | ResultType: &literalType); |
| 7167 | if (Result.isInvalid()) |
| 7168 | return ExprError(); |
| 7169 | LiteralExpr = Result.get(); |
| 7170 | |
| 7171 | // We treat the compound literal as being at file scope if it's not in a |
| 7172 | // function or method body, or within the function's prototype scope. This |
| 7173 | // means the following compound literal is not at file scope: |
| 7174 | // void func(char *para[(int [1]){ 0 }[0]); |
| 7175 | const Scope *S = getCurScope(); |
| 7176 | bool IsFileScope = !CurContext->isFunctionOrMethod() && |
| 7177 | !S->isInCFunctionScope() && |
| 7178 | (!S || !S->isFunctionPrototypeScope()); |
| 7179 | |
| 7180 | // In C, compound literals are l-values for some reason. |
| 7181 | // For GCC compatibility, in C++, file-scope array compound literals with |
| 7182 | // constant initializers are also l-values, and compound literals are |
| 7183 | // otherwise prvalues. |
| 7184 | // |
| 7185 | // (GCC also treats C++ list-initialized file-scope array prvalues with |
| 7186 | // constant initializers as l-values, but that's non-conforming, so we don't |
| 7187 | // follow it there.) |
| 7188 | // |
| 7189 | // FIXME: It would be better to handle the lvalue cases as materializing and |
| 7190 | // lifetime-extending a temporary object, but our materialized temporaries |
| 7191 | // representation only supports lifetime extension from a variable, not "out |
| 7192 | // of thin air". |
| 7193 | // FIXME: For C++, we might want to instead lifetime-extend only if a pointer |
| 7194 | // is bound to the result of applying array-to-pointer decay to the compound |
| 7195 | // literal. |
| 7196 | // FIXME: GCC supports compound literals of reference type, which should |
| 7197 | // obviously have a value kind derived from the kind of reference involved. |
| 7198 | ExprValueKind VK = |
| 7199 | (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType())) |
| 7200 | ? VK_PRValue |
| 7201 | : VK_LValue; |
| 7202 | |
| 7203 | // C99 6.5.2.5 |
| 7204 | // "If the compound literal occurs outside the body of a function, the |
| 7205 | // initializer list shall consist of constant expressions." |
| 7206 | if (IsFileScope) |
| 7207 | if (auto ILE = dyn_cast<InitListExpr>(Val: LiteralExpr)) |
| 7208 | for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { |
| 7209 | Expr *Init = ILE->getInit(Init: i); |
| 7210 | if (!Init->isTypeDependent() && !Init->isValueDependent() && |
| 7211 | !Init->isConstantInitializer(Ctx&: Context, /*IsForRef=*/ForRef: false)) { |
| 7212 | Diag(Loc: Init->getExprLoc(), DiagID: diag::err_init_element_not_constant) |
| 7213 | << Init->getSourceBitField(); |
| 7214 | return ExprError(); |
| 7215 | } |
| 7216 | |
| 7217 | ILE->setInit(Init: i, expr: ConstantExpr::Create(Context, E: Init)); |
| 7218 | } |
| 7219 | |
| 7220 | auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK, |
| 7221 | LiteralExpr, IsFileScope); |
| 7222 | if (IsFileScope) { |
| 7223 | if (!LiteralExpr->isTypeDependent() && |
| 7224 | !LiteralExpr->isValueDependent() && |
| 7225 | !literalType->isDependentType()) // C99 6.5.2.5p3 |
| 7226 | if (CheckForConstantInitializer(Init: LiteralExpr)) |
| 7227 | return ExprError(); |
| 7228 | } else if (literalType.getAddressSpace() != LangAS::opencl_private && |
| 7229 | literalType.getAddressSpace() != LangAS::Default) { |
| 7230 | // Embedded-C extensions to C99 6.5.2.5: |
| 7231 | // "If the compound literal occurs inside the body of a function, the |
| 7232 | // type name shall not be qualified by an address-space qualifier." |
| 7233 | Diag(Loc: LParenLoc, DiagID: diag::err_compound_literal_with_address_space) |
| 7234 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); |
| 7235 | return ExprError(); |
| 7236 | } |
| 7237 | |
| 7238 | if (!IsFileScope && !getLangOpts().CPlusPlus) { |
| 7239 | // Compound literals that have automatic storage duration are destroyed at |
| 7240 | // the end of the scope in C; in C++, they're just temporaries. |
| 7241 | |
| 7242 | // Emit diagnostics if it is or contains a C union type that is non-trivial |
| 7243 | // to destruct. |
| 7244 | if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) |
| 7245 | checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(), |
| 7246 | UseContext: NonTrivialCUnionContext::CompoundLiteral, |
| 7247 | NonTrivialKind: NTCUK_Destruct); |
| 7248 | |
| 7249 | // Diagnose jumps that enter or exit the lifetime of the compound literal. |
| 7250 | if (literalType.isDestructedType()) { |
| 7251 | Cleanup.setExprNeedsCleanups(true); |
| 7252 | ExprCleanupObjects.push_back(Elt: E); |
| 7253 | getCurFunction()->setHasBranchProtectedScope(); |
| 7254 | } |
| 7255 | } |
| 7256 | |
| 7257 | if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || |
| 7258 | E->getType().hasNonTrivialToPrimitiveCopyCUnion()) |
| 7259 | checkNonTrivialCUnionInInitializer(Init: E->getInitializer(), |
| 7260 | Loc: E->getInitializer()->getExprLoc()); |
| 7261 | |
| 7262 | return MaybeBindToTemporary(E); |
| 7263 | } |
| 7264 | |
| 7265 | ExprResult |
| 7266 | Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, |
| 7267 | SourceLocation RBraceLoc) { |
| 7268 | // Only produce each kind of designated initialization diagnostic once. |
| 7269 | SourceLocation FirstDesignator; |
| 7270 | bool DiagnosedArrayDesignator = false; |
| 7271 | bool DiagnosedNestedDesignator = false; |
| 7272 | bool DiagnosedMixedDesignator = false; |
| 7273 | |
| 7274 | // Check that any designated initializers are syntactically valid in the |
| 7275 | // current language mode. |
| 7276 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { |
| 7277 | if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) { |
| 7278 | if (FirstDesignator.isInvalid()) |
| 7279 | FirstDesignator = DIE->getBeginLoc(); |
| 7280 | |
| 7281 | if (!getLangOpts().CPlusPlus) |
| 7282 | break; |
| 7283 | |
| 7284 | if (!DiagnosedNestedDesignator && DIE->size() > 1) { |
| 7285 | DiagnosedNestedDesignator = true; |
| 7286 | Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_nested) |
| 7287 | << DIE->getDesignatorsSourceRange(); |
| 7288 | } |
| 7289 | |
| 7290 | for (auto &Desig : DIE->designators()) { |
| 7291 | if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { |
| 7292 | DiagnosedArrayDesignator = true; |
| 7293 | Diag(Loc: Desig.getBeginLoc(), DiagID: diag::ext_designated_init_array) |
| 7294 | << Desig.getSourceRange(); |
| 7295 | } |
| 7296 | } |
| 7297 | |
| 7298 | if (!DiagnosedMixedDesignator && |
| 7299 | !isa<DesignatedInitExpr>(Val: InitArgList[0])) { |
| 7300 | DiagnosedMixedDesignator = true; |
| 7301 | Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed) |
| 7302 | << DIE->getSourceRange(); |
| 7303 | Diag(Loc: InitArgList[0]->getBeginLoc(), DiagID: diag::note_designated_init_mixed) |
| 7304 | << InitArgList[0]->getSourceRange(); |
| 7305 | } |
| 7306 | } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && |
| 7307 | isa<DesignatedInitExpr>(Val: InitArgList[0])) { |
| 7308 | DiagnosedMixedDesignator = true; |
| 7309 | auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]); |
| 7310 | Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed) |
| 7311 | << DIE->getSourceRange(); |
| 7312 | Diag(Loc: InitArgList[I]->getBeginLoc(), DiagID: diag::note_designated_init_mixed) |
| 7313 | << InitArgList[I]->getSourceRange(); |
| 7314 | } |
| 7315 | } |
| 7316 | |
| 7317 | if (FirstDesignator.isValid()) { |
| 7318 | // Only diagnose designated initiaization as a C++20 extension if we didn't |
| 7319 | // already diagnose use of (non-C++20) C99 designator syntax. |
| 7320 | if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && |
| 7321 | !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { |
| 7322 | Diag(Loc: FirstDesignator, DiagID: getLangOpts().CPlusPlus20 |
| 7323 | ? diag::warn_cxx17_compat_designated_init |
| 7324 | : diag::ext_cxx_designated_init); |
| 7325 | } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { |
| 7326 | Diag(Loc: FirstDesignator, DiagID: diag::ext_designated_init); |
| 7327 | } |
| 7328 | } |
| 7329 | |
| 7330 | return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); |
| 7331 | } |
| 7332 | |
| 7333 | ExprResult |
| 7334 | Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, |
| 7335 | SourceLocation RBraceLoc) { |
| 7336 | // Semantic analysis for initializers is done by ActOnDeclarator() and |
| 7337 | // CheckInitializer() - it requires knowledge of the object being initialized. |
| 7338 | |
| 7339 | // Immediately handle non-overload placeholders. Overloads can be |
| 7340 | // resolved contextually, but everything else here can't. |
| 7341 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { |
| 7342 | if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { |
| 7343 | ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]); |
| 7344 | |
| 7345 | // Ignore failures; dropping the entire initializer list because |
| 7346 | // of one failure would be terrible for indexing/etc. |
| 7347 | if (result.isInvalid()) continue; |
| 7348 | |
| 7349 | InitArgList[I] = result.get(); |
| 7350 | } |
| 7351 | } |
| 7352 | |
| 7353 | InitListExpr *E = |
| 7354 | new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc); |
| 7355 | E->setType(Context.VoidTy); // FIXME: just a place holder for now. |
| 7356 | return E; |
| 7357 | } |
| 7358 | |
| 7359 | void Sema::maybeExtendBlockObject(ExprResult &E) { |
| 7360 | assert(E.get()->getType()->isBlockPointerType()); |
| 7361 | assert(E.get()->isPRValue()); |
| 7362 | |
| 7363 | // Only do this in an r-value context. |
| 7364 | if (!getLangOpts().ObjCAutoRefCount) return; |
| 7365 | |
| 7366 | E = ImplicitCastExpr::Create( |
| 7367 | Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(), |
| 7368 | /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
| 7369 | Cleanup.setExprNeedsCleanups(true); |
| 7370 | } |
| 7371 | |
| 7372 | CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { |
| 7373 | // Both Src and Dest are scalar types, i.e. arithmetic or pointer. |
| 7374 | // Also, callers should have filtered out the invalid cases with |
| 7375 | // pointers. Everything else should be possible. |
| 7376 | |
| 7377 | QualType SrcTy = Src.get()->getType(); |
| 7378 | if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy)) |
| 7379 | return CK_NoOp; |
| 7380 | |
| 7381 | switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { |
| 7382 | case Type::STK_MemberPointer: |
| 7383 | llvm_unreachable("member pointer type in C" ); |
| 7384 | |
| 7385 | case Type::STK_CPointer: |
| 7386 | case Type::STK_BlockPointer: |
| 7387 | case Type::STK_ObjCObjectPointer: |
| 7388 | switch (DestTy->getScalarTypeKind()) { |
| 7389 | case Type::STK_CPointer: { |
| 7390 | LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); |
| 7391 | LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); |
| 7392 | if (SrcAS != DestAS) |
| 7393 | return CK_AddressSpaceConversion; |
| 7394 | if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy)) |
| 7395 | return CK_NoOp; |
| 7396 | return CK_BitCast; |
| 7397 | } |
| 7398 | case Type::STK_BlockPointer: |
| 7399 | return (SrcKind == Type::STK_BlockPointer |
| 7400 | ? CK_BitCast : CK_AnyPointerToBlockPointerCast); |
| 7401 | case Type::STK_ObjCObjectPointer: |
| 7402 | if (SrcKind == Type::STK_ObjCObjectPointer) |
| 7403 | return CK_BitCast; |
| 7404 | if (SrcKind == Type::STK_CPointer) |
| 7405 | return CK_CPointerToObjCPointerCast; |
| 7406 | maybeExtendBlockObject(E&: Src); |
| 7407 | return CK_BlockPointerToObjCPointerCast; |
| 7408 | case Type::STK_Bool: |
| 7409 | return CK_PointerToBoolean; |
| 7410 | case Type::STK_Integral: |
| 7411 | return CK_PointerToIntegral; |
| 7412 | case Type::STK_Floating: |
| 7413 | case Type::STK_FloatingComplex: |
| 7414 | case Type::STK_IntegralComplex: |
| 7415 | case Type::STK_MemberPointer: |
| 7416 | case Type::STK_FixedPoint: |
| 7417 | llvm_unreachable("illegal cast from pointer" ); |
| 7418 | } |
| 7419 | llvm_unreachable("Should have returned before this" ); |
| 7420 | |
| 7421 | case Type::STK_FixedPoint: |
| 7422 | switch (DestTy->getScalarTypeKind()) { |
| 7423 | case Type::STK_FixedPoint: |
| 7424 | return CK_FixedPointCast; |
| 7425 | case Type::STK_Bool: |
| 7426 | return CK_FixedPointToBoolean; |
| 7427 | case Type::STK_Integral: |
| 7428 | return CK_FixedPointToIntegral; |
| 7429 | case Type::STK_Floating: |
| 7430 | return CK_FixedPointToFloating; |
| 7431 | case Type::STK_IntegralComplex: |
| 7432 | case Type::STK_FloatingComplex: |
| 7433 | Diag(Loc: Src.get()->getExprLoc(), |
| 7434 | DiagID: diag::err_unimplemented_conversion_with_fixed_point_type) |
| 7435 | << DestTy; |
| 7436 | return CK_IntegralCast; |
| 7437 | case Type::STK_CPointer: |
| 7438 | case Type::STK_ObjCObjectPointer: |
| 7439 | case Type::STK_BlockPointer: |
| 7440 | case Type::STK_MemberPointer: |
| 7441 | llvm_unreachable("illegal cast to pointer type" ); |
| 7442 | } |
| 7443 | llvm_unreachable("Should have returned before this" ); |
| 7444 | |
| 7445 | case Type::STK_Bool: // casting from bool is like casting from an integer |
| 7446 | case Type::STK_Integral: |
| 7447 | switch (DestTy->getScalarTypeKind()) { |
| 7448 | case Type::STK_CPointer: |
| 7449 | case Type::STK_ObjCObjectPointer: |
| 7450 | case Type::STK_BlockPointer: |
| 7451 | if (Src.get()->isNullPointerConstant(Ctx&: Context, |
| 7452 | NPC: Expr::NPC_ValueDependentIsNull)) |
| 7453 | return CK_NullToPointer; |
| 7454 | return CK_IntegralToPointer; |
| 7455 | case Type::STK_Bool: |
| 7456 | return CK_IntegralToBoolean; |
| 7457 | case Type::STK_Integral: |
| 7458 | return CK_IntegralCast; |
| 7459 | case Type::STK_Floating: |
| 7460 | return CK_IntegralToFloating; |
| 7461 | case Type::STK_IntegralComplex: |
| 7462 | Src = ImpCastExprToType(E: Src.get(), |
| 7463 | Type: DestTy->castAs<ComplexType>()->getElementType(), |
| 7464 | CK: CK_IntegralCast); |
| 7465 | return CK_IntegralRealToComplex; |
| 7466 | case Type::STK_FloatingComplex: |
| 7467 | Src = ImpCastExprToType(E: Src.get(), |
| 7468 | Type: DestTy->castAs<ComplexType>()->getElementType(), |
| 7469 | CK: CK_IntegralToFloating); |
| 7470 | return CK_FloatingRealToComplex; |
| 7471 | case Type::STK_MemberPointer: |
| 7472 | llvm_unreachable("member pointer type in C" ); |
| 7473 | case Type::STK_FixedPoint: |
| 7474 | return CK_IntegralToFixedPoint; |
| 7475 | } |
| 7476 | llvm_unreachable("Should have returned before this" ); |
| 7477 | |
| 7478 | case Type::STK_Floating: |
| 7479 | switch (DestTy->getScalarTypeKind()) { |
| 7480 | case Type::STK_Floating: |
| 7481 | return CK_FloatingCast; |
| 7482 | case Type::STK_Bool: |
| 7483 | return CK_FloatingToBoolean; |
| 7484 | case Type::STK_Integral: |
| 7485 | return CK_FloatingToIntegral; |
| 7486 | case Type::STK_FloatingComplex: |
| 7487 | Src = ImpCastExprToType(E: Src.get(), |
| 7488 | Type: DestTy->castAs<ComplexType>()->getElementType(), |
| 7489 | CK: CK_FloatingCast); |
| 7490 | return CK_FloatingRealToComplex; |
| 7491 | case Type::STK_IntegralComplex: |
| 7492 | Src = ImpCastExprToType(E: Src.get(), |
| 7493 | Type: DestTy->castAs<ComplexType>()->getElementType(), |
| 7494 | CK: CK_FloatingToIntegral); |
| 7495 | return CK_IntegralRealToComplex; |
| 7496 | case Type::STK_CPointer: |
| 7497 | case Type::STK_ObjCObjectPointer: |
| 7498 | case Type::STK_BlockPointer: |
| 7499 | llvm_unreachable("valid float->pointer cast?" ); |
| 7500 | case Type::STK_MemberPointer: |
| 7501 | llvm_unreachable("member pointer type in C" ); |
| 7502 | case Type::STK_FixedPoint: |
| 7503 | return CK_FloatingToFixedPoint; |
| 7504 | } |
| 7505 | llvm_unreachable("Should have returned before this" ); |
| 7506 | |
| 7507 | case Type::STK_FloatingComplex: |
| 7508 | switch (DestTy->getScalarTypeKind()) { |
| 7509 | case Type::STK_FloatingComplex: |
| 7510 | return CK_FloatingComplexCast; |
| 7511 | case Type::STK_IntegralComplex: |
| 7512 | return CK_FloatingComplexToIntegralComplex; |
| 7513 | case Type::STK_Floating: { |
| 7514 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); |
| 7515 | if (Context.hasSameType(T1: ET, T2: DestTy)) |
| 7516 | return CK_FloatingComplexToReal; |
| 7517 | Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal); |
| 7518 | return CK_FloatingCast; |
| 7519 | } |
| 7520 | case Type::STK_Bool: |
| 7521 | return CK_FloatingComplexToBoolean; |
| 7522 | case Type::STK_Integral: |
| 7523 | Src = ImpCastExprToType(E: Src.get(), |
| 7524 | Type: SrcTy->castAs<ComplexType>()->getElementType(), |
| 7525 | CK: CK_FloatingComplexToReal); |
| 7526 | return CK_FloatingToIntegral; |
| 7527 | case Type::STK_CPointer: |
| 7528 | case Type::STK_ObjCObjectPointer: |
| 7529 | case Type::STK_BlockPointer: |
| 7530 | llvm_unreachable("valid complex float->pointer cast?" ); |
| 7531 | case Type::STK_MemberPointer: |
| 7532 | llvm_unreachable("member pointer type in C" ); |
| 7533 | case Type::STK_FixedPoint: |
| 7534 | Diag(Loc: Src.get()->getExprLoc(), |
| 7535 | DiagID: diag::err_unimplemented_conversion_with_fixed_point_type) |
| 7536 | << SrcTy; |
| 7537 | return CK_IntegralCast; |
| 7538 | } |
| 7539 | llvm_unreachable("Should have returned before this" ); |
| 7540 | |
| 7541 | case Type::STK_IntegralComplex: |
| 7542 | switch (DestTy->getScalarTypeKind()) { |
| 7543 | case Type::STK_FloatingComplex: |
| 7544 | return CK_IntegralComplexToFloatingComplex; |
| 7545 | case Type::STK_IntegralComplex: |
| 7546 | return CK_IntegralComplexCast; |
| 7547 | case Type::STK_Integral: { |
| 7548 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); |
| 7549 | if (Context.hasSameType(T1: ET, T2: DestTy)) |
| 7550 | return CK_IntegralComplexToReal; |
| 7551 | Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal); |
| 7552 | return CK_IntegralCast; |
| 7553 | } |
| 7554 | case Type::STK_Bool: |
| 7555 | return CK_IntegralComplexToBoolean; |
| 7556 | case Type::STK_Floating: |
| 7557 | Src = ImpCastExprToType(E: Src.get(), |
| 7558 | Type: SrcTy->castAs<ComplexType>()->getElementType(), |
| 7559 | CK: CK_IntegralComplexToReal); |
| 7560 | return CK_IntegralToFloating; |
| 7561 | case Type::STK_CPointer: |
| 7562 | case Type::STK_ObjCObjectPointer: |
| 7563 | case Type::STK_BlockPointer: |
| 7564 | llvm_unreachable("valid complex int->pointer cast?" ); |
| 7565 | case Type::STK_MemberPointer: |
| 7566 | llvm_unreachable("member pointer type in C" ); |
| 7567 | case Type::STK_FixedPoint: |
| 7568 | Diag(Loc: Src.get()->getExprLoc(), |
| 7569 | DiagID: diag::err_unimplemented_conversion_with_fixed_point_type) |
| 7570 | << SrcTy; |
| 7571 | return CK_IntegralCast; |
| 7572 | } |
| 7573 | llvm_unreachable("Should have returned before this" ); |
| 7574 | } |
| 7575 | |
| 7576 | llvm_unreachable("Unhandled scalar cast" ); |
| 7577 | } |
| 7578 | |
| 7579 | static bool breakDownVectorType(QualType type, uint64_t &len, |
| 7580 | QualType &eltType) { |
| 7581 | // Vectors are simple. |
| 7582 | if (const VectorType *vecType = type->getAs<VectorType>()) { |
| 7583 | len = vecType->getNumElements(); |
| 7584 | eltType = vecType->getElementType(); |
| 7585 | assert(eltType->isScalarType() || eltType->isMFloat8Type()); |
| 7586 | return true; |
| 7587 | } |
| 7588 | |
| 7589 | // We allow lax conversion to and from non-vector types, but only if |
| 7590 | // they're real types (i.e. non-complex, non-pointer scalar types). |
| 7591 | if (!type->isRealType()) return false; |
| 7592 | |
| 7593 | len = 1; |
| 7594 | eltType = type; |
| 7595 | return true; |
| 7596 | } |
| 7597 | |
| 7598 | bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { |
| 7599 | assert(srcTy->isVectorType() || destTy->isVectorType()); |
| 7600 | |
| 7601 | auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { |
| 7602 | if (!FirstType->isSVESizelessBuiltinType()) |
| 7603 | return false; |
| 7604 | |
| 7605 | const auto *VecTy = SecondType->getAs<VectorType>(); |
| 7606 | return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData; |
| 7607 | }; |
| 7608 | |
| 7609 | return ValidScalableConversion(srcTy, destTy) || |
| 7610 | ValidScalableConversion(destTy, srcTy); |
| 7611 | } |
| 7612 | |
| 7613 | bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { |
| 7614 | if (!destTy->isMatrixType() || !srcTy->isMatrixType()) |
| 7615 | return false; |
| 7616 | |
| 7617 | const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); |
| 7618 | const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); |
| 7619 | |
| 7620 | return matSrcType->getNumRows() == matDestType->getNumRows() && |
| 7621 | matSrcType->getNumColumns() == matDestType->getNumColumns(); |
| 7622 | } |
| 7623 | |
| 7624 | bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { |
| 7625 | assert(DestTy->isVectorType() || SrcTy->isVectorType()); |
| 7626 | |
| 7627 | uint64_t SrcLen, DestLen; |
| 7628 | QualType SrcEltTy, DestEltTy; |
| 7629 | if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy)) |
| 7630 | return false; |
| 7631 | if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy)) |
| 7632 | return false; |
| 7633 | |
| 7634 | // ASTContext::getTypeSize will return the size rounded up to a |
| 7635 | // power of 2, so instead of using that, we need to use the raw |
| 7636 | // element size multiplied by the element count. |
| 7637 | uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy); |
| 7638 | uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy); |
| 7639 | |
| 7640 | return (SrcLen * SrcEltSize == DestLen * DestEltSize); |
| 7641 | } |
| 7642 | |
| 7643 | bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) { |
| 7644 | assert((DestTy->isVectorType() || SrcTy->isVectorType()) && |
| 7645 | "expected at least one type to be a vector here" ); |
| 7646 | |
| 7647 | bool IsSrcTyAltivec = |
| 7648 | SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() == |
| 7649 | VectorKind::AltiVecVector) || |
| 7650 | (SrcTy->castAs<VectorType>()->getVectorKind() == |
| 7651 | VectorKind::AltiVecBool) || |
| 7652 | (SrcTy->castAs<VectorType>()->getVectorKind() == |
| 7653 | VectorKind::AltiVecPixel)); |
| 7654 | |
| 7655 | bool IsDestTyAltivec = DestTy->isVectorType() && |
| 7656 | ((DestTy->castAs<VectorType>()->getVectorKind() == |
| 7657 | VectorKind::AltiVecVector) || |
| 7658 | (DestTy->castAs<VectorType>()->getVectorKind() == |
| 7659 | VectorKind::AltiVecBool) || |
| 7660 | (DestTy->castAs<VectorType>()->getVectorKind() == |
| 7661 | VectorKind::AltiVecPixel)); |
| 7662 | |
| 7663 | return (IsSrcTyAltivec || IsDestTyAltivec); |
| 7664 | } |
| 7665 | |
| 7666 | bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { |
| 7667 | assert(destTy->isVectorType() || srcTy->isVectorType()); |
| 7668 | |
| 7669 | // Disallow lax conversions between scalars and ExtVectors (these |
| 7670 | // conversions are allowed for other vector types because common headers |
| 7671 | // depend on them). Most scalar OP ExtVector cases are handled by the |
| 7672 | // splat path anyway, which does what we want (convert, not bitcast). |
| 7673 | // What this rules out for ExtVectors is crazy things like char4*float. |
| 7674 | if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; |
| 7675 | if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; |
| 7676 | |
| 7677 | return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy); |
| 7678 | } |
| 7679 | |
| 7680 | bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { |
| 7681 | assert(destTy->isVectorType() || srcTy->isVectorType()); |
| 7682 | |
| 7683 | switch (Context.getLangOpts().getLaxVectorConversions()) { |
| 7684 | case LangOptions::LaxVectorConversionKind::None: |
| 7685 | return false; |
| 7686 | |
| 7687 | case LangOptions::LaxVectorConversionKind::Integer: |
| 7688 | if (!srcTy->isIntegralOrEnumerationType()) { |
| 7689 | auto *Vec = srcTy->getAs<VectorType>(); |
| 7690 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) |
| 7691 | return false; |
| 7692 | } |
| 7693 | if (!destTy->isIntegralOrEnumerationType()) { |
| 7694 | auto *Vec = destTy->getAs<VectorType>(); |
| 7695 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) |
| 7696 | return false; |
| 7697 | } |
| 7698 | // OK, integer (vector) -> integer (vector) bitcast. |
| 7699 | break; |
| 7700 | |
| 7701 | case LangOptions::LaxVectorConversionKind::All: |
| 7702 | break; |
| 7703 | } |
| 7704 | |
| 7705 | return areLaxCompatibleVectorTypes(srcTy, destTy); |
| 7706 | } |
| 7707 | |
| 7708 | bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, |
| 7709 | CastKind &Kind) { |
| 7710 | if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { |
| 7711 | if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) { |
| 7712 | return Diag(Loc: R.getBegin(), DiagID: diag::err_invalid_conversion_between_matrixes) |
| 7713 | << DestTy << SrcTy << R; |
| 7714 | } |
| 7715 | } else if (SrcTy->isMatrixType()) { |
| 7716 | return Diag(Loc: R.getBegin(), |
| 7717 | DiagID: diag::err_invalid_conversion_between_matrix_and_type) |
| 7718 | << SrcTy << DestTy << R; |
| 7719 | } else if (DestTy->isMatrixType()) { |
| 7720 | return Diag(Loc: R.getBegin(), |
| 7721 | DiagID: diag::err_invalid_conversion_between_matrix_and_type) |
| 7722 | << DestTy << SrcTy << R; |
| 7723 | } |
| 7724 | |
| 7725 | Kind = CK_MatrixCast; |
| 7726 | return false; |
| 7727 | } |
| 7728 | |
| 7729 | bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, |
| 7730 | CastKind &Kind) { |
| 7731 | assert(VectorTy->isVectorType() && "Not a vector type!" ); |
| 7732 | |
| 7733 | if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) { |
| 7734 | if (!areLaxCompatibleVectorTypes(srcTy: Ty, destTy: VectorTy)) |
| 7735 | return Diag(Loc: R.getBegin(), |
| 7736 | DiagID: Ty->isVectorType() ? |
| 7737 | diag::err_invalid_conversion_between_vectors : |
| 7738 | diag::err_invalid_conversion_between_vector_and_integer) |
| 7739 | << VectorTy << Ty << R; |
| 7740 | } else |
| 7741 | return Diag(Loc: R.getBegin(), |
| 7742 | DiagID: diag::err_invalid_conversion_between_vector_and_scalar) |
| 7743 | << VectorTy << Ty << R; |
| 7744 | |
| 7745 | Kind = CK_BitCast; |
| 7746 | return false; |
| 7747 | } |
| 7748 | |
| 7749 | ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { |
| 7750 | QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); |
| 7751 | |
| 7752 | if (DestElemTy == SplattedExpr->getType()) |
| 7753 | return SplattedExpr; |
| 7754 | |
| 7755 | assert(DestElemTy->isFloatingType() || |
| 7756 | DestElemTy->isIntegralOrEnumerationType()); |
| 7757 | |
| 7758 | CastKind CK; |
| 7759 | if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { |
| 7760 | // OpenCL requires that we convert `true` boolean expressions to -1, but |
| 7761 | // only when splatting vectors. |
| 7762 | if (DestElemTy->isFloatingType()) { |
| 7763 | // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast |
| 7764 | // in two steps: boolean to signed integral, then to floating. |
| 7765 | ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy, |
| 7766 | CK: CK_BooleanToSignedIntegral); |
| 7767 | SplattedExpr = CastExprRes.get(); |
| 7768 | CK = CK_IntegralToFloating; |
| 7769 | } else { |
| 7770 | CK = CK_BooleanToSignedIntegral; |
| 7771 | } |
| 7772 | } else { |
| 7773 | ExprResult CastExprRes = SplattedExpr; |
| 7774 | CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy); |
| 7775 | if (CastExprRes.isInvalid()) |
| 7776 | return ExprError(); |
| 7777 | SplattedExpr = CastExprRes.get(); |
| 7778 | } |
| 7779 | return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK); |
| 7780 | } |
| 7781 | |
| 7782 | ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, |
| 7783 | Expr *CastExpr, CastKind &Kind) { |
| 7784 | assert(DestTy->isExtVectorType() && "Not an extended vector type!" ); |
| 7785 | |
| 7786 | QualType SrcTy = CastExpr->getType(); |
| 7787 | |
| 7788 | // If SrcTy is a VectorType, the total size must match to explicitly cast to |
| 7789 | // an ExtVectorType. |
| 7790 | // In OpenCL, casts between vectors of different types are not allowed. |
| 7791 | // (See OpenCL 6.2). |
| 7792 | if (SrcTy->isVectorType()) { |
| 7793 | if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) || |
| 7794 | (getLangOpts().OpenCL && |
| 7795 | !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy))) { |
| 7796 | Diag(Loc: R.getBegin(),DiagID: diag::err_invalid_conversion_between_ext_vectors) |
| 7797 | << DestTy << SrcTy << R; |
| 7798 | return ExprError(); |
| 7799 | } |
| 7800 | Kind = CK_BitCast; |
| 7801 | return CastExpr; |
| 7802 | } |
| 7803 | |
| 7804 | // All non-pointer scalars can be cast to ExtVector type. The appropriate |
| 7805 | // conversion will take place first from scalar to elt type, and then |
| 7806 | // splat from elt type to vector. |
| 7807 | if (SrcTy->isPointerType()) |
| 7808 | return Diag(Loc: R.getBegin(), |
| 7809 | DiagID: diag::err_invalid_conversion_between_vector_and_scalar) |
| 7810 | << DestTy << SrcTy << R; |
| 7811 | |
| 7812 | Kind = CK_VectorSplat; |
| 7813 | return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr); |
| 7814 | } |
| 7815 | |
| 7816 | ExprResult |
| 7817 | Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, |
| 7818 | Declarator &D, ParsedType &Ty, |
| 7819 | SourceLocation RParenLoc, Expr *CastExpr) { |
| 7820 | assert(!D.isInvalidType() && (CastExpr != nullptr) && |
| 7821 | "ActOnCastExpr(): missing type or expr" ); |
| 7822 | |
| 7823 | TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType()); |
| 7824 | if (D.isInvalidType()) |
| 7825 | return ExprError(); |
| 7826 | |
| 7827 | if (getLangOpts().CPlusPlus) { |
| 7828 | // Check that there are no default arguments (C++ only). |
| 7829 | CheckExtraCXXDefaultArguments(D); |
| 7830 | } |
| 7831 | |
| 7832 | checkUnusedDeclAttributes(D); |
| 7833 | |
| 7834 | QualType castType = castTInfo->getType(); |
| 7835 | Ty = CreateParsedType(T: castType, TInfo: castTInfo); |
| 7836 | |
| 7837 | bool isVectorLiteral = false; |
| 7838 | |
| 7839 | // Check for an altivec or OpenCL literal, |
| 7840 | // i.e. all the elements are integer constants. |
| 7841 | ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr); |
| 7842 | ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr); |
| 7843 | if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) |
| 7844 | && castType->isVectorType() && (PE || PLE)) { |
| 7845 | if (PLE && PLE->getNumExprs() == 0) { |
| 7846 | Diag(Loc: PLE->getExprLoc(), DiagID: diag::err_altivec_empty_initializer); |
| 7847 | return ExprError(); |
| 7848 | } |
| 7849 | if (PE || PLE->getNumExprs() == 1) { |
| 7850 | Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0)); |
| 7851 | if (!E->isTypeDependent() && !E->getType()->isVectorType()) |
| 7852 | isVectorLiteral = true; |
| 7853 | } |
| 7854 | else |
| 7855 | isVectorLiteral = true; |
| 7856 | } |
| 7857 | |
| 7858 | // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' |
| 7859 | // then handle it as such. |
| 7860 | if (isVectorLiteral) |
| 7861 | return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo); |
| 7862 | |
| 7863 | // If the Expr being casted is a ParenListExpr, handle it specially. |
| 7864 | // This is not an AltiVec-style cast, so turn the ParenListExpr into a |
| 7865 | // sequence of BinOp comma operators. |
| 7866 | if (isa<ParenListExpr>(Val: CastExpr)) { |
| 7867 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr); |
| 7868 | if (Result.isInvalid()) return ExprError(); |
| 7869 | CastExpr = Result.get(); |
| 7870 | } |
| 7871 | |
| 7872 | if (getLangOpts().CPlusPlus && !castType->isVoidType()) |
| 7873 | Diag(Loc: LParenLoc, DiagID: diag::warn_old_style_cast) << CastExpr->getSourceRange(); |
| 7874 | |
| 7875 | ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr); |
| 7876 | |
| 7877 | ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr); |
| 7878 | |
| 7879 | DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr); |
| 7880 | |
| 7881 | return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr); |
| 7882 | } |
| 7883 | |
| 7884 | ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, |
| 7885 | SourceLocation RParenLoc, Expr *E, |
| 7886 | TypeSourceInfo *TInfo) { |
| 7887 | assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && |
| 7888 | "Expected paren or paren list expression" ); |
| 7889 | |
| 7890 | Expr **exprs; |
| 7891 | unsigned numExprs; |
| 7892 | Expr *subExpr; |
| 7893 | SourceLocation LiteralLParenLoc, LiteralRParenLoc; |
| 7894 | if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) { |
| 7895 | LiteralLParenLoc = PE->getLParenLoc(); |
| 7896 | LiteralRParenLoc = PE->getRParenLoc(); |
| 7897 | exprs = PE->getExprs(); |
| 7898 | numExprs = PE->getNumExprs(); |
| 7899 | } else { // isa<ParenExpr> by assertion at function entrance |
| 7900 | LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen(); |
| 7901 | LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen(); |
| 7902 | subExpr = cast<ParenExpr>(Val: E)->getSubExpr(); |
| 7903 | exprs = &subExpr; |
| 7904 | numExprs = 1; |
| 7905 | } |
| 7906 | |
| 7907 | QualType Ty = TInfo->getType(); |
| 7908 | assert(Ty->isVectorType() && "Expected vector type" ); |
| 7909 | |
| 7910 | SmallVector<Expr *, 8> initExprs; |
| 7911 | const VectorType *VTy = Ty->castAs<VectorType>(); |
| 7912 | unsigned numElems = VTy->getNumElements(); |
| 7913 | |
| 7914 | // '(...)' form of vector initialization in AltiVec: the number of |
| 7915 | // initializers must be one or must match the size of the vector. |
| 7916 | // If a single value is specified in the initializer then it will be |
| 7917 | // replicated to all the components of the vector |
| 7918 | if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty, |
| 7919 | SrcTy: VTy->getElementType())) |
| 7920 | return ExprError(); |
| 7921 | if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) { |
| 7922 | // The number of initializers must be one or must match the size of the |
| 7923 | // vector. If a single value is specified in the initializer then it will |
| 7924 | // be replicated to all the components of the vector |
| 7925 | if (numExprs == 1) { |
| 7926 | QualType ElemTy = VTy->getElementType(); |
| 7927 | ExprResult Literal = DefaultLvalueConversion(E: exprs[0]); |
| 7928 | if (Literal.isInvalid()) |
| 7929 | return ExprError(); |
| 7930 | Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy, |
| 7931 | CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy)); |
| 7932 | return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get()); |
| 7933 | } |
| 7934 | else if (numExprs < numElems) { |
| 7935 | Diag(Loc: E->getExprLoc(), |
| 7936 | DiagID: diag::err_incorrect_number_of_vector_initializers); |
| 7937 | return ExprError(); |
| 7938 | } |
| 7939 | else |
| 7940 | initExprs.append(in_start: exprs, in_end: exprs + numExprs); |
| 7941 | } |
| 7942 | else { |
| 7943 | // For OpenCL, when the number of initializers is a single value, |
| 7944 | // it will be replicated to all components of the vector. |
| 7945 | if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic && |
| 7946 | numExprs == 1) { |
| 7947 | QualType ElemTy = VTy->getElementType(); |
| 7948 | ExprResult Literal = DefaultLvalueConversion(E: exprs[0]); |
| 7949 | if (Literal.isInvalid()) |
| 7950 | return ExprError(); |
| 7951 | Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy, |
| 7952 | CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy)); |
| 7953 | return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get()); |
| 7954 | } |
| 7955 | |
| 7956 | initExprs.append(in_start: exprs, in_end: exprs + numExprs); |
| 7957 | } |
| 7958 | // FIXME: This means that pretty-printing the final AST will produce curly |
| 7959 | // braces instead of the original commas. |
| 7960 | InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, |
| 7961 | initExprs, LiteralRParenLoc); |
| 7962 | initE->setType(Ty); |
| 7963 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: initE); |
| 7964 | } |
| 7965 | |
| 7966 | ExprResult |
| 7967 | Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { |
| 7968 | ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr); |
| 7969 | if (!E) |
| 7970 | return OrigExpr; |
| 7971 | |
| 7972 | ExprResult Result(E->getExpr(Init: 0)); |
| 7973 | |
| 7974 | for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) |
| 7975 | Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(), |
| 7976 | RHSExpr: E->getExpr(Init: i)); |
| 7977 | |
| 7978 | if (Result.isInvalid()) return ExprError(); |
| 7979 | |
| 7980 | return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get()); |
| 7981 | } |
| 7982 | |
| 7983 | ExprResult Sema::ActOnParenListExpr(SourceLocation L, |
| 7984 | SourceLocation R, |
| 7985 | MultiExprArg Val) { |
| 7986 | return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R); |
| 7987 | } |
| 7988 | |
| 7989 | ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T, |
| 7990 | unsigned NumUserSpecifiedExprs, |
| 7991 | SourceLocation InitLoc, |
| 7992 | SourceLocation LParenLoc, |
| 7993 | SourceLocation RParenLoc) { |
| 7994 | return CXXParenListInitExpr::Create(C&: Context, Args, T, NumUserSpecifiedExprs, |
| 7995 | InitLoc, LParenLoc, RParenLoc); |
| 7996 | } |
| 7997 | |
| 7998 | bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, |
| 7999 | SourceLocation QuestionLoc) { |
| 8000 | const Expr *NullExpr = LHSExpr; |
| 8001 | const Expr *NonPointerExpr = RHSExpr; |
| 8002 | Expr::NullPointerConstantKind NullKind = |
| 8003 | NullExpr->isNullPointerConstant(Ctx&: Context, |
| 8004 | NPC: Expr::NPC_ValueDependentIsNotNull); |
| 8005 | |
| 8006 | if (NullKind == Expr::NPCK_NotNull) { |
| 8007 | NullExpr = RHSExpr; |
| 8008 | NonPointerExpr = LHSExpr; |
| 8009 | NullKind = |
| 8010 | NullExpr->isNullPointerConstant(Ctx&: Context, |
| 8011 | NPC: Expr::NPC_ValueDependentIsNotNull); |
| 8012 | } |
| 8013 | |
| 8014 | if (NullKind == Expr::NPCK_NotNull) |
| 8015 | return false; |
| 8016 | |
| 8017 | if (NullKind == Expr::NPCK_ZeroExpression) |
| 8018 | return false; |
| 8019 | |
| 8020 | if (NullKind == Expr::NPCK_ZeroLiteral) { |
| 8021 | // In this case, check to make sure that we got here from a "NULL" |
| 8022 | // string in the source code. |
| 8023 | NullExpr = NullExpr->IgnoreParenImpCasts(); |
| 8024 | SourceLocation loc = NullExpr->getExprLoc(); |
| 8025 | if (!findMacroSpelling(loc, name: "NULL" )) |
| 8026 | return false; |
| 8027 | } |
| 8028 | |
| 8029 | int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); |
| 8030 | Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands_null) |
| 8031 | << NonPointerExpr->getType() << DiagType |
| 8032 | << NonPointerExpr->getSourceRange(); |
| 8033 | return true; |
| 8034 | } |
| 8035 | |
| 8036 | /// Return false if the condition expression is valid, true otherwise. |
| 8037 | static bool checkCondition(Sema &S, const Expr *Cond, |
| 8038 | SourceLocation QuestionLoc) { |
| 8039 | QualType CondTy = Cond->getType(); |
| 8040 | |
| 8041 | // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. |
| 8042 | if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { |
| 8043 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat) |
| 8044 | << CondTy << Cond->getSourceRange(); |
| 8045 | return true; |
| 8046 | } |
| 8047 | |
| 8048 | // C99 6.5.15p2 |
| 8049 | if (CondTy->isScalarType()) return false; |
| 8050 | |
| 8051 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_scalar) |
| 8052 | << CondTy << Cond->getSourceRange(); |
| 8053 | return true; |
| 8054 | } |
| 8055 | |
| 8056 | /// Return false if the NullExpr can be promoted to PointerTy, |
| 8057 | /// true otherwise. |
| 8058 | static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, |
| 8059 | QualType PointerTy) { |
| 8060 | if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || |
| 8061 | !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context, |
| 8062 | NPC: Expr::NPC_ValueDependentIsNull)) |
| 8063 | return true; |
| 8064 | |
| 8065 | NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer); |
| 8066 | return false; |
| 8067 | } |
| 8068 | |
| 8069 | /// Checks compatibility between two pointers and return the resulting |
| 8070 | /// type. |
| 8071 | static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, |
| 8072 | ExprResult &RHS, |
| 8073 | SourceLocation Loc) { |
| 8074 | QualType LHSTy = LHS.get()->getType(); |
| 8075 | QualType RHSTy = RHS.get()->getType(); |
| 8076 | |
| 8077 | if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) { |
| 8078 | // Two identical pointers types are always compatible. |
| 8079 | return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy); |
| 8080 | } |
| 8081 | |
| 8082 | QualType lhptee, rhptee; |
| 8083 | |
| 8084 | // Get the pointee types. |
| 8085 | bool IsBlockPointer = false; |
| 8086 | if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { |
| 8087 | lhptee = LHSBTy->getPointeeType(); |
| 8088 | rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); |
| 8089 | IsBlockPointer = true; |
| 8090 | } else { |
| 8091 | lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); |
| 8092 | rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); |
| 8093 | } |
| 8094 | |
| 8095 | // C99 6.5.15p6: If both operands are pointers to compatible types or to |
| 8096 | // differently qualified versions of compatible types, the result type is |
| 8097 | // a pointer to an appropriately qualified version of the composite |
| 8098 | // type. |
| 8099 | |
| 8100 | // Only CVR-qualifiers exist in the standard, and the differently-qualified |
| 8101 | // clause doesn't make sense for our extensions. E.g. address space 2 should |
| 8102 | // be incompatible with address space 3: they may live on different devices or |
| 8103 | // anything. |
| 8104 | Qualifiers lhQual = lhptee.getQualifiers(); |
| 8105 | Qualifiers rhQual = rhptee.getQualifiers(); |
| 8106 | |
| 8107 | LangAS ResultAddrSpace = LangAS::Default; |
| 8108 | LangAS LAddrSpace = lhQual.getAddressSpace(); |
| 8109 | LangAS RAddrSpace = rhQual.getAddressSpace(); |
| 8110 | |
| 8111 | // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address |
| 8112 | // spaces is disallowed. |
| 8113 | if (lhQual.isAddressSpaceSupersetOf(other: rhQual, Ctx: S.getASTContext())) |
| 8114 | ResultAddrSpace = LAddrSpace; |
| 8115 | else if (rhQual.isAddressSpaceSupersetOf(other: lhQual, Ctx: S.getASTContext())) |
| 8116 | ResultAddrSpace = RAddrSpace; |
| 8117 | else { |
| 8118 | S.Diag(Loc, DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) |
| 8119 | << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() |
| 8120 | << RHS.get()->getSourceRange(); |
| 8121 | return QualType(); |
| 8122 | } |
| 8123 | |
| 8124 | unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); |
| 8125 | auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; |
| 8126 | lhQual.removeCVRQualifiers(); |
| 8127 | rhQual.removeCVRQualifiers(); |
| 8128 | |
| 8129 | if (!lhQual.getPointerAuth().isEquivalent(Other: rhQual.getPointerAuth())) { |
| 8130 | S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_ptrauth) |
| 8131 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
| 8132 | << RHS.get()->getSourceRange(); |
| 8133 | return QualType(); |
| 8134 | } |
| 8135 | |
| 8136 | // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers |
| 8137 | // (C99 6.7.3) for address spaces. We assume that the check should behave in |
| 8138 | // the same manner as it's defined for CVR qualifiers, so for OpenCL two |
| 8139 | // qual types are compatible iff |
| 8140 | // * corresponded types are compatible |
| 8141 | // * CVR qualifiers are equal |
| 8142 | // * address spaces are equal |
| 8143 | // Thus for conditional operator we merge CVR and address space unqualified |
| 8144 | // pointees and if there is a composite type we return a pointer to it with |
| 8145 | // merged qualifiers. |
| 8146 | LHSCastKind = |
| 8147 | LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; |
| 8148 | RHSCastKind = |
| 8149 | RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; |
| 8150 | lhQual.removeAddressSpace(); |
| 8151 | rhQual.removeAddressSpace(); |
| 8152 | |
| 8153 | lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual); |
| 8154 | rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual); |
| 8155 | |
| 8156 | QualType CompositeTy = S.Context.mergeTypes( |
| 8157 | lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false, |
| 8158 | /*BlockReturnType=*/false, /*IsConditionalOperator=*/true); |
| 8159 | |
| 8160 | if (CompositeTy.isNull()) { |
| 8161 | // In this situation, we assume void* type. No especially good |
| 8162 | // reason, but this is what gcc does, and we do have to pick |
| 8163 | // to get a consistent AST. |
| 8164 | QualType incompatTy; |
| 8165 | incompatTy = S.Context.getPointerType( |
| 8166 | T: S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace)); |
| 8167 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind); |
| 8168 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind); |
| 8169 | |
| 8170 | // FIXME: For OpenCL the warning emission and cast to void* leaves a room |
| 8171 | // for casts between types with incompatible address space qualifiers. |
| 8172 | // For the following code the compiler produces casts between global and |
| 8173 | // local address spaces of the corresponded innermost pointees: |
| 8174 | // local int *global *a; |
| 8175 | // global int *global *b; |
| 8176 | // a = (0 ? a : b); // see C99 6.5.16.1.p1. |
| 8177 | S.Diag(Loc, DiagID: diag::ext_typecheck_cond_incompatible_pointers) |
| 8178 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
| 8179 | << RHS.get()->getSourceRange(); |
| 8180 | |
| 8181 | return incompatTy; |
| 8182 | } |
| 8183 | |
| 8184 | // The pointer types are compatible. |
| 8185 | // In case of OpenCL ResultTy should have the address space qualifier |
| 8186 | // which is a superset of address spaces of both the 2nd and the 3rd |
| 8187 | // operands of the conditional operator. |
| 8188 | QualType ResultTy = [&, ResultAddrSpace]() { |
| 8189 | if (S.getLangOpts().OpenCL) { |
| 8190 | Qualifiers CompositeQuals = CompositeTy.getQualifiers(); |
| 8191 | CompositeQuals.setAddressSpace(ResultAddrSpace); |
| 8192 | return S.Context |
| 8193 | .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals) |
| 8194 | .withCVRQualifiers(CVR: MergedCVRQual); |
| 8195 | } |
| 8196 | return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual); |
| 8197 | }(); |
| 8198 | if (IsBlockPointer) |
| 8199 | ResultTy = S.Context.getBlockPointerType(T: ResultTy); |
| 8200 | else |
| 8201 | ResultTy = S.Context.getPointerType(T: ResultTy); |
| 8202 | |
| 8203 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind); |
| 8204 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind); |
| 8205 | return ResultTy; |
| 8206 | } |
| 8207 | |
| 8208 | /// Return the resulting type when the operands are both block pointers. |
| 8209 | static QualType checkConditionalBlockPointerCompatibility(Sema &S, |
| 8210 | ExprResult &LHS, |
| 8211 | ExprResult &RHS, |
| 8212 | SourceLocation Loc) { |
| 8213 | QualType LHSTy = LHS.get()->getType(); |
| 8214 | QualType RHSTy = RHS.get()->getType(); |
| 8215 | |
| 8216 | if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { |
| 8217 | if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { |
| 8218 | QualType destType = S.Context.getPointerType(T: S.Context.VoidTy); |
| 8219 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast); |
| 8220 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast); |
| 8221 | return destType; |
| 8222 | } |
| 8223 | S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_operands) |
| 8224 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
| 8225 | << RHS.get()->getSourceRange(); |
| 8226 | return QualType(); |
| 8227 | } |
| 8228 | |
| 8229 | // We have 2 block pointer types. |
| 8230 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); |
| 8231 | } |
| 8232 | |
| 8233 | /// Return the resulting type when the operands are both pointers. |
| 8234 | static QualType |
| 8235 | checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, |
| 8236 | ExprResult &RHS, |
| 8237 | SourceLocation Loc) { |
| 8238 | // get the pointer types |
| 8239 | QualType LHSTy = LHS.get()->getType(); |
| 8240 | QualType RHSTy = RHS.get()->getType(); |
| 8241 | |
| 8242 | // get the "pointed to" types |
| 8243 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); |
| 8244 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); |
| 8245 | |
| 8246 | // ignore qualifiers on void (C99 6.5.15p3, clause 6) |
| 8247 | if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { |
| 8248 | // Figure out necessary qualifiers (C99 6.5.15p6) |
| 8249 | QualType destPointee |
| 8250 | = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers()); |
| 8251 | QualType destType = S.Context.getPointerType(T: destPointee); |
| 8252 | // Add qualifiers if necessary. |
| 8253 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp); |
| 8254 | // Promote to void*. |
| 8255 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast); |
| 8256 | return destType; |
| 8257 | } |
| 8258 | if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { |
| 8259 | QualType destPointee |
| 8260 | = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers()); |
| 8261 | QualType destType = S.Context.getPointerType(T: destPointee); |
| 8262 | // Add qualifiers if necessary. |
| 8263 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp); |
| 8264 | // Promote to void*. |
| 8265 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast); |
| 8266 | return destType; |
| 8267 | } |
| 8268 | |
| 8269 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); |
| 8270 | } |
| 8271 | |
| 8272 | /// Return false if the first expression is not an integer and the second |
| 8273 | /// expression is not a pointer, true otherwise. |
| 8274 | static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, |
| 8275 | Expr* PointerExpr, SourceLocation Loc, |
| 8276 | bool IsIntFirstExpr) { |
| 8277 | if (!PointerExpr->getType()->isPointerType() || |
| 8278 | !Int.get()->getType()->isIntegerType()) |
| 8279 | return false; |
| 8280 | |
| 8281 | Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; |
| 8282 | Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); |
| 8283 | |
| 8284 | S.Diag(Loc, DiagID: diag::ext_typecheck_cond_pointer_integer_mismatch) |
| 8285 | << Expr1->getType() << Expr2->getType() |
| 8286 | << Expr1->getSourceRange() << Expr2->getSourceRange(); |
| 8287 | Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(), |
| 8288 | CK: CK_IntegralToPointer); |
| 8289 | return true; |
| 8290 | } |
| 8291 | |
| 8292 | /// Simple conversion between integer and floating point types. |
| 8293 | /// |
| 8294 | /// Used when handling the OpenCL conditional operator where the |
| 8295 | /// condition is a vector while the other operands are scalar. |
| 8296 | /// |
| 8297 | /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar |
| 8298 | /// types are either integer or floating type. Between the two |
| 8299 | /// operands, the type with the higher rank is defined as the "result |
| 8300 | /// type". The other operand needs to be promoted to the same type. No |
| 8301 | /// other type promotion is allowed. We cannot use |
| 8302 | /// UsualArithmeticConversions() for this purpose, since it always |
| 8303 | /// promotes promotable types. |
| 8304 | static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, |
| 8305 | ExprResult &RHS, |
| 8306 | SourceLocation QuestionLoc) { |
| 8307 | LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
| 8308 | if (LHS.isInvalid()) |
| 8309 | return QualType(); |
| 8310 | RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
| 8311 | if (RHS.isInvalid()) |
| 8312 | return QualType(); |
| 8313 | |
| 8314 | // For conversion purposes, we ignore any qualifiers. |
| 8315 | // For example, "const float" and "float" are equivalent. |
| 8316 | QualType LHSType = |
| 8317 | S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType(); |
| 8318 | QualType RHSType = |
| 8319 | S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType(); |
| 8320 | |
| 8321 | if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { |
| 8322 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float) |
| 8323 | << LHSType << LHS.get()->getSourceRange(); |
| 8324 | return QualType(); |
| 8325 | } |
| 8326 | |
| 8327 | if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { |
| 8328 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float) |
| 8329 | << RHSType << RHS.get()->getSourceRange(); |
| 8330 | return QualType(); |
| 8331 | } |
| 8332 | |
| 8333 | // If both types are identical, no conversion is needed. |
| 8334 | if (LHSType == RHSType) |
| 8335 | return LHSType; |
| 8336 | |
| 8337 | // Now handle "real" floating types (i.e. float, double, long double). |
| 8338 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) |
| 8339 | return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, |
| 8340 | /*IsCompAssign = */ false); |
| 8341 | |
| 8342 | // Finally, we have two differing integer types. |
| 8343 | return handleIntegerConversion<doIntegralCast, doIntegralCast> |
| 8344 | (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); |
| 8345 | } |
| 8346 | |
| 8347 | /// Convert scalar operands to a vector that matches the |
| 8348 | /// condition in length. |
| 8349 | /// |
| 8350 | /// Used when handling the OpenCL conditional operator where the |
| 8351 | /// condition is a vector while the other operands are scalar. |
| 8352 | /// |
| 8353 | /// We first compute the "result type" for the scalar operands |
| 8354 | /// according to OpenCL v1.1 s6.3.i. Both operands are then converted |
| 8355 | /// into a vector of that type where the length matches the condition |
| 8356 | /// vector type. s6.11.6 requires that the element types of the result |
| 8357 | /// and the condition must have the same number of bits. |
| 8358 | static QualType |
| 8359 | OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, |
| 8360 | QualType CondTy, SourceLocation QuestionLoc) { |
| 8361 | QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); |
| 8362 | if (ResTy.isNull()) return QualType(); |
| 8363 | |
| 8364 | const VectorType *CV = CondTy->getAs<VectorType>(); |
| 8365 | assert(CV); |
| 8366 | |
| 8367 | // Determine the vector result type |
| 8368 | unsigned NumElements = CV->getNumElements(); |
| 8369 | QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements); |
| 8370 | |
| 8371 | // Ensure that all types have the same number of bits |
| 8372 | if (S.Context.getTypeSize(T: CV->getElementType()) |
| 8373 | != S.Context.getTypeSize(T: ResTy)) { |
| 8374 | // Since VectorTy is created internally, it does not pretty print |
| 8375 | // with an OpenCL name. Instead, we just print a description. |
| 8376 | std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); |
| 8377 | SmallString<64> Str; |
| 8378 | llvm::raw_svector_ostream OS(Str); |
| 8379 | OS << "(vector of " << NumElements << " '" << EleTyName << "' values)" ; |
| 8380 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size) |
| 8381 | << CondTy << OS.str(); |
| 8382 | return QualType(); |
| 8383 | } |
| 8384 | |
| 8385 | // Convert operands to the vector result type |
| 8386 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat); |
| 8387 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat); |
| 8388 | |
| 8389 | return VectorTy; |
| 8390 | } |
| 8391 | |
| 8392 | /// Return false if this is a valid OpenCL condition vector |
| 8393 | static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, |
| 8394 | SourceLocation QuestionLoc) { |
| 8395 | // OpenCL v1.1 s6.11.6 says the elements of the vector must be of |
| 8396 | // integral type. |
| 8397 | const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); |
| 8398 | assert(CondTy); |
| 8399 | QualType EleTy = CondTy->getElementType(); |
| 8400 | if (EleTy->isIntegerType()) return false; |
| 8401 | |
| 8402 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat) |
| 8403 | << Cond->getType() << Cond->getSourceRange(); |
| 8404 | return true; |
| 8405 | } |
| 8406 | |
| 8407 | /// Return false if the vector condition type and the vector |
| 8408 | /// result type are compatible. |
| 8409 | /// |
| 8410 | /// OpenCL v1.1 s6.11.6 requires that both vector types have the same |
| 8411 | /// number of elements, and their element types have the same number |
| 8412 | /// of bits. |
| 8413 | static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, |
| 8414 | SourceLocation QuestionLoc) { |
| 8415 | const VectorType *CV = CondTy->getAs<VectorType>(); |
| 8416 | const VectorType *RV = VecResTy->getAs<VectorType>(); |
| 8417 | assert(CV && RV); |
| 8418 | |
| 8419 | if (CV->getNumElements() != RV->getNumElements()) { |
| 8420 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size) |
| 8421 | << CondTy << VecResTy; |
| 8422 | return true; |
| 8423 | } |
| 8424 | |
| 8425 | QualType CVE = CV->getElementType(); |
| 8426 | QualType RVE = RV->getElementType(); |
| 8427 | |
| 8428 | if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE)) { |
| 8429 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size) |
| 8430 | << CondTy << VecResTy; |
| 8431 | return true; |
| 8432 | } |
| 8433 | |
| 8434 | return false; |
| 8435 | } |
| 8436 | |
| 8437 | /// Return the resulting type for the conditional operator in |
| 8438 | /// OpenCL (aka "ternary selection operator", OpenCL v1.1 |
| 8439 | /// s6.3.i) when the condition is a vector type. |
| 8440 | static QualType |
| 8441 | OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, |
| 8442 | ExprResult &LHS, ExprResult &RHS, |
| 8443 | SourceLocation QuestionLoc) { |
| 8444 | Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get()); |
| 8445 | if (Cond.isInvalid()) |
| 8446 | return QualType(); |
| 8447 | QualType CondTy = Cond.get()->getType(); |
| 8448 | |
| 8449 | if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc)) |
| 8450 | return QualType(); |
| 8451 | |
| 8452 | // If either operand is a vector then find the vector type of the |
| 8453 | // result as specified in OpenCL v1.1 s6.3.i. |
| 8454 | if (LHS.get()->getType()->isVectorType() || |
| 8455 | RHS.get()->getType()->isVectorType()) { |
| 8456 | bool IsBoolVecLang = |
| 8457 | !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus; |
| 8458 | QualType VecResTy = |
| 8459 | S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, |
| 8460 | /*isCompAssign*/ IsCompAssign: false, |
| 8461 | /*AllowBothBool*/ true, |
| 8462 | /*AllowBoolConversions*/ AllowBoolConversion: false, |
| 8463 | /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang, |
| 8464 | /*ReportInvalid*/ true); |
| 8465 | if (VecResTy.isNull()) |
| 8466 | return QualType(); |
| 8467 | // The result type must match the condition type as specified in |
| 8468 | // OpenCL v1.1 s6.11.6. |
| 8469 | if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) |
| 8470 | return QualType(); |
| 8471 | return VecResTy; |
| 8472 | } |
| 8473 | |
| 8474 | // Both operands are scalar. |
| 8475 | return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); |
| 8476 | } |
| 8477 | |
| 8478 | /// Return true if the Expr is block type |
| 8479 | static bool checkBlockType(Sema &S, const Expr *E) { |
| 8480 | if (E->getType()->isBlockPointerType()) { |
| 8481 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block); |
| 8482 | return true; |
| 8483 | } |
| 8484 | |
| 8485 | if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) { |
| 8486 | QualType Ty = CE->getCallee()->getType(); |
| 8487 | if (Ty->isBlockPointerType()) { |
| 8488 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block); |
| 8489 | return true; |
| 8490 | } |
| 8491 | } |
| 8492 | return false; |
| 8493 | } |
| 8494 | |
| 8495 | /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. |
| 8496 | /// In that case, LHS = cond. |
| 8497 | /// C99 6.5.15 |
| 8498 | QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, |
| 8499 | ExprResult &RHS, ExprValueKind &VK, |
| 8500 | ExprObjectKind &OK, |
| 8501 | SourceLocation QuestionLoc) { |
| 8502 | |
| 8503 | ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get()); |
| 8504 | if (!LHSResult.isUsable()) return QualType(); |
| 8505 | LHS = LHSResult; |
| 8506 | |
| 8507 | ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get()); |
| 8508 | if (!RHSResult.isUsable()) return QualType(); |
| 8509 | RHS = RHSResult; |
| 8510 | |
| 8511 | // C++ is sufficiently different to merit its own checker. |
| 8512 | if (getLangOpts().CPlusPlus) |
| 8513 | return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc); |
| 8514 | |
| 8515 | VK = VK_PRValue; |
| 8516 | OK = OK_Ordinary; |
| 8517 | |
| 8518 | if (Context.isDependenceAllowed() && |
| 8519 | (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || |
| 8520 | RHS.get()->isTypeDependent())) { |
| 8521 | assert(!getLangOpts().CPlusPlus); |
| 8522 | assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || |
| 8523 | RHS.get()->containsErrors()) && |
| 8524 | "should only occur in error-recovery path." ); |
| 8525 | return Context.DependentTy; |
| 8526 | } |
| 8527 | |
| 8528 | // The OpenCL operator with a vector condition is sufficiently |
| 8529 | // different to merit its own checker. |
| 8530 | if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || |
| 8531 | Cond.get()->getType()->isExtVectorType()) |
| 8532 | return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc); |
| 8533 | |
| 8534 | // First, check the condition. |
| 8535 | Cond = UsualUnaryConversions(E: Cond.get()); |
| 8536 | if (Cond.isInvalid()) |
| 8537 | return QualType(); |
| 8538 | if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc)) |
| 8539 | return QualType(); |
| 8540 | |
| 8541 | // Handle vectors. |
| 8542 | if (LHS.get()->getType()->isVectorType() || |
| 8543 | RHS.get()->getType()->isVectorType()) |
| 8544 | return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false, |
| 8545 | /*AllowBothBool*/ true, |
| 8546 | /*AllowBoolConversions*/ AllowBoolConversion: false, |
| 8547 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
| 8548 | /*ReportInvalid*/ true); |
| 8549 | |
| 8550 | QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc, |
| 8551 | ACK: ArithConvKind::Conditional); |
| 8552 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 8553 | return QualType(); |
| 8554 | |
| 8555 | // WebAssembly tables are not allowed as conditional LHS or RHS. |
| 8556 | QualType LHSTy = LHS.get()->getType(); |
| 8557 | QualType RHSTy = RHS.get()->getType(); |
| 8558 | if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) { |
| 8559 | Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression) |
| 8560 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 8561 | return QualType(); |
| 8562 | } |
| 8563 | |
| 8564 | // Diagnose attempts to convert between __ibm128, __float128 and long double |
| 8565 | // where such conversions currently can't be handled. |
| 8566 | if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) { |
| 8567 | Diag(Loc: QuestionLoc, |
| 8568 | DiagID: diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy |
| 8569 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 8570 | return QualType(); |
| 8571 | } |
| 8572 | |
| 8573 | // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary |
| 8574 | // selection operator (?:). |
| 8575 | if (getLangOpts().OpenCL && |
| 8576 | ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) { |
| 8577 | return QualType(); |
| 8578 | } |
| 8579 | |
| 8580 | // If both operands have arithmetic type, do the usual arithmetic conversions |
| 8581 | // to find a common type: C99 6.5.15p3,5. |
| 8582 | if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { |
| 8583 | // Disallow invalid arithmetic conversions, such as those between bit- |
| 8584 | // precise integers types of different sizes, or between a bit-precise |
| 8585 | // integer and another type. |
| 8586 | if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { |
| 8587 | Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands) |
| 8588 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
| 8589 | << RHS.get()->getSourceRange(); |
| 8590 | return QualType(); |
| 8591 | } |
| 8592 | |
| 8593 | LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy)); |
| 8594 | RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy)); |
| 8595 | |
| 8596 | return ResTy; |
| 8597 | } |
| 8598 | |
| 8599 | // If both operands are the same structure or union type, the result is that |
| 8600 | // type. |
| 8601 | if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 |
| 8602 | if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) |
| 8603 | if (LHSRT->getDecl() == RHSRT->getDecl()) |
| 8604 | // "If both the operands have structure or union type, the result has |
| 8605 | // that type." This implies that CV qualifiers are dropped. |
| 8606 | return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(), |
| 8607 | Y: RHSTy.getUnqualifiedType()); |
| 8608 | // FIXME: Type of conditional expression must be complete in C mode. |
| 8609 | } |
| 8610 | |
| 8611 | // C99 6.5.15p5: "If both operands have void type, the result has void type." |
| 8612 | // The following || allows only one side to be void (a GCC-ism). |
| 8613 | if (LHSTy->isVoidType() || RHSTy->isVoidType()) { |
| 8614 | QualType ResTy; |
| 8615 | if (LHSTy->isVoidType() && RHSTy->isVoidType()) { |
| 8616 | ResTy = Context.getCommonSugaredType(X: LHSTy, Y: RHSTy); |
| 8617 | } else if (RHSTy->isVoidType()) { |
| 8618 | ResTy = RHSTy; |
| 8619 | Diag(Loc: RHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void) |
| 8620 | << RHS.get()->getSourceRange(); |
| 8621 | } else { |
| 8622 | ResTy = LHSTy; |
| 8623 | Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void) |
| 8624 | << LHS.get()->getSourceRange(); |
| 8625 | } |
| 8626 | LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid); |
| 8627 | RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid); |
| 8628 | return ResTy; |
| 8629 | } |
| 8630 | |
| 8631 | // C23 6.5.15p7: |
| 8632 | // ... if both the second and third operands have nullptr_t type, the |
| 8633 | // result also has that type. |
| 8634 | if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy)) |
| 8635 | return ResTy; |
| 8636 | |
| 8637 | // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has |
| 8638 | // the type of the other operand." |
| 8639 | if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy; |
| 8640 | if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy; |
| 8641 | |
| 8642 | // All objective-c pointer type analysis is done here. |
| 8643 | QualType compositeType = |
| 8644 | ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); |
| 8645 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 8646 | return QualType(); |
| 8647 | if (!compositeType.isNull()) |
| 8648 | return compositeType; |
| 8649 | |
| 8650 | |
| 8651 | // Handle block pointer types. |
| 8652 | if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) |
| 8653 | return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS, |
| 8654 | Loc: QuestionLoc); |
| 8655 | |
| 8656 | // Check constraints for C object pointers types (C99 6.5.15p3,6). |
| 8657 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) |
| 8658 | return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS, |
| 8659 | Loc: QuestionLoc); |
| 8660 | |
| 8661 | // GCC compatibility: soften pointer/integer mismatch. Note that |
| 8662 | // null pointers have been filtered out by this point. |
| 8663 | if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc, |
| 8664 | /*IsIntFirstExpr=*/true)) |
| 8665 | return RHSTy; |
| 8666 | if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc, |
| 8667 | /*IsIntFirstExpr=*/false)) |
| 8668 | return LHSTy; |
| 8669 | |
| 8670 | // Emit a better diagnostic if one of the expressions is a null pointer |
| 8671 | // constant and the other is not a pointer type. In this case, the user most |
| 8672 | // likely forgot to take the address of the other expression. |
| 8673 | if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc)) |
| 8674 | return QualType(); |
| 8675 | |
| 8676 | // Finally, if the LHS and RHS types are canonically the same type, we can |
| 8677 | // use the common sugared type. |
| 8678 | if (Context.hasSameType(T1: LHSTy, T2: RHSTy)) |
| 8679 | return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy); |
| 8680 | |
| 8681 | // Otherwise, the operands are not compatible. |
| 8682 | Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands) |
| 8683 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
| 8684 | << RHS.get()->getSourceRange(); |
| 8685 | return QualType(); |
| 8686 | } |
| 8687 | |
| 8688 | /// SuggestParentheses - Emit a note with a fixit hint that wraps |
| 8689 | /// ParenRange in parentheses. |
| 8690 | static void SuggestParentheses(Sema &Self, SourceLocation Loc, |
| 8691 | const PartialDiagnostic &Note, |
| 8692 | SourceRange ParenRange) { |
| 8693 | SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd()); |
| 8694 | if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && |
| 8695 | EndLoc.isValid()) { |
| 8696 | Self.Diag(Loc, PD: Note) |
| 8697 | << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(" ) |
| 8698 | << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")" ); |
| 8699 | } else { |
| 8700 | // We can't display the parentheses, so just show the bare note. |
| 8701 | Self.Diag(Loc, PD: Note) << ParenRange; |
| 8702 | } |
| 8703 | } |
| 8704 | |
| 8705 | static bool IsArithmeticOp(BinaryOperatorKind Opc) { |
| 8706 | return BinaryOperator::isAdditiveOp(Opc) || |
| 8707 | BinaryOperator::isMultiplicativeOp(Opc) || |
| 8708 | BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; |
| 8709 | // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and |
| 8710 | // not any of the logical operators. Bitwise-xor is commonly used as a |
| 8711 | // logical-xor because there is no logical-xor operator. The logical |
| 8712 | // operators, including uses of xor, have a high false positive rate for |
| 8713 | // precedence warnings. |
| 8714 | } |
| 8715 | |
| 8716 | /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary |
| 8717 | /// expression, either using a built-in or overloaded operator, |
| 8718 | /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side |
| 8719 | /// expression. |
| 8720 | static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, |
| 8721 | const Expr **RHSExprs) { |
| 8722 | // Don't strip parenthesis: we should not warn if E is in parenthesis. |
| 8723 | E = E->IgnoreImpCasts(); |
| 8724 | E = E->IgnoreConversionOperatorSingleStep(); |
| 8725 | E = E->IgnoreImpCasts(); |
| 8726 | if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) { |
| 8727 | E = MTE->getSubExpr(); |
| 8728 | E = E->IgnoreImpCasts(); |
| 8729 | } |
| 8730 | |
| 8731 | // Built-in binary operator. |
| 8732 | if (const auto *OP = dyn_cast<BinaryOperator>(Val: E); |
| 8733 | OP && IsArithmeticOp(Opc: OP->getOpcode())) { |
| 8734 | *Opcode = OP->getOpcode(); |
| 8735 | *RHSExprs = OP->getRHS(); |
| 8736 | return true; |
| 8737 | } |
| 8738 | |
| 8739 | // Overloaded operator. |
| 8740 | if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) { |
| 8741 | if (Call->getNumArgs() != 2) |
| 8742 | return false; |
| 8743 | |
| 8744 | // Make sure this is really a binary operator that is safe to pass into |
| 8745 | // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. |
| 8746 | OverloadedOperatorKind OO = Call->getOperator(); |
| 8747 | if (OO < OO_Plus || OO > OO_Arrow || |
| 8748 | OO == OO_PlusPlus || OO == OO_MinusMinus) |
| 8749 | return false; |
| 8750 | |
| 8751 | BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); |
| 8752 | if (IsArithmeticOp(Opc: OpKind)) { |
| 8753 | *Opcode = OpKind; |
| 8754 | *RHSExprs = Call->getArg(Arg: 1); |
| 8755 | return true; |
| 8756 | } |
| 8757 | } |
| 8758 | |
| 8759 | return false; |
| 8760 | } |
| 8761 | |
| 8762 | /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type |
| 8763 | /// or is a logical expression such as (x==y) which has int type, but is |
| 8764 | /// commonly interpreted as boolean. |
| 8765 | static bool ExprLooksBoolean(const Expr *E) { |
| 8766 | E = E->IgnoreParenImpCasts(); |
| 8767 | |
| 8768 | if (E->getType()->isBooleanType()) |
| 8769 | return true; |
| 8770 | if (const auto *OP = dyn_cast<BinaryOperator>(Val: E)) |
| 8771 | return OP->isComparisonOp() || OP->isLogicalOp(); |
| 8772 | if (const auto *OP = dyn_cast<UnaryOperator>(Val: E)) |
| 8773 | return OP->getOpcode() == UO_LNot; |
| 8774 | if (E->getType()->isPointerType()) |
| 8775 | return true; |
| 8776 | // FIXME: What about overloaded operator calls returning "unspecified boolean |
| 8777 | // type"s (commonly pointer-to-members)? |
| 8778 | |
| 8779 | return false; |
| 8780 | } |
| 8781 | |
| 8782 | /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator |
| 8783 | /// and binary operator are mixed in a way that suggests the programmer assumed |
| 8784 | /// the conditional operator has higher precedence, for example: |
| 8785 | /// "int x = a + someBinaryCondition ? 1 : 2". |
| 8786 | static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, |
| 8787 | Expr *Condition, const Expr *LHSExpr, |
| 8788 | const Expr *RHSExpr) { |
| 8789 | BinaryOperatorKind CondOpcode; |
| 8790 | const Expr *CondRHS; |
| 8791 | |
| 8792 | if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS)) |
| 8793 | return; |
| 8794 | if (!ExprLooksBoolean(E: CondRHS)) |
| 8795 | return; |
| 8796 | |
| 8797 | // The condition is an arithmetic binary expression, with a right- |
| 8798 | // hand side that looks boolean, so warn. |
| 8799 | |
| 8800 | unsigned DiagID = BinaryOperator::isBitwiseOp(Opc: CondOpcode) |
| 8801 | ? diag::warn_precedence_bitwise_conditional |
| 8802 | : diag::warn_precedence_conditional; |
| 8803 | |
| 8804 | Self.Diag(Loc: OpLoc, DiagID) |
| 8805 | << Condition->getSourceRange() |
| 8806 | << BinaryOperator::getOpcodeStr(Op: CondOpcode); |
| 8807 | |
| 8808 | SuggestParentheses( |
| 8809 | Self, Loc: OpLoc, |
| 8810 | Note: Self.PDiag(DiagID: diag::note_precedence_silence) |
| 8811 | << BinaryOperator::getOpcodeStr(Op: CondOpcode), |
| 8812 | ParenRange: SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); |
| 8813 | |
| 8814 | SuggestParentheses(Self, Loc: OpLoc, |
| 8815 | Note: Self.PDiag(DiagID: diag::note_precedence_conditional_first), |
| 8816 | ParenRange: SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); |
| 8817 | } |
| 8818 | |
| 8819 | /// Compute the nullability of a conditional expression. |
| 8820 | static QualType computeConditionalNullability(QualType ResTy, bool IsBin, |
| 8821 | QualType LHSTy, QualType RHSTy, |
| 8822 | ASTContext &Ctx) { |
| 8823 | if (!ResTy->isAnyPointerType()) |
| 8824 | return ResTy; |
| 8825 | |
| 8826 | auto GetNullability = [](QualType Ty) { |
| 8827 | std::optional<NullabilityKind> Kind = Ty->getNullability(); |
| 8828 | if (Kind) { |
| 8829 | // For our purposes, treat _Nullable_result as _Nullable. |
| 8830 | if (*Kind == NullabilityKind::NullableResult) |
| 8831 | return NullabilityKind::Nullable; |
| 8832 | return *Kind; |
| 8833 | } |
| 8834 | return NullabilityKind::Unspecified; |
| 8835 | }; |
| 8836 | |
| 8837 | auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); |
| 8838 | NullabilityKind MergedKind; |
| 8839 | |
| 8840 | // Compute nullability of a binary conditional expression. |
| 8841 | if (IsBin) { |
| 8842 | if (LHSKind == NullabilityKind::NonNull) |
| 8843 | MergedKind = NullabilityKind::NonNull; |
| 8844 | else |
| 8845 | MergedKind = RHSKind; |
| 8846 | // Compute nullability of a normal conditional expression. |
| 8847 | } else { |
| 8848 | if (LHSKind == NullabilityKind::Nullable || |
| 8849 | RHSKind == NullabilityKind::Nullable) |
| 8850 | MergedKind = NullabilityKind::Nullable; |
| 8851 | else if (LHSKind == NullabilityKind::NonNull) |
| 8852 | MergedKind = RHSKind; |
| 8853 | else if (RHSKind == NullabilityKind::NonNull) |
| 8854 | MergedKind = LHSKind; |
| 8855 | else |
| 8856 | MergedKind = NullabilityKind::Unspecified; |
| 8857 | } |
| 8858 | |
| 8859 | // Return if ResTy already has the correct nullability. |
| 8860 | if (GetNullability(ResTy) == MergedKind) |
| 8861 | return ResTy; |
| 8862 | |
| 8863 | // Strip all nullability from ResTy. |
| 8864 | while (ResTy->getNullability()) |
| 8865 | ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx); |
| 8866 | |
| 8867 | // Create a new AttributedType with the new nullability kind. |
| 8868 | return Ctx.getAttributedType(nullability: MergedKind, modifiedType: ResTy, equivalentType: ResTy); |
| 8869 | } |
| 8870 | |
| 8871 | ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, |
| 8872 | SourceLocation ColonLoc, |
| 8873 | Expr *CondExpr, Expr *LHSExpr, |
| 8874 | Expr *RHSExpr) { |
| 8875 | // If this is the gnu "x ?: y" extension, analyze the types as though the LHS |
| 8876 | // was the condition. |
| 8877 | OpaqueValueExpr *opaqueValue = nullptr; |
| 8878 | Expr *commonExpr = nullptr; |
| 8879 | if (!LHSExpr) { |
| 8880 | commonExpr = CondExpr; |
| 8881 | // Lower out placeholder types first. This is important so that we don't |
| 8882 | // try to capture a placeholder. This happens in few cases in C++; such |
| 8883 | // as Objective-C++'s dictionary subscripting syntax. |
| 8884 | if (commonExpr->hasPlaceholderType()) { |
| 8885 | ExprResult result = CheckPlaceholderExpr(E: commonExpr); |
| 8886 | if (!result.isUsable()) return ExprError(); |
| 8887 | commonExpr = result.get(); |
| 8888 | } |
| 8889 | // We usually want to apply unary conversions *before* saving, except |
| 8890 | // in the special case of a C++ l-value conditional. |
| 8891 | if (!(getLangOpts().CPlusPlus |
| 8892 | && !commonExpr->isTypeDependent() |
| 8893 | && commonExpr->getValueKind() == RHSExpr->getValueKind() |
| 8894 | && commonExpr->isGLValue() |
| 8895 | && commonExpr->isOrdinaryOrBitFieldObject() |
| 8896 | && RHSExpr->isOrdinaryOrBitFieldObject() |
| 8897 | && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) { |
| 8898 | ExprResult commonRes = UsualUnaryConversions(E: commonExpr); |
| 8899 | if (commonRes.isInvalid()) |
| 8900 | return ExprError(); |
| 8901 | commonExpr = commonRes.get(); |
| 8902 | } |
| 8903 | |
| 8904 | // If the common expression is a class or array prvalue, materialize it |
| 8905 | // so that we can safely refer to it multiple times. |
| 8906 | if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || |
| 8907 | commonExpr->getType()->isArrayType())) { |
| 8908 | ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr); |
| 8909 | if (MatExpr.isInvalid()) |
| 8910 | return ExprError(); |
| 8911 | commonExpr = MatExpr.get(); |
| 8912 | } |
| 8913 | |
| 8914 | opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), |
| 8915 | commonExpr->getType(), |
| 8916 | commonExpr->getValueKind(), |
| 8917 | commonExpr->getObjectKind(), |
| 8918 | commonExpr); |
| 8919 | LHSExpr = CondExpr = opaqueValue; |
| 8920 | } |
| 8921 | |
| 8922 | QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); |
| 8923 | ExprValueKind VK = VK_PRValue; |
| 8924 | ExprObjectKind OK = OK_Ordinary; |
| 8925 | ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; |
| 8926 | QualType result = CheckConditionalOperands(Cond, LHS, RHS, |
| 8927 | VK, OK, QuestionLoc); |
| 8928 | if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || |
| 8929 | RHS.isInvalid()) |
| 8930 | return ExprError(); |
| 8931 | |
| 8932 | DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(), |
| 8933 | RHSExpr: RHS.get()); |
| 8934 | |
| 8935 | CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc); |
| 8936 | |
| 8937 | result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy, |
| 8938 | Ctx&: Context); |
| 8939 | |
| 8940 | if (!commonExpr) |
| 8941 | return new (Context) |
| 8942 | ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, |
| 8943 | RHS.get(), result, VK, OK); |
| 8944 | |
| 8945 | return new (Context) BinaryConditionalOperator( |
| 8946 | commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, |
| 8947 | ColonLoc, result, VK, OK); |
| 8948 | } |
| 8949 | |
| 8950 | bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) { |
| 8951 | unsigned FromAttributes = 0, ToAttributes = 0; |
| 8952 | if (const auto *FromFn = |
| 8953 | dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType))) |
| 8954 | FromAttributes = |
| 8955 | FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask; |
| 8956 | if (const auto *ToFn = |
| 8957 | dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType))) |
| 8958 | ToAttributes = |
| 8959 | ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask; |
| 8960 | |
| 8961 | return FromAttributes != ToAttributes; |
| 8962 | } |
| 8963 | |
| 8964 | // Check if we have a conversion between incompatible cmse function pointer |
| 8965 | // types, that is, a conversion between a function pointer with the |
| 8966 | // cmse_nonsecure_call attribute and one without. |
| 8967 | static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, |
| 8968 | QualType ToType) { |
| 8969 | if (const auto *ToFn = |
| 8970 | dyn_cast<FunctionType>(Val: S.Context.getCanonicalType(T: ToType))) { |
| 8971 | if (const auto *FromFn = |
| 8972 | dyn_cast<FunctionType>(Val: S.Context.getCanonicalType(T: FromType))) { |
| 8973 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); |
| 8974 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); |
| 8975 | |
| 8976 | return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); |
| 8977 | } |
| 8978 | } |
| 8979 | return false; |
| 8980 | } |
| 8981 | |
| 8982 | // checkPointerTypesForAssignment - This is a very tricky routine (despite |
| 8983 | // being closely modeled after the C99 spec:-). The odd characteristic of this |
| 8984 | // routine is it effectively iqnores the qualifiers on the top level pointee. |
| 8985 | // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. |
| 8986 | // FIXME: add a couple examples in this comment. |
| 8987 | static AssignConvertType checkPointerTypesForAssignment(Sema &S, |
| 8988 | QualType LHSType, |
| 8989 | QualType RHSType, |
| 8990 | SourceLocation Loc) { |
| 8991 | assert(LHSType.isCanonical() && "LHS not canonicalized!" ); |
| 8992 | assert(RHSType.isCanonical() && "RHS not canonicalized!" ); |
| 8993 | |
| 8994 | // get the "pointed to" type (ignoring qualifiers at the top level) |
| 8995 | const Type *lhptee, *rhptee; |
| 8996 | Qualifiers lhq, rhq; |
| 8997 | std::tie(args&: lhptee, args&: lhq) = |
| 8998 | cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair(); |
| 8999 | std::tie(args&: rhptee, args&: rhq) = |
| 9000 | cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair(); |
| 9001 | |
| 9002 | AssignConvertType ConvTy = AssignConvertType::Compatible; |
| 9003 | |
| 9004 | // C99 6.5.16.1p1: This following citation is common to constraints |
| 9005 | // 3 & 4 (below). ...and the type *pointed to* by the left has all the |
| 9006 | // qualifiers of the type *pointed to* by the right; |
| 9007 | |
| 9008 | // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. |
| 9009 | if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && |
| 9010 | lhq.compatiblyIncludesObjCLifetime(other: rhq)) { |
| 9011 | // Ignore lifetime for further calculation. |
| 9012 | lhq.removeObjCLifetime(); |
| 9013 | rhq.removeObjCLifetime(); |
| 9014 | } |
| 9015 | |
| 9016 | if (!lhq.compatiblyIncludes(other: rhq, Ctx: S.getASTContext())) { |
| 9017 | // Treat address-space mismatches as fatal. |
| 9018 | if (!lhq.isAddressSpaceSupersetOf(other: rhq, Ctx: S.getASTContext())) |
| 9019 | return AssignConvertType::IncompatiblePointerDiscardsQualifiers; |
| 9020 | |
| 9021 | // It's okay to add or remove GC or lifetime qualifiers when converting to |
| 9022 | // and from void*. |
| 9023 | else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes( |
| 9024 | other: rhq.withoutObjCGCAttr().withoutObjCLifetime(), |
| 9025 | Ctx: S.getASTContext()) && |
| 9026 | (lhptee->isVoidType() || rhptee->isVoidType())) |
| 9027 | ; // keep old |
| 9028 | |
| 9029 | // Treat lifetime mismatches as fatal. |
| 9030 | else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) |
| 9031 | ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers; |
| 9032 | |
| 9033 | // Treat pointer-auth mismatches as fatal. |
| 9034 | else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) |
| 9035 | ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers; |
| 9036 | |
| 9037 | // For GCC/MS compatibility, other qualifier mismatches are treated |
| 9038 | // as still compatible in C. |
| 9039 | else |
| 9040 | ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers; |
| 9041 | } |
| 9042 | |
| 9043 | // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or |
| 9044 | // incomplete type and the other is a pointer to a qualified or unqualified |
| 9045 | // version of void... |
| 9046 | if (lhptee->isVoidType()) { |
| 9047 | if (rhptee->isIncompleteOrObjectType()) |
| 9048 | return ConvTy; |
| 9049 | |
| 9050 | // As an extension, we allow cast to/from void* to function pointer. |
| 9051 | assert(rhptee->isFunctionType()); |
| 9052 | return AssignConvertType::FunctionVoidPointer; |
| 9053 | } |
| 9054 | |
| 9055 | if (rhptee->isVoidType()) { |
| 9056 | // In C, void * to another pointer type is compatible, but we want to note |
| 9057 | // that there will be an implicit conversion happening here. |
| 9058 | if (lhptee->isIncompleteOrObjectType()) |
| 9059 | return ConvTy == AssignConvertType::Compatible && |
| 9060 | !S.getLangOpts().CPlusPlus |
| 9061 | ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr |
| 9062 | : ConvTy; |
| 9063 | |
| 9064 | // As an extension, we allow cast to/from void* to function pointer. |
| 9065 | assert(lhptee->isFunctionType()); |
| 9066 | return AssignConvertType::FunctionVoidPointer; |
| 9067 | } |
| 9068 | |
| 9069 | if (!S.Diags.isIgnored( |
| 9070 | DiagID: diag::warn_typecheck_convert_incompatible_function_pointer_strict, |
| 9071 | Loc) && |
| 9072 | RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() && |
| 9073 | !S.TryFunctionConversion(FromType: RHSType, ToType: LHSType, ResultTy&: RHSType)) |
| 9074 | return AssignConvertType::IncompatibleFunctionPointerStrict; |
| 9075 | |
| 9076 | // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or |
| 9077 | // unqualified versions of compatible types, ... |
| 9078 | QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); |
| 9079 | if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) { |
| 9080 | // Check if the pointee types are compatible ignoring the sign. |
| 9081 | // We explicitly check for char so that we catch "char" vs |
| 9082 | // "unsigned char" on systems where "char" is unsigned. |
| 9083 | if (lhptee->isCharType()) |
| 9084 | ltrans = S.Context.UnsignedCharTy; |
| 9085 | else if (lhptee->hasSignedIntegerRepresentation()) |
| 9086 | ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans); |
| 9087 | |
| 9088 | if (rhptee->isCharType()) |
| 9089 | rtrans = S.Context.UnsignedCharTy; |
| 9090 | else if (rhptee->hasSignedIntegerRepresentation()) |
| 9091 | rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans); |
| 9092 | |
| 9093 | if (ltrans == rtrans) { |
| 9094 | // Types are compatible ignoring the sign. Qualifier incompatibility |
| 9095 | // takes priority over sign incompatibility because the sign |
| 9096 | // warning can be disabled. |
| 9097 | if (!S.IsAssignConvertCompatible(ConvTy)) |
| 9098 | return ConvTy; |
| 9099 | |
| 9100 | return AssignConvertType::IncompatiblePointerSign; |
| 9101 | } |
| 9102 | |
| 9103 | // If we are a multi-level pointer, it's possible that our issue is simply |
| 9104 | // one of qualification - e.g. char ** -> const char ** is not allowed. If |
| 9105 | // the eventual target type is the same and the pointers have the same |
| 9106 | // level of indirection, this must be the issue. |
| 9107 | if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) { |
| 9108 | do { |
| 9109 | std::tie(args&: lhptee, args&: lhq) = |
| 9110 | cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair(); |
| 9111 | std::tie(args&: rhptee, args&: rhq) = |
| 9112 | cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair(); |
| 9113 | |
| 9114 | // Inconsistent address spaces at this point is invalid, even if the |
| 9115 | // address spaces would be compatible. |
| 9116 | // FIXME: This doesn't catch address space mismatches for pointers of |
| 9117 | // different nesting levels, like: |
| 9118 | // __local int *** a; |
| 9119 | // int ** b = a; |
| 9120 | // It's not clear how to actually determine when such pointers are |
| 9121 | // invalidly incompatible. |
| 9122 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) |
| 9123 | return AssignConvertType:: |
| 9124 | IncompatibleNestedPointerAddressSpaceMismatch; |
| 9125 | |
| 9126 | } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)); |
| 9127 | |
| 9128 | if (lhptee == rhptee) |
| 9129 | return AssignConvertType::IncompatibleNestedPointerQualifiers; |
| 9130 | } |
| 9131 | |
| 9132 | // General pointer incompatibility takes priority over qualifiers. |
| 9133 | if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) |
| 9134 | return AssignConvertType::IncompatibleFunctionPointer; |
| 9135 | return AssignConvertType::IncompatiblePointer; |
| 9136 | } |
| 9137 | bool DiscardingCFIUncheckedCallee, AddingCFIUncheckedCallee; |
| 9138 | if (!S.getLangOpts().CPlusPlus && |
| 9139 | S.IsFunctionConversion(FromType: ltrans, ToType: rtrans, DiscardingCFIUncheckedCallee: &DiscardingCFIUncheckedCallee, |
| 9140 | AddingCFIUncheckedCallee: &AddingCFIUncheckedCallee)) { |
| 9141 | // Allow conversions between CFIUncheckedCallee-ness. |
| 9142 | if (!DiscardingCFIUncheckedCallee && !AddingCFIUncheckedCallee) |
| 9143 | return AssignConvertType::IncompatibleFunctionPointer; |
| 9144 | } |
| 9145 | if (IsInvalidCmseNSCallConversion(S, FromType: ltrans, ToType: rtrans)) |
| 9146 | return AssignConvertType::IncompatibleFunctionPointer; |
| 9147 | if (S.IsInvalidSMECallConversion(FromType: rtrans, ToType: ltrans)) |
| 9148 | return AssignConvertType::IncompatibleFunctionPointer; |
| 9149 | return ConvTy; |
| 9150 | } |
| 9151 | |
| 9152 | /// checkBlockPointerTypesForAssignment - This routine determines whether two |
| 9153 | /// block pointer types are compatible or whether a block and normal pointer |
| 9154 | /// are compatible. It is more restrict than comparing two function pointer |
| 9155 | // types. |
| 9156 | static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, |
| 9157 | QualType LHSType, |
| 9158 | QualType RHSType) { |
| 9159 | assert(LHSType.isCanonical() && "LHS not canonicalized!" ); |
| 9160 | assert(RHSType.isCanonical() && "RHS not canonicalized!" ); |
| 9161 | |
| 9162 | QualType lhptee, rhptee; |
| 9163 | |
| 9164 | // get the "pointed to" type (ignoring qualifiers at the top level) |
| 9165 | lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType(); |
| 9166 | rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType(); |
| 9167 | |
| 9168 | // In C++, the types have to match exactly. |
| 9169 | if (S.getLangOpts().CPlusPlus) |
| 9170 | return AssignConvertType::IncompatibleBlockPointer; |
| 9171 | |
| 9172 | AssignConvertType ConvTy = AssignConvertType::Compatible; |
| 9173 | |
| 9174 | // For blocks we enforce that qualifiers are identical. |
| 9175 | Qualifiers LQuals = lhptee.getLocalQualifiers(); |
| 9176 | Qualifiers RQuals = rhptee.getLocalQualifiers(); |
| 9177 | if (S.getLangOpts().OpenCL) { |
| 9178 | LQuals.removeAddressSpace(); |
| 9179 | RQuals.removeAddressSpace(); |
| 9180 | } |
| 9181 | if (LQuals != RQuals) |
| 9182 | ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers; |
| 9183 | |
| 9184 | // FIXME: OpenCL doesn't define the exact compile time semantics for a block |
| 9185 | // assignment. |
| 9186 | // The current behavior is similar to C++ lambdas. A block might be |
| 9187 | // assigned to a variable iff its return type and parameters are compatible |
| 9188 | // (C99 6.2.7) with the corresponding return type and parameters of the LHS of |
| 9189 | // an assignment. Presumably it should behave in way that a function pointer |
| 9190 | // assignment does in C, so for each parameter and return type: |
| 9191 | // * CVR and address space of LHS should be a superset of CVR and address |
| 9192 | // space of RHS. |
| 9193 | // * unqualified types should be compatible. |
| 9194 | if (S.getLangOpts().OpenCL) { |
| 9195 | if (!S.Context.typesAreBlockPointerCompatible( |
| 9196 | S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals), |
| 9197 | S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals))) |
| 9198 | return AssignConvertType::IncompatibleBlockPointer; |
| 9199 | } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) |
| 9200 | return AssignConvertType::IncompatibleBlockPointer; |
| 9201 | |
| 9202 | return ConvTy; |
| 9203 | } |
| 9204 | |
| 9205 | /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types |
| 9206 | /// for assignment compatibility. |
| 9207 | static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, |
| 9208 | QualType LHSType, |
| 9209 | QualType RHSType) { |
| 9210 | assert(LHSType.isCanonical() && "LHS was not canonicalized!" ); |
| 9211 | assert(RHSType.isCanonical() && "RHS was not canonicalized!" ); |
| 9212 | |
| 9213 | if (LHSType->isObjCBuiltinType()) { |
| 9214 | // Class is not compatible with ObjC object pointers. |
| 9215 | if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && |
| 9216 | !RHSType->isObjCQualifiedClassType()) |
| 9217 | return AssignConvertType::IncompatiblePointer; |
| 9218 | return AssignConvertType::Compatible; |
| 9219 | } |
| 9220 | if (RHSType->isObjCBuiltinType()) { |
| 9221 | if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && |
| 9222 | !LHSType->isObjCQualifiedClassType()) |
| 9223 | return AssignConvertType::IncompatiblePointer; |
| 9224 | return AssignConvertType::Compatible; |
| 9225 | } |
| 9226 | QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); |
| 9227 | QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); |
| 9228 | |
| 9229 | if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee, Ctx: S.getASTContext()) && |
| 9230 | // make an exception for id<P> |
| 9231 | !LHSType->isObjCQualifiedIdType()) |
| 9232 | return AssignConvertType::CompatiblePointerDiscardsQualifiers; |
| 9233 | |
| 9234 | if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType)) |
| 9235 | return AssignConvertType::Compatible; |
| 9236 | if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) |
| 9237 | return AssignConvertType::IncompatibleObjCQualifiedId; |
| 9238 | return AssignConvertType::IncompatiblePointer; |
| 9239 | } |
| 9240 | |
| 9241 | AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc, |
| 9242 | QualType LHSType, |
| 9243 | QualType RHSType) { |
| 9244 | // Fake up an opaque expression. We don't actually care about what |
| 9245 | // cast operations are required, so if CheckAssignmentConstraints |
| 9246 | // adds casts to this they'll be wasted, but fortunately that doesn't |
| 9247 | // usually happen on valid code. |
| 9248 | OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); |
| 9249 | ExprResult RHSPtr = &RHSExpr; |
| 9250 | CastKind K; |
| 9251 | |
| 9252 | return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false); |
| 9253 | } |
| 9254 | |
| 9255 | /// This helper function returns true if QT is a vector type that has element |
| 9256 | /// type ElementType. |
| 9257 | static bool isVector(QualType QT, QualType ElementType) { |
| 9258 | if (const VectorType *VT = QT->getAs<VectorType>()) |
| 9259 | return VT->getElementType().getCanonicalType() == ElementType; |
| 9260 | return false; |
| 9261 | } |
| 9262 | |
| 9263 | /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently |
| 9264 | /// has code to accommodate several GCC extensions when type checking |
| 9265 | /// pointers. Here are some objectionable examples that GCC considers warnings: |
| 9266 | /// |
| 9267 | /// int a, *pint; |
| 9268 | /// short *pshort; |
| 9269 | /// struct foo *pfoo; |
| 9270 | /// |
| 9271 | /// pint = pshort; // warning: assignment from incompatible pointer type |
| 9272 | /// a = pint; // warning: assignment makes integer from pointer without a cast |
| 9273 | /// pint = a; // warning: assignment makes pointer from integer without a cast |
| 9274 | /// pint = pfoo; // warning: assignment from incompatible pointer type |
| 9275 | /// |
| 9276 | /// As a result, the code for dealing with pointers is more complex than the |
| 9277 | /// C99 spec dictates. |
| 9278 | /// |
| 9279 | /// Sets 'Kind' for any result kind except Incompatible. |
| 9280 | AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType, |
| 9281 | ExprResult &RHS, |
| 9282 | CastKind &Kind, |
| 9283 | bool ConvertRHS) { |
| 9284 | QualType RHSType = RHS.get()->getType(); |
| 9285 | QualType OrigLHSType = LHSType; |
| 9286 | |
| 9287 | // Get canonical types. We're not formatting these types, just comparing |
| 9288 | // them. |
| 9289 | LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType(); |
| 9290 | RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType(); |
| 9291 | |
| 9292 | // Common case: no conversion required. |
| 9293 | if (LHSType == RHSType) { |
| 9294 | Kind = CK_NoOp; |
| 9295 | return AssignConvertType::Compatible; |
| 9296 | } |
| 9297 | |
| 9298 | // If the LHS has an __auto_type, there are no additional type constraints |
| 9299 | // to be worried about. |
| 9300 | if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) { |
| 9301 | if (AT->isGNUAutoType()) { |
| 9302 | Kind = CK_NoOp; |
| 9303 | return AssignConvertType::Compatible; |
| 9304 | } |
| 9305 | } |
| 9306 | |
| 9307 | // If we have an atomic type, try a non-atomic assignment, then just add an |
| 9308 | // atomic qualification step. |
| 9309 | if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) { |
| 9310 | AssignConvertType result = |
| 9311 | CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind); |
| 9312 | if (result != AssignConvertType::Compatible) |
| 9313 | return result; |
| 9314 | if (Kind != CK_NoOp && ConvertRHS) |
| 9315 | RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind); |
| 9316 | Kind = CK_NonAtomicToAtomic; |
| 9317 | return AssignConvertType::Compatible; |
| 9318 | } |
| 9319 | |
| 9320 | // If the left-hand side is a reference type, then we are in a |
| 9321 | // (rare!) case where we've allowed the use of references in C, |
| 9322 | // e.g., as a parameter type in a built-in function. In this case, |
| 9323 | // just make sure that the type referenced is compatible with the |
| 9324 | // right-hand side type. The caller is responsible for adjusting |
| 9325 | // LHSType so that the resulting expression does not have reference |
| 9326 | // type. |
| 9327 | if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { |
| 9328 | if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) { |
| 9329 | Kind = CK_LValueBitCast; |
| 9330 | return AssignConvertType::Compatible; |
| 9331 | } |
| 9332 | return AssignConvertType::Incompatible; |
| 9333 | } |
| 9334 | |
| 9335 | // Allow scalar to ExtVector assignments, and assignments of an ExtVector type |
| 9336 | // to the same ExtVector type. |
| 9337 | if (LHSType->isExtVectorType()) { |
| 9338 | if (RHSType->isExtVectorType()) |
| 9339 | return AssignConvertType::Incompatible; |
| 9340 | if (RHSType->isArithmeticType()) { |
| 9341 | // CK_VectorSplat does T -> vector T, so first cast to the element type. |
| 9342 | if (ConvertRHS) |
| 9343 | RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get()); |
| 9344 | Kind = CK_VectorSplat; |
| 9345 | return AssignConvertType::Compatible; |
| 9346 | } |
| 9347 | } |
| 9348 | |
| 9349 | // Conversions to or from vector type. |
| 9350 | if (LHSType->isVectorType() || RHSType->isVectorType()) { |
| 9351 | if (LHSType->isVectorType() && RHSType->isVectorType()) { |
| 9352 | // Allow assignments of an AltiVec vector type to an equivalent GCC |
| 9353 | // vector type and vice versa |
| 9354 | if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) { |
| 9355 | Kind = CK_BitCast; |
| 9356 | return AssignConvertType::Compatible; |
| 9357 | } |
| 9358 | |
| 9359 | // If we are allowing lax vector conversions, and LHS and RHS are both |
| 9360 | // vectors, the total size only needs to be the same. This is a bitcast; |
| 9361 | // no bits are changed but the result type is different. |
| 9362 | if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) { |
| 9363 | // The default for lax vector conversions with Altivec vectors will |
| 9364 | // change, so if we are converting between vector types where |
| 9365 | // at least one is an Altivec vector, emit a warning. |
| 9366 | if (Context.getTargetInfo().getTriple().isPPC() && |
| 9367 | anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) && |
| 9368 | !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType)) |
| 9369 | Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all) |
| 9370 | << RHSType << LHSType; |
| 9371 | Kind = CK_BitCast; |
| 9372 | return AssignConvertType::IncompatibleVectors; |
| 9373 | } |
| 9374 | } |
| 9375 | |
| 9376 | // When the RHS comes from another lax conversion (e.g. binops between |
| 9377 | // scalars and vectors) the result is canonicalized as a vector. When the |
| 9378 | // LHS is also a vector, the lax is allowed by the condition above. Handle |
| 9379 | // the case where LHS is a scalar. |
| 9380 | if (LHSType->isScalarType()) { |
| 9381 | const VectorType *VecType = RHSType->getAs<VectorType>(); |
| 9382 | if (VecType && VecType->getNumElements() == 1 && |
| 9383 | isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) { |
| 9384 | if (Context.getTargetInfo().getTriple().isPPC() && |
| 9385 | (VecType->getVectorKind() == VectorKind::AltiVecVector || |
| 9386 | VecType->getVectorKind() == VectorKind::AltiVecBool || |
| 9387 | VecType->getVectorKind() == VectorKind::AltiVecPixel)) |
| 9388 | Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all) |
| 9389 | << RHSType << LHSType; |
| 9390 | ExprResult *VecExpr = &RHS; |
| 9391 | *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast); |
| 9392 | Kind = CK_BitCast; |
| 9393 | return AssignConvertType::Compatible; |
| 9394 | } |
| 9395 | } |
| 9396 | |
| 9397 | // Allow assignments between fixed-length and sizeless SVE vectors. |
| 9398 | if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) || |
| 9399 | (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType())) |
| 9400 | if (ARM().areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) || |
| 9401 | ARM().areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) { |
| 9402 | Kind = CK_BitCast; |
| 9403 | return AssignConvertType::Compatible; |
| 9404 | } |
| 9405 | |
| 9406 | // Allow assignments between fixed-length and sizeless RVV vectors. |
| 9407 | if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) || |
| 9408 | (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) { |
| 9409 | if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) || |
| 9410 | Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) { |
| 9411 | Kind = CK_BitCast; |
| 9412 | return AssignConvertType::Compatible; |
| 9413 | } |
| 9414 | } |
| 9415 | |
| 9416 | return AssignConvertType::Incompatible; |
| 9417 | } |
| 9418 | |
| 9419 | // Diagnose attempts to convert between __ibm128, __float128 and long double |
| 9420 | // where such conversions currently can't be handled. |
| 9421 | if (unsupportedTypeConversion(S: *this, LHSType, RHSType)) |
| 9422 | return AssignConvertType::Incompatible; |
| 9423 | |
| 9424 | // Disallow assigning a _Complex to a real type in C++ mode since it simply |
| 9425 | // discards the imaginary part. |
| 9426 | if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && |
| 9427 | !LHSType->getAs<ComplexType>()) |
| 9428 | return AssignConvertType::Incompatible; |
| 9429 | |
| 9430 | // Arithmetic conversions. |
| 9431 | if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && |
| 9432 | !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { |
| 9433 | if (ConvertRHS) |
| 9434 | Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType); |
| 9435 | return AssignConvertType::Compatible; |
| 9436 | } |
| 9437 | |
| 9438 | // Conversions to normal pointers. |
| 9439 | if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) { |
| 9440 | // U* -> T* |
| 9441 | if (isa<PointerType>(Val: RHSType)) { |
| 9442 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); |
| 9443 | LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); |
| 9444 | if (AddrSpaceL != AddrSpaceR) |
| 9445 | Kind = CK_AddressSpaceConversion; |
| 9446 | else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType)) |
| 9447 | Kind = CK_NoOp; |
| 9448 | else |
| 9449 | Kind = CK_BitCast; |
| 9450 | return checkPointerTypesForAssignment(S&: *this, LHSType, RHSType, |
| 9451 | Loc: RHS.get()->getBeginLoc()); |
| 9452 | } |
| 9453 | |
| 9454 | // int -> T* |
| 9455 | if (RHSType->isIntegerType()) { |
| 9456 | Kind = CK_IntegralToPointer; // FIXME: null? |
| 9457 | return AssignConvertType::IntToPointer; |
| 9458 | } |
| 9459 | |
| 9460 | // C pointers are not compatible with ObjC object pointers, |
| 9461 | // with two exceptions: |
| 9462 | if (isa<ObjCObjectPointerType>(Val: RHSType)) { |
| 9463 | // - conversions to void* |
| 9464 | if (LHSPointer->getPointeeType()->isVoidType()) { |
| 9465 | Kind = CK_BitCast; |
| 9466 | return AssignConvertType::Compatible; |
| 9467 | } |
| 9468 | |
| 9469 | // - conversions from 'Class' to the redefinition type |
| 9470 | if (RHSType->isObjCClassType() && |
| 9471 | Context.hasSameType(T1: LHSType, |
| 9472 | T2: Context.getObjCClassRedefinitionType())) { |
| 9473 | Kind = CK_BitCast; |
| 9474 | return AssignConvertType::Compatible; |
| 9475 | } |
| 9476 | |
| 9477 | Kind = CK_BitCast; |
| 9478 | return AssignConvertType::IncompatiblePointer; |
| 9479 | } |
| 9480 | |
| 9481 | // U^ -> void* |
| 9482 | if (RHSType->getAs<BlockPointerType>()) { |
| 9483 | if (LHSPointer->getPointeeType()->isVoidType()) { |
| 9484 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); |
| 9485 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() |
| 9486 | ->getPointeeType() |
| 9487 | .getAddressSpace(); |
| 9488 | Kind = |
| 9489 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; |
| 9490 | return AssignConvertType::Compatible; |
| 9491 | } |
| 9492 | } |
| 9493 | |
| 9494 | return AssignConvertType::Incompatible; |
| 9495 | } |
| 9496 | |
| 9497 | // Conversions to block pointers. |
| 9498 | if (isa<BlockPointerType>(Val: LHSType)) { |
| 9499 | // U^ -> T^ |
| 9500 | if (RHSType->isBlockPointerType()) { |
| 9501 | LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() |
| 9502 | ->getPointeeType() |
| 9503 | .getAddressSpace(); |
| 9504 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() |
| 9505 | ->getPointeeType() |
| 9506 | .getAddressSpace(); |
| 9507 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; |
| 9508 | return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType); |
| 9509 | } |
| 9510 | |
| 9511 | // int or null -> T^ |
| 9512 | if (RHSType->isIntegerType()) { |
| 9513 | Kind = CK_IntegralToPointer; // FIXME: null |
| 9514 | return AssignConvertType::IntToBlockPointer; |
| 9515 | } |
| 9516 | |
| 9517 | // id -> T^ |
| 9518 | if (getLangOpts().ObjC && RHSType->isObjCIdType()) { |
| 9519 | Kind = CK_AnyPointerToBlockPointerCast; |
| 9520 | return AssignConvertType::Compatible; |
| 9521 | } |
| 9522 | |
| 9523 | // void* -> T^ |
| 9524 | if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) |
| 9525 | if (RHSPT->getPointeeType()->isVoidType()) { |
| 9526 | Kind = CK_AnyPointerToBlockPointerCast; |
| 9527 | return AssignConvertType::Compatible; |
| 9528 | } |
| 9529 | |
| 9530 | return AssignConvertType::Incompatible; |
| 9531 | } |
| 9532 | |
| 9533 | // Conversions to Objective-C pointers. |
| 9534 | if (isa<ObjCObjectPointerType>(Val: LHSType)) { |
| 9535 | // A* -> B* |
| 9536 | if (RHSType->isObjCObjectPointerType()) { |
| 9537 | Kind = CK_BitCast; |
| 9538 | AssignConvertType result = |
| 9539 | checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType); |
| 9540 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
| 9541 | result == AssignConvertType::Compatible && |
| 9542 | !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType)) |
| 9543 | result = AssignConvertType::IncompatibleObjCWeakRef; |
| 9544 | return result; |
| 9545 | } |
| 9546 | |
| 9547 | // int or null -> A* |
| 9548 | if (RHSType->isIntegerType()) { |
| 9549 | Kind = CK_IntegralToPointer; // FIXME: null |
| 9550 | return AssignConvertType::IntToPointer; |
| 9551 | } |
| 9552 | |
| 9553 | // In general, C pointers are not compatible with ObjC object pointers, |
| 9554 | // with two exceptions: |
| 9555 | if (isa<PointerType>(Val: RHSType)) { |
| 9556 | Kind = CK_CPointerToObjCPointerCast; |
| 9557 | |
| 9558 | // - conversions from 'void*' |
| 9559 | if (RHSType->isVoidPointerType()) { |
| 9560 | return AssignConvertType::Compatible; |
| 9561 | } |
| 9562 | |
| 9563 | // - conversions to 'Class' from its redefinition type |
| 9564 | if (LHSType->isObjCClassType() && |
| 9565 | Context.hasSameType(T1: RHSType, |
| 9566 | T2: Context.getObjCClassRedefinitionType())) { |
| 9567 | return AssignConvertType::Compatible; |
| 9568 | } |
| 9569 | |
| 9570 | return AssignConvertType::IncompatiblePointer; |
| 9571 | } |
| 9572 | |
| 9573 | // Only under strict condition T^ is compatible with an Objective-C pointer. |
| 9574 | if (RHSType->isBlockPointerType() && |
| 9575 | LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) { |
| 9576 | if (ConvertRHS) |
| 9577 | maybeExtendBlockObject(E&: RHS); |
| 9578 | Kind = CK_BlockPointerToObjCPointerCast; |
| 9579 | return AssignConvertType::Compatible; |
| 9580 | } |
| 9581 | |
| 9582 | return AssignConvertType::Incompatible; |
| 9583 | } |
| 9584 | |
| 9585 | // Conversion to nullptr_t (C23 only) |
| 9586 | if (getLangOpts().C23 && LHSType->isNullPtrType() && |
| 9587 | RHS.get()->isNullPointerConstant(Ctx&: Context, |
| 9588 | NPC: Expr::NPC_ValueDependentIsNull)) { |
| 9589 | // null -> nullptr_t |
| 9590 | Kind = CK_NullToPointer; |
| 9591 | return AssignConvertType::Compatible; |
| 9592 | } |
| 9593 | |
| 9594 | // Conversions from pointers that are not covered by the above. |
| 9595 | if (isa<PointerType>(Val: RHSType)) { |
| 9596 | // T* -> _Bool |
| 9597 | if (LHSType == Context.BoolTy) { |
| 9598 | Kind = CK_PointerToBoolean; |
| 9599 | return AssignConvertType::Compatible; |
| 9600 | } |
| 9601 | |
| 9602 | // T* -> int |
| 9603 | if (LHSType->isIntegerType()) { |
| 9604 | Kind = CK_PointerToIntegral; |
| 9605 | return AssignConvertType::PointerToInt; |
| 9606 | } |
| 9607 | |
| 9608 | return AssignConvertType::Incompatible; |
| 9609 | } |
| 9610 | |
| 9611 | // Conversions from Objective-C pointers that are not covered by the above. |
| 9612 | if (isa<ObjCObjectPointerType>(Val: RHSType)) { |
| 9613 | // T* -> _Bool |
| 9614 | if (LHSType == Context.BoolTy) { |
| 9615 | Kind = CK_PointerToBoolean; |
| 9616 | return AssignConvertType::Compatible; |
| 9617 | } |
| 9618 | |
| 9619 | // T* -> int |
| 9620 | if (LHSType->isIntegerType()) { |
| 9621 | Kind = CK_PointerToIntegral; |
| 9622 | return AssignConvertType::PointerToInt; |
| 9623 | } |
| 9624 | |
| 9625 | return AssignConvertType::Incompatible; |
| 9626 | } |
| 9627 | |
| 9628 | // struct A -> struct B |
| 9629 | if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) { |
| 9630 | if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) { |
| 9631 | Kind = CK_NoOp; |
| 9632 | return AssignConvertType::Compatible; |
| 9633 | } |
| 9634 | } |
| 9635 | |
| 9636 | if (LHSType->isSamplerT() && RHSType->isIntegerType()) { |
| 9637 | Kind = CK_IntToOCLSampler; |
| 9638 | return AssignConvertType::Compatible; |
| 9639 | } |
| 9640 | |
| 9641 | return AssignConvertType::Incompatible; |
| 9642 | } |
| 9643 | |
| 9644 | /// Constructs a transparent union from an expression that is |
| 9645 | /// used to initialize the transparent union. |
| 9646 | static void ConstructTransparentUnion(Sema &S, ASTContext &C, |
| 9647 | ExprResult &EResult, QualType UnionType, |
| 9648 | FieldDecl *Field) { |
| 9649 | // Build an initializer list that designates the appropriate member |
| 9650 | // of the transparent union. |
| 9651 | Expr *E = EResult.get(); |
| 9652 | InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), |
| 9653 | E, SourceLocation()); |
| 9654 | Initializer->setType(UnionType); |
| 9655 | Initializer->setInitializedFieldInUnion(Field); |
| 9656 | |
| 9657 | // Build a compound literal constructing a value of the transparent |
| 9658 | // union type from this initializer list. |
| 9659 | TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType); |
| 9660 | EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, |
| 9661 | VK_PRValue, Initializer, false); |
| 9662 | } |
| 9663 | |
| 9664 | AssignConvertType |
| 9665 | Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, |
| 9666 | ExprResult &RHS) { |
| 9667 | QualType RHSType = RHS.get()->getType(); |
| 9668 | |
| 9669 | // If the ArgType is a Union type, we want to handle a potential |
| 9670 | // transparent_union GCC extension. |
| 9671 | const RecordType *UT = ArgType->getAsUnionType(); |
| 9672 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) |
| 9673 | return AssignConvertType::Incompatible; |
| 9674 | |
| 9675 | // The field to initialize within the transparent union. |
| 9676 | RecordDecl *UD = UT->getDecl(); |
| 9677 | FieldDecl *InitField = nullptr; |
| 9678 | // It's compatible if the expression matches any of the fields. |
| 9679 | for (auto *it : UD->fields()) { |
| 9680 | if (it->getType()->isPointerType()) { |
| 9681 | // If the transparent union contains a pointer type, we allow: |
| 9682 | // 1) void pointer |
| 9683 | // 2) null pointer constant |
| 9684 | if (RHSType->isPointerType()) |
| 9685 | if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { |
| 9686 | RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: CK_BitCast); |
| 9687 | InitField = it; |
| 9688 | break; |
| 9689 | } |
| 9690 | |
| 9691 | if (RHS.get()->isNullPointerConstant(Ctx&: Context, |
| 9692 | NPC: Expr::NPC_ValueDependentIsNull)) { |
| 9693 | RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), |
| 9694 | CK: CK_NullToPointer); |
| 9695 | InitField = it; |
| 9696 | break; |
| 9697 | } |
| 9698 | } |
| 9699 | |
| 9700 | CastKind Kind; |
| 9701 | if (CheckAssignmentConstraints(LHSType: it->getType(), RHS, Kind) == |
| 9702 | AssignConvertType::Compatible) { |
| 9703 | RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: Kind); |
| 9704 | InitField = it; |
| 9705 | break; |
| 9706 | } |
| 9707 | } |
| 9708 | |
| 9709 | if (!InitField) |
| 9710 | return AssignConvertType::Incompatible; |
| 9711 | |
| 9712 | ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField); |
| 9713 | return AssignConvertType::Compatible; |
| 9714 | } |
| 9715 | |
| 9716 | AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType, |
| 9717 | ExprResult &CallerRHS, |
| 9718 | bool Diagnose, |
| 9719 | bool DiagnoseCFAudited, |
| 9720 | bool ConvertRHS) { |
| 9721 | // We need to be able to tell the caller whether we diagnosed a problem, if |
| 9722 | // they ask us to issue diagnostics. |
| 9723 | assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed" ); |
| 9724 | |
| 9725 | // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, |
| 9726 | // we can't avoid *all* modifications at the moment, so we need some somewhere |
| 9727 | // to put the updated value. |
| 9728 | ExprResult LocalRHS = CallerRHS; |
| 9729 | ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; |
| 9730 | |
| 9731 | if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { |
| 9732 | if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { |
| 9733 | if (RHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) && |
| 9734 | !LHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) { |
| 9735 | Diag(Loc: RHS.get()->getExprLoc(), |
| 9736 | DiagID: diag::warn_noderef_to_dereferenceable_pointer) |
| 9737 | << RHS.get()->getSourceRange(); |
| 9738 | } |
| 9739 | } |
| 9740 | } |
| 9741 | |
| 9742 | if (getLangOpts().CPlusPlus) { |
| 9743 | if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { |
| 9744 | // C++ 5.17p3: If the left operand is not of class type, the |
| 9745 | // expression is implicitly converted (C++ 4) to the |
| 9746 | // cv-unqualified type of the left operand. |
| 9747 | QualType RHSType = RHS.get()->getType(); |
| 9748 | if (Diagnose) { |
| 9749 | RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(), |
| 9750 | Action: AssignmentAction::Assigning); |
| 9751 | } else { |
| 9752 | ImplicitConversionSequence ICS = |
| 9753 | TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(), |
| 9754 | /*SuppressUserConversions=*/false, |
| 9755 | AllowExplicit: AllowedExplicit::None, |
| 9756 | /*InOverloadResolution=*/false, |
| 9757 | /*CStyle=*/false, |
| 9758 | /*AllowObjCWritebackConversion=*/false); |
| 9759 | if (ICS.isFailure()) |
| 9760 | return AssignConvertType::Incompatible; |
| 9761 | RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(), |
| 9762 | ICS, Action: AssignmentAction::Assigning); |
| 9763 | } |
| 9764 | if (RHS.isInvalid()) |
| 9765 | return AssignConvertType::Incompatible; |
| 9766 | AssignConvertType result = AssignConvertType::Compatible; |
| 9767 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
| 9768 | !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType)) |
| 9769 | result = AssignConvertType::IncompatibleObjCWeakRef; |
| 9770 | return result; |
| 9771 | } |
| 9772 | |
| 9773 | // FIXME: Currently, we fall through and treat C++ classes like C |
| 9774 | // structures. |
| 9775 | // FIXME: We also fall through for atomics; not sure what should |
| 9776 | // happen there, though. |
| 9777 | } else if (RHS.get()->getType() == Context.OverloadTy) { |
| 9778 | // As a set of extensions to C, we support overloading on functions. These |
| 9779 | // functions need to be resolved here. |
| 9780 | DeclAccessPair DAP; |
| 9781 | if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( |
| 9782 | AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP)) |
| 9783 | RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD); |
| 9784 | else |
| 9785 | return AssignConvertType::Incompatible; |
| 9786 | } |
| 9787 | |
| 9788 | // This check seems unnatural, however it is necessary to ensure the proper |
| 9789 | // conversion of functions/arrays. If the conversion were done for all |
| 9790 | // DeclExpr's (created by ActOnIdExpression), it would mess up the unary |
| 9791 | // expressions that suppress this implicit conversion (&, sizeof). This needs |
| 9792 | // to happen before we check for null pointer conversions because C does not |
| 9793 | // undergo the same implicit conversions as C++ does above (by the calls to |
| 9794 | // TryImplicitConversion() and PerformImplicitConversion()) which insert the |
| 9795 | // lvalue to rvalue cast before checking for null pointer constraints. This |
| 9796 | // addresses code like: nullptr_t val; int *ptr; ptr = val; |
| 9797 | // |
| 9798 | // Suppress this for references: C++ 8.5.3p5. |
| 9799 | if (!LHSType->isReferenceType()) { |
| 9800 | // FIXME: We potentially allocate here even if ConvertRHS is false. |
| 9801 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose); |
| 9802 | if (RHS.isInvalid()) |
| 9803 | return AssignConvertType::Incompatible; |
| 9804 | } |
| 9805 | |
| 9806 | // The constraints are expressed in terms of the atomic, qualified, or |
| 9807 | // unqualified type of the LHS. |
| 9808 | QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType(); |
| 9809 | |
| 9810 | // C99 6.5.16.1p1: the left operand is a pointer and the right is |
| 9811 | // a null pointer constant <C23>or its type is nullptr_t;</C23>. |
| 9812 | if ((LHSTypeAfterConversion->isPointerType() || |
| 9813 | LHSTypeAfterConversion->isObjCObjectPointerType() || |
| 9814 | LHSTypeAfterConversion->isBlockPointerType()) && |
| 9815 | ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) || |
| 9816 | RHS.get()->isNullPointerConstant(Ctx&: Context, |
| 9817 | NPC: Expr::NPC_ValueDependentIsNull))) { |
| 9818 | AssignConvertType Ret = AssignConvertType::Compatible; |
| 9819 | if (Diagnose || ConvertRHS) { |
| 9820 | CastKind Kind; |
| 9821 | CXXCastPath Path; |
| 9822 | CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path, |
| 9823 | /*IgnoreBaseAccess=*/false, Diagnose); |
| 9824 | |
| 9825 | // If there is a conversion of some kind, check to see what kind of |
| 9826 | // pointer conversion happened so we can diagnose a C++ compatibility |
| 9827 | // diagnostic if the conversion is invalid. This only matters if the RHS |
| 9828 | // is some kind of void pointer. We have a carve-out when the RHS is from |
| 9829 | // a macro expansion because the use of a macro may indicate different |
| 9830 | // code between C and C++. Consider: char *s = NULL; where NULL is |
| 9831 | // defined as (void *)0 in C (which would be invalid in C++), but 0 in |
| 9832 | // C++, which is valid in C++. |
| 9833 | if (Kind != CK_NoOp && !getLangOpts().CPlusPlus && |
| 9834 | !RHS.get()->getBeginLoc().isMacroID()) { |
| 9835 | QualType CanRHS = |
| 9836 | RHS.get()->getType().getCanonicalType().getUnqualifiedType(); |
| 9837 | QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType(); |
| 9838 | if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) { |
| 9839 | Ret = checkPointerTypesForAssignment(S&: *this, LHSType: CanLHS, RHSType: CanRHS, |
| 9840 | Loc: RHS.get()->getExprLoc()); |
| 9841 | // Anything that's not considered perfectly compatible would be |
| 9842 | // incompatible in C++. |
| 9843 | if (Ret != AssignConvertType::Compatible) |
| 9844 | Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr; |
| 9845 | } |
| 9846 | } |
| 9847 | |
| 9848 | if (ConvertRHS) |
| 9849 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path); |
| 9850 | } |
| 9851 | return Ret; |
| 9852 | } |
| 9853 | // C23 6.5.16.1p1: the left operand has type atomic, qualified, or |
| 9854 | // unqualified bool, and the right operand is a pointer or its type is |
| 9855 | // nullptr_t. |
| 9856 | if (getLangOpts().C23 && LHSType->isBooleanType() && |
| 9857 | RHS.get()->getType()->isNullPtrType()) { |
| 9858 | // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only |
| 9859 | // only handles nullptr -> _Bool due to needing an extra conversion |
| 9860 | // step. |
| 9861 | // We model this by converting from nullptr -> void * and then let the |
| 9862 | // conversion from void * -> _Bool happen naturally. |
| 9863 | if (Diagnose || ConvertRHS) { |
| 9864 | CastKind Kind; |
| 9865 | CXXCastPath Path; |
| 9866 | CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path, |
| 9867 | /*IgnoreBaseAccess=*/false, Diagnose); |
| 9868 | if (ConvertRHS) |
| 9869 | RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue, |
| 9870 | BasePath: &Path); |
| 9871 | } |
| 9872 | } |
| 9873 | |
| 9874 | // OpenCL queue_t type assignment. |
| 9875 | if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( |
| 9876 | Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) { |
| 9877 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
| 9878 | return AssignConvertType::Compatible; |
| 9879 | } |
| 9880 | |
| 9881 | CastKind Kind; |
| 9882 | AssignConvertType result = |
| 9883 | CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); |
| 9884 | |
| 9885 | // C99 6.5.16.1p2: The value of the right operand is converted to the |
| 9886 | // type of the assignment expression. |
| 9887 | // CheckAssignmentConstraints allows the left-hand side to be a reference, |
| 9888 | // so that we can use references in built-in functions even in C. |
| 9889 | // The getNonReferenceType() call makes sure that the resulting expression |
| 9890 | // does not have reference type. |
| 9891 | if (result != AssignConvertType::Incompatible && |
| 9892 | RHS.get()->getType() != LHSType) { |
| 9893 | QualType Ty = LHSType.getNonLValueExprType(Context); |
| 9894 | Expr *E = RHS.get(); |
| 9895 | |
| 9896 | // Check for various Objective-C errors. If we are not reporting |
| 9897 | // diagnostics and just checking for errors, e.g., during overload |
| 9898 | // resolution, return Incompatible to indicate the failure. |
| 9899 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
| 9900 | ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E, |
| 9901 | CCK: CheckedConversionKind::Implicit, Diagnose, |
| 9902 | DiagnoseCFAudited) != SemaObjC::ACR_okay) { |
| 9903 | if (!Diagnose) |
| 9904 | return AssignConvertType::Incompatible; |
| 9905 | } |
| 9906 | if (getLangOpts().ObjC && |
| 9907 | (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType, |
| 9908 | SrcType: E->getType(), SrcExpr&: E, Diagnose) || |
| 9909 | ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) { |
| 9910 | if (!Diagnose) |
| 9911 | return AssignConvertType::Incompatible; |
| 9912 | // Replace the expression with a corrected version and continue so we |
| 9913 | // can find further errors. |
| 9914 | RHS = E; |
| 9915 | return AssignConvertType::Compatible; |
| 9916 | } |
| 9917 | |
| 9918 | if (ConvertRHS) |
| 9919 | RHS = ImpCastExprToType(E, Type: Ty, CK: Kind); |
| 9920 | } |
| 9921 | |
| 9922 | return result; |
| 9923 | } |
| 9924 | |
| 9925 | namespace { |
| 9926 | /// The original operand to an operator, prior to the application of the usual |
| 9927 | /// arithmetic conversions and converting the arguments of a builtin operator |
| 9928 | /// candidate. |
| 9929 | struct OriginalOperand { |
| 9930 | explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { |
| 9931 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op)) |
| 9932 | Op = MTE->getSubExpr(); |
| 9933 | if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op)) |
| 9934 | Op = BTE->getSubExpr(); |
| 9935 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) { |
| 9936 | Orig = ICE->getSubExprAsWritten(); |
| 9937 | Conversion = ICE->getConversionFunction(); |
| 9938 | } |
| 9939 | } |
| 9940 | |
| 9941 | QualType getType() const { return Orig->getType(); } |
| 9942 | |
| 9943 | Expr *Orig; |
| 9944 | NamedDecl *Conversion; |
| 9945 | }; |
| 9946 | } |
| 9947 | |
| 9948 | QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, |
| 9949 | ExprResult &RHS) { |
| 9950 | OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); |
| 9951 | |
| 9952 | Diag(Loc, DiagID: diag::err_typecheck_invalid_operands) |
| 9953 | << OrigLHS.getType() << OrigRHS.getType() |
| 9954 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 9955 | |
| 9956 | // If a user-defined conversion was applied to either of the operands prior |
| 9957 | // to applying the built-in operator rules, tell the user about it. |
| 9958 | if (OrigLHS.Conversion) { |
| 9959 | Diag(Loc: OrigLHS.Conversion->getLocation(), |
| 9960 | DiagID: diag::note_typecheck_invalid_operands_converted) |
| 9961 | << 0 << LHS.get()->getType(); |
| 9962 | } |
| 9963 | if (OrigRHS.Conversion) { |
| 9964 | Diag(Loc: OrigRHS.Conversion->getLocation(), |
| 9965 | DiagID: diag::note_typecheck_invalid_operands_converted) |
| 9966 | << 1 << RHS.get()->getType(); |
| 9967 | } |
| 9968 | |
| 9969 | return QualType(); |
| 9970 | } |
| 9971 | |
| 9972 | QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, |
| 9973 | ExprResult &RHS) { |
| 9974 | QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); |
| 9975 | QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); |
| 9976 | |
| 9977 | bool LHSNatVec = LHSType->isVectorType(); |
| 9978 | bool RHSNatVec = RHSType->isVectorType(); |
| 9979 | |
| 9980 | if (!(LHSNatVec && RHSNatVec)) { |
| 9981 | Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); |
| 9982 | Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); |
| 9983 | Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) |
| 9984 | << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() |
| 9985 | << Vector->getSourceRange(); |
| 9986 | return QualType(); |
| 9987 | } |
| 9988 | |
| 9989 | Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) |
| 9990 | << 1 << LHSType << RHSType << LHS.get()->getSourceRange() |
| 9991 | << RHS.get()->getSourceRange(); |
| 9992 | |
| 9993 | return QualType(); |
| 9994 | } |
| 9995 | |
| 9996 | /// Try to convert a value of non-vector type to a vector type by converting |
| 9997 | /// the type to the element type of the vector and then performing a splat. |
| 9998 | /// If the language is OpenCL, we only use conversions that promote scalar |
| 9999 | /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except |
| 10000 | /// for float->int. |
| 10001 | /// |
| 10002 | /// OpenCL V2.0 6.2.6.p2: |
| 10003 | /// An error shall occur if any scalar operand type has greater rank |
| 10004 | /// than the type of the vector element. |
| 10005 | /// |
| 10006 | /// \param scalar - if non-null, actually perform the conversions |
| 10007 | /// \return true if the operation fails (but without diagnosing the failure) |
| 10008 | static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, |
| 10009 | QualType scalarTy, |
| 10010 | QualType vectorEltTy, |
| 10011 | QualType vectorTy, |
| 10012 | unsigned &DiagID) { |
| 10013 | // The conversion to apply to the scalar before splatting it, |
| 10014 | // if necessary. |
| 10015 | CastKind scalarCast = CK_NoOp; |
| 10016 | |
| 10017 | if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(Ctx: S.Context)) { |
| 10018 | scalarCast = CK_IntegralToBoolean; |
| 10019 | } else if (vectorEltTy->isIntegralType(Ctx: S.Context)) { |
| 10020 | if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || |
| 10021 | (scalarTy->isIntegerType() && |
| 10022 | S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) { |
| 10023 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; |
| 10024 | return true; |
| 10025 | } |
| 10026 | if (!scalarTy->isIntegralType(Ctx: S.Context)) |
| 10027 | return true; |
| 10028 | scalarCast = CK_IntegralCast; |
| 10029 | } else if (vectorEltTy->isRealFloatingType()) { |
| 10030 | if (scalarTy->isRealFloatingType()) { |
| 10031 | if (S.getLangOpts().OpenCL && |
| 10032 | S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) { |
| 10033 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; |
| 10034 | return true; |
| 10035 | } |
| 10036 | scalarCast = CK_FloatingCast; |
| 10037 | } |
| 10038 | else if (scalarTy->isIntegralType(Ctx: S.Context)) |
| 10039 | scalarCast = CK_IntegralToFloating; |
| 10040 | else |
| 10041 | return true; |
| 10042 | } else { |
| 10043 | return true; |
| 10044 | } |
| 10045 | |
| 10046 | // Adjust scalar if desired. |
| 10047 | if (scalar) { |
| 10048 | if (scalarCast != CK_NoOp) |
| 10049 | *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast); |
| 10050 | *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat); |
| 10051 | } |
| 10052 | return false; |
| 10053 | } |
| 10054 | |
| 10055 | /// Convert vector E to a vector with the same number of elements but different |
| 10056 | /// element type. |
| 10057 | static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { |
| 10058 | const auto *VecTy = E->getType()->getAs<VectorType>(); |
| 10059 | assert(VecTy && "Expression E must be a vector" ); |
| 10060 | QualType NewVecTy = |
| 10061 | VecTy->isExtVectorType() |
| 10062 | ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements()) |
| 10063 | : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(), |
| 10064 | VecKind: VecTy->getVectorKind()); |
| 10065 | |
| 10066 | // Look through the implicit cast. Return the subexpression if its type is |
| 10067 | // NewVecTy. |
| 10068 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) |
| 10069 | if (ICE->getSubExpr()->getType() == NewVecTy) |
| 10070 | return ICE->getSubExpr(); |
| 10071 | |
| 10072 | auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; |
| 10073 | return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast); |
| 10074 | } |
| 10075 | |
| 10076 | /// Test if a (constant) integer Int can be casted to another integer type |
| 10077 | /// IntTy without losing precision. |
| 10078 | static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, |
| 10079 | QualType OtherIntTy) { |
| 10080 | if (Int->get()->containsErrors()) |
| 10081 | return false; |
| 10082 | |
| 10083 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); |
| 10084 | |
| 10085 | // Reject cases where the value of the Int is unknown as that would |
| 10086 | // possibly cause truncation, but accept cases where the scalar can be |
| 10087 | // demoted without loss of precision. |
| 10088 | Expr::EvalResult EVResult; |
| 10089 | bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context); |
| 10090 | int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy); |
| 10091 | bool IntSigned = IntTy->hasSignedIntegerRepresentation(); |
| 10092 | bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); |
| 10093 | |
| 10094 | if (CstInt) { |
| 10095 | // If the scalar is constant and is of a higher order and has more active |
| 10096 | // bits that the vector element type, reject it. |
| 10097 | llvm::APSInt Result = EVResult.Val.getInt(); |
| 10098 | unsigned NumBits = IntSigned |
| 10099 | ? (Result.isNegative() ? Result.getSignificantBits() |
| 10100 | : Result.getActiveBits()) |
| 10101 | : Result.getActiveBits(); |
| 10102 | if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits) |
| 10103 | return true; |
| 10104 | |
| 10105 | // If the signedness of the scalar type and the vector element type |
| 10106 | // differs and the number of bits is greater than that of the vector |
| 10107 | // element reject it. |
| 10108 | return (IntSigned != OtherIntSigned && |
| 10109 | NumBits > S.Context.getIntWidth(T: OtherIntTy)); |
| 10110 | } |
| 10111 | |
| 10112 | // Reject cases where the value of the scalar is not constant and it's |
| 10113 | // order is greater than that of the vector element type. |
| 10114 | return (Order < 0); |
| 10115 | } |
| 10116 | |
| 10117 | /// Test if a (constant) integer Int can be casted to floating point type |
| 10118 | /// FloatTy without losing precision. |
| 10119 | static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, |
| 10120 | QualType FloatTy) { |
| 10121 | if (Int->get()->containsErrors()) |
| 10122 | return false; |
| 10123 | |
| 10124 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); |
| 10125 | |
| 10126 | // Determine if the integer constant can be expressed as a floating point |
| 10127 | // number of the appropriate type. |
| 10128 | Expr::EvalResult EVResult; |
| 10129 | bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context); |
| 10130 | |
| 10131 | uint64_t Bits = 0; |
| 10132 | if (CstInt) { |
| 10133 | // Reject constants that would be truncated if they were converted to |
| 10134 | // the floating point type. Test by simple to/from conversion. |
| 10135 | // FIXME: Ideally the conversion to an APFloat and from an APFloat |
| 10136 | // could be avoided if there was a convertFromAPInt method |
| 10137 | // which could signal back if implicit truncation occurred. |
| 10138 | llvm::APSInt Result = EVResult.Val.getInt(); |
| 10139 | llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy)); |
| 10140 | Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(), |
| 10141 | RM: llvm::APFloat::rmTowardZero); |
| 10142 | llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy), |
| 10143 | !IntTy->hasSignedIntegerRepresentation()); |
| 10144 | bool Ignored = false; |
| 10145 | Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven, |
| 10146 | IsExact: &Ignored); |
| 10147 | if (Result != ConvertBack) |
| 10148 | return true; |
| 10149 | } else { |
| 10150 | // Reject types that cannot be fully encoded into the mantissa of |
| 10151 | // the float. |
| 10152 | Bits = S.Context.getTypeSize(T: IntTy); |
| 10153 | unsigned FloatPrec = llvm::APFloat::semanticsPrecision( |
| 10154 | S.Context.getFloatTypeSemantics(T: FloatTy)); |
| 10155 | if (Bits > FloatPrec) |
| 10156 | return true; |
| 10157 | } |
| 10158 | |
| 10159 | return false; |
| 10160 | } |
| 10161 | |
| 10162 | /// Attempt to convert and splat Scalar into a vector whose types matches |
| 10163 | /// Vector following GCC conversion rules. The rule is that implicit |
| 10164 | /// conversion can occur when Scalar can be casted to match Vector's element |
| 10165 | /// type without causing truncation of Scalar. |
| 10166 | static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, |
| 10167 | ExprResult *Vector) { |
| 10168 | QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); |
| 10169 | QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); |
| 10170 | QualType VectorEltTy; |
| 10171 | |
| 10172 | if (const auto *VT = VectorTy->getAs<VectorType>()) { |
| 10173 | assert(!isa<ExtVectorType>(VT) && |
| 10174 | "ExtVectorTypes should not be handled here!" ); |
| 10175 | VectorEltTy = VT->getElementType(); |
| 10176 | } else if (VectorTy->isSveVLSBuiltinType()) { |
| 10177 | VectorEltTy = |
| 10178 | VectorTy->castAs<BuiltinType>()->getSveEltType(Ctx: S.getASTContext()); |
| 10179 | } else { |
| 10180 | llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here" ); |
| 10181 | } |
| 10182 | |
| 10183 | // Reject cases where the vector element type or the scalar element type are |
| 10184 | // not integral or floating point types. |
| 10185 | if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) |
| 10186 | return true; |
| 10187 | |
| 10188 | // The conversion to apply to the scalar before splatting it, |
| 10189 | // if necessary. |
| 10190 | CastKind ScalarCast = CK_NoOp; |
| 10191 | |
| 10192 | // Accept cases where the vector elements are integers and the scalar is |
| 10193 | // an integer. |
| 10194 | // FIXME: Notionally if the scalar was a floating point value with a precise |
| 10195 | // integral representation, we could cast it to an appropriate integer |
| 10196 | // type and then perform the rest of the checks here. GCC will perform |
| 10197 | // this conversion in some cases as determined by the input language. |
| 10198 | // We should accept it on a language independent basis. |
| 10199 | if (VectorEltTy->isIntegralType(Ctx: S.Context) && |
| 10200 | ScalarTy->isIntegralType(Ctx: S.Context) && |
| 10201 | S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) { |
| 10202 | |
| 10203 | if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy)) |
| 10204 | return true; |
| 10205 | |
| 10206 | ScalarCast = CK_IntegralCast; |
| 10207 | } else if (VectorEltTy->isIntegralType(Ctx: S.Context) && |
| 10208 | ScalarTy->isRealFloatingType()) { |
| 10209 | if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy)) |
| 10210 | ScalarCast = CK_FloatingToIntegral; |
| 10211 | else |
| 10212 | return true; |
| 10213 | } else if (VectorEltTy->isRealFloatingType()) { |
| 10214 | if (ScalarTy->isRealFloatingType()) { |
| 10215 | |
| 10216 | // Reject cases where the scalar type is not a constant and has a higher |
| 10217 | // Order than the vector element type. |
| 10218 | llvm::APFloat Result(0.0); |
| 10219 | |
| 10220 | // Determine whether this is a constant scalar. In the event that the |
| 10221 | // value is dependent (and thus cannot be evaluated by the constant |
| 10222 | // evaluator), skip the evaluation. This will then diagnose once the |
| 10223 | // expression is instantiated. |
| 10224 | bool CstScalar = Scalar->get()->isValueDependent() || |
| 10225 | Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context); |
| 10226 | int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy); |
| 10227 | if (!CstScalar && Order < 0) |
| 10228 | return true; |
| 10229 | |
| 10230 | // If the scalar cannot be safely casted to the vector element type, |
| 10231 | // reject it. |
| 10232 | if (CstScalar) { |
| 10233 | bool Truncated = false; |
| 10234 | Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy), |
| 10235 | RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated); |
| 10236 | if (Truncated) |
| 10237 | return true; |
| 10238 | } |
| 10239 | |
| 10240 | ScalarCast = CK_FloatingCast; |
| 10241 | } else if (ScalarTy->isIntegralType(Ctx: S.Context)) { |
| 10242 | if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy)) |
| 10243 | return true; |
| 10244 | |
| 10245 | ScalarCast = CK_IntegralToFloating; |
| 10246 | } else |
| 10247 | return true; |
| 10248 | } else if (ScalarTy->isEnumeralType()) |
| 10249 | return true; |
| 10250 | |
| 10251 | // Adjust scalar if desired. |
| 10252 | if (ScalarCast != CK_NoOp) |
| 10253 | *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast); |
| 10254 | *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat); |
| 10255 | return false; |
| 10256 | } |
| 10257 | |
| 10258 | QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, |
| 10259 | SourceLocation Loc, bool IsCompAssign, |
| 10260 | bool AllowBothBool, |
| 10261 | bool AllowBoolConversions, |
| 10262 | bool AllowBoolOperation, |
| 10263 | bool ReportInvalid) { |
| 10264 | if (!IsCompAssign) { |
| 10265 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
| 10266 | if (LHS.isInvalid()) |
| 10267 | return QualType(); |
| 10268 | } |
| 10269 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
| 10270 | if (RHS.isInvalid()) |
| 10271 | return QualType(); |
| 10272 | |
| 10273 | // For conversion purposes, we ignore any qualifiers. |
| 10274 | // For example, "const float" and "float" are equivalent. |
| 10275 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); |
| 10276 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); |
| 10277 | |
| 10278 | const VectorType *LHSVecType = LHSType->getAs<VectorType>(); |
| 10279 | const VectorType *RHSVecType = RHSType->getAs<VectorType>(); |
| 10280 | assert(LHSVecType || RHSVecType); |
| 10281 | |
| 10282 | if (getLangOpts().HLSL) |
| 10283 | return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType, |
| 10284 | IsCompAssign); |
| 10285 | |
| 10286 | // Any operation with MFloat8 type is only possible with C intrinsics |
| 10287 | if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) || |
| 10288 | (RHSVecType && RHSVecType->getElementType()->isMFloat8Type())) |
| 10289 | return InvalidOperands(Loc, LHS, RHS); |
| 10290 | |
| 10291 | // AltiVec-style "vector bool op vector bool" combinations are allowed |
| 10292 | // for some operators but not others. |
| 10293 | if (!AllowBothBool && LHSVecType && |
| 10294 | LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType && |
| 10295 | RHSVecType->getVectorKind() == VectorKind::AltiVecBool) |
| 10296 | return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); |
| 10297 | |
| 10298 | // This operation may not be performed on boolean vectors. |
| 10299 | if (!AllowBoolOperation && |
| 10300 | (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType())) |
| 10301 | return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); |
| 10302 | |
| 10303 | // If the vector types are identical, return. |
| 10304 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
| 10305 | return Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
| 10306 | |
| 10307 | // If we have compatible AltiVec and GCC vector types, use the AltiVec type. |
| 10308 | if (LHSVecType && RHSVecType && |
| 10309 | Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) { |
| 10310 | if (isa<ExtVectorType>(Val: LHSVecType)) { |
| 10311 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
| 10312 | return LHSType; |
| 10313 | } |
| 10314 | |
| 10315 | if (!IsCompAssign) |
| 10316 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast); |
| 10317 | return RHSType; |
| 10318 | } |
| 10319 | |
| 10320 | // AllowBoolConversions says that bool and non-bool AltiVec vectors |
| 10321 | // can be mixed, with the result being the non-bool type. The non-bool |
| 10322 | // operand must have integer element type. |
| 10323 | if (AllowBoolConversions && LHSVecType && RHSVecType && |
| 10324 | LHSVecType->getNumElements() == RHSVecType->getNumElements() && |
| 10325 | (Context.getTypeSize(T: LHSVecType->getElementType()) == |
| 10326 | Context.getTypeSize(T: RHSVecType->getElementType()))) { |
| 10327 | if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector && |
| 10328 | LHSVecType->getElementType()->isIntegerType() && |
| 10329 | RHSVecType->getVectorKind() == VectorKind::AltiVecBool) { |
| 10330 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
| 10331 | return LHSType; |
| 10332 | } |
| 10333 | if (!IsCompAssign && |
| 10334 | LHSVecType->getVectorKind() == VectorKind::AltiVecBool && |
| 10335 | RHSVecType->getVectorKind() == VectorKind::AltiVecVector && |
| 10336 | RHSVecType->getElementType()->isIntegerType()) { |
| 10337 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast); |
| 10338 | return RHSType; |
| 10339 | } |
| 10340 | } |
| 10341 | |
| 10342 | // Expressions containing fixed-length and sizeless SVE/RVV vectors are |
| 10343 | // invalid since the ambiguity can affect the ABI. |
| 10344 | auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType, |
| 10345 | unsigned &SVEorRVV) { |
| 10346 | const VectorType *VecType = SecondType->getAs<VectorType>(); |
| 10347 | SVEorRVV = 0; |
| 10348 | if (FirstType->isSizelessBuiltinType() && VecType) { |
| 10349 | if (VecType->getVectorKind() == VectorKind::SveFixedLengthData || |
| 10350 | VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate) |
| 10351 | return true; |
| 10352 | if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData || |
| 10353 | VecType->getVectorKind() == VectorKind::RVVFixedLengthMask || |
| 10354 | VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 || |
| 10355 | VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 || |
| 10356 | VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) { |
| 10357 | SVEorRVV = 1; |
| 10358 | return true; |
| 10359 | } |
| 10360 | } |
| 10361 | |
| 10362 | return false; |
| 10363 | }; |
| 10364 | |
| 10365 | unsigned SVEorRVV; |
| 10366 | if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) || |
| 10367 | IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) { |
| 10368 | Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_ambiguous) |
| 10369 | << SVEorRVV << LHSType << RHSType; |
| 10370 | return QualType(); |
| 10371 | } |
| 10372 | |
| 10373 | // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are |
| 10374 | // invalid since the ambiguity can affect the ABI. |
| 10375 | auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType, |
| 10376 | unsigned &SVEorRVV) { |
| 10377 | const VectorType *FirstVecType = FirstType->getAs<VectorType>(); |
| 10378 | const VectorType *SecondVecType = SecondType->getAs<VectorType>(); |
| 10379 | |
| 10380 | SVEorRVV = 0; |
| 10381 | if (FirstVecType && SecondVecType) { |
| 10382 | if (FirstVecType->getVectorKind() == VectorKind::Generic) { |
| 10383 | if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData || |
| 10384 | SecondVecType->getVectorKind() == |
| 10385 | VectorKind::SveFixedLengthPredicate) |
| 10386 | return true; |
| 10387 | if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData || |
| 10388 | SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask || |
| 10389 | SecondVecType->getVectorKind() == |
| 10390 | VectorKind::RVVFixedLengthMask_1 || |
| 10391 | SecondVecType->getVectorKind() == |
| 10392 | VectorKind::RVVFixedLengthMask_2 || |
| 10393 | SecondVecType->getVectorKind() == |
| 10394 | VectorKind::RVVFixedLengthMask_4) { |
| 10395 | SVEorRVV = 1; |
| 10396 | return true; |
| 10397 | } |
| 10398 | } |
| 10399 | return false; |
| 10400 | } |
| 10401 | |
| 10402 | if (SecondVecType && |
| 10403 | SecondVecType->getVectorKind() == VectorKind::Generic) { |
| 10404 | if (FirstType->isSVESizelessBuiltinType()) |
| 10405 | return true; |
| 10406 | if (FirstType->isRVVSizelessBuiltinType()) { |
| 10407 | SVEorRVV = 1; |
| 10408 | return true; |
| 10409 | } |
| 10410 | } |
| 10411 | |
| 10412 | return false; |
| 10413 | }; |
| 10414 | |
| 10415 | if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) || |
| 10416 | IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) { |
| 10417 | Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_gnu_ambiguous) |
| 10418 | << SVEorRVV << LHSType << RHSType; |
| 10419 | return QualType(); |
| 10420 | } |
| 10421 | |
| 10422 | // If there's a vector type and a scalar, try to convert the scalar to |
| 10423 | // the vector element type and splat. |
| 10424 | unsigned DiagID = diag::err_typecheck_vector_not_convertable; |
| 10425 | if (!RHSVecType) { |
| 10426 | if (isa<ExtVectorType>(Val: LHSVecType)) { |
| 10427 | if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType, |
| 10428 | vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType, |
| 10429 | DiagID)) |
| 10430 | return LHSType; |
| 10431 | } else { |
| 10432 | if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS)) |
| 10433 | return LHSType; |
| 10434 | } |
| 10435 | } |
| 10436 | if (!LHSVecType) { |
| 10437 | if (isa<ExtVectorType>(Val: RHSVecType)) { |
| 10438 | if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS), |
| 10439 | scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(), |
| 10440 | vectorTy: RHSType, DiagID)) |
| 10441 | return RHSType; |
| 10442 | } else { |
| 10443 | if (LHS.get()->isLValue() || |
| 10444 | !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS)) |
| 10445 | return RHSType; |
| 10446 | } |
| 10447 | } |
| 10448 | |
| 10449 | // FIXME: The code below also handles conversion between vectors and |
| 10450 | // non-scalars, we should break this down into fine grained specific checks |
| 10451 | // and emit proper diagnostics. |
| 10452 | QualType VecType = LHSVecType ? LHSType : RHSType; |
| 10453 | const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; |
| 10454 | QualType OtherType = LHSVecType ? RHSType : LHSType; |
| 10455 | ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; |
| 10456 | if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) { |
| 10457 | if (Context.getTargetInfo().getTriple().isPPC() && |
| 10458 | anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) && |
| 10459 | !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType)) |
| 10460 | Diag(Loc, DiagID: diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType; |
| 10461 | // If we're allowing lax vector conversions, only the total (data) size |
| 10462 | // needs to be the same. For non compound assignment, if one of the types is |
| 10463 | // scalar, the result is always the vector type. |
| 10464 | if (!IsCompAssign) { |
| 10465 | *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast); |
| 10466 | return VecType; |
| 10467 | // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding |
| 10468 | // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' |
| 10469 | // type. Note that this is already done by non-compound assignments in |
| 10470 | // CheckAssignmentConstraints. If it's a scalar type, only bitcast for |
| 10471 | // <1 x T> -> T. The result is also a vector type. |
| 10472 | } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || |
| 10473 | (OtherType->isScalarType() && VT->getNumElements() == 1)) { |
| 10474 | ExprResult *RHSExpr = &RHS; |
| 10475 | *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast); |
| 10476 | return VecType; |
| 10477 | } |
| 10478 | } |
| 10479 | |
| 10480 | // Okay, the expression is invalid. |
| 10481 | |
| 10482 | // If there's a non-vector, non-real operand, diagnose that. |
| 10483 | if ((!RHSVecType && !RHSType->isRealType()) || |
| 10484 | (!LHSVecType && !LHSType->isRealType())) { |
| 10485 | Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar) |
| 10486 | << LHSType << RHSType |
| 10487 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 10488 | return QualType(); |
| 10489 | } |
| 10490 | |
| 10491 | // OpenCL V1.1 6.2.6.p1: |
| 10492 | // If the operands are of more than one vector type, then an error shall |
| 10493 | // occur. Implicit conversions between vector types are not permitted, per |
| 10494 | // section 6.2.1. |
| 10495 | if (getLangOpts().OpenCL && |
| 10496 | RHSVecType && isa<ExtVectorType>(Val: RHSVecType) && |
| 10497 | LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) { |
| 10498 | Diag(Loc, DiagID: diag::err_opencl_implicit_vector_conversion) << LHSType |
| 10499 | << RHSType; |
| 10500 | return QualType(); |
| 10501 | } |
| 10502 | |
| 10503 | |
| 10504 | // If there is a vector type that is not a ExtVector and a scalar, we reach |
| 10505 | // this point if scalar could not be converted to the vector's element type |
| 10506 | // without truncation. |
| 10507 | if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) || |
| 10508 | (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) { |
| 10509 | QualType Scalar = LHSVecType ? RHSType : LHSType; |
| 10510 | QualType Vector = LHSVecType ? LHSType : RHSType; |
| 10511 | unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; |
| 10512 | Diag(Loc, |
| 10513 | DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation) |
| 10514 | << ScalarOrVector << Scalar << Vector; |
| 10515 | |
| 10516 | return QualType(); |
| 10517 | } |
| 10518 | |
| 10519 | // Otherwise, use the generic diagnostic. |
| 10520 | Diag(Loc, DiagID) |
| 10521 | << LHSType << RHSType |
| 10522 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 10523 | return QualType(); |
| 10524 | } |
| 10525 | |
| 10526 | QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, |
| 10527 | SourceLocation Loc, |
| 10528 | bool IsCompAssign, |
| 10529 | ArithConvKind OperationKind) { |
| 10530 | if (!IsCompAssign) { |
| 10531 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
| 10532 | if (LHS.isInvalid()) |
| 10533 | return QualType(); |
| 10534 | } |
| 10535 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
| 10536 | if (RHS.isInvalid()) |
| 10537 | return QualType(); |
| 10538 | |
| 10539 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); |
| 10540 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); |
| 10541 | |
| 10542 | const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); |
| 10543 | const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); |
| 10544 | |
| 10545 | unsigned DiagID = diag::err_typecheck_invalid_operands; |
| 10546 | if ((OperationKind == ArithConvKind::Arithmetic) && |
| 10547 | ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || |
| 10548 | (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) { |
| 10549 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() |
| 10550 | << RHS.get()->getSourceRange(); |
| 10551 | return QualType(); |
| 10552 | } |
| 10553 | |
| 10554 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
| 10555 | return LHSType; |
| 10556 | |
| 10557 | if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) { |
| 10558 | if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS)) |
| 10559 | return LHSType; |
| 10560 | } |
| 10561 | if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) { |
| 10562 | if (LHS.get()->isLValue() || |
| 10563 | !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS)) |
| 10564 | return RHSType; |
| 10565 | } |
| 10566 | |
| 10567 | if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) || |
| 10568 | (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) { |
| 10569 | Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar) |
| 10570 | << LHSType << RHSType << LHS.get()->getSourceRange() |
| 10571 | << RHS.get()->getSourceRange(); |
| 10572 | return QualType(); |
| 10573 | } |
| 10574 | |
| 10575 | if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() && |
| 10576 | Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC != |
| 10577 | Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) { |
| 10578 | Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal) |
| 10579 | << LHSType << RHSType << LHS.get()->getSourceRange() |
| 10580 | << RHS.get()->getSourceRange(); |
| 10581 | return QualType(); |
| 10582 | } |
| 10583 | |
| 10584 | if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) { |
| 10585 | QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType; |
| 10586 | QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType; |
| 10587 | bool ScalarOrVector = |
| 10588 | LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType(); |
| 10589 | |
| 10590 | Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation) |
| 10591 | << ScalarOrVector << Scalar << Vector; |
| 10592 | |
| 10593 | return QualType(); |
| 10594 | } |
| 10595 | |
| 10596 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() |
| 10597 | << RHS.get()->getSourceRange(); |
| 10598 | return QualType(); |
| 10599 | } |
| 10600 | |
| 10601 | // checkArithmeticNull - Detect when a NULL constant is used improperly in an |
| 10602 | // expression. These are mainly cases where the null pointer is used as an |
| 10603 | // integer instead of a pointer. |
| 10604 | static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, |
| 10605 | SourceLocation Loc, bool IsCompare) { |
| 10606 | // The canonical way to check for a GNU null is with isNullPointerConstant, |
| 10607 | // but we use a bit of a hack here for speed; this is a relatively |
| 10608 | // hot path, and isNullPointerConstant is slow. |
| 10609 | bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts()); |
| 10610 | bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts()); |
| 10611 | |
| 10612 | QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); |
| 10613 | |
| 10614 | // Avoid analyzing cases where the result will either be invalid (and |
| 10615 | // diagnosed as such) or entirely valid and not something to warn about. |
| 10616 | if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || |
| 10617 | NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) |
| 10618 | return; |
| 10619 | |
| 10620 | // Comparison operations would not make sense with a null pointer no matter |
| 10621 | // what the other expression is. |
| 10622 | if (!IsCompare) { |
| 10623 | S.Diag(Loc, DiagID: diag::warn_null_in_arithmetic_operation) |
| 10624 | << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) |
| 10625 | << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); |
| 10626 | return; |
| 10627 | } |
| 10628 | |
| 10629 | // The rest of the operations only make sense with a null pointer |
| 10630 | // if the other expression is a pointer. |
| 10631 | if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || |
| 10632 | NonNullType->canDecayToPointerType()) |
| 10633 | return; |
| 10634 | |
| 10635 | S.Diag(Loc, DiagID: diag::warn_null_in_comparison_operation) |
| 10636 | << LHSNull /* LHS is NULL */ << NonNullType |
| 10637 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 10638 | } |
| 10639 | |
| 10640 | static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy, |
| 10641 | SourceLocation OpLoc) { |
| 10642 | // If the divisor is real, then this is real/real or complex/real division. |
| 10643 | // Either way there can be no precision loss. |
| 10644 | auto *CT = DivisorTy->getAs<ComplexType>(); |
| 10645 | if (!CT) |
| 10646 | return; |
| 10647 | |
| 10648 | QualType ElementType = CT->getElementType(); |
| 10649 | bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() == |
| 10650 | LangOptions::ComplexRangeKind::CX_Promoted; |
| 10651 | if (!ElementType->isFloatingType() || !IsComplexRangePromoted) |
| 10652 | return; |
| 10653 | |
| 10654 | ASTContext &Ctx = S.getASTContext(); |
| 10655 | QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType); |
| 10656 | const llvm::fltSemantics &ElementTypeSemantics = |
| 10657 | Ctx.getFloatTypeSemantics(T: ElementType); |
| 10658 | const llvm::fltSemantics &HigherElementTypeSemantics = |
| 10659 | Ctx.getFloatTypeSemantics(T: HigherElementType); |
| 10660 | |
| 10661 | if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 > |
| 10662 | llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) || |
| 10663 | (HigherElementType == Ctx.LongDoubleTy && |
| 10664 | !Ctx.getTargetInfo().hasLongDoubleType())) { |
| 10665 | // Retain the location of the first use of higher precision type. |
| 10666 | if (!S.LocationOfExcessPrecisionNotSatisfied.isValid()) |
| 10667 | S.LocationOfExcessPrecisionNotSatisfied = OpLoc; |
| 10668 | for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) { |
| 10669 | if (Type == HigherElementType) { |
| 10670 | Num++; |
| 10671 | return; |
| 10672 | } |
| 10673 | } |
| 10674 | S.ExcessPrecisionNotSatisfied.push_back(x: std::make_pair( |
| 10675 | x&: HigherElementType, y: S.ExcessPrecisionNotSatisfied.size())); |
| 10676 | } |
| 10677 | } |
| 10678 | |
| 10679 | static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, |
| 10680 | SourceLocation Loc) { |
| 10681 | const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS); |
| 10682 | const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS); |
| 10683 | if (!LUE || !RUE) |
| 10684 | return; |
| 10685 | if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || |
| 10686 | RUE->getKind() != UETT_SizeOf) |
| 10687 | return; |
| 10688 | |
| 10689 | const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); |
| 10690 | QualType LHSTy = LHSArg->getType(); |
| 10691 | QualType RHSTy; |
| 10692 | |
| 10693 | if (RUE->isArgumentType()) |
| 10694 | RHSTy = RUE->getArgumentType().getNonReferenceType(); |
| 10695 | else |
| 10696 | RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); |
| 10697 | |
| 10698 | if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { |
| 10699 | if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy)) |
| 10700 | return; |
| 10701 | |
| 10702 | S.Diag(Loc, DiagID: diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); |
| 10703 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) { |
| 10704 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) |
| 10705 | S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_pointer_declared_here) |
| 10706 | << LHSArgDecl; |
| 10707 | } |
| 10708 | } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) { |
| 10709 | QualType ArrayElemTy = ArrayTy->getElementType(); |
| 10710 | if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) || |
| 10711 | ArrayElemTy->isDependentType() || RHSTy->isDependentType() || |
| 10712 | RHSTy->isReferenceType() || ArrayElemTy->isCharType() || |
| 10713 | S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy)) |
| 10714 | return; |
| 10715 | S.Diag(Loc, DiagID: diag::warn_division_sizeof_array) |
| 10716 | << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; |
| 10717 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) { |
| 10718 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) |
| 10719 | S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_array_declared_here) |
| 10720 | << LHSArgDecl; |
| 10721 | } |
| 10722 | |
| 10723 | S.Diag(Loc, DiagID: diag::note_precedence_silence) << RHS; |
| 10724 | } |
| 10725 | } |
| 10726 | |
| 10727 | static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, |
| 10728 | ExprResult &RHS, |
| 10729 | SourceLocation Loc, bool IsDiv) { |
| 10730 | // Check for division/remainder by zero. |
| 10731 | Expr::EvalResult RHSValue; |
| 10732 | if (!RHS.get()->isValueDependent() && |
| 10733 | RHS.get()->EvaluateAsInt(Result&: RHSValue, Ctx: S.Context) && |
| 10734 | RHSValue.Val.getInt() == 0) |
| 10735 | S.DiagRuntimeBehavior(Loc, Statement: RHS.get(), |
| 10736 | PD: S.PDiag(DiagID: diag::warn_remainder_division_by_zero) |
| 10737 | << IsDiv << RHS.get()->getSourceRange()); |
| 10738 | } |
| 10739 | |
| 10740 | QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, |
| 10741 | SourceLocation Loc, |
| 10742 | bool IsCompAssign, bool IsDiv) { |
| 10743 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
| 10744 | |
| 10745 | QualType LHSTy = LHS.get()->getType(); |
| 10746 | QualType RHSTy = RHS.get()->getType(); |
| 10747 | if (LHSTy->isVectorType() || RHSTy->isVectorType()) |
| 10748 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, |
| 10749 | /*AllowBothBool*/ getLangOpts().AltiVec, |
| 10750 | /*AllowBoolConversions*/ false, |
| 10751 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
| 10752 | /*ReportInvalid*/ true); |
| 10753 | if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType()) |
| 10754 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, |
| 10755 | OperationKind: ArithConvKind::Arithmetic); |
| 10756 | if (!IsDiv && |
| 10757 | (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) |
| 10758 | return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); |
| 10759 | // For division, only matrix-by-scalar is supported. Other combinations with |
| 10760 | // matrix types are invalid. |
| 10761 | if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) |
| 10762 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); |
| 10763 | |
| 10764 | QualType compType = UsualArithmeticConversions( |
| 10765 | LHS, RHS, Loc, |
| 10766 | ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic); |
| 10767 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 10768 | return QualType(); |
| 10769 | |
| 10770 | |
| 10771 | if (compType.isNull() || !compType->isArithmeticType()) |
| 10772 | return InvalidOperands(Loc, LHS, RHS); |
| 10773 | if (IsDiv) { |
| 10774 | DetectPrecisionLossInComplexDivision(S&: *this, DivisorTy: RHS.get()->getType(), OpLoc: Loc); |
| 10775 | DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv); |
| 10776 | DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc); |
| 10777 | } |
| 10778 | return compType; |
| 10779 | } |
| 10780 | |
| 10781 | QualType Sema::CheckRemainderOperands( |
| 10782 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { |
| 10783 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
| 10784 | |
| 10785 | // Note: This check is here to simplify the double exclusions of |
| 10786 | // scalar and vector HLSL checks. No getLangOpts().HLSL |
| 10787 | // is needed since all languages exlcude doubles. |
| 10788 | if (LHS.get()->getType()->isDoubleType() || |
| 10789 | RHS.get()->getType()->isDoubleType() || |
| 10790 | (LHS.get()->getType()->isVectorType() && LHS.get() |
| 10791 | ->getType() |
| 10792 | ->getAs<VectorType>() |
| 10793 | ->getElementType() |
| 10794 | ->isDoubleType()) || |
| 10795 | (RHS.get()->getType()->isVectorType() && RHS.get() |
| 10796 | ->getType() |
| 10797 | ->getAs<VectorType>() |
| 10798 | ->getElementType() |
| 10799 | ->isDoubleType())) |
| 10800 | return InvalidOperands(Loc, LHS, RHS); |
| 10801 | |
| 10802 | if (LHS.get()->getType()->isVectorType() || |
| 10803 | RHS.get()->getType()->isVectorType()) { |
| 10804 | if ((LHS.get()->getType()->hasIntegerRepresentation() && |
| 10805 | RHS.get()->getType()->hasIntegerRepresentation()) || |
| 10806 | (getLangOpts().HLSL && |
| 10807 | (LHS.get()->getType()->hasFloatingRepresentation() || |
| 10808 | RHS.get()->getType()->hasFloatingRepresentation()))) |
| 10809 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, |
| 10810 | /*AllowBothBool*/ getLangOpts().AltiVec, |
| 10811 | /*AllowBoolConversions*/ false, |
| 10812 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
| 10813 | /*ReportInvalid*/ true); |
| 10814 | return InvalidOperands(Loc, LHS, RHS); |
| 10815 | } |
| 10816 | |
| 10817 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
| 10818 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
| 10819 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
| 10820 | RHS.get()->getType()->hasIntegerRepresentation()) |
| 10821 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, |
| 10822 | OperationKind: ArithConvKind::Arithmetic); |
| 10823 | |
| 10824 | return InvalidOperands(Loc, LHS, RHS); |
| 10825 | } |
| 10826 | |
| 10827 | QualType compType = UsualArithmeticConversions( |
| 10828 | LHS, RHS, Loc, |
| 10829 | ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic); |
| 10830 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 10831 | return QualType(); |
| 10832 | |
| 10833 | if (compType.isNull() || |
| 10834 | (!compType->isIntegerType() && |
| 10835 | !(getLangOpts().HLSL && compType->isFloatingType()))) |
| 10836 | return InvalidOperands(Loc, LHS, RHS); |
| 10837 | DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */); |
| 10838 | return compType; |
| 10839 | } |
| 10840 | |
| 10841 | /// Diagnose invalid arithmetic on two void pointers. |
| 10842 | static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, |
| 10843 | Expr *LHSExpr, Expr *RHSExpr) { |
| 10844 | S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus |
| 10845 | ? diag::err_typecheck_pointer_arith_void_type |
| 10846 | : diag::ext_gnu_void_ptr) |
| 10847 | << 1 /* two pointers */ << LHSExpr->getSourceRange() |
| 10848 | << RHSExpr->getSourceRange(); |
| 10849 | } |
| 10850 | |
| 10851 | /// Diagnose invalid arithmetic on a void pointer. |
| 10852 | static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, |
| 10853 | Expr *Pointer) { |
| 10854 | S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus |
| 10855 | ? diag::err_typecheck_pointer_arith_void_type |
| 10856 | : diag::ext_gnu_void_ptr) |
| 10857 | << 0 /* one pointer */ << Pointer->getSourceRange(); |
| 10858 | } |
| 10859 | |
| 10860 | /// Diagnose invalid arithmetic on a null pointer. |
| 10861 | /// |
| 10862 | /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' |
| 10863 | /// idiom, which we recognize as a GNU extension. |
| 10864 | /// |
| 10865 | static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, |
| 10866 | Expr *Pointer, bool IsGNUIdiom) { |
| 10867 | if (IsGNUIdiom) |
| 10868 | S.Diag(Loc, DiagID: diag::warn_gnu_null_ptr_arith) |
| 10869 | << Pointer->getSourceRange(); |
| 10870 | else |
| 10871 | S.Diag(Loc, DiagID: diag::warn_pointer_arith_null_ptr) |
| 10872 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); |
| 10873 | } |
| 10874 | |
| 10875 | /// Diagnose invalid subraction on a null pointer. |
| 10876 | /// |
| 10877 | static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, |
| 10878 | Expr *Pointer, bool BothNull) { |
| 10879 | // Null - null is valid in C++ [expr.add]p7 |
| 10880 | if (BothNull && S.getLangOpts().CPlusPlus) |
| 10881 | return; |
| 10882 | |
| 10883 | // Is this s a macro from a system header? |
| 10884 | if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc)) |
| 10885 | return; |
| 10886 | |
| 10887 | S.DiagRuntimeBehavior(Loc, Statement: Pointer, |
| 10888 | PD: S.PDiag(DiagID: diag::warn_pointer_sub_null_ptr) |
| 10889 | << S.getLangOpts().CPlusPlus |
| 10890 | << Pointer->getSourceRange()); |
| 10891 | } |
| 10892 | |
| 10893 | /// Diagnose invalid arithmetic on two function pointers. |
| 10894 | static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, |
| 10895 | Expr *LHS, Expr *RHS) { |
| 10896 | assert(LHS->getType()->isAnyPointerType()); |
| 10897 | assert(RHS->getType()->isAnyPointerType()); |
| 10898 | S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus |
| 10899 | ? diag::err_typecheck_pointer_arith_function_type |
| 10900 | : diag::ext_gnu_ptr_func_arith) |
| 10901 | << 1 /* two pointers */ << LHS->getType()->getPointeeType() |
| 10902 | // We only show the second type if it differs from the first. |
| 10903 | << (unsigned)!S.Context.hasSameUnqualifiedType(T1: LHS->getType(), |
| 10904 | T2: RHS->getType()) |
| 10905 | << RHS->getType()->getPointeeType() |
| 10906 | << LHS->getSourceRange() << RHS->getSourceRange(); |
| 10907 | } |
| 10908 | |
| 10909 | /// Diagnose invalid arithmetic on a function pointer. |
| 10910 | static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, |
| 10911 | Expr *Pointer) { |
| 10912 | assert(Pointer->getType()->isAnyPointerType()); |
| 10913 | S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus |
| 10914 | ? diag::err_typecheck_pointer_arith_function_type |
| 10915 | : diag::ext_gnu_ptr_func_arith) |
| 10916 | << 0 /* one pointer */ << Pointer->getType()->getPointeeType() |
| 10917 | << 0 /* one pointer, so only one type */ |
| 10918 | << Pointer->getSourceRange(); |
| 10919 | } |
| 10920 | |
| 10921 | /// Emit error if Operand is incomplete pointer type |
| 10922 | /// |
| 10923 | /// \returns True if pointer has incomplete type |
| 10924 | static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, |
| 10925 | Expr *Operand) { |
| 10926 | QualType ResType = Operand->getType(); |
| 10927 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) |
| 10928 | ResType = ResAtomicType->getValueType(); |
| 10929 | |
| 10930 | assert(ResType->isAnyPointerType()); |
| 10931 | QualType PointeeTy = ResType->getPointeeType(); |
| 10932 | return S.RequireCompleteSizedType( |
| 10933 | Loc, T: PointeeTy, |
| 10934 | DiagID: diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, |
| 10935 | Args: Operand->getSourceRange()); |
| 10936 | } |
| 10937 | |
| 10938 | /// Check the validity of an arithmetic pointer operand. |
| 10939 | /// |
| 10940 | /// If the operand has pointer type, this code will check for pointer types |
| 10941 | /// which are invalid in arithmetic operations. These will be diagnosed |
| 10942 | /// appropriately, including whether or not the use is supported as an |
| 10943 | /// extension. |
| 10944 | /// |
| 10945 | /// \returns True when the operand is valid to use (even if as an extension). |
| 10946 | static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, |
| 10947 | Expr *Operand) { |
| 10948 | QualType ResType = Operand->getType(); |
| 10949 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) |
| 10950 | ResType = ResAtomicType->getValueType(); |
| 10951 | |
| 10952 | if (!ResType->isAnyPointerType()) return true; |
| 10953 | |
| 10954 | QualType PointeeTy = ResType->getPointeeType(); |
| 10955 | if (PointeeTy->isVoidType()) { |
| 10956 | diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand); |
| 10957 | return !S.getLangOpts().CPlusPlus; |
| 10958 | } |
| 10959 | if (PointeeTy->isFunctionType()) { |
| 10960 | diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand); |
| 10961 | return !S.getLangOpts().CPlusPlus; |
| 10962 | } |
| 10963 | |
| 10964 | if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; |
| 10965 | |
| 10966 | return true; |
| 10967 | } |
| 10968 | |
| 10969 | /// Check the validity of a binary arithmetic operation w.r.t. pointer |
| 10970 | /// operands. |
| 10971 | /// |
| 10972 | /// This routine will diagnose any invalid arithmetic on pointer operands much |
| 10973 | /// like \see checkArithmeticOpPointerOperand. However, it has special logic |
| 10974 | /// for emitting a single diagnostic even for operations where both LHS and RHS |
| 10975 | /// are (potentially problematic) pointers. |
| 10976 | /// |
| 10977 | /// \returns True when the operand is valid to use (even if as an extension). |
| 10978 | static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, |
| 10979 | Expr *LHSExpr, Expr *RHSExpr) { |
| 10980 | bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); |
| 10981 | bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); |
| 10982 | if (!isLHSPointer && !isRHSPointer) return true; |
| 10983 | |
| 10984 | QualType LHSPointeeTy, RHSPointeeTy; |
| 10985 | if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); |
| 10986 | if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); |
| 10987 | |
| 10988 | // if both are pointers check if operation is valid wrt address spaces |
| 10989 | if (isLHSPointer && isRHSPointer) { |
| 10990 | if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy, |
| 10991 | Ctx: S.getASTContext())) { |
| 10992 | S.Diag(Loc, |
| 10993 | DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) |
| 10994 | << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ |
| 10995 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); |
| 10996 | return false; |
| 10997 | } |
| 10998 | } |
| 10999 | |
| 11000 | // Check for arithmetic on pointers to incomplete types. |
| 11001 | bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); |
| 11002 | bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); |
| 11003 | if (isLHSVoidPtr || isRHSVoidPtr) { |
| 11004 | if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr); |
| 11005 | else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr); |
| 11006 | else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); |
| 11007 | |
| 11008 | return !S.getLangOpts().CPlusPlus; |
| 11009 | } |
| 11010 | |
| 11011 | bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); |
| 11012 | bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); |
| 11013 | if (isLHSFuncPtr || isRHSFuncPtr) { |
| 11014 | if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr); |
| 11015 | else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, |
| 11016 | Pointer: RHSExpr); |
| 11017 | else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr); |
| 11018 | |
| 11019 | return !S.getLangOpts().CPlusPlus; |
| 11020 | } |
| 11021 | |
| 11022 | if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr)) |
| 11023 | return false; |
| 11024 | if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr)) |
| 11025 | return false; |
| 11026 | |
| 11027 | return true; |
| 11028 | } |
| 11029 | |
| 11030 | /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string |
| 11031 | /// literal. |
| 11032 | static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, |
| 11033 | Expr *LHSExpr, Expr *RHSExpr) { |
| 11034 | StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts()); |
| 11035 | Expr* IndexExpr = RHSExpr; |
| 11036 | if (!StrExpr) { |
| 11037 | StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts()); |
| 11038 | IndexExpr = LHSExpr; |
| 11039 | } |
| 11040 | |
| 11041 | bool IsStringPlusInt = StrExpr && |
| 11042 | IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); |
| 11043 | if (!IsStringPlusInt || IndexExpr->isValueDependent()) |
| 11044 | return; |
| 11045 | |
| 11046 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
| 11047 | Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_int) |
| 11048 | << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); |
| 11049 | |
| 11050 | // Only print a fixit for "str" + int, not for int + "str". |
| 11051 | if (IndexExpr == RHSExpr) { |
| 11052 | SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc()); |
| 11053 | Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence) |
| 11054 | << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&" ) |
| 11055 | << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[" ) |
| 11056 | << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]" ); |
| 11057 | } else |
| 11058 | Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence); |
| 11059 | } |
| 11060 | |
| 11061 | /// Emit a warning when adding a char literal to a string. |
| 11062 | static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, |
| 11063 | Expr *LHSExpr, Expr *RHSExpr) { |
| 11064 | const Expr *StringRefExpr = LHSExpr; |
| 11065 | const CharacterLiteral *CharExpr = |
| 11066 | dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts()); |
| 11067 | |
| 11068 | if (!CharExpr) { |
| 11069 | CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts()); |
| 11070 | StringRefExpr = RHSExpr; |
| 11071 | } |
| 11072 | |
| 11073 | if (!CharExpr || !StringRefExpr) |
| 11074 | return; |
| 11075 | |
| 11076 | const QualType StringType = StringRefExpr->getType(); |
| 11077 | |
| 11078 | // Return if not a PointerType. |
| 11079 | if (!StringType->isAnyPointerType()) |
| 11080 | return; |
| 11081 | |
| 11082 | // Return if not a CharacterType. |
| 11083 | if (!StringType->getPointeeType()->isAnyCharacterType()) |
| 11084 | return; |
| 11085 | |
| 11086 | ASTContext &Ctx = Self.getASTContext(); |
| 11087 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
| 11088 | |
| 11089 | const QualType CharType = CharExpr->getType(); |
| 11090 | if (!CharType->isAnyCharacterType() && |
| 11091 | CharType->isIntegerType() && |
| 11092 | llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) { |
| 11093 | Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char) |
| 11094 | << DiagRange << Ctx.CharTy; |
| 11095 | } else { |
| 11096 | Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char) |
| 11097 | << DiagRange << CharExpr->getType(); |
| 11098 | } |
| 11099 | |
| 11100 | // Only print a fixit for str + char, not for char + str. |
| 11101 | if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) { |
| 11102 | SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc()); |
| 11103 | Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence) |
| 11104 | << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&" ) |
| 11105 | << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[" ) |
| 11106 | << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]" ); |
| 11107 | } else { |
| 11108 | Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence); |
| 11109 | } |
| 11110 | } |
| 11111 | |
| 11112 | /// Emit error when two pointers are incompatible. |
| 11113 | static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, |
| 11114 | Expr *LHSExpr, Expr *RHSExpr) { |
| 11115 | assert(LHSExpr->getType()->isAnyPointerType()); |
| 11116 | assert(RHSExpr->getType()->isAnyPointerType()); |
| 11117 | S.Diag(Loc, DiagID: diag::err_typecheck_sub_ptr_compatible) |
| 11118 | << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() |
| 11119 | << RHSExpr->getSourceRange(); |
| 11120 | } |
| 11121 | |
| 11122 | // C99 6.5.6 |
| 11123 | QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, |
| 11124 | SourceLocation Loc, BinaryOperatorKind Opc, |
| 11125 | QualType* CompLHSTy) { |
| 11126 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
| 11127 | |
| 11128 | if (LHS.get()->getType()->isVectorType() || |
| 11129 | RHS.get()->getType()->isVectorType()) { |
| 11130 | QualType compType = |
| 11131 | CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, |
| 11132 | /*AllowBothBool*/ getLangOpts().AltiVec, |
| 11133 | /*AllowBoolConversions*/ getLangOpts().ZVector, |
| 11134 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
| 11135 | /*ReportInvalid*/ true); |
| 11136 | if (CompLHSTy) *CompLHSTy = compType; |
| 11137 | return compType; |
| 11138 | } |
| 11139 | |
| 11140 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
| 11141 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
| 11142 | QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, |
| 11143 | OperationKind: ArithConvKind::Arithmetic); |
| 11144 | if (CompLHSTy) |
| 11145 | *CompLHSTy = compType; |
| 11146 | return compType; |
| 11147 | } |
| 11148 | |
| 11149 | if (LHS.get()->getType()->isConstantMatrixType() || |
| 11150 | RHS.get()->getType()->isConstantMatrixType()) { |
| 11151 | QualType compType = |
| 11152 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy); |
| 11153 | if (CompLHSTy) |
| 11154 | *CompLHSTy = compType; |
| 11155 | return compType; |
| 11156 | } |
| 11157 | |
| 11158 | QualType compType = UsualArithmeticConversions( |
| 11159 | LHS, RHS, Loc, |
| 11160 | ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic); |
| 11161 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 11162 | return QualType(); |
| 11163 | |
| 11164 | // Diagnose "string literal" '+' int and string '+' "char literal". |
| 11165 | if (Opc == BO_Add) { |
| 11166 | diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
| 11167 | diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
| 11168 | } |
| 11169 | |
| 11170 | // handle the common case first (both operands are arithmetic). |
| 11171 | if (!compType.isNull() && compType->isArithmeticType()) { |
| 11172 | if (CompLHSTy) *CompLHSTy = compType; |
| 11173 | return compType; |
| 11174 | } |
| 11175 | |
| 11176 | // Type-checking. Ultimately the pointer's going to be in PExp; |
| 11177 | // note that we bias towards the LHS being the pointer. |
| 11178 | Expr *PExp = LHS.get(), *IExp = RHS.get(); |
| 11179 | |
| 11180 | bool isObjCPointer; |
| 11181 | if (PExp->getType()->isPointerType()) { |
| 11182 | isObjCPointer = false; |
| 11183 | } else if (PExp->getType()->isObjCObjectPointerType()) { |
| 11184 | isObjCPointer = true; |
| 11185 | } else { |
| 11186 | std::swap(a&: PExp, b&: IExp); |
| 11187 | if (PExp->getType()->isPointerType()) { |
| 11188 | isObjCPointer = false; |
| 11189 | } else if (PExp->getType()->isObjCObjectPointerType()) { |
| 11190 | isObjCPointer = true; |
| 11191 | } else { |
| 11192 | return InvalidOperands(Loc, LHS, RHS); |
| 11193 | } |
| 11194 | } |
| 11195 | assert(PExp->getType()->isAnyPointerType()); |
| 11196 | |
| 11197 | if (!IExp->getType()->isIntegerType()) |
| 11198 | return InvalidOperands(Loc, LHS, RHS); |
| 11199 | |
| 11200 | // Adding to a null pointer results in undefined behavior. |
| 11201 | if (PExp->IgnoreParenCasts()->isNullPointerConstant( |
| 11202 | Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) { |
| 11203 | // In C++ adding zero to a null pointer is defined. |
| 11204 | Expr::EvalResult KnownVal; |
| 11205 | if (!getLangOpts().CPlusPlus || |
| 11206 | (!IExp->isValueDependent() && |
| 11207 | (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) || |
| 11208 | KnownVal.Val.getInt() != 0))) { |
| 11209 | // Check the conditions to see if this is the 'p = nullptr + n' idiom. |
| 11210 | bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( |
| 11211 | Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp); |
| 11212 | diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom); |
| 11213 | } |
| 11214 | } |
| 11215 | |
| 11216 | if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp)) |
| 11217 | return QualType(); |
| 11218 | |
| 11219 | if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp)) |
| 11220 | return QualType(); |
| 11221 | |
| 11222 | // Arithmetic on label addresses is normally allowed, except when we add |
| 11223 | // a ptrauth signature to the addresses. |
| 11224 | if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) { |
| 11225 | Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic) |
| 11226 | << /*addition*/ 1; |
| 11227 | return QualType(); |
| 11228 | } |
| 11229 | |
| 11230 | // Check array bounds for pointer arithemtic |
| 11231 | CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp); |
| 11232 | |
| 11233 | if (CompLHSTy) { |
| 11234 | QualType LHSTy = Context.isPromotableBitField(E: LHS.get()); |
| 11235 | if (LHSTy.isNull()) { |
| 11236 | LHSTy = LHS.get()->getType(); |
| 11237 | if (Context.isPromotableIntegerType(T: LHSTy)) |
| 11238 | LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy); |
| 11239 | } |
| 11240 | *CompLHSTy = LHSTy; |
| 11241 | } |
| 11242 | |
| 11243 | return PExp->getType(); |
| 11244 | } |
| 11245 | |
| 11246 | // C99 6.5.6 |
| 11247 | QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, |
| 11248 | SourceLocation Loc, |
| 11249 | QualType* CompLHSTy) { |
| 11250 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
| 11251 | |
| 11252 | if (LHS.get()->getType()->isVectorType() || |
| 11253 | RHS.get()->getType()->isVectorType()) { |
| 11254 | QualType compType = |
| 11255 | CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, |
| 11256 | /*AllowBothBool*/ getLangOpts().AltiVec, |
| 11257 | /*AllowBoolConversions*/ getLangOpts().ZVector, |
| 11258 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
| 11259 | /*ReportInvalid*/ true); |
| 11260 | if (CompLHSTy) *CompLHSTy = compType; |
| 11261 | return compType; |
| 11262 | } |
| 11263 | |
| 11264 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
| 11265 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
| 11266 | QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, |
| 11267 | OperationKind: ArithConvKind::Arithmetic); |
| 11268 | if (CompLHSTy) |
| 11269 | *CompLHSTy = compType; |
| 11270 | return compType; |
| 11271 | } |
| 11272 | |
| 11273 | if (LHS.get()->getType()->isConstantMatrixType() || |
| 11274 | RHS.get()->getType()->isConstantMatrixType()) { |
| 11275 | QualType compType = |
| 11276 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy); |
| 11277 | if (CompLHSTy) |
| 11278 | *CompLHSTy = compType; |
| 11279 | return compType; |
| 11280 | } |
| 11281 | |
| 11282 | QualType compType = UsualArithmeticConversions( |
| 11283 | LHS, RHS, Loc, |
| 11284 | ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic); |
| 11285 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 11286 | return QualType(); |
| 11287 | |
| 11288 | // Enforce type constraints: C99 6.5.6p3. |
| 11289 | |
| 11290 | // Handle the common case first (both operands are arithmetic). |
| 11291 | if (!compType.isNull() && compType->isArithmeticType()) { |
| 11292 | if (CompLHSTy) *CompLHSTy = compType; |
| 11293 | return compType; |
| 11294 | } |
| 11295 | |
| 11296 | // Either ptr - int or ptr - ptr. |
| 11297 | if (LHS.get()->getType()->isAnyPointerType()) { |
| 11298 | QualType lpointee = LHS.get()->getType()->getPointeeType(); |
| 11299 | |
| 11300 | // Diagnose bad cases where we step over interface counts. |
| 11301 | if (LHS.get()->getType()->isObjCObjectPointerType() && |
| 11302 | checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get())) |
| 11303 | return QualType(); |
| 11304 | |
| 11305 | // Arithmetic on label addresses is normally allowed, except when we add |
| 11306 | // a ptrauth signature to the addresses. |
| 11307 | if (isa<AddrLabelExpr>(Val: LHS.get()) && |
| 11308 | getLangOpts().PointerAuthIndirectGotos) { |
| 11309 | Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic) |
| 11310 | << /*subtraction*/ 0; |
| 11311 | return QualType(); |
| 11312 | } |
| 11313 | |
| 11314 | // The result type of a pointer-int computation is the pointer type. |
| 11315 | if (RHS.get()->getType()->isIntegerType()) { |
| 11316 | // Subtracting from a null pointer should produce a warning. |
| 11317 | // The last argument to the diagnose call says this doesn't match the |
| 11318 | // GNU int-to-pointer idiom. |
| 11319 | if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context, |
| 11320 | NPC: Expr::NPC_ValueDependentIsNotNull)) { |
| 11321 | // In C++ adding zero to a null pointer is defined. |
| 11322 | Expr::EvalResult KnownVal; |
| 11323 | if (!getLangOpts().CPlusPlus || |
| 11324 | (!RHS.get()->isValueDependent() && |
| 11325 | (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) || |
| 11326 | KnownVal.Val.getInt() != 0))) { |
| 11327 | diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false); |
| 11328 | } |
| 11329 | } |
| 11330 | |
| 11331 | if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get())) |
| 11332 | return QualType(); |
| 11333 | |
| 11334 | // Check array bounds for pointer arithemtic |
| 11335 | CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr, |
| 11336 | /*AllowOnePastEnd*/true, /*IndexNegated*/true); |
| 11337 | |
| 11338 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); |
| 11339 | return LHS.get()->getType(); |
| 11340 | } |
| 11341 | |
| 11342 | // Handle pointer-pointer subtractions. |
| 11343 | if (const PointerType *RHSPTy |
| 11344 | = RHS.get()->getType()->getAs<PointerType>()) { |
| 11345 | QualType rpointee = RHSPTy->getPointeeType(); |
| 11346 | |
| 11347 | if (getLangOpts().CPlusPlus) { |
| 11348 | // Pointee types must be the same: C++ [expr.add] |
| 11349 | if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) { |
| 11350 | diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
| 11351 | } |
| 11352 | } else { |
| 11353 | // Pointee types must be compatible C99 6.5.6p3 |
| 11354 | if (!Context.typesAreCompatible( |
| 11355 | T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(), |
| 11356 | T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) { |
| 11357 | diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
| 11358 | return QualType(); |
| 11359 | } |
| 11360 | } |
| 11361 | |
| 11362 | if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc, |
| 11363 | LHSExpr: LHS.get(), RHSExpr: RHS.get())) |
| 11364 | return QualType(); |
| 11365 | |
| 11366 | bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( |
| 11367 | Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull); |
| 11368 | bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( |
| 11369 | Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull); |
| 11370 | |
| 11371 | // Subtracting nullptr or from nullptr is suspect |
| 11372 | if (LHSIsNullPtr) |
| 11373 | diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr); |
| 11374 | if (RHSIsNullPtr) |
| 11375 | diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr); |
| 11376 | |
| 11377 | // The pointee type may have zero size. As an extension, a structure or |
| 11378 | // union may have zero size or an array may have zero length. In this |
| 11379 | // case subtraction does not make sense. |
| 11380 | if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { |
| 11381 | CharUnits ElementSize = Context.getTypeSizeInChars(T: rpointee); |
| 11382 | if (ElementSize.isZero()) { |
| 11383 | Diag(Loc,DiagID: diag::warn_sub_ptr_zero_size_types) |
| 11384 | << rpointee.getUnqualifiedType() |
| 11385 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 11386 | } |
| 11387 | } |
| 11388 | |
| 11389 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); |
| 11390 | return Context.getPointerDiffType(); |
| 11391 | } |
| 11392 | } |
| 11393 | |
| 11394 | return InvalidOperands(Loc, LHS, RHS); |
| 11395 | } |
| 11396 | |
| 11397 | static bool isScopedEnumerationType(QualType T) { |
| 11398 | if (const EnumType *ET = T->getAs<EnumType>()) |
| 11399 | return ET->getDecl()->isScoped(); |
| 11400 | return false; |
| 11401 | } |
| 11402 | |
| 11403 | static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, |
| 11404 | SourceLocation Loc, BinaryOperatorKind Opc, |
| 11405 | QualType LHSType) { |
| 11406 | // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), |
| 11407 | // so skip remaining warnings as we don't want to modify values within Sema. |
| 11408 | if (S.getLangOpts().OpenCL) |
| 11409 | return; |
| 11410 | |
| 11411 | if (Opc == BO_Shr && |
| 11412 | LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType()) |
| 11413 | S.Diag(Loc, DiagID: diag::warn_shift_bool) << LHS.get()->getSourceRange(); |
| 11414 | |
| 11415 | // Check right/shifter operand |
| 11416 | Expr::EvalResult RHSResult; |
| 11417 | if (RHS.get()->isValueDependent() || |
| 11418 | !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context)) |
| 11419 | return; |
| 11420 | llvm::APSInt Right = RHSResult.Val.getInt(); |
| 11421 | |
| 11422 | if (Right.isNegative()) { |
| 11423 | S.DiagRuntimeBehavior(Loc, Statement: RHS.get(), |
| 11424 | PD: S.PDiag(DiagID: diag::warn_shift_negative) |
| 11425 | << RHS.get()->getSourceRange()); |
| 11426 | return; |
| 11427 | } |
| 11428 | |
| 11429 | QualType LHSExprType = LHS.get()->getType(); |
| 11430 | uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType); |
| 11431 | if (LHSExprType->isBitIntType()) |
| 11432 | LeftSize = S.Context.getIntWidth(T: LHSExprType); |
| 11433 | else if (LHSExprType->isFixedPointType()) { |
| 11434 | auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType); |
| 11435 | LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); |
| 11436 | } |
| 11437 | if (Right.uge(RHS: LeftSize)) { |
| 11438 | S.DiagRuntimeBehavior(Loc, Statement: RHS.get(), |
| 11439 | PD: S.PDiag(DiagID: diag::warn_shift_gt_typewidth) |
| 11440 | << RHS.get()->getSourceRange()); |
| 11441 | return; |
| 11442 | } |
| 11443 | |
| 11444 | // FIXME: We probably need to handle fixed point types specially here. |
| 11445 | if (Opc != BO_Shl || LHSExprType->isFixedPointType()) |
| 11446 | return; |
| 11447 | |
| 11448 | // When left shifting an ICE which is signed, we can check for overflow which |
| 11449 | // according to C++ standards prior to C++2a has undefined behavior |
| 11450 | // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one |
| 11451 | // more than the maximum value representable in the result type, so never |
| 11452 | // warn for those. (FIXME: Unsigned left-shift overflow in a constant |
| 11453 | // expression is still probably a bug.) |
| 11454 | Expr::EvalResult LHSResult; |
| 11455 | if (LHS.get()->isValueDependent() || |
| 11456 | LHSType->hasUnsignedIntegerRepresentation() || |
| 11457 | !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context)) |
| 11458 | return; |
| 11459 | llvm::APSInt Left = LHSResult.Val.getInt(); |
| 11460 | |
| 11461 | // Don't warn if signed overflow is defined, then all the rest of the |
| 11462 | // diagnostics will not be triggered because the behavior is defined. |
| 11463 | // Also don't warn in C++20 mode (and newer), as signed left shifts |
| 11464 | // always wrap and never overflow. |
| 11465 | if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20) |
| 11466 | return; |
| 11467 | |
| 11468 | // If LHS does not have a non-negative value then, the |
| 11469 | // behavior is undefined before C++2a. Warn about it. |
| 11470 | if (Left.isNegative()) { |
| 11471 | S.DiagRuntimeBehavior(Loc, Statement: LHS.get(), |
| 11472 | PD: S.PDiag(DiagID: diag::warn_shift_lhs_negative) |
| 11473 | << LHS.get()->getSourceRange()); |
| 11474 | return; |
| 11475 | } |
| 11476 | |
| 11477 | llvm::APInt ResultBits = |
| 11478 | static_cast<llvm::APInt &>(Right) + Left.getSignificantBits(); |
| 11479 | if (ResultBits.ule(RHS: LeftSize)) |
| 11480 | return; |
| 11481 | llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue()); |
| 11482 | Result = Result.shl(ShiftAmt: Right); |
| 11483 | |
| 11484 | // Print the bit representation of the signed integer as an unsigned |
| 11485 | // hexadecimal number. |
| 11486 | SmallString<40> HexResult; |
| 11487 | Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true); |
| 11488 | |
| 11489 | // If we are only missing a sign bit, this is less likely to result in actual |
| 11490 | // bugs -- if the result is cast back to an unsigned type, it will have the |
| 11491 | // expected value. Thus we place this behind a different warning that can be |
| 11492 | // turned off separately if needed. |
| 11493 | if (ResultBits - 1 == LeftSize) { |
| 11494 | S.Diag(Loc, DiagID: diag::warn_shift_result_sets_sign_bit) |
| 11495 | << HexResult << LHSType |
| 11496 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 11497 | return; |
| 11498 | } |
| 11499 | |
| 11500 | S.Diag(Loc, DiagID: diag::warn_shift_result_gt_typewidth) |
| 11501 | << HexResult.str() << Result.getSignificantBits() << LHSType |
| 11502 | << Left.getBitWidth() << LHS.get()->getSourceRange() |
| 11503 | << RHS.get()->getSourceRange(); |
| 11504 | } |
| 11505 | |
| 11506 | /// Return the resulting type when a vector is shifted |
| 11507 | /// by a scalar or vector shift amount. |
| 11508 | static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, |
| 11509 | SourceLocation Loc, bool IsCompAssign) { |
| 11510 | // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. |
| 11511 | if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && |
| 11512 | !LHS.get()->getType()->isVectorType()) { |
| 11513 | S.Diag(Loc, DiagID: diag::err_shift_rhs_only_vector) |
| 11514 | << RHS.get()->getType() << LHS.get()->getType() |
| 11515 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 11516 | return QualType(); |
| 11517 | } |
| 11518 | |
| 11519 | if (!IsCompAssign) { |
| 11520 | LHS = S.UsualUnaryConversions(E: LHS.get()); |
| 11521 | if (LHS.isInvalid()) return QualType(); |
| 11522 | } |
| 11523 | |
| 11524 | RHS = S.UsualUnaryConversions(E: RHS.get()); |
| 11525 | if (RHS.isInvalid()) return QualType(); |
| 11526 | |
| 11527 | QualType LHSType = LHS.get()->getType(); |
| 11528 | // Note that LHS might be a scalar because the routine calls not only in |
| 11529 | // OpenCL case. |
| 11530 | const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); |
| 11531 | QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; |
| 11532 | |
| 11533 | // Note that RHS might not be a vector. |
| 11534 | QualType RHSType = RHS.get()->getType(); |
| 11535 | const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); |
| 11536 | QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; |
| 11537 | |
| 11538 | // Do not allow shifts for boolean vectors. |
| 11539 | if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) || |
| 11540 | (RHSVecTy && RHSVecTy->isExtVectorBoolType())) { |
| 11541 | S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands) |
| 11542 | << LHS.get()->getType() << RHS.get()->getType() |
| 11543 | << LHS.get()->getSourceRange(); |
| 11544 | return QualType(); |
| 11545 | } |
| 11546 | |
| 11547 | // The operands need to be integers. |
| 11548 | if (!LHSEleType->isIntegerType()) { |
| 11549 | S.Diag(Loc, DiagID: diag::err_typecheck_expect_int) |
| 11550 | << LHS.get()->getType() << LHS.get()->getSourceRange(); |
| 11551 | return QualType(); |
| 11552 | } |
| 11553 | |
| 11554 | if (!RHSEleType->isIntegerType()) { |
| 11555 | S.Diag(Loc, DiagID: diag::err_typecheck_expect_int) |
| 11556 | << RHS.get()->getType() << RHS.get()->getSourceRange(); |
| 11557 | return QualType(); |
| 11558 | } |
| 11559 | |
| 11560 | if (!LHSVecTy) { |
| 11561 | assert(RHSVecTy); |
| 11562 | if (IsCompAssign) |
| 11563 | return RHSType; |
| 11564 | if (LHSEleType != RHSEleType) { |
| 11565 | LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast); |
| 11566 | LHSEleType = RHSEleType; |
| 11567 | } |
| 11568 | QualType VecTy = |
| 11569 | S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements()); |
| 11570 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat); |
| 11571 | LHSType = VecTy; |
| 11572 | } else if (RHSVecTy) { |
| 11573 | // OpenCL v1.1 s6.3.j says that for vector types, the operators |
| 11574 | // are applied component-wise. So if RHS is a vector, then ensure |
| 11575 | // that the number of elements is the same as LHS... |
| 11576 | if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { |
| 11577 | S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal) |
| 11578 | << LHS.get()->getType() << RHS.get()->getType() |
| 11579 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 11580 | return QualType(); |
| 11581 | } |
| 11582 | if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { |
| 11583 | const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); |
| 11584 | const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); |
| 11585 | if (LHSBT != RHSBT && |
| 11586 | S.Context.getTypeSize(T: LHSBT) != S.Context.getTypeSize(T: RHSBT)) { |
| 11587 | S.Diag(Loc, DiagID: diag::warn_typecheck_vector_element_sizes_not_equal) |
| 11588 | << LHS.get()->getType() << RHS.get()->getType() |
| 11589 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 11590 | } |
| 11591 | } |
| 11592 | } else { |
| 11593 | // ...else expand RHS to match the number of elements in LHS. |
| 11594 | QualType VecTy = |
| 11595 | S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements()); |
| 11596 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat); |
| 11597 | } |
| 11598 | |
| 11599 | return LHSType; |
| 11600 | } |
| 11601 | |
| 11602 | static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, |
| 11603 | ExprResult &RHS, SourceLocation Loc, |
| 11604 | bool IsCompAssign) { |
| 11605 | if (!IsCompAssign) { |
| 11606 | LHS = S.UsualUnaryConversions(E: LHS.get()); |
| 11607 | if (LHS.isInvalid()) |
| 11608 | return QualType(); |
| 11609 | } |
| 11610 | |
| 11611 | RHS = S.UsualUnaryConversions(E: RHS.get()); |
| 11612 | if (RHS.isInvalid()) |
| 11613 | return QualType(); |
| 11614 | |
| 11615 | QualType LHSType = LHS.get()->getType(); |
| 11616 | const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>(); |
| 11617 | QualType LHSEleType = LHSType->isSveVLSBuiltinType() |
| 11618 | ? LHSBuiltinTy->getSveEltType(Ctx: S.getASTContext()) |
| 11619 | : LHSType; |
| 11620 | |
| 11621 | // Note that RHS might not be a vector |
| 11622 | QualType RHSType = RHS.get()->getType(); |
| 11623 | const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>(); |
| 11624 | QualType RHSEleType = RHSType->isSveVLSBuiltinType() |
| 11625 | ? RHSBuiltinTy->getSveEltType(Ctx: S.getASTContext()) |
| 11626 | : RHSType; |
| 11627 | |
| 11628 | if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || |
| 11629 | (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) { |
| 11630 | S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands) |
| 11631 | << LHSType << RHSType << LHS.get()->getSourceRange(); |
| 11632 | return QualType(); |
| 11633 | } |
| 11634 | |
| 11635 | if (!LHSEleType->isIntegerType()) { |
| 11636 | S.Diag(Loc, DiagID: diag::err_typecheck_expect_int) |
| 11637 | << LHS.get()->getType() << LHS.get()->getSourceRange(); |
| 11638 | return QualType(); |
| 11639 | } |
| 11640 | |
| 11641 | if (!RHSEleType->isIntegerType()) { |
| 11642 | S.Diag(Loc, DiagID: diag::err_typecheck_expect_int) |
| 11643 | << RHS.get()->getType() << RHS.get()->getSourceRange(); |
| 11644 | return QualType(); |
| 11645 | } |
| 11646 | |
| 11647 | if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() && |
| 11648 | (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC != |
| 11649 | S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) { |
| 11650 | S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands) |
| 11651 | << LHSType << RHSType << LHS.get()->getSourceRange() |
| 11652 | << RHS.get()->getSourceRange(); |
| 11653 | return QualType(); |
| 11654 | } |
| 11655 | |
| 11656 | if (!LHSType->isSveVLSBuiltinType()) { |
| 11657 | assert(RHSType->isSveVLSBuiltinType()); |
| 11658 | if (IsCompAssign) |
| 11659 | return RHSType; |
| 11660 | if (LHSEleType != RHSEleType) { |
| 11661 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast); |
| 11662 | LHSEleType = RHSEleType; |
| 11663 | } |
| 11664 | const llvm::ElementCount VecSize = |
| 11665 | S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC; |
| 11666 | QualType VecTy = |
| 11667 | S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue()); |
| 11668 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat); |
| 11669 | LHSType = VecTy; |
| 11670 | } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) { |
| 11671 | if (S.Context.getTypeSize(T: RHSBuiltinTy) != |
| 11672 | S.Context.getTypeSize(T: LHSBuiltinTy)) { |
| 11673 | S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal) |
| 11674 | << LHSType << RHSType << LHS.get()->getSourceRange() |
| 11675 | << RHS.get()->getSourceRange(); |
| 11676 | return QualType(); |
| 11677 | } |
| 11678 | } else { |
| 11679 | const llvm::ElementCount VecSize = |
| 11680 | S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC; |
| 11681 | if (LHSEleType != RHSEleType) { |
| 11682 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast); |
| 11683 | RHSEleType = LHSEleType; |
| 11684 | } |
| 11685 | QualType VecTy = |
| 11686 | S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue()); |
| 11687 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat); |
| 11688 | } |
| 11689 | |
| 11690 | return LHSType; |
| 11691 | } |
| 11692 | |
| 11693 | // C99 6.5.7 |
| 11694 | QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, |
| 11695 | SourceLocation Loc, BinaryOperatorKind Opc, |
| 11696 | bool IsCompAssign) { |
| 11697 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
| 11698 | |
| 11699 | // Vector shifts promote their scalar inputs to vector type. |
| 11700 | if (LHS.get()->getType()->isVectorType() || |
| 11701 | RHS.get()->getType()->isVectorType()) { |
| 11702 | if (LangOpts.ZVector) { |
| 11703 | // The shift operators for the z vector extensions work basically |
| 11704 | // like general shifts, except that neither the LHS nor the RHS is |
| 11705 | // allowed to be a "vector bool". |
| 11706 | if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) |
| 11707 | if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool) |
| 11708 | return InvalidOperands(Loc, LHS, RHS); |
| 11709 | if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) |
| 11710 | if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool) |
| 11711 | return InvalidOperands(Loc, LHS, RHS); |
| 11712 | } |
| 11713 | return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign); |
| 11714 | } |
| 11715 | |
| 11716 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
| 11717 | RHS.get()->getType()->isSveVLSBuiltinType()) |
| 11718 | return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign); |
| 11719 | |
| 11720 | // Shifts don't perform usual arithmetic conversions, they just do integer |
| 11721 | // promotions on each operand. C99 6.5.7p3 |
| 11722 | |
| 11723 | // For the LHS, do usual unary conversions, but then reset them away |
| 11724 | // if this is a compound assignment. |
| 11725 | ExprResult OldLHS = LHS; |
| 11726 | LHS = UsualUnaryConversions(E: LHS.get()); |
| 11727 | if (LHS.isInvalid()) |
| 11728 | return QualType(); |
| 11729 | QualType LHSType = LHS.get()->getType(); |
| 11730 | if (IsCompAssign) LHS = OldLHS; |
| 11731 | |
| 11732 | // The RHS is simpler. |
| 11733 | RHS = UsualUnaryConversions(E: RHS.get()); |
| 11734 | if (RHS.isInvalid()) |
| 11735 | return QualType(); |
| 11736 | QualType RHSType = RHS.get()->getType(); |
| 11737 | |
| 11738 | // C99 6.5.7p2: Each of the operands shall have integer type. |
| 11739 | // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. |
| 11740 | if ((!LHSType->isFixedPointOrIntegerType() && |
| 11741 | !LHSType->hasIntegerRepresentation()) || |
| 11742 | !RHSType->hasIntegerRepresentation()) |
| 11743 | return InvalidOperands(Loc, LHS, RHS); |
| 11744 | |
| 11745 | // C++0x: Don't allow scoped enums. FIXME: Use something better than |
| 11746 | // hasIntegerRepresentation() above instead of this. |
| 11747 | if (isScopedEnumerationType(T: LHSType) || |
| 11748 | isScopedEnumerationType(T: RHSType)) { |
| 11749 | return InvalidOperands(Loc, LHS, RHS); |
| 11750 | } |
| 11751 | DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType); |
| 11752 | |
| 11753 | // "The type of the result is that of the promoted left operand." |
| 11754 | return LHSType; |
| 11755 | } |
| 11756 | |
| 11757 | /// Diagnose bad pointer comparisons. |
| 11758 | static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, |
| 11759 | ExprResult &LHS, ExprResult &RHS, |
| 11760 | bool IsError) { |
| 11761 | S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_distinct_pointers |
| 11762 | : diag::ext_typecheck_comparison_of_distinct_pointers) |
| 11763 | << LHS.get()->getType() << RHS.get()->getType() |
| 11764 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 11765 | } |
| 11766 | |
| 11767 | /// Returns false if the pointers are converted to a composite type, |
| 11768 | /// true otherwise. |
| 11769 | static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, |
| 11770 | ExprResult &LHS, ExprResult &RHS) { |
| 11771 | // C++ [expr.rel]p2: |
| 11772 | // [...] Pointer conversions (4.10) and qualification |
| 11773 | // conversions (4.4) are performed on pointer operands (or on |
| 11774 | // a pointer operand and a null pointer constant) to bring |
| 11775 | // them to their composite pointer type. [...] |
| 11776 | // |
| 11777 | // C++ [expr.eq]p1 uses the same notion for (in)equality |
| 11778 | // comparisons of pointers. |
| 11779 | |
| 11780 | QualType LHSType = LHS.get()->getType(); |
| 11781 | QualType RHSType = RHS.get()->getType(); |
| 11782 | assert(LHSType->isPointerType() || RHSType->isPointerType() || |
| 11783 | LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); |
| 11784 | |
| 11785 | QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS); |
| 11786 | if (T.isNull()) { |
| 11787 | if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && |
| 11788 | (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) |
| 11789 | diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true); |
| 11790 | else |
| 11791 | S.InvalidOperands(Loc, LHS, RHS); |
| 11792 | return true; |
| 11793 | } |
| 11794 | |
| 11795 | return false; |
| 11796 | } |
| 11797 | |
| 11798 | static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, |
| 11799 | ExprResult &LHS, |
| 11800 | ExprResult &RHS, |
| 11801 | bool IsError) { |
| 11802 | S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_fptr_to_void |
| 11803 | : diag::ext_typecheck_comparison_of_fptr_to_void) |
| 11804 | << LHS.get()->getType() << RHS.get()->getType() |
| 11805 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 11806 | } |
| 11807 | |
| 11808 | static bool isObjCObjectLiteral(ExprResult &E) { |
| 11809 | switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { |
| 11810 | case Stmt::ObjCArrayLiteralClass: |
| 11811 | case Stmt::ObjCDictionaryLiteralClass: |
| 11812 | case Stmt::ObjCStringLiteralClass: |
| 11813 | case Stmt::ObjCBoxedExprClass: |
| 11814 | return true; |
| 11815 | default: |
| 11816 | // Note that ObjCBoolLiteral is NOT an object literal! |
| 11817 | return false; |
| 11818 | } |
| 11819 | } |
| 11820 | |
| 11821 | static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { |
| 11822 | const ObjCObjectPointerType *Type = |
| 11823 | LHS->getType()->getAs<ObjCObjectPointerType>(); |
| 11824 | |
| 11825 | // If this is not actually an Objective-C object, bail out. |
| 11826 | if (!Type) |
| 11827 | return false; |
| 11828 | |
| 11829 | // Get the LHS object's interface type. |
| 11830 | QualType InterfaceType = Type->getPointeeType(); |
| 11831 | |
| 11832 | // If the RHS isn't an Objective-C object, bail out. |
| 11833 | if (!RHS->getType()->isObjCObjectPointerType()) |
| 11834 | return false; |
| 11835 | |
| 11836 | // Try to find the -isEqual: method. |
| 11837 | Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector(); |
| 11838 | ObjCMethodDecl *Method = |
| 11839 | S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType, |
| 11840 | /*IsInstance=*/true); |
| 11841 | if (!Method) { |
| 11842 | if (Type->isObjCIdType()) { |
| 11843 | // For 'id', just check the global pool. |
| 11844 | Method = |
| 11845 | S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(), |
| 11846 | /*receiverId=*/receiverIdOrClass: true); |
| 11847 | } else { |
| 11848 | // Check protocols. |
| 11849 | Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type, |
| 11850 | /*IsInstance=*/true); |
| 11851 | } |
| 11852 | } |
| 11853 | |
| 11854 | if (!Method) |
| 11855 | return false; |
| 11856 | |
| 11857 | QualType T = Method->parameters()[0]->getType(); |
| 11858 | if (!T->isObjCObjectPointerType()) |
| 11859 | return false; |
| 11860 | |
| 11861 | QualType R = Method->getReturnType(); |
| 11862 | if (!R->isScalarType()) |
| 11863 | return false; |
| 11864 | |
| 11865 | return true; |
| 11866 | } |
| 11867 | |
| 11868 | static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, |
| 11869 | ExprResult &LHS, ExprResult &RHS, |
| 11870 | BinaryOperator::Opcode Opc){ |
| 11871 | Expr *Literal; |
| 11872 | Expr *Other; |
| 11873 | if (isObjCObjectLiteral(E&: LHS)) { |
| 11874 | Literal = LHS.get(); |
| 11875 | Other = RHS.get(); |
| 11876 | } else { |
| 11877 | Literal = RHS.get(); |
| 11878 | Other = LHS.get(); |
| 11879 | } |
| 11880 | |
| 11881 | // Don't warn on comparisons against nil. |
| 11882 | Other = Other->IgnoreParenCasts(); |
| 11883 | if (Other->isNullPointerConstant(Ctx&: S.getASTContext(), |
| 11884 | NPC: Expr::NPC_ValueDependentIsNotNull)) |
| 11885 | return; |
| 11886 | |
| 11887 | // This should be kept in sync with warn_objc_literal_comparison. |
| 11888 | // LK_String should always be after the other literals, since it has its own |
| 11889 | // warning flag. |
| 11890 | SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal); |
| 11891 | assert(LiteralKind != SemaObjC::LK_Block); |
| 11892 | if (LiteralKind == SemaObjC::LK_None) { |
| 11893 | llvm_unreachable("Unknown Objective-C object literal kind" ); |
| 11894 | } |
| 11895 | |
| 11896 | if (LiteralKind == SemaObjC::LK_String) |
| 11897 | S.Diag(Loc, DiagID: diag::warn_objc_string_literal_comparison) |
| 11898 | << Literal->getSourceRange(); |
| 11899 | else |
| 11900 | S.Diag(Loc, DiagID: diag::warn_objc_literal_comparison) |
| 11901 | << LiteralKind << Literal->getSourceRange(); |
| 11902 | |
| 11903 | if (BinaryOperator::isEqualityOp(Opc) && |
| 11904 | hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) { |
| 11905 | SourceLocation Start = LHS.get()->getBeginLoc(); |
| 11906 | SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc()); |
| 11907 | CharSourceRange OpRange = |
| 11908 | CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc)); |
| 11909 | |
| 11910 | S.Diag(Loc, DiagID: diag::note_objc_literal_comparison_isequal) |
| 11911 | << FixItHint::CreateInsertion(InsertionLoc: Start, Code: Opc == BO_EQ ? "[" : "![" ) |
| 11912 | << FixItHint::CreateReplacement(RemoveRange: OpRange, Code: " isEqual:" ) |
| 11913 | << FixItHint::CreateInsertion(InsertionLoc: End, Code: "]" ); |
| 11914 | } |
| 11915 | } |
| 11916 | |
| 11917 | /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. |
| 11918 | static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, |
| 11919 | ExprResult &RHS, SourceLocation Loc, |
| 11920 | BinaryOperatorKind Opc) { |
| 11921 | // Check that left hand side is !something. |
| 11922 | UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts()); |
| 11923 | if (!UO || UO->getOpcode() != UO_LNot) return; |
| 11924 | |
| 11925 | // Only check if the right hand side is non-bool arithmetic type. |
| 11926 | if (RHS.get()->isKnownToHaveBooleanValue()) return; |
| 11927 | |
| 11928 | // Make sure that the something in !something is not bool. |
| 11929 | Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); |
| 11930 | if (SubExpr->isKnownToHaveBooleanValue()) return; |
| 11931 | |
| 11932 | // Emit warning. |
| 11933 | bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; |
| 11934 | S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::warn_logical_not_on_lhs_of_check) |
| 11935 | << Loc << IsBitwiseOp; |
| 11936 | |
| 11937 | // First note suggest !(x < y) |
| 11938 | SourceLocation FirstOpen = SubExpr->getBeginLoc(); |
| 11939 | SourceLocation FirstClose = RHS.get()->getEndLoc(); |
| 11940 | FirstClose = S.getLocForEndOfToken(Loc: FirstClose); |
| 11941 | if (FirstClose.isInvalid()) |
| 11942 | FirstOpen = SourceLocation(); |
| 11943 | S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_fix) |
| 11944 | << IsBitwiseOp |
| 11945 | << FixItHint::CreateInsertion(InsertionLoc: FirstOpen, Code: "(" ) |
| 11946 | << FixItHint::CreateInsertion(InsertionLoc: FirstClose, Code: ")" ); |
| 11947 | |
| 11948 | // Second note suggests (!x) < y |
| 11949 | SourceLocation SecondOpen = LHS.get()->getBeginLoc(); |
| 11950 | SourceLocation SecondClose = LHS.get()->getEndLoc(); |
| 11951 | SecondClose = S.getLocForEndOfToken(Loc: SecondClose); |
| 11952 | if (SecondClose.isInvalid()) |
| 11953 | SecondOpen = SourceLocation(); |
| 11954 | S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_silence_with_parens) |
| 11955 | << FixItHint::CreateInsertion(InsertionLoc: SecondOpen, Code: "(" ) |
| 11956 | << FixItHint::CreateInsertion(InsertionLoc: SecondClose, Code: ")" ); |
| 11957 | } |
| 11958 | |
| 11959 | // Returns true if E refers to a non-weak array. |
| 11960 | static bool checkForArray(const Expr *E) { |
| 11961 | const ValueDecl *D = nullptr; |
| 11962 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) { |
| 11963 | D = DR->getDecl(); |
| 11964 | } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) { |
| 11965 | if (Mem->isImplicitAccess()) |
| 11966 | D = Mem->getMemberDecl(); |
| 11967 | } |
| 11968 | if (!D) |
| 11969 | return false; |
| 11970 | return D->getType()->isArrayType() && !D->isWeak(); |
| 11971 | } |
| 11972 | |
| 11973 | /// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a |
| 11974 | /// pointer and size is an unsigned integer. Return whether the result is |
| 11975 | /// always true/false. |
| 11976 | static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS, |
| 11977 | const Expr *RHS, |
| 11978 | BinaryOperatorKind Opc) { |
| 11979 | if (!LHS->getType()->isPointerType() || |
| 11980 | S.getLangOpts().PointerOverflowDefined) |
| 11981 | return std::nullopt; |
| 11982 | |
| 11983 | // Canonicalize to >= or < predicate. |
| 11984 | switch (Opc) { |
| 11985 | case BO_GE: |
| 11986 | case BO_LT: |
| 11987 | break; |
| 11988 | case BO_GT: |
| 11989 | std::swap(a&: LHS, b&: RHS); |
| 11990 | Opc = BO_LT; |
| 11991 | break; |
| 11992 | case BO_LE: |
| 11993 | std::swap(a&: LHS, b&: RHS); |
| 11994 | Opc = BO_GE; |
| 11995 | break; |
| 11996 | default: |
| 11997 | return std::nullopt; |
| 11998 | } |
| 11999 | |
| 12000 | auto *BO = dyn_cast<BinaryOperator>(Val: LHS); |
| 12001 | if (!BO || BO->getOpcode() != BO_Add) |
| 12002 | return std::nullopt; |
| 12003 | |
| 12004 | Expr *Other; |
| 12005 | if (Expr::isSameComparisonOperand(E1: BO->getLHS(), E2: RHS)) |
| 12006 | Other = BO->getRHS(); |
| 12007 | else if (Expr::isSameComparisonOperand(E1: BO->getRHS(), E2: RHS)) |
| 12008 | Other = BO->getLHS(); |
| 12009 | else |
| 12010 | return std::nullopt; |
| 12011 | |
| 12012 | if (!Other->getType()->isUnsignedIntegerType()) |
| 12013 | return std::nullopt; |
| 12014 | |
| 12015 | return Opc == BO_GE; |
| 12016 | } |
| 12017 | |
| 12018 | /// Diagnose some forms of syntactically-obvious tautological comparison. |
| 12019 | static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, |
| 12020 | Expr *LHS, Expr *RHS, |
| 12021 | BinaryOperatorKind Opc) { |
| 12022 | Expr *LHSStripped = LHS->IgnoreParenImpCasts(); |
| 12023 | Expr *RHSStripped = RHS->IgnoreParenImpCasts(); |
| 12024 | |
| 12025 | QualType LHSType = LHS->getType(); |
| 12026 | QualType RHSType = RHS->getType(); |
| 12027 | if (LHSType->hasFloatingRepresentation() || |
| 12028 | (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || |
| 12029 | S.inTemplateInstantiation()) |
| 12030 | return; |
| 12031 | |
| 12032 | // WebAssembly Tables cannot be compared, therefore shouldn't emit |
| 12033 | // Tautological diagnostics. |
| 12034 | if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType()) |
| 12035 | return; |
| 12036 | |
| 12037 | // Comparisons between two array types are ill-formed for operator<=>, so |
| 12038 | // we shouldn't emit any additional warnings about it. |
| 12039 | if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) |
| 12040 | return; |
| 12041 | |
| 12042 | // For non-floating point types, check for self-comparisons of the form |
| 12043 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and |
| 12044 | // often indicate logic errors in the program. |
| 12045 | // |
| 12046 | // NOTE: Don't warn about comparison expressions resulting from macro |
| 12047 | // expansion. Also don't warn about comparisons which are only self |
| 12048 | // comparisons within a template instantiation. The warnings should catch |
| 12049 | // obvious cases in the definition of the template anyways. The idea is to |
| 12050 | // warn when the typed comparison operator will always evaluate to the same |
| 12051 | // result. |
| 12052 | |
| 12053 | // Used for indexing into %select in warn_comparison_always |
| 12054 | enum { |
| 12055 | AlwaysConstant, |
| 12056 | AlwaysTrue, |
| 12057 | AlwaysFalse, |
| 12058 | AlwaysEqual, // std::strong_ordering::equal from operator<=> |
| 12059 | }; |
| 12060 | |
| 12061 | // C++1a [array.comp]: |
| 12062 | // Equality and relational comparisons ([expr.eq], [expr.rel]) between two |
| 12063 | // operands of array type. |
| 12064 | // C++2a [depr.array.comp]: |
| 12065 | // Equality and relational comparisons ([expr.eq], [expr.rel]) between two |
| 12066 | // operands of array type are deprecated. |
| 12067 | if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() && |
| 12068 | RHSStripped->getType()->isArrayType()) { |
| 12069 | auto IsDeprArrayComparionIgnored = |
| 12070 | S.getDiagnostics().isIgnored(DiagID: diag::warn_depr_array_comparison, Loc); |
| 12071 | auto DiagID = S.getLangOpts().CPlusPlus26 |
| 12072 | ? diag::warn_array_comparison_cxx26 |
| 12073 | : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored |
| 12074 | ? diag::warn_array_comparison |
| 12075 | : diag::warn_depr_array_comparison; |
| 12076 | S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() |
| 12077 | << LHSStripped->getType() << RHSStripped->getType(); |
| 12078 | // Carry on to produce the tautological comparison warning, if this |
| 12079 | // expression is potentially-evaluated, we can resolve the array to a |
| 12080 | // non-weak declaration, and so on. |
| 12081 | } |
| 12082 | |
| 12083 | if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { |
| 12084 | if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) { |
| 12085 | unsigned Result; |
| 12086 | switch (Opc) { |
| 12087 | case BO_EQ: |
| 12088 | case BO_LE: |
| 12089 | case BO_GE: |
| 12090 | Result = AlwaysTrue; |
| 12091 | break; |
| 12092 | case BO_NE: |
| 12093 | case BO_LT: |
| 12094 | case BO_GT: |
| 12095 | Result = AlwaysFalse; |
| 12096 | break; |
| 12097 | case BO_Cmp: |
| 12098 | Result = AlwaysEqual; |
| 12099 | break; |
| 12100 | default: |
| 12101 | Result = AlwaysConstant; |
| 12102 | break; |
| 12103 | } |
| 12104 | S.DiagRuntimeBehavior(Loc, Statement: nullptr, |
| 12105 | PD: S.PDiag(DiagID: diag::warn_comparison_always) |
| 12106 | << 0 /*self-comparison*/ |
| 12107 | << Result); |
| 12108 | } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) { |
| 12109 | // What is it always going to evaluate to? |
| 12110 | unsigned Result; |
| 12111 | switch (Opc) { |
| 12112 | case BO_EQ: // e.g. array1 == array2 |
| 12113 | Result = AlwaysFalse; |
| 12114 | break; |
| 12115 | case BO_NE: // e.g. array1 != array2 |
| 12116 | Result = AlwaysTrue; |
| 12117 | break; |
| 12118 | default: // e.g. array1 <= array2 |
| 12119 | // The best we can say is 'a constant' |
| 12120 | Result = AlwaysConstant; |
| 12121 | break; |
| 12122 | } |
| 12123 | S.DiagRuntimeBehavior(Loc, Statement: nullptr, |
| 12124 | PD: S.PDiag(DiagID: diag::warn_comparison_always) |
| 12125 | << 1 /*array comparison*/ |
| 12126 | << Result); |
| 12127 | } else if (std::optional<bool> Res = |
| 12128 | isTautologicalBoundsCheck(S, LHS, RHS, Opc)) { |
| 12129 | S.DiagRuntimeBehavior(Loc, Statement: nullptr, |
| 12130 | PD: S.PDiag(DiagID: diag::warn_comparison_always) |
| 12131 | << 2 /*pointer comparison*/ |
| 12132 | << (*Res ? AlwaysTrue : AlwaysFalse)); |
| 12133 | } |
| 12134 | } |
| 12135 | |
| 12136 | if (isa<CastExpr>(Val: LHSStripped)) |
| 12137 | LHSStripped = LHSStripped->IgnoreParenCasts(); |
| 12138 | if (isa<CastExpr>(Val: RHSStripped)) |
| 12139 | RHSStripped = RHSStripped->IgnoreParenCasts(); |
| 12140 | |
| 12141 | // Warn about comparisons against a string constant (unless the other |
| 12142 | // operand is null); the user probably wants string comparison function. |
| 12143 | Expr *LiteralString = nullptr; |
| 12144 | Expr *LiteralStringStripped = nullptr; |
| 12145 | if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) && |
| 12146 | !RHSStripped->isNullPointerConstant(Ctx&: S.Context, |
| 12147 | NPC: Expr::NPC_ValueDependentIsNull)) { |
| 12148 | LiteralString = LHS; |
| 12149 | LiteralStringStripped = LHSStripped; |
| 12150 | } else if ((isa<StringLiteral>(Val: RHSStripped) || |
| 12151 | isa<ObjCEncodeExpr>(Val: RHSStripped)) && |
| 12152 | !LHSStripped->isNullPointerConstant(Ctx&: S.Context, |
| 12153 | NPC: Expr::NPC_ValueDependentIsNull)) { |
| 12154 | LiteralString = RHS; |
| 12155 | LiteralStringStripped = RHSStripped; |
| 12156 | } |
| 12157 | |
| 12158 | if (LiteralString) { |
| 12159 | S.DiagRuntimeBehavior(Loc, Statement: nullptr, |
| 12160 | PD: S.PDiag(DiagID: diag::warn_stringcompare) |
| 12161 | << isa<ObjCEncodeExpr>(Val: LiteralStringStripped) |
| 12162 | << LiteralString->getSourceRange()); |
| 12163 | } |
| 12164 | } |
| 12165 | |
| 12166 | static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { |
| 12167 | switch (CK) { |
| 12168 | default: { |
| 12169 | #ifndef NDEBUG |
| 12170 | llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) |
| 12171 | << "\n" ; |
| 12172 | #endif |
| 12173 | llvm_unreachable("unhandled cast kind" ); |
| 12174 | } |
| 12175 | case CK_UserDefinedConversion: |
| 12176 | return ICK_Identity; |
| 12177 | case CK_LValueToRValue: |
| 12178 | return ICK_Lvalue_To_Rvalue; |
| 12179 | case CK_ArrayToPointerDecay: |
| 12180 | return ICK_Array_To_Pointer; |
| 12181 | case CK_FunctionToPointerDecay: |
| 12182 | return ICK_Function_To_Pointer; |
| 12183 | case CK_IntegralCast: |
| 12184 | return ICK_Integral_Conversion; |
| 12185 | case CK_FloatingCast: |
| 12186 | return ICK_Floating_Conversion; |
| 12187 | case CK_IntegralToFloating: |
| 12188 | case CK_FloatingToIntegral: |
| 12189 | return ICK_Floating_Integral; |
| 12190 | case CK_IntegralComplexCast: |
| 12191 | case CK_FloatingComplexCast: |
| 12192 | case CK_FloatingComplexToIntegralComplex: |
| 12193 | case CK_IntegralComplexToFloatingComplex: |
| 12194 | return ICK_Complex_Conversion; |
| 12195 | case CK_FloatingComplexToReal: |
| 12196 | case CK_FloatingRealToComplex: |
| 12197 | case CK_IntegralComplexToReal: |
| 12198 | case CK_IntegralRealToComplex: |
| 12199 | return ICK_Complex_Real; |
| 12200 | case CK_HLSLArrayRValue: |
| 12201 | return ICK_HLSL_Array_RValue; |
| 12202 | } |
| 12203 | } |
| 12204 | |
| 12205 | static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, |
| 12206 | QualType FromType, |
| 12207 | SourceLocation Loc) { |
| 12208 | // Check for a narrowing implicit conversion. |
| 12209 | StandardConversionSequence SCS; |
| 12210 | SCS.setAsIdentityConversion(); |
| 12211 | SCS.setToType(Idx: 0, T: FromType); |
| 12212 | SCS.setToType(Idx: 1, T: ToType); |
| 12213 | if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) |
| 12214 | SCS.Second = castKindToImplicitConversionKind(CK: ICE->getCastKind()); |
| 12215 | |
| 12216 | APValue PreNarrowingValue; |
| 12217 | QualType PreNarrowingType; |
| 12218 | switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue, |
| 12219 | ConstantType&: PreNarrowingType, |
| 12220 | /*IgnoreFloatToIntegralConversion*/ true)) { |
| 12221 | case NK_Dependent_Narrowing: |
| 12222 | // Implicit conversion to a narrower type, but the expression is |
| 12223 | // value-dependent so we can't tell whether it's actually narrowing. |
| 12224 | case NK_Not_Narrowing: |
| 12225 | return false; |
| 12226 | |
| 12227 | case NK_Constant_Narrowing: |
| 12228 | // Implicit conversion to a narrower type, and the value is not a constant |
| 12229 | // expression. |
| 12230 | S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing) |
| 12231 | << /*Constant*/ 1 |
| 12232 | << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType; |
| 12233 | return true; |
| 12234 | |
| 12235 | case NK_Variable_Narrowing: |
| 12236 | // Implicit conversion to a narrower type, and the value is not a constant |
| 12237 | // expression. |
| 12238 | case NK_Type_Narrowing: |
| 12239 | S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing) |
| 12240 | << /*Constant*/ 0 << FromType << ToType; |
| 12241 | // TODO: It's not a constant expression, but what if the user intended it |
| 12242 | // to be? Can we produce notes to help them figure out why it isn't? |
| 12243 | return true; |
| 12244 | } |
| 12245 | llvm_unreachable("unhandled case in switch" ); |
| 12246 | } |
| 12247 | |
| 12248 | static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, |
| 12249 | ExprResult &LHS, |
| 12250 | ExprResult &RHS, |
| 12251 | SourceLocation Loc) { |
| 12252 | QualType LHSType = LHS.get()->getType(); |
| 12253 | QualType RHSType = RHS.get()->getType(); |
| 12254 | // Dig out the original argument type and expression before implicit casts |
| 12255 | // were applied. These are the types/expressions we need to check the |
| 12256 | // [expr.spaceship] requirements against. |
| 12257 | ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); |
| 12258 | ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); |
| 12259 | QualType LHSStrippedType = LHSStripped.get()->getType(); |
| 12260 | QualType RHSStrippedType = RHSStripped.get()->getType(); |
| 12261 | |
| 12262 | // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the |
| 12263 | // other is not, the program is ill-formed. |
| 12264 | if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { |
| 12265 | S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped); |
| 12266 | return QualType(); |
| 12267 | } |
| 12268 | |
| 12269 | // FIXME: Consider combining this with checkEnumArithmeticConversions. |
| 12270 | int = (int)LHSStrippedType->isEnumeralType() + |
| 12271 | RHSStrippedType->isEnumeralType(); |
| 12272 | if (NumEnumArgs == 1) { |
| 12273 | bool LHSIsEnum = LHSStrippedType->isEnumeralType(); |
| 12274 | QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; |
| 12275 | if (OtherTy->hasFloatingRepresentation()) { |
| 12276 | S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped); |
| 12277 | return QualType(); |
| 12278 | } |
| 12279 | } |
| 12280 | if (NumEnumArgs == 2) { |
| 12281 | // C++2a [expr.spaceship]p5: If both operands have the same enumeration |
| 12282 | // type E, the operator yields the result of converting the operands |
| 12283 | // to the underlying type of E and applying <=> to the converted operands. |
| 12284 | if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) { |
| 12285 | S.InvalidOperands(Loc, LHS, RHS); |
| 12286 | return QualType(); |
| 12287 | } |
| 12288 | QualType IntType = |
| 12289 | LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); |
| 12290 | assert(IntType->isArithmeticType()); |
| 12291 | |
| 12292 | // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we |
| 12293 | // promote the boolean type, and all other promotable integer types, to |
| 12294 | // avoid this. |
| 12295 | if (S.Context.isPromotableIntegerType(T: IntType)) |
| 12296 | IntType = S.Context.getPromotedIntegerType(PromotableType: IntType); |
| 12297 | |
| 12298 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast); |
| 12299 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast); |
| 12300 | LHSType = RHSType = IntType; |
| 12301 | } |
| 12302 | |
| 12303 | // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the |
| 12304 | // usual arithmetic conversions are applied to the operands. |
| 12305 | QualType Type = |
| 12306 | S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison); |
| 12307 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 12308 | return QualType(); |
| 12309 | if (Type.isNull()) |
| 12310 | return S.InvalidOperands(Loc, LHS, RHS); |
| 12311 | |
| 12312 | std::optional<ComparisonCategoryType> CCT = |
| 12313 | getComparisonCategoryForBuiltinCmp(T: Type); |
| 12314 | if (!CCT) |
| 12315 | return S.InvalidOperands(Loc, LHS, RHS); |
| 12316 | |
| 12317 | bool HasNarrowing = checkThreeWayNarrowingConversion( |
| 12318 | S, ToType: Type, E: LHS.get(), FromType: LHSType, Loc: LHS.get()->getBeginLoc()); |
| 12319 | HasNarrowing |= checkThreeWayNarrowingConversion(S, ToType: Type, E: RHS.get(), FromType: RHSType, |
| 12320 | Loc: RHS.get()->getBeginLoc()); |
| 12321 | if (HasNarrowing) |
| 12322 | return QualType(); |
| 12323 | |
| 12324 | assert(!Type.isNull() && "composite type for <=> has not been set" ); |
| 12325 | |
| 12326 | return S.CheckComparisonCategoryType( |
| 12327 | Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression); |
| 12328 | } |
| 12329 | |
| 12330 | static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, |
| 12331 | ExprResult &RHS, |
| 12332 | SourceLocation Loc, |
| 12333 | BinaryOperatorKind Opc) { |
| 12334 | if (Opc == BO_Cmp) |
| 12335 | return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); |
| 12336 | |
| 12337 | // C99 6.5.8p3 / C99 6.5.9p4 |
| 12338 | QualType Type = |
| 12339 | S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison); |
| 12340 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 12341 | return QualType(); |
| 12342 | if (Type.isNull()) |
| 12343 | return S.InvalidOperands(Loc, LHS, RHS); |
| 12344 | assert(Type->isArithmeticType() || Type->isEnumeralType()); |
| 12345 | |
| 12346 | if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) |
| 12347 | return S.InvalidOperands(Loc, LHS, RHS); |
| 12348 | |
| 12349 | // Check for comparisons of floating point operands using != and ==. |
| 12350 | if (Type->hasFloatingRepresentation()) |
| 12351 | S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc); |
| 12352 | |
| 12353 | // The result of comparisons is 'bool' in C++, 'int' in C. |
| 12354 | return S.Context.getLogicalOperationType(); |
| 12355 | } |
| 12356 | |
| 12357 | void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { |
| 12358 | if (!NullE.get()->getType()->isAnyPointerType()) |
| 12359 | return; |
| 12360 | int NullValue = PP.isMacroDefined(Id: "NULL" ) ? 0 : 1; |
| 12361 | if (!E.get()->getType()->isAnyPointerType() && |
| 12362 | E.get()->isNullPointerConstant(Ctx&: Context, |
| 12363 | NPC: Expr::NPC_ValueDependentIsNotNull) == |
| 12364 | Expr::NPCK_ZeroExpression) { |
| 12365 | if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) { |
| 12366 | if (CL->getValue() == 0) |
| 12367 | Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare) |
| 12368 | << NullValue |
| 12369 | << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(), |
| 12370 | Code: NullValue ? "NULL" : "(void *)0" ); |
| 12371 | } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) { |
| 12372 | TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); |
| 12373 | QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType(); |
| 12374 | if (T == Context.CharTy) |
| 12375 | Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare) |
| 12376 | << NullValue |
| 12377 | << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(), |
| 12378 | Code: NullValue ? "NULL" : "(void *)0" ); |
| 12379 | } |
| 12380 | } |
| 12381 | } |
| 12382 | |
| 12383 | // C99 6.5.8, C++ [expr.rel] |
| 12384 | QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, |
| 12385 | SourceLocation Loc, |
| 12386 | BinaryOperatorKind Opc) { |
| 12387 | bool IsRelational = BinaryOperator::isRelationalOp(Opc); |
| 12388 | bool IsThreeWay = Opc == BO_Cmp; |
| 12389 | bool IsOrdered = IsRelational || IsThreeWay; |
| 12390 | auto IsAnyPointerType = [](ExprResult E) { |
| 12391 | QualType Ty = E.get()->getType(); |
| 12392 | return Ty->isPointerType() || Ty->isMemberPointerType(); |
| 12393 | }; |
| 12394 | |
| 12395 | // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer |
| 12396 | // type, array-to-pointer, ..., conversions are performed on both operands to |
| 12397 | // bring them to their composite type. |
| 12398 | // Otherwise, all comparisons expect an rvalue, so convert to rvalue before |
| 12399 | // any type-related checks. |
| 12400 | if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { |
| 12401 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
| 12402 | if (LHS.isInvalid()) |
| 12403 | return QualType(); |
| 12404 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
| 12405 | if (RHS.isInvalid()) |
| 12406 | return QualType(); |
| 12407 | } else { |
| 12408 | LHS = DefaultLvalueConversion(E: LHS.get()); |
| 12409 | if (LHS.isInvalid()) |
| 12410 | return QualType(); |
| 12411 | RHS = DefaultLvalueConversion(E: RHS.get()); |
| 12412 | if (RHS.isInvalid()) |
| 12413 | return QualType(); |
| 12414 | } |
| 12415 | |
| 12416 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true); |
| 12417 | if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { |
| 12418 | CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS); |
| 12419 | CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS); |
| 12420 | } |
| 12421 | |
| 12422 | // Handle vector comparisons separately. |
| 12423 | if (LHS.get()->getType()->isVectorType() || |
| 12424 | RHS.get()->getType()->isVectorType()) |
| 12425 | return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); |
| 12426 | |
| 12427 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
| 12428 | RHS.get()->getType()->isSveVLSBuiltinType()) |
| 12429 | return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc); |
| 12430 | |
| 12431 | diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc); |
| 12432 | diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc); |
| 12433 | |
| 12434 | QualType LHSType = LHS.get()->getType(); |
| 12435 | QualType RHSType = RHS.get()->getType(); |
| 12436 | if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && |
| 12437 | (RHSType->isArithmeticType() || RHSType->isEnumeralType())) |
| 12438 | return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc); |
| 12439 | |
| 12440 | if ((LHSType->isPointerType() && |
| 12441 | LHSType->getPointeeType().isWebAssemblyReferenceType()) || |
| 12442 | (RHSType->isPointerType() && |
| 12443 | RHSType->getPointeeType().isWebAssemblyReferenceType())) |
| 12444 | return InvalidOperands(Loc, LHS, RHS); |
| 12445 | |
| 12446 | const Expr::NullPointerConstantKind LHSNullKind = |
| 12447 | LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull); |
| 12448 | const Expr::NullPointerConstantKind RHSNullKind = |
| 12449 | RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull); |
| 12450 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; |
| 12451 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; |
| 12452 | |
| 12453 | auto computeResultTy = [&]() { |
| 12454 | if (Opc != BO_Cmp) |
| 12455 | return Context.getLogicalOperationType(); |
| 12456 | assert(getLangOpts().CPlusPlus); |
| 12457 | assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); |
| 12458 | |
| 12459 | QualType CompositeTy = LHS.get()->getType(); |
| 12460 | assert(!CompositeTy->isReferenceType()); |
| 12461 | |
| 12462 | std::optional<ComparisonCategoryType> CCT = |
| 12463 | getComparisonCategoryForBuiltinCmp(T: CompositeTy); |
| 12464 | if (!CCT) |
| 12465 | return InvalidOperands(Loc, LHS, RHS); |
| 12466 | |
| 12467 | if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { |
| 12468 | // P0946R0: Comparisons between a null pointer constant and an object |
| 12469 | // pointer result in std::strong_equality, which is ill-formed under |
| 12470 | // P1959R0. |
| 12471 | Diag(Loc, DiagID: diag::err_typecheck_three_way_comparison_of_pointer_and_zero) |
| 12472 | << (LHSIsNull ? LHS.get()->getSourceRange() |
| 12473 | : RHS.get()->getSourceRange()); |
| 12474 | return QualType(); |
| 12475 | } |
| 12476 | |
| 12477 | return CheckComparisonCategoryType( |
| 12478 | Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression); |
| 12479 | }; |
| 12480 | |
| 12481 | if (!IsOrdered && LHSIsNull != RHSIsNull) { |
| 12482 | bool IsEquality = Opc == BO_EQ; |
| 12483 | if (RHSIsNull) |
| 12484 | DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality, |
| 12485 | Range: RHS.get()->getSourceRange()); |
| 12486 | else |
| 12487 | DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality, |
| 12488 | Range: LHS.get()->getSourceRange()); |
| 12489 | } |
| 12490 | |
| 12491 | if (IsOrdered && LHSType->isFunctionPointerType() && |
| 12492 | RHSType->isFunctionPointerType()) { |
| 12493 | // Valid unless a relational comparison of function pointers |
| 12494 | bool IsError = Opc == BO_Cmp; |
| 12495 | auto DiagID = |
| 12496 | IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers |
| 12497 | : getLangOpts().CPlusPlus |
| 12498 | ? diag::warn_typecheck_ordered_comparison_of_function_pointers |
| 12499 | : diag::ext_typecheck_ordered_comparison_of_function_pointers; |
| 12500 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() |
| 12501 | << RHS.get()->getSourceRange(); |
| 12502 | if (IsError) |
| 12503 | return QualType(); |
| 12504 | } |
| 12505 | |
| 12506 | if ((LHSType->isIntegerType() && !LHSIsNull) || |
| 12507 | (RHSType->isIntegerType() && !RHSIsNull)) { |
| 12508 | // Skip normal pointer conversion checks in this case; we have better |
| 12509 | // diagnostics for this below. |
| 12510 | } else if (getLangOpts().CPlusPlus) { |
| 12511 | // Equality comparison of a function pointer to a void pointer is invalid, |
| 12512 | // but we allow it as an extension. |
| 12513 | // FIXME: If we really want to allow this, should it be part of composite |
| 12514 | // pointer type computation so it works in conditionals too? |
| 12515 | if (!IsOrdered && |
| 12516 | ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || |
| 12517 | (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { |
| 12518 | // This is a gcc extension compatibility comparison. |
| 12519 | // In a SFINAE context, we treat this as a hard error to maintain |
| 12520 | // conformance with the C++ standard. |
| 12521 | diagnoseFunctionPointerToVoidComparison( |
| 12522 | S&: *this, Loc, LHS, RHS, /*isError*/ IsError: (bool)isSFINAEContext()); |
| 12523 | |
| 12524 | if (isSFINAEContext()) |
| 12525 | return QualType(); |
| 12526 | |
| 12527 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
| 12528 | return computeResultTy(); |
| 12529 | } |
| 12530 | |
| 12531 | // C++ [expr.eq]p2: |
| 12532 | // If at least one operand is a pointer [...] bring them to their |
| 12533 | // composite pointer type. |
| 12534 | // C++ [expr.spaceship]p6 |
| 12535 | // If at least one of the operands is of pointer type, [...] bring them |
| 12536 | // to their composite pointer type. |
| 12537 | // C++ [expr.rel]p2: |
| 12538 | // If both operands are pointers, [...] bring them to their composite |
| 12539 | // pointer type. |
| 12540 | // For <=>, the only valid non-pointer types are arrays and functions, and |
| 12541 | // we already decayed those, so this is really the same as the relational |
| 12542 | // comparison rule. |
| 12543 | if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= |
| 12544 | (IsOrdered ? 2 : 1) && |
| 12545 | (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || |
| 12546 | RHSType->isObjCObjectPointerType()))) { |
| 12547 | if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS)) |
| 12548 | return QualType(); |
| 12549 | return computeResultTy(); |
| 12550 | } |
| 12551 | } else if (LHSType->isPointerType() && |
| 12552 | RHSType->isPointerType()) { // C99 6.5.8p2 |
| 12553 | // All of the following pointer-related warnings are GCC extensions, except |
| 12554 | // when handling null pointer constants. |
| 12555 | QualType LCanPointeeTy = |
| 12556 | LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); |
| 12557 | QualType RCanPointeeTy = |
| 12558 | RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); |
| 12559 | |
| 12560 | // C99 6.5.9p2 and C99 6.5.8p2 |
| 12561 | if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(), |
| 12562 | T2: RCanPointeeTy.getUnqualifiedType())) { |
| 12563 | if (IsRelational) { |
| 12564 | // Pointers both need to point to complete or incomplete types |
| 12565 | if ((LCanPointeeTy->isIncompleteType() != |
| 12566 | RCanPointeeTy->isIncompleteType()) && |
| 12567 | !getLangOpts().C11) { |
| 12568 | Diag(Loc, DiagID: diag::ext_typecheck_compare_complete_incomplete_pointers) |
| 12569 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() |
| 12570 | << LHSType << RHSType << LCanPointeeTy->isIncompleteType() |
| 12571 | << RCanPointeeTy->isIncompleteType(); |
| 12572 | } |
| 12573 | } |
| 12574 | } else if (!IsRelational && |
| 12575 | (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { |
| 12576 | // Valid unless comparison between non-null pointer and function pointer |
| 12577 | if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) |
| 12578 | && !LHSIsNull && !RHSIsNull) |
| 12579 | diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, |
| 12580 | /*isError*/IsError: false); |
| 12581 | } else { |
| 12582 | // Invalid |
| 12583 | diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false); |
| 12584 | } |
| 12585 | if (LCanPointeeTy != RCanPointeeTy) { |
| 12586 | // Treat NULL constant as a special case in OpenCL. |
| 12587 | if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { |
| 12588 | if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy, |
| 12589 | Ctx: getASTContext())) { |
| 12590 | Diag(Loc, |
| 12591 | DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) |
| 12592 | << LHSType << RHSType << 0 /* comparison */ |
| 12593 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 12594 | } |
| 12595 | } |
| 12596 | LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); |
| 12597 | LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); |
| 12598 | CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion |
| 12599 | : CK_BitCast; |
| 12600 | |
| 12601 | const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>(); |
| 12602 | const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>(); |
| 12603 | bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr(); |
| 12604 | bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr(); |
| 12605 | bool ChangingCFIUncheckedCallee = |
| 12606 | LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee; |
| 12607 | |
| 12608 | if (LHSIsNull && !RHSIsNull) |
| 12609 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind); |
| 12610 | else if (!ChangingCFIUncheckedCallee) |
| 12611 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind); |
| 12612 | } |
| 12613 | return computeResultTy(); |
| 12614 | } |
| 12615 | |
| 12616 | |
| 12617 | // C++ [expr.eq]p4: |
| 12618 | // Two operands of type std::nullptr_t or one operand of type |
| 12619 | // std::nullptr_t and the other a null pointer constant compare |
| 12620 | // equal. |
| 12621 | // C23 6.5.9p5: |
| 12622 | // If both operands have type nullptr_t or one operand has type nullptr_t |
| 12623 | // and the other is a null pointer constant, they compare equal if the |
| 12624 | // former is a null pointer. |
| 12625 | if (!IsOrdered && LHSIsNull && RHSIsNull) { |
| 12626 | if (LHSType->isNullPtrType()) { |
| 12627 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
| 12628 | return computeResultTy(); |
| 12629 | } |
| 12630 | if (RHSType->isNullPtrType()) { |
| 12631 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
| 12632 | return computeResultTy(); |
| 12633 | } |
| 12634 | } |
| 12635 | |
| 12636 | if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) { |
| 12637 | // C23 6.5.9p6: |
| 12638 | // Otherwise, at least one operand is a pointer. If one is a pointer and |
| 12639 | // the other is a null pointer constant or has type nullptr_t, they |
| 12640 | // compare equal |
| 12641 | if (LHSIsNull && RHSType->isPointerType()) { |
| 12642 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
| 12643 | return computeResultTy(); |
| 12644 | } |
| 12645 | if (RHSIsNull && LHSType->isPointerType()) { |
| 12646 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
| 12647 | return computeResultTy(); |
| 12648 | } |
| 12649 | } |
| 12650 | |
| 12651 | // Comparison of Objective-C pointers and block pointers against nullptr_t. |
| 12652 | // These aren't covered by the composite pointer type rules. |
| 12653 | if (!IsOrdered && RHSType->isNullPtrType() && |
| 12654 | (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { |
| 12655 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
| 12656 | return computeResultTy(); |
| 12657 | } |
| 12658 | if (!IsOrdered && LHSType->isNullPtrType() && |
| 12659 | (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { |
| 12660 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
| 12661 | return computeResultTy(); |
| 12662 | } |
| 12663 | |
| 12664 | if (getLangOpts().CPlusPlus) { |
| 12665 | if (IsRelational && |
| 12666 | ((LHSType->isNullPtrType() && RHSType->isPointerType()) || |
| 12667 | (RHSType->isNullPtrType() && LHSType->isPointerType()))) { |
| 12668 | // HACK: Relational comparison of nullptr_t against a pointer type is |
| 12669 | // invalid per DR583, but we allow it within std::less<> and friends, |
| 12670 | // since otherwise common uses of it break. |
| 12671 | // FIXME: Consider removing this hack once LWG fixes std::less<> and |
| 12672 | // friends to have std::nullptr_t overload candidates. |
| 12673 | DeclContext *DC = CurContext; |
| 12674 | if (isa<FunctionDecl>(Val: DC)) |
| 12675 | DC = DC->getParent(); |
| 12676 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) { |
| 12677 | if (CTSD->isInStdNamespace() && |
| 12678 | llvm::StringSwitch<bool>(CTSD->getName()) |
| 12679 | .Cases(S0: "less" , S1: "less_equal" , S2: "greater" , S3: "greater_equal" , Value: true) |
| 12680 | .Default(Value: false)) { |
| 12681 | if (RHSType->isNullPtrType()) |
| 12682 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
| 12683 | else |
| 12684 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
| 12685 | return computeResultTy(); |
| 12686 | } |
| 12687 | } |
| 12688 | } |
| 12689 | |
| 12690 | // C++ [expr.eq]p2: |
| 12691 | // If at least one operand is a pointer to member, [...] bring them to |
| 12692 | // their composite pointer type. |
| 12693 | if (!IsOrdered && |
| 12694 | (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { |
| 12695 | if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS)) |
| 12696 | return QualType(); |
| 12697 | else |
| 12698 | return computeResultTy(); |
| 12699 | } |
| 12700 | } |
| 12701 | |
| 12702 | // Handle block pointer types. |
| 12703 | if (!IsOrdered && LHSType->isBlockPointerType() && |
| 12704 | RHSType->isBlockPointerType()) { |
| 12705 | QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); |
| 12706 | QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); |
| 12707 | |
| 12708 | if (!LHSIsNull && !RHSIsNull && |
| 12709 | !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) { |
| 12710 | Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks) |
| 12711 | << LHSType << RHSType << LHS.get()->getSourceRange() |
| 12712 | << RHS.get()->getSourceRange(); |
| 12713 | } |
| 12714 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
| 12715 | return computeResultTy(); |
| 12716 | } |
| 12717 | |
| 12718 | // Allow block pointers to be compared with null pointer constants. |
| 12719 | if (!IsOrdered |
| 12720 | && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) |
| 12721 | || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { |
| 12722 | if (!LHSIsNull && !RHSIsNull) { |
| 12723 | if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() |
| 12724 | ->getPointeeType()->isVoidType()) |
| 12725 | || (LHSType->isPointerType() && LHSType->castAs<PointerType>() |
| 12726 | ->getPointeeType()->isVoidType()))) |
| 12727 | Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks) |
| 12728 | << LHSType << RHSType << LHS.get()->getSourceRange() |
| 12729 | << RHS.get()->getSourceRange(); |
| 12730 | } |
| 12731 | if (LHSIsNull && !RHSIsNull) |
| 12732 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, |
| 12733 | CK: RHSType->isPointerType() ? CK_BitCast |
| 12734 | : CK_AnyPointerToBlockPointerCast); |
| 12735 | else |
| 12736 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, |
| 12737 | CK: LHSType->isPointerType() ? CK_BitCast |
| 12738 | : CK_AnyPointerToBlockPointerCast); |
| 12739 | return computeResultTy(); |
| 12740 | } |
| 12741 | |
| 12742 | if (LHSType->isObjCObjectPointerType() || |
| 12743 | RHSType->isObjCObjectPointerType()) { |
| 12744 | const PointerType *LPT = LHSType->getAs<PointerType>(); |
| 12745 | const PointerType *RPT = RHSType->getAs<PointerType>(); |
| 12746 | if (LPT || RPT) { |
| 12747 | bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; |
| 12748 | bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; |
| 12749 | |
| 12750 | if (!LPtrToVoid && !RPtrToVoid && |
| 12751 | !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) { |
| 12752 | diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, |
| 12753 | /*isError*/IsError: false); |
| 12754 | } |
| 12755 | // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than |
| 12756 | // the RHS, but we have test coverage for this behavior. |
| 12757 | // FIXME: Consider using convertPointersToCompositeType in C++. |
| 12758 | if (LHSIsNull && !RHSIsNull) { |
| 12759 | Expr *E = LHS.get(); |
| 12760 | if (getLangOpts().ObjCAutoRefCount) |
| 12761 | ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E, |
| 12762 | CCK: CheckedConversionKind::Implicit); |
| 12763 | LHS = ImpCastExprToType(E, Type: RHSType, |
| 12764 | CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); |
| 12765 | } |
| 12766 | else { |
| 12767 | Expr *E = RHS.get(); |
| 12768 | if (getLangOpts().ObjCAutoRefCount) |
| 12769 | ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E, |
| 12770 | CCK: CheckedConversionKind::Implicit, |
| 12771 | /*Diagnose=*/true, |
| 12772 | /*DiagnoseCFAudited=*/false, Opc); |
| 12773 | RHS = ImpCastExprToType(E, Type: LHSType, |
| 12774 | CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); |
| 12775 | } |
| 12776 | return computeResultTy(); |
| 12777 | } |
| 12778 | if (LHSType->isObjCObjectPointerType() && |
| 12779 | RHSType->isObjCObjectPointerType()) { |
| 12780 | if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType)) |
| 12781 | diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, |
| 12782 | /*isError*/IsError: false); |
| 12783 | if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS)) |
| 12784 | diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc); |
| 12785 | |
| 12786 | if (LHSIsNull && !RHSIsNull) |
| 12787 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast); |
| 12788 | else |
| 12789 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
| 12790 | return computeResultTy(); |
| 12791 | } |
| 12792 | |
| 12793 | if (!IsOrdered && LHSType->isBlockPointerType() && |
| 12794 | RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) { |
| 12795 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, |
| 12796 | CK: CK_BlockPointerToObjCPointerCast); |
| 12797 | return computeResultTy(); |
| 12798 | } else if (!IsOrdered && |
| 12799 | LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) && |
| 12800 | RHSType->isBlockPointerType()) { |
| 12801 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, |
| 12802 | CK: CK_BlockPointerToObjCPointerCast); |
| 12803 | return computeResultTy(); |
| 12804 | } |
| 12805 | } |
| 12806 | if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || |
| 12807 | (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { |
| 12808 | unsigned DiagID = 0; |
| 12809 | bool isError = false; |
| 12810 | if (LangOpts.DebuggerSupport) { |
| 12811 | // Under a debugger, allow the comparison of pointers to integers, |
| 12812 | // since users tend to want to compare addresses. |
| 12813 | } else if ((LHSIsNull && LHSType->isIntegerType()) || |
| 12814 | (RHSIsNull && RHSType->isIntegerType())) { |
| 12815 | if (IsOrdered) { |
| 12816 | isError = getLangOpts().CPlusPlus; |
| 12817 | DiagID = |
| 12818 | isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero |
| 12819 | : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; |
| 12820 | } |
| 12821 | } else if (getLangOpts().CPlusPlus) { |
| 12822 | DiagID = diag::err_typecheck_comparison_of_pointer_integer; |
| 12823 | isError = true; |
| 12824 | } else if (IsOrdered) |
| 12825 | DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; |
| 12826 | else |
| 12827 | DiagID = diag::ext_typecheck_comparison_of_pointer_integer; |
| 12828 | |
| 12829 | if (DiagID) { |
| 12830 | Diag(Loc, DiagID) |
| 12831 | << LHSType << RHSType << LHS.get()->getSourceRange() |
| 12832 | << RHS.get()->getSourceRange(); |
| 12833 | if (isError) |
| 12834 | return QualType(); |
| 12835 | } |
| 12836 | |
| 12837 | if (LHSType->isIntegerType()) |
| 12838 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, |
| 12839 | CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); |
| 12840 | else |
| 12841 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, |
| 12842 | CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); |
| 12843 | return computeResultTy(); |
| 12844 | } |
| 12845 | |
| 12846 | // Handle block pointers. |
| 12847 | if (!IsOrdered && RHSIsNull |
| 12848 | && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { |
| 12849 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
| 12850 | return computeResultTy(); |
| 12851 | } |
| 12852 | if (!IsOrdered && LHSIsNull |
| 12853 | && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { |
| 12854 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
| 12855 | return computeResultTy(); |
| 12856 | } |
| 12857 | |
| 12858 | if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { |
| 12859 | if (LHSType->isClkEventT() && RHSType->isClkEventT()) { |
| 12860 | return computeResultTy(); |
| 12861 | } |
| 12862 | |
| 12863 | if (LHSType->isQueueT() && RHSType->isQueueT()) { |
| 12864 | return computeResultTy(); |
| 12865 | } |
| 12866 | |
| 12867 | if (LHSIsNull && RHSType->isQueueT()) { |
| 12868 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
| 12869 | return computeResultTy(); |
| 12870 | } |
| 12871 | |
| 12872 | if (LHSType->isQueueT() && RHSIsNull) { |
| 12873 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
| 12874 | return computeResultTy(); |
| 12875 | } |
| 12876 | } |
| 12877 | |
| 12878 | return InvalidOperands(Loc, LHS, RHS); |
| 12879 | } |
| 12880 | |
| 12881 | QualType Sema::GetSignedVectorType(QualType V) { |
| 12882 | const VectorType *VTy = V->castAs<VectorType>(); |
| 12883 | unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType()); |
| 12884 | |
| 12885 | if (isa<ExtVectorType>(Val: VTy)) { |
| 12886 | if (VTy->isExtVectorBoolType()) |
| 12887 | return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements()); |
| 12888 | if (TypeSize == Context.getTypeSize(T: Context.CharTy)) |
| 12889 | return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements()); |
| 12890 | if (TypeSize == Context.getTypeSize(T: Context.ShortTy)) |
| 12891 | return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements()); |
| 12892 | if (TypeSize == Context.getTypeSize(T: Context.IntTy)) |
| 12893 | return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements()); |
| 12894 | if (TypeSize == Context.getTypeSize(T: Context.Int128Ty)) |
| 12895 | return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements()); |
| 12896 | if (TypeSize == Context.getTypeSize(T: Context.LongTy)) |
| 12897 | return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements()); |
| 12898 | assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && |
| 12899 | "Unhandled vector element size in vector compare" ); |
| 12900 | return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements()); |
| 12901 | } |
| 12902 | |
| 12903 | if (TypeSize == Context.getTypeSize(T: Context.Int128Ty)) |
| 12904 | return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(), |
| 12905 | VecKind: VectorKind::Generic); |
| 12906 | if (TypeSize == Context.getTypeSize(T: Context.LongLongTy)) |
| 12907 | return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(), |
| 12908 | VecKind: VectorKind::Generic); |
| 12909 | if (TypeSize == Context.getTypeSize(T: Context.LongTy)) |
| 12910 | return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(), |
| 12911 | VecKind: VectorKind::Generic); |
| 12912 | if (TypeSize == Context.getTypeSize(T: Context.IntTy)) |
| 12913 | return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(), |
| 12914 | VecKind: VectorKind::Generic); |
| 12915 | if (TypeSize == Context.getTypeSize(T: Context.ShortTy)) |
| 12916 | return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(), |
| 12917 | VecKind: VectorKind::Generic); |
| 12918 | assert(TypeSize == Context.getTypeSize(Context.CharTy) && |
| 12919 | "Unhandled vector element size in vector compare" ); |
| 12920 | return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(), |
| 12921 | VecKind: VectorKind::Generic); |
| 12922 | } |
| 12923 | |
| 12924 | QualType Sema::GetSignedSizelessVectorType(QualType V) { |
| 12925 | const BuiltinType *VTy = V->castAs<BuiltinType>(); |
| 12926 | assert(VTy->isSizelessBuiltinType() && "expected sizeless type" ); |
| 12927 | |
| 12928 | const QualType ETy = V->getSveEltType(Ctx: Context); |
| 12929 | const auto TypeSize = Context.getTypeSize(T: ETy); |
| 12930 | |
| 12931 | const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true); |
| 12932 | const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC; |
| 12933 | return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue()); |
| 12934 | } |
| 12935 | |
| 12936 | QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, |
| 12937 | SourceLocation Loc, |
| 12938 | BinaryOperatorKind Opc) { |
| 12939 | if (Opc == BO_Cmp) { |
| 12940 | Diag(Loc, DiagID: diag::err_three_way_vector_comparison); |
| 12941 | return QualType(); |
| 12942 | } |
| 12943 | |
| 12944 | // Check to make sure we're operating on vectors of the same type and width, |
| 12945 | // Allowing one side to be a scalar of element type. |
| 12946 | QualType vType = |
| 12947 | CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, |
| 12948 | /*AllowBothBool*/ true, |
| 12949 | /*AllowBoolConversions*/ getLangOpts().ZVector, |
| 12950 | /*AllowBooleanOperation*/ AllowBoolOperation: true, |
| 12951 | /*ReportInvalid*/ true); |
| 12952 | if (vType.isNull()) |
| 12953 | return vType; |
| 12954 | |
| 12955 | QualType LHSType = LHS.get()->getType(); |
| 12956 | |
| 12957 | // Determine the return type of a vector compare. By default clang will return |
| 12958 | // a scalar for all vector compares except vector bool and vector pixel. |
| 12959 | // With the gcc compiler we will always return a vector type and with the xl |
| 12960 | // compiler we will always return a scalar type. This switch allows choosing |
| 12961 | // which behavior is prefered. |
| 12962 | if (getLangOpts().AltiVec) { |
| 12963 | switch (getLangOpts().getAltivecSrcCompat()) { |
| 12964 | case LangOptions::AltivecSrcCompatKind::Mixed: |
| 12965 | // If AltiVec, the comparison results in a numeric type, i.e. |
| 12966 | // bool for C++, int for C |
| 12967 | if (vType->castAs<VectorType>()->getVectorKind() == |
| 12968 | VectorKind::AltiVecVector) |
| 12969 | return Context.getLogicalOperationType(); |
| 12970 | else |
| 12971 | Diag(Loc, DiagID: diag::warn_deprecated_altivec_src_compat); |
| 12972 | break; |
| 12973 | case LangOptions::AltivecSrcCompatKind::GCC: |
| 12974 | // For GCC we always return the vector type. |
| 12975 | break; |
| 12976 | case LangOptions::AltivecSrcCompatKind::XL: |
| 12977 | return Context.getLogicalOperationType(); |
| 12978 | break; |
| 12979 | } |
| 12980 | } |
| 12981 | |
| 12982 | // For non-floating point types, check for self-comparisons of the form |
| 12983 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and |
| 12984 | // often indicate logic errors in the program. |
| 12985 | diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc); |
| 12986 | |
| 12987 | // Check for comparisons of floating point operands using != and ==. |
| 12988 | if (LHSType->hasFloatingRepresentation()) { |
| 12989 | assert(RHS.get()->getType()->hasFloatingRepresentation()); |
| 12990 | CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc); |
| 12991 | } |
| 12992 | |
| 12993 | // Return a signed type for the vector. |
| 12994 | return GetSignedVectorType(V: vType); |
| 12995 | } |
| 12996 | |
| 12997 | QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS, |
| 12998 | ExprResult &RHS, |
| 12999 | SourceLocation Loc, |
| 13000 | BinaryOperatorKind Opc) { |
| 13001 | if (Opc == BO_Cmp) { |
| 13002 | Diag(Loc, DiagID: diag::err_three_way_vector_comparison); |
| 13003 | return QualType(); |
| 13004 | } |
| 13005 | |
| 13006 | // Check to make sure we're operating on vectors of the same type and width, |
| 13007 | // Allowing one side to be a scalar of element type. |
| 13008 | QualType vType = CheckSizelessVectorOperands( |
| 13009 | LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ArithConvKind::Comparison); |
| 13010 | |
| 13011 | if (vType.isNull()) |
| 13012 | return vType; |
| 13013 | |
| 13014 | QualType LHSType = LHS.get()->getType(); |
| 13015 | |
| 13016 | // For non-floating point types, check for self-comparisons of the form |
| 13017 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and |
| 13018 | // often indicate logic errors in the program. |
| 13019 | diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc); |
| 13020 | |
| 13021 | // Check for comparisons of floating point operands using != and ==. |
| 13022 | if (LHSType->hasFloatingRepresentation()) { |
| 13023 | assert(RHS.get()->getType()->hasFloatingRepresentation()); |
| 13024 | CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc); |
| 13025 | } |
| 13026 | |
| 13027 | const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); |
| 13028 | const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>(); |
| 13029 | |
| 13030 | if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() && |
| 13031 | RHSBuiltinTy->isSVEBool()) |
| 13032 | return LHSType; |
| 13033 | |
| 13034 | // Return a signed type for the vector. |
| 13035 | return GetSignedSizelessVectorType(V: vType); |
| 13036 | } |
| 13037 | |
| 13038 | static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, |
| 13039 | const ExprResult &XorRHS, |
| 13040 | const SourceLocation Loc) { |
| 13041 | // Do not diagnose macros. |
| 13042 | if (Loc.isMacroID()) |
| 13043 | return; |
| 13044 | |
| 13045 | // Do not diagnose if both LHS and RHS are macros. |
| 13046 | if (XorLHS.get()->getExprLoc().isMacroID() && |
| 13047 | XorRHS.get()->getExprLoc().isMacroID()) |
| 13048 | return; |
| 13049 | |
| 13050 | bool Negative = false; |
| 13051 | bool ExplicitPlus = false; |
| 13052 | const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get()); |
| 13053 | const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get()); |
| 13054 | |
| 13055 | if (!LHSInt) |
| 13056 | return; |
| 13057 | if (!RHSInt) { |
| 13058 | // Check negative literals. |
| 13059 | if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) { |
| 13060 | UnaryOperatorKind Opc = UO->getOpcode(); |
| 13061 | if (Opc != UO_Minus && Opc != UO_Plus) |
| 13062 | return; |
| 13063 | RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr()); |
| 13064 | if (!RHSInt) |
| 13065 | return; |
| 13066 | Negative = (Opc == UO_Minus); |
| 13067 | ExplicitPlus = !Negative; |
| 13068 | } else { |
| 13069 | return; |
| 13070 | } |
| 13071 | } |
| 13072 | |
| 13073 | const llvm::APInt &LeftSideValue = LHSInt->getValue(); |
| 13074 | llvm::APInt RightSideValue = RHSInt->getValue(); |
| 13075 | if (LeftSideValue != 2 && LeftSideValue != 10) |
| 13076 | return; |
| 13077 | |
| 13078 | if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) |
| 13079 | return; |
| 13080 | |
| 13081 | CharSourceRange ExprRange = CharSourceRange::getCharRange( |
| 13082 | B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation())); |
| 13083 | llvm::StringRef ExprStr = |
| 13084 | Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts()); |
| 13085 | |
| 13086 | CharSourceRange XorRange = |
| 13087 | CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc)); |
| 13088 | llvm::StringRef XorStr = |
| 13089 | Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts()); |
| 13090 | // Do not diagnose if xor keyword/macro is used. |
| 13091 | if (XorStr == "xor" ) |
| 13092 | return; |
| 13093 | |
| 13094 | std::string LHSStr = std::string(Lexer::getSourceText( |
| 13095 | Range: CharSourceRange::getTokenRange(R: LHSInt->getSourceRange()), |
| 13096 | SM: S.getSourceManager(), LangOpts: S.getLangOpts())); |
| 13097 | std::string RHSStr = std::string(Lexer::getSourceText( |
| 13098 | Range: CharSourceRange::getTokenRange(R: RHSInt->getSourceRange()), |
| 13099 | SM: S.getSourceManager(), LangOpts: S.getLangOpts())); |
| 13100 | |
| 13101 | if (Negative) { |
| 13102 | RightSideValue = -RightSideValue; |
| 13103 | RHSStr = "-" + RHSStr; |
| 13104 | } else if (ExplicitPlus) { |
| 13105 | RHSStr = "+" + RHSStr; |
| 13106 | } |
| 13107 | |
| 13108 | StringRef LHSStrRef = LHSStr; |
| 13109 | StringRef RHSStrRef = RHSStr; |
| 13110 | // Do not diagnose literals with digit separators, binary, hexadecimal, octal |
| 13111 | // literals. |
| 13112 | if (LHSStrRef.starts_with(Prefix: "0b" ) || LHSStrRef.starts_with(Prefix: "0B" ) || |
| 13113 | RHSStrRef.starts_with(Prefix: "0b" ) || RHSStrRef.starts_with(Prefix: "0B" ) || |
| 13114 | LHSStrRef.starts_with(Prefix: "0x" ) || LHSStrRef.starts_with(Prefix: "0X" ) || |
| 13115 | RHSStrRef.starts_with(Prefix: "0x" ) || RHSStrRef.starts_with(Prefix: "0X" ) || |
| 13116 | (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0" )) || |
| 13117 | (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0" )) || |
| 13118 | LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\'')) |
| 13119 | return; |
| 13120 | |
| 13121 | bool SuggestXor = |
| 13122 | S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor" ); |
| 13123 | const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; |
| 13124 | int64_t RightSideIntValue = RightSideValue.getSExtValue(); |
| 13125 | if (LeftSideValue == 2 && RightSideIntValue >= 0) { |
| 13126 | std::string SuggestedExpr = "1 << " + RHSStr; |
| 13127 | bool Overflow = false; |
| 13128 | llvm::APInt One = (LeftSideValue - 1); |
| 13129 | llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow); |
| 13130 | if (Overflow) { |
| 13131 | if (RightSideIntValue < 64) |
| 13132 | S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base) |
| 13133 | << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << ("1LL << " + RHSStr) |
| 13134 | << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: "1LL << " + RHSStr); |
| 13135 | else if (RightSideIntValue == 64) |
| 13136 | S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow) |
| 13137 | << ExprStr << toString(I: XorValue, Radix: 10, Signed: true); |
| 13138 | else |
| 13139 | return; |
| 13140 | } else { |
| 13141 | S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base_extra) |
| 13142 | << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedExpr |
| 13143 | << toString(I: PowValue, Radix: 10, Signed: true) |
| 13144 | << FixItHint::CreateReplacement( |
| 13145 | RemoveRange: ExprRange, Code: (RightSideIntValue == 0) ? "1" : SuggestedExpr); |
| 13146 | } |
| 13147 | |
| 13148 | S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence) |
| 13149 | << ("0x2 ^ " + RHSStr) << SuggestXor; |
| 13150 | } else if (LeftSideValue == 10) { |
| 13151 | std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue); |
| 13152 | S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base) |
| 13153 | << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedValue |
| 13154 | << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: SuggestedValue); |
| 13155 | S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence) |
| 13156 | << ("0xA ^ " + RHSStr) << SuggestXor; |
| 13157 | } |
| 13158 | } |
| 13159 | |
| 13160 | QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, |
| 13161 | SourceLocation Loc, |
| 13162 | BinaryOperatorKind Opc) { |
| 13163 | // Ensure that either both operands are of the same vector type, or |
| 13164 | // one operand is of a vector type and the other is of its element type. |
| 13165 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false, |
| 13166 | /*AllowBothBool*/ true, |
| 13167 | /*AllowBoolConversions*/ false, |
| 13168 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
| 13169 | /*ReportInvalid*/ false); |
| 13170 | if (vType.isNull()) |
| 13171 | return InvalidOperands(Loc, LHS, RHS); |
| 13172 | if (getLangOpts().OpenCL && |
| 13173 | getLangOpts().getOpenCLCompatibleVersion() < 120 && |
| 13174 | vType->hasFloatingRepresentation()) |
| 13175 | return InvalidOperands(Loc, LHS, RHS); |
| 13176 | // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the |
| 13177 | // usage of the logical operators && and || with vectors in C. This |
| 13178 | // check could be notionally dropped. |
| 13179 | if (!getLangOpts().CPlusPlus && |
| 13180 | !(isa<ExtVectorType>(Val: vType->getAs<VectorType>()))) |
| 13181 | return InvalidLogicalVectorOperands(Loc, LHS, RHS); |
| 13182 | // Beginning with HLSL 2021, HLSL disallows logical operators on vector |
| 13183 | // operands and instead requires the use of the `and`, `or`, `any`, `all`, and |
| 13184 | // `select` functions. |
| 13185 | if (getLangOpts().HLSL && |
| 13186 | getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) { |
| 13187 | (void)InvalidOperands(Loc, LHS, RHS); |
| 13188 | HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc); |
| 13189 | return QualType(); |
| 13190 | } |
| 13191 | |
| 13192 | return GetSignedVectorType(V: LHS.get()->getType()); |
| 13193 | } |
| 13194 | |
| 13195 | QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, |
| 13196 | SourceLocation Loc, |
| 13197 | bool IsCompAssign) { |
| 13198 | if (!IsCompAssign) { |
| 13199 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
| 13200 | if (LHS.isInvalid()) |
| 13201 | return QualType(); |
| 13202 | } |
| 13203 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
| 13204 | if (RHS.isInvalid()) |
| 13205 | return QualType(); |
| 13206 | |
| 13207 | // For conversion purposes, we ignore any qualifiers. |
| 13208 | // For example, "const float" and "float" are equivalent. |
| 13209 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); |
| 13210 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); |
| 13211 | |
| 13212 | const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); |
| 13213 | const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); |
| 13214 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix" ); |
| 13215 | |
| 13216 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
| 13217 | return Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
| 13218 | |
| 13219 | // Type conversion may change LHS/RHS. Keep copies to the original results, in |
| 13220 | // case we have to return InvalidOperands. |
| 13221 | ExprResult OriginalLHS = LHS; |
| 13222 | ExprResult OriginalRHS = RHS; |
| 13223 | if (LHSMatType && !RHSMatType) { |
| 13224 | RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType()); |
| 13225 | if (!RHS.isInvalid()) |
| 13226 | return LHSType; |
| 13227 | |
| 13228 | return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS); |
| 13229 | } |
| 13230 | |
| 13231 | if (!LHSMatType && RHSMatType) { |
| 13232 | LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType()); |
| 13233 | if (!LHS.isInvalid()) |
| 13234 | return RHSType; |
| 13235 | return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS); |
| 13236 | } |
| 13237 | |
| 13238 | return InvalidOperands(Loc, LHS, RHS); |
| 13239 | } |
| 13240 | |
| 13241 | QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, |
| 13242 | SourceLocation Loc, |
| 13243 | bool IsCompAssign) { |
| 13244 | if (!IsCompAssign) { |
| 13245 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
| 13246 | if (LHS.isInvalid()) |
| 13247 | return QualType(); |
| 13248 | } |
| 13249 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
| 13250 | if (RHS.isInvalid()) |
| 13251 | return QualType(); |
| 13252 | |
| 13253 | auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); |
| 13254 | auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); |
| 13255 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix" ); |
| 13256 | |
| 13257 | if (LHSMatType && RHSMatType) { |
| 13258 | if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) |
| 13259 | return InvalidOperands(Loc, LHS, RHS); |
| 13260 | |
| 13261 | if (Context.hasSameType(T1: LHSMatType, T2: RHSMatType)) |
| 13262 | return Context.getCommonSugaredType( |
| 13263 | X: LHS.get()->getType().getUnqualifiedType(), |
| 13264 | Y: RHS.get()->getType().getUnqualifiedType()); |
| 13265 | |
| 13266 | QualType LHSELTy = LHSMatType->getElementType(), |
| 13267 | RHSELTy = RHSMatType->getElementType(); |
| 13268 | if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy)) |
| 13269 | return InvalidOperands(Loc, LHS, RHS); |
| 13270 | |
| 13271 | return Context.getConstantMatrixType( |
| 13272 | ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy), |
| 13273 | NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns()); |
| 13274 | } |
| 13275 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); |
| 13276 | } |
| 13277 | |
| 13278 | static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) { |
| 13279 | switch (Opc) { |
| 13280 | default: |
| 13281 | return false; |
| 13282 | case BO_And: |
| 13283 | case BO_AndAssign: |
| 13284 | case BO_Or: |
| 13285 | case BO_OrAssign: |
| 13286 | case BO_Xor: |
| 13287 | case BO_XorAssign: |
| 13288 | return true; |
| 13289 | } |
| 13290 | } |
| 13291 | |
| 13292 | inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, |
| 13293 | SourceLocation Loc, |
| 13294 | BinaryOperatorKind Opc) { |
| 13295 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
| 13296 | |
| 13297 | bool IsCompAssign = |
| 13298 | Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; |
| 13299 | |
| 13300 | bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc); |
| 13301 | |
| 13302 | if (LHS.get()->getType()->isVectorType() || |
| 13303 | RHS.get()->getType()->isVectorType()) { |
| 13304 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
| 13305 | RHS.get()->getType()->hasIntegerRepresentation()) |
| 13306 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, |
| 13307 | /*AllowBothBool*/ true, |
| 13308 | /*AllowBoolConversions*/ getLangOpts().ZVector, |
| 13309 | /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator, |
| 13310 | /*ReportInvalid*/ true); |
| 13311 | return InvalidOperands(Loc, LHS, RHS); |
| 13312 | } |
| 13313 | |
| 13314 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
| 13315 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
| 13316 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
| 13317 | RHS.get()->getType()->hasIntegerRepresentation()) |
| 13318 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, |
| 13319 | OperationKind: ArithConvKind::BitwiseOp); |
| 13320 | return InvalidOperands(Loc, LHS, RHS); |
| 13321 | } |
| 13322 | |
| 13323 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
| 13324 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
| 13325 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
| 13326 | RHS.get()->getType()->hasIntegerRepresentation()) |
| 13327 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, |
| 13328 | OperationKind: ArithConvKind::BitwiseOp); |
| 13329 | return InvalidOperands(Loc, LHS, RHS); |
| 13330 | } |
| 13331 | |
| 13332 | if (Opc == BO_And) |
| 13333 | diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc); |
| 13334 | |
| 13335 | if (LHS.get()->getType()->hasFloatingRepresentation() || |
| 13336 | RHS.get()->getType()->hasFloatingRepresentation()) |
| 13337 | return InvalidOperands(Loc, LHS, RHS); |
| 13338 | |
| 13339 | ExprResult LHSResult = LHS, RHSResult = RHS; |
| 13340 | QualType compType = UsualArithmeticConversions( |
| 13341 | LHS&: LHSResult, RHS&: RHSResult, Loc, |
| 13342 | ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp); |
| 13343 | if (LHSResult.isInvalid() || RHSResult.isInvalid()) |
| 13344 | return QualType(); |
| 13345 | LHS = LHSResult.get(); |
| 13346 | RHS = RHSResult.get(); |
| 13347 | |
| 13348 | if (Opc == BO_Xor) |
| 13349 | diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc); |
| 13350 | |
| 13351 | if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) |
| 13352 | return compType; |
| 13353 | return InvalidOperands(Loc, LHS, RHS); |
| 13354 | } |
| 13355 | |
| 13356 | // C99 6.5.[13,14] |
| 13357 | inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, |
| 13358 | SourceLocation Loc, |
| 13359 | BinaryOperatorKind Opc) { |
| 13360 | // Check vector operands differently. |
| 13361 | if (LHS.get()->getType()->isVectorType() || |
| 13362 | RHS.get()->getType()->isVectorType()) |
| 13363 | return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc); |
| 13364 | |
| 13365 | bool EnumConstantInBoolContext = false; |
| 13366 | for (const ExprResult &HS : {LHS, RHS}) { |
| 13367 | if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) { |
| 13368 | const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl()); |
| 13369 | if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) |
| 13370 | EnumConstantInBoolContext = true; |
| 13371 | } |
| 13372 | } |
| 13373 | |
| 13374 | if (EnumConstantInBoolContext) |
| 13375 | Diag(Loc, DiagID: diag::warn_enum_constant_in_bool_context); |
| 13376 | |
| 13377 | // WebAssembly tables can't be used with logical operators. |
| 13378 | QualType LHSTy = LHS.get()->getType(); |
| 13379 | QualType RHSTy = RHS.get()->getType(); |
| 13380 | const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy); |
| 13381 | const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy); |
| 13382 | if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) || |
| 13383 | (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) { |
| 13384 | return InvalidOperands(Loc, LHS, RHS); |
| 13385 | } |
| 13386 | |
| 13387 | // Diagnose cases where the user write a logical and/or but probably meant a |
| 13388 | // bitwise one. We do this when the LHS is a non-bool integer and the RHS |
| 13389 | // is a constant. |
| 13390 | if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && |
| 13391 | !LHS.get()->getType()->isBooleanType() && |
| 13392 | RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && |
| 13393 | // Don't warn in macros or template instantiations. |
| 13394 | !Loc.isMacroID() && !inTemplateInstantiation()) { |
| 13395 | // If the RHS can be constant folded, and if it constant folds to something |
| 13396 | // that isn't 0 or 1 (which indicate a potential logical operation that |
| 13397 | // happened to fold to true/false) then warn. |
| 13398 | // Parens on the RHS are ignored. |
| 13399 | Expr::EvalResult EVResult; |
| 13400 | if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) { |
| 13401 | llvm::APSInt Result = EVResult.Val.getInt(); |
| 13402 | if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() && |
| 13403 | !RHS.get()->getExprLoc().isMacroID()) || |
| 13404 | (Result != 0 && Result != 1)) { |
| 13405 | Diag(Loc, DiagID: diag::warn_logical_instead_of_bitwise) |
| 13406 | << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||" ); |
| 13407 | // Suggest replacing the logical operator with the bitwise version |
| 13408 | Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_change_operator) |
| 13409 | << (Opc == BO_LAnd ? "&" : "|" ) |
| 13410 | << FixItHint::CreateReplacement( |
| 13411 | RemoveRange: SourceRange(Loc, getLocForEndOfToken(Loc)), |
| 13412 | Code: Opc == BO_LAnd ? "&" : "|" ); |
| 13413 | if (Opc == BO_LAnd) |
| 13414 | // Suggest replacing "Foo() && kNonZero" with "Foo()" |
| 13415 | Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_remove_constant) |
| 13416 | << FixItHint::CreateRemoval( |
| 13417 | RemoveRange: SourceRange(getLocForEndOfToken(Loc: LHS.get()->getEndLoc()), |
| 13418 | RHS.get()->getEndLoc())); |
| 13419 | } |
| 13420 | } |
| 13421 | } |
| 13422 | |
| 13423 | if (!Context.getLangOpts().CPlusPlus) { |
| 13424 | // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do |
| 13425 | // not operate on the built-in scalar and vector float types. |
| 13426 | if (Context.getLangOpts().OpenCL && |
| 13427 | Context.getLangOpts().OpenCLVersion < 120) { |
| 13428 | if (LHS.get()->getType()->isFloatingType() || |
| 13429 | RHS.get()->getType()->isFloatingType()) |
| 13430 | return InvalidOperands(Loc, LHS, RHS); |
| 13431 | } |
| 13432 | |
| 13433 | LHS = UsualUnaryConversions(E: LHS.get()); |
| 13434 | if (LHS.isInvalid()) |
| 13435 | return QualType(); |
| 13436 | |
| 13437 | RHS = UsualUnaryConversions(E: RHS.get()); |
| 13438 | if (RHS.isInvalid()) |
| 13439 | return QualType(); |
| 13440 | |
| 13441 | if (!LHS.get()->getType()->isScalarType() || |
| 13442 | !RHS.get()->getType()->isScalarType()) |
| 13443 | return InvalidOperands(Loc, LHS, RHS); |
| 13444 | |
| 13445 | return Context.IntTy; |
| 13446 | } |
| 13447 | |
| 13448 | // The following is safe because we only use this method for |
| 13449 | // non-overloadable operands. |
| 13450 | |
| 13451 | // C++ [expr.log.and]p1 |
| 13452 | // C++ [expr.log.or]p1 |
| 13453 | // The operands are both contextually converted to type bool. |
| 13454 | ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get()); |
| 13455 | if (LHSRes.isInvalid()) |
| 13456 | return InvalidOperands(Loc, LHS, RHS); |
| 13457 | LHS = LHSRes; |
| 13458 | |
| 13459 | ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get()); |
| 13460 | if (RHSRes.isInvalid()) |
| 13461 | return InvalidOperands(Loc, LHS, RHS); |
| 13462 | RHS = RHSRes; |
| 13463 | |
| 13464 | // C++ [expr.log.and]p2 |
| 13465 | // C++ [expr.log.or]p2 |
| 13466 | // The result is a bool. |
| 13467 | return Context.BoolTy; |
| 13468 | } |
| 13469 | |
| 13470 | static bool IsReadonlyMessage(Expr *E, Sema &S) { |
| 13471 | const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E); |
| 13472 | if (!ME) return false; |
| 13473 | if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false; |
| 13474 | ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( |
| 13475 | Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); |
| 13476 | if (!Base) return false; |
| 13477 | return Base->getMethodDecl() != nullptr; |
| 13478 | } |
| 13479 | |
| 13480 | /// Is the given expression (which must be 'const') a reference to a |
| 13481 | /// variable which was originally non-const, but which has become |
| 13482 | /// 'const' due to being captured within a block? |
| 13483 | enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; |
| 13484 | static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { |
| 13485 | assert(E->isLValue() && E->getType().isConstQualified()); |
| 13486 | E = E->IgnoreParens(); |
| 13487 | |
| 13488 | // Must be a reference to a declaration from an enclosing scope. |
| 13489 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E); |
| 13490 | if (!DRE) return NCCK_None; |
| 13491 | if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; |
| 13492 | |
| 13493 | ValueDecl *Value = dyn_cast<ValueDecl>(Val: DRE->getDecl()); |
| 13494 | |
| 13495 | // The declaration must be a value which is not declared 'const'. |
| 13496 | if (!Value || Value->getType().isConstQualified()) |
| 13497 | return NCCK_None; |
| 13498 | |
| 13499 | BindingDecl *Binding = dyn_cast<BindingDecl>(Val: Value); |
| 13500 | if (Binding) { |
| 13501 | assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?" ); |
| 13502 | assert(!isa<BlockDecl>(Binding->getDeclContext())); |
| 13503 | return NCCK_Lambda; |
| 13504 | } |
| 13505 | |
| 13506 | VarDecl *Var = dyn_cast<VarDecl>(Val: Value); |
| 13507 | if (!Var) |
| 13508 | return NCCK_None; |
| 13509 | |
| 13510 | assert(Var->hasLocalStorage() && "capture added 'const' to non-local?" ); |
| 13511 | |
| 13512 | // Decide whether the first capture was for a block or a lambda. |
| 13513 | DeclContext *DC = S.CurContext, *Prev = nullptr; |
| 13514 | // Decide whether the first capture was for a block or a lambda. |
| 13515 | while (DC) { |
| 13516 | // For init-capture, it is possible that the variable belongs to the |
| 13517 | // template pattern of the current context. |
| 13518 | if (auto *FD = dyn_cast<FunctionDecl>(Val: DC)) |
| 13519 | if (Var->isInitCapture() && |
| 13520 | FD->getTemplateInstantiationPattern() == Var->getDeclContext()) |
| 13521 | break; |
| 13522 | if (DC == Var->getDeclContext()) |
| 13523 | break; |
| 13524 | Prev = DC; |
| 13525 | DC = DC->getParent(); |
| 13526 | } |
| 13527 | // Unless we have an init-capture, we've gone one step too far. |
| 13528 | if (!Var->isInitCapture()) |
| 13529 | DC = Prev; |
| 13530 | return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda); |
| 13531 | } |
| 13532 | |
| 13533 | static bool IsTypeModifiable(QualType Ty, bool IsDereference) { |
| 13534 | Ty = Ty.getNonReferenceType(); |
| 13535 | if (IsDereference && Ty->isPointerType()) |
| 13536 | Ty = Ty->getPointeeType(); |
| 13537 | return !Ty.isConstQualified(); |
| 13538 | } |
| 13539 | |
| 13540 | // Update err_typecheck_assign_const and note_typecheck_assign_const |
| 13541 | // when this enum is changed. |
| 13542 | enum { |
| 13543 | ConstFunction, |
| 13544 | ConstVariable, |
| 13545 | ConstMember, |
| 13546 | ConstMethod, |
| 13547 | NestedConstMember, |
| 13548 | ConstUnknown, // Keep as last element |
| 13549 | }; |
| 13550 | |
| 13551 | /// Emit the "read-only variable not assignable" error and print notes to give |
| 13552 | /// more information about why the variable is not assignable, such as pointing |
| 13553 | /// to the declaration of a const variable, showing that a method is const, or |
| 13554 | /// that the function is returning a const reference. |
| 13555 | static void DiagnoseConstAssignment(Sema &S, const Expr *E, |
| 13556 | SourceLocation Loc) { |
| 13557 | SourceRange ExprRange = E->getSourceRange(); |
| 13558 | |
| 13559 | // Only emit one error on the first const found. All other consts will emit |
| 13560 | // a note to the error. |
| 13561 | bool DiagnosticEmitted = false; |
| 13562 | |
| 13563 | // Track if the current expression is the result of a dereference, and if the |
| 13564 | // next checked expression is the result of a dereference. |
| 13565 | bool IsDereference = false; |
| 13566 | bool NextIsDereference = false; |
| 13567 | |
| 13568 | // Loop to process MemberExpr chains. |
| 13569 | while (true) { |
| 13570 | IsDereference = NextIsDereference; |
| 13571 | |
| 13572 | E = E->IgnoreImplicit()->IgnoreParenImpCasts(); |
| 13573 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) { |
| 13574 | NextIsDereference = ME->isArrow(); |
| 13575 | const ValueDecl *VD = ME->getMemberDecl(); |
| 13576 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) { |
| 13577 | // Mutable fields can be modified even if the class is const. |
| 13578 | if (Field->isMutable()) { |
| 13579 | assert(DiagnosticEmitted && "Expected diagnostic not emitted." ); |
| 13580 | break; |
| 13581 | } |
| 13582 | |
| 13583 | if (!IsTypeModifiable(Ty: Field->getType(), IsDereference)) { |
| 13584 | if (!DiagnosticEmitted) { |
| 13585 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) |
| 13586 | << ExprRange << ConstMember << false /*static*/ << Field |
| 13587 | << Field->getType(); |
| 13588 | DiagnosticEmitted = true; |
| 13589 | } |
| 13590 | S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const) |
| 13591 | << ConstMember << false /*static*/ << Field << Field->getType() |
| 13592 | << Field->getSourceRange(); |
| 13593 | } |
| 13594 | E = ME->getBase(); |
| 13595 | continue; |
| 13596 | } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) { |
| 13597 | if (VDecl->getType().isConstQualified()) { |
| 13598 | if (!DiagnosticEmitted) { |
| 13599 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) |
| 13600 | << ExprRange << ConstMember << true /*static*/ << VDecl |
| 13601 | << VDecl->getType(); |
| 13602 | DiagnosticEmitted = true; |
| 13603 | } |
| 13604 | S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const) |
| 13605 | << ConstMember << true /*static*/ << VDecl << VDecl->getType() |
| 13606 | << VDecl->getSourceRange(); |
| 13607 | } |
| 13608 | // Static fields do not inherit constness from parents. |
| 13609 | break; |
| 13610 | } |
| 13611 | break; // End MemberExpr |
| 13612 | } else if (const ArraySubscriptExpr *ASE = |
| 13613 | dyn_cast<ArraySubscriptExpr>(Val: E)) { |
| 13614 | E = ASE->getBase()->IgnoreParenImpCasts(); |
| 13615 | continue; |
| 13616 | } else if (const ExtVectorElementExpr *EVE = |
| 13617 | dyn_cast<ExtVectorElementExpr>(Val: E)) { |
| 13618 | E = EVE->getBase()->IgnoreParenImpCasts(); |
| 13619 | continue; |
| 13620 | } |
| 13621 | break; |
| 13622 | } |
| 13623 | |
| 13624 | if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) { |
| 13625 | // Function calls |
| 13626 | const FunctionDecl *FD = CE->getDirectCallee(); |
| 13627 | if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) { |
| 13628 | if (!DiagnosticEmitted) { |
| 13629 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange |
| 13630 | << ConstFunction << FD; |
| 13631 | DiagnosticEmitted = true; |
| 13632 | } |
| 13633 | S.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(), |
| 13634 | DiagID: diag::note_typecheck_assign_const) |
| 13635 | << ConstFunction << FD << FD->getReturnType() |
| 13636 | << FD->getReturnTypeSourceRange(); |
| 13637 | } |
| 13638 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) { |
| 13639 | // Point to variable declaration. |
| 13640 | if (const ValueDecl *VD = DRE->getDecl()) { |
| 13641 | if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) { |
| 13642 | if (!DiagnosticEmitted) { |
| 13643 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) |
| 13644 | << ExprRange << ConstVariable << VD << VD->getType(); |
| 13645 | DiagnosticEmitted = true; |
| 13646 | } |
| 13647 | S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const) |
| 13648 | << ConstVariable << VD << VD->getType() << VD->getSourceRange(); |
| 13649 | } |
| 13650 | } |
| 13651 | } else if (isa<CXXThisExpr>(Val: E)) { |
| 13652 | if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { |
| 13653 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) { |
| 13654 | if (MD->isConst()) { |
| 13655 | if (!DiagnosticEmitted) { |
| 13656 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange |
| 13657 | << ConstMethod << MD; |
| 13658 | DiagnosticEmitted = true; |
| 13659 | } |
| 13660 | S.Diag(Loc: MD->getLocation(), DiagID: diag::note_typecheck_assign_const) |
| 13661 | << ConstMethod << MD << MD->getSourceRange(); |
| 13662 | } |
| 13663 | } |
| 13664 | } |
| 13665 | } |
| 13666 | |
| 13667 | if (DiagnosticEmitted) |
| 13668 | return; |
| 13669 | |
| 13670 | // Can't determine a more specific message, so display the generic error. |
| 13671 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; |
| 13672 | } |
| 13673 | |
| 13674 | enum OriginalExprKind { |
| 13675 | OEK_Variable, |
| 13676 | OEK_Member, |
| 13677 | OEK_LValue |
| 13678 | }; |
| 13679 | |
| 13680 | static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, |
| 13681 | const RecordType *Ty, |
| 13682 | SourceLocation Loc, SourceRange Range, |
| 13683 | OriginalExprKind OEK, |
| 13684 | bool &DiagnosticEmitted) { |
| 13685 | std::vector<const RecordType *> RecordTypeList; |
| 13686 | RecordTypeList.push_back(x: Ty); |
| 13687 | unsigned NextToCheckIndex = 0; |
| 13688 | // We walk the record hierarchy breadth-first to ensure that we print |
| 13689 | // diagnostics in field nesting order. |
| 13690 | while (RecordTypeList.size() > NextToCheckIndex) { |
| 13691 | bool IsNested = NextToCheckIndex > 0; |
| 13692 | for (const FieldDecl *Field : |
| 13693 | RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { |
| 13694 | // First, check every field for constness. |
| 13695 | QualType FieldTy = Field->getType(); |
| 13696 | if (FieldTy.isConstQualified()) { |
| 13697 | if (!DiagnosticEmitted) { |
| 13698 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) |
| 13699 | << Range << NestedConstMember << OEK << VD |
| 13700 | << IsNested << Field; |
| 13701 | DiagnosticEmitted = true; |
| 13702 | } |
| 13703 | S.Diag(Loc: Field->getLocation(), DiagID: diag::note_typecheck_assign_const) |
| 13704 | << NestedConstMember << IsNested << Field |
| 13705 | << FieldTy << Field->getSourceRange(); |
| 13706 | } |
| 13707 | |
| 13708 | // Then we append it to the list to check next in order. |
| 13709 | FieldTy = FieldTy.getCanonicalType(); |
| 13710 | if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { |
| 13711 | if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy)) |
| 13712 | RecordTypeList.push_back(x: FieldRecTy); |
| 13713 | } |
| 13714 | } |
| 13715 | ++NextToCheckIndex; |
| 13716 | } |
| 13717 | } |
| 13718 | |
| 13719 | /// Emit an error for the case where a record we are trying to assign to has a |
| 13720 | /// const-qualified field somewhere in its hierarchy. |
| 13721 | static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, |
| 13722 | SourceLocation Loc) { |
| 13723 | QualType Ty = E->getType(); |
| 13724 | assert(Ty->isRecordType() && "lvalue was not record?" ); |
| 13725 | SourceRange Range = E->getSourceRange(); |
| 13726 | const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); |
| 13727 | bool DiagEmitted = false; |
| 13728 | |
| 13729 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) |
| 13730 | DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc, |
| 13731 | Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted); |
| 13732 | else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
| 13733 | DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc, |
| 13734 | Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted); |
| 13735 | else |
| 13736 | DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc, |
| 13737 | Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted); |
| 13738 | if (!DiagEmitted) |
| 13739 | DiagnoseConstAssignment(S, E, Loc); |
| 13740 | } |
| 13741 | |
| 13742 | /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, |
| 13743 | /// emit an error and return true. If so, return false. |
| 13744 | static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { |
| 13745 | assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); |
| 13746 | |
| 13747 | S.CheckShadowingDeclModification(E, Loc); |
| 13748 | |
| 13749 | SourceLocation OrigLoc = Loc; |
| 13750 | Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context, |
| 13751 | Loc: &Loc); |
| 13752 | if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) |
| 13753 | IsLV = Expr::MLV_InvalidMessageExpression; |
| 13754 | if (IsLV == Expr::MLV_Valid) |
| 13755 | return false; |
| 13756 | |
| 13757 | unsigned DiagID = 0; |
| 13758 | bool NeedType = false; |
| 13759 | switch (IsLV) { // C99 6.5.16p2 |
| 13760 | case Expr::MLV_ConstQualified: |
| 13761 | // Use a specialized diagnostic when we're assigning to an object |
| 13762 | // from an enclosing function or block. |
| 13763 | if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { |
| 13764 | if (NCCK == NCCK_Block) |
| 13765 | DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; |
| 13766 | else |
| 13767 | DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; |
| 13768 | break; |
| 13769 | } |
| 13770 | |
| 13771 | // In ARC, use some specialized diagnostics for occasions where we |
| 13772 | // infer 'const'. These are always pseudo-strong variables. |
| 13773 | if (S.getLangOpts().ObjCAutoRefCount) { |
| 13774 | DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()); |
| 13775 | if (declRef && isa<VarDecl>(Val: declRef->getDecl())) { |
| 13776 | VarDecl *var = cast<VarDecl>(Val: declRef->getDecl()); |
| 13777 | |
| 13778 | // Use the normal diagnostic if it's pseudo-__strong but the |
| 13779 | // user actually wrote 'const'. |
| 13780 | if (var->isARCPseudoStrong() && |
| 13781 | (!var->getTypeSourceInfo() || |
| 13782 | !var->getTypeSourceInfo()->getType().isConstQualified())) { |
| 13783 | // There are three pseudo-strong cases: |
| 13784 | // - self |
| 13785 | ObjCMethodDecl *method = S.getCurMethodDecl(); |
| 13786 | if (method && var == method->getSelfDecl()) { |
| 13787 | DiagID = method->isClassMethod() |
| 13788 | ? diag::err_typecheck_arc_assign_self_class_method |
| 13789 | : diag::err_typecheck_arc_assign_self; |
| 13790 | |
| 13791 | // - Objective-C externally_retained attribute. |
| 13792 | } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || |
| 13793 | isa<ParmVarDecl>(Val: var)) { |
| 13794 | DiagID = diag::err_typecheck_arc_assign_externally_retained; |
| 13795 | |
| 13796 | // - fast enumeration variables |
| 13797 | } else { |
| 13798 | DiagID = diag::err_typecheck_arr_assign_enumeration; |
| 13799 | } |
| 13800 | |
| 13801 | SourceRange Assign; |
| 13802 | if (Loc != OrigLoc) |
| 13803 | Assign = SourceRange(OrigLoc, OrigLoc); |
| 13804 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; |
| 13805 | // We need to preserve the AST regardless, so migration tool |
| 13806 | // can do its job. |
| 13807 | return false; |
| 13808 | } |
| 13809 | } |
| 13810 | } |
| 13811 | |
| 13812 | // If none of the special cases above are triggered, then this is a |
| 13813 | // simple const assignment. |
| 13814 | if (DiagID == 0) { |
| 13815 | DiagnoseConstAssignment(S, E, Loc); |
| 13816 | return true; |
| 13817 | } |
| 13818 | |
| 13819 | break; |
| 13820 | case Expr::MLV_ConstAddrSpace: |
| 13821 | DiagnoseConstAssignment(S, E, Loc); |
| 13822 | return true; |
| 13823 | case Expr::MLV_ConstQualifiedField: |
| 13824 | DiagnoseRecursiveConstFields(S, E, Loc); |
| 13825 | return true; |
| 13826 | case Expr::MLV_ArrayType: |
| 13827 | case Expr::MLV_ArrayTemporary: |
| 13828 | DiagID = diag::err_typecheck_array_not_modifiable_lvalue; |
| 13829 | NeedType = true; |
| 13830 | break; |
| 13831 | case Expr::MLV_NotObjectType: |
| 13832 | DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; |
| 13833 | NeedType = true; |
| 13834 | break; |
| 13835 | case Expr::MLV_LValueCast: |
| 13836 | DiagID = diag::err_typecheck_lvalue_casts_not_supported; |
| 13837 | break; |
| 13838 | case Expr::MLV_Valid: |
| 13839 | llvm_unreachable("did not take early return for MLV_Valid" ); |
| 13840 | case Expr::MLV_InvalidExpression: |
| 13841 | case Expr::MLV_MemberFunction: |
| 13842 | case Expr::MLV_ClassTemporary: |
| 13843 | DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; |
| 13844 | break; |
| 13845 | case Expr::MLV_IncompleteType: |
| 13846 | case Expr::MLV_IncompleteVoidType: |
| 13847 | return S.RequireCompleteType(Loc, T: E->getType(), |
| 13848 | DiagID: diag::err_typecheck_incomplete_type_not_modifiable_lvalue, Args: E); |
| 13849 | case Expr::MLV_DuplicateVectorComponents: |
| 13850 | DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; |
| 13851 | break; |
| 13852 | case Expr::MLV_NoSetterProperty: |
| 13853 | llvm_unreachable("readonly properties should be processed differently" ); |
| 13854 | case Expr::MLV_InvalidMessageExpression: |
| 13855 | DiagID = diag::err_readonly_message_assignment; |
| 13856 | break; |
| 13857 | case Expr::MLV_SubObjCPropertySetting: |
| 13858 | DiagID = diag::err_no_subobject_property_setting; |
| 13859 | break; |
| 13860 | } |
| 13861 | |
| 13862 | SourceRange Assign; |
| 13863 | if (Loc != OrigLoc) |
| 13864 | Assign = SourceRange(OrigLoc, OrigLoc); |
| 13865 | if (NeedType) |
| 13866 | S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; |
| 13867 | else |
| 13868 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; |
| 13869 | return true; |
| 13870 | } |
| 13871 | |
| 13872 | static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, |
| 13873 | SourceLocation Loc, |
| 13874 | Sema &Sema) { |
| 13875 | if (Sema.inTemplateInstantiation()) |
| 13876 | return; |
| 13877 | if (Sema.isUnevaluatedContext()) |
| 13878 | return; |
| 13879 | if (Loc.isInvalid() || Loc.isMacroID()) |
| 13880 | return; |
| 13881 | if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) |
| 13882 | return; |
| 13883 | |
| 13884 | // C / C++ fields |
| 13885 | MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr); |
| 13886 | MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr); |
| 13887 | if (ML && MR) { |
| 13888 | if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase()))) |
| 13889 | return; |
| 13890 | const ValueDecl *LHSDecl = |
| 13891 | cast<ValueDecl>(Val: ML->getMemberDecl()->getCanonicalDecl()); |
| 13892 | const ValueDecl *RHSDecl = |
| 13893 | cast<ValueDecl>(Val: MR->getMemberDecl()->getCanonicalDecl()); |
| 13894 | if (LHSDecl != RHSDecl) |
| 13895 | return; |
| 13896 | if (LHSDecl->getType().isVolatileQualified()) |
| 13897 | return; |
| 13898 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) |
| 13899 | if (RefTy->getPointeeType().isVolatileQualified()) |
| 13900 | return; |
| 13901 | |
| 13902 | Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 0; |
| 13903 | } |
| 13904 | |
| 13905 | // Objective-C instance variables |
| 13906 | ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr); |
| 13907 | ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr); |
| 13908 | if (OL && OR && OL->getDecl() == OR->getDecl()) { |
| 13909 | DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts()); |
| 13910 | DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts()); |
| 13911 | if (RL && RR && RL->getDecl() == RR->getDecl()) |
| 13912 | Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 1; |
| 13913 | } |
| 13914 | } |
| 13915 | |
| 13916 | // C99 6.5.16.1 |
| 13917 | QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, |
| 13918 | SourceLocation Loc, |
| 13919 | QualType CompoundType, |
| 13920 | BinaryOperatorKind Opc) { |
| 13921 | assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); |
| 13922 | |
| 13923 | // Verify that LHS is a modifiable lvalue, and emit error if not. |
| 13924 | if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this)) |
| 13925 | return QualType(); |
| 13926 | |
| 13927 | QualType LHSType = LHSExpr->getType(); |
| 13928 | QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : |
| 13929 | CompoundType; |
| 13930 | |
| 13931 | if (RHS.isUsable()) { |
| 13932 | // Even if this check fails don't return early to allow the best |
| 13933 | // possible error recovery and to allow any subsequent diagnostics to |
| 13934 | // work. |
| 13935 | const ValueDecl *Assignee = nullptr; |
| 13936 | bool ShowFullyQualifiedAssigneeName = false; |
| 13937 | // In simple cases describe what is being assigned to |
| 13938 | if (auto *DR = dyn_cast<DeclRefExpr>(Val: LHSExpr->IgnoreParenCasts())) { |
| 13939 | Assignee = DR->getDecl(); |
| 13940 | } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHSExpr->IgnoreParenCasts())) { |
| 13941 | Assignee = ME->getMemberDecl(); |
| 13942 | ShowFullyQualifiedAssigneeName = true; |
| 13943 | } |
| 13944 | |
| 13945 | BoundsSafetyCheckAssignmentToCountAttrPtr( |
| 13946 | LHSTy: LHSType, RHSExpr: RHS.get(), Action: AssignmentAction::Assigning, Loc, Assignee, |
| 13947 | ShowFullyQualifiedAssigneeName); |
| 13948 | } |
| 13949 | |
| 13950 | // OpenCL v1.2 s6.1.1.1 p2: |
| 13951 | // The half data type can only be used to declare a pointer to a buffer that |
| 13952 | // contains half values |
| 13953 | if (getLangOpts().OpenCL && |
| 13954 | !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16" , LO: getLangOpts()) && |
| 13955 | LHSType->isHalfType()) { |
| 13956 | Diag(Loc, DiagID: diag::err_opencl_half_load_store) << 1 |
| 13957 | << LHSType.getUnqualifiedType(); |
| 13958 | return QualType(); |
| 13959 | } |
| 13960 | |
| 13961 | // WebAssembly tables can't be used on RHS of an assignment expression. |
| 13962 | if (RHSType->isWebAssemblyTableType()) { |
| 13963 | Diag(Loc, DiagID: diag::err_wasm_table_art) << 0; |
| 13964 | return QualType(); |
| 13965 | } |
| 13966 | |
| 13967 | AssignConvertType ConvTy; |
| 13968 | if (CompoundType.isNull()) { |
| 13969 | Expr *RHSCheck = RHS.get(); |
| 13970 | |
| 13971 | CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this); |
| 13972 | |
| 13973 | QualType LHSTy(LHSType); |
| 13974 | ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS); |
| 13975 | if (RHS.isInvalid()) |
| 13976 | return QualType(); |
| 13977 | // Special case of NSObject attributes on c-style pointer types. |
| 13978 | if (ConvTy == AssignConvertType::IncompatiblePointer && |
| 13979 | ((Context.isObjCNSObjectType(Ty: LHSType) && |
| 13980 | RHSType->isObjCObjectPointerType()) || |
| 13981 | (Context.isObjCNSObjectType(Ty: RHSType) && |
| 13982 | LHSType->isObjCObjectPointerType()))) |
| 13983 | ConvTy = AssignConvertType::Compatible; |
| 13984 | |
| 13985 | if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType()) |
| 13986 | Diag(Loc, DiagID: diag::err_objc_object_assignment) << LHSType; |
| 13987 | |
| 13988 | // If the RHS is a unary plus or minus, check to see if they = and + are |
| 13989 | // right next to each other. If so, the user may have typo'd "x =+ 4" |
| 13990 | // instead of "x += 4". |
| 13991 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck)) |
| 13992 | RHSCheck = ICE->getSubExpr(); |
| 13993 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) { |
| 13994 | if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && |
| 13995 | Loc.isFileID() && UO->getOperatorLoc().isFileID() && |
| 13996 | // Only if the two operators are exactly adjacent. |
| 13997 | Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() && |
| 13998 | // And there is a space or other character before the subexpr of the |
| 13999 | // unary +/-. We don't want to warn on "x=-1". |
| 14000 | Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() && |
| 14001 | UO->getSubExpr()->getBeginLoc().isFileID()) { |
| 14002 | Diag(Loc, DiagID: diag::warn_not_compound_assign) |
| 14003 | << (UO->getOpcode() == UO_Plus ? "+" : "-" ) |
| 14004 | << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); |
| 14005 | } |
| 14006 | } |
| 14007 | |
| 14008 | if (IsAssignConvertCompatible(ConvTy)) { |
| 14009 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { |
| 14010 | // Warn about retain cycles where a block captures the LHS, but |
| 14011 | // not if the LHS is a simple variable into which the block is |
| 14012 | // being stored...unless that variable can be captured by reference! |
| 14013 | const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); |
| 14014 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS); |
| 14015 | if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) |
| 14016 | ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get()); |
| 14017 | } |
| 14018 | |
| 14019 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || |
| 14020 | LHSType.isNonWeakInMRRWithObjCWeak(Context)) { |
| 14021 | // It is safe to assign a weak reference into a strong variable. |
| 14022 | // Although this code can still have problems: |
| 14023 | // id x = self.weakProp; |
| 14024 | // id y = self.weakProp; |
| 14025 | // we do not warn to warn spuriously when 'x' and 'y' are on separate |
| 14026 | // paths through the function. This should be revisited if |
| 14027 | // -Wrepeated-use-of-weak is made flow-sensitive. |
| 14028 | // For ObjCWeak only, we do not warn if the assign is to a non-weak |
| 14029 | // variable, which will be valid for the current autorelease scope. |
| 14030 | if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, |
| 14031 | Loc: RHS.get()->getBeginLoc())) |
| 14032 | getCurFunction()->markSafeWeakUse(E: RHS.get()); |
| 14033 | |
| 14034 | } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { |
| 14035 | checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get()); |
| 14036 | } |
| 14037 | } |
| 14038 | } else { |
| 14039 | // Compound assignment "x += y" |
| 14040 | ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); |
| 14041 | } |
| 14042 | |
| 14043 | if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, SrcExpr: RHS.get(), |
| 14044 | Action: AssignmentAction::Assigning)) |
| 14045 | return QualType(); |
| 14046 | |
| 14047 | CheckForNullPointerDereference(S&: *this, E: LHSExpr); |
| 14048 | |
| 14049 | AssignedEntity AE{.LHS: LHSExpr}; |
| 14050 | checkAssignmentLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get()); |
| 14051 | |
| 14052 | if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { |
| 14053 | if (CompoundType.isNull()) { |
| 14054 | // C++2a [expr.ass]p5: |
| 14055 | // A simple-assignment whose left operand is of a volatile-qualified |
| 14056 | // type is deprecated unless the assignment is either a discarded-value |
| 14057 | // expression or an unevaluated operand |
| 14058 | ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr); |
| 14059 | } |
| 14060 | } |
| 14061 | |
| 14062 | // C11 6.5.16p3: The type of an assignment expression is the type of the |
| 14063 | // left operand would have after lvalue conversion. |
| 14064 | // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has |
| 14065 | // qualified type, the value has the unqualified version of the type of the |
| 14066 | // lvalue; additionally, if the lvalue has atomic type, the value has the |
| 14067 | // non-atomic version of the type of the lvalue. |
| 14068 | // C++ 5.17p1: the type of the assignment expression is that of its left |
| 14069 | // operand. |
| 14070 | return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType(); |
| 14071 | } |
| 14072 | |
| 14073 | // Scenarios to ignore if expression E is: |
| 14074 | // 1. an explicit cast expression into void |
| 14075 | // 2. a function call expression that returns void |
| 14076 | static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) { |
| 14077 | E = E->IgnoreParens(); |
| 14078 | |
| 14079 | if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) { |
| 14080 | if (CE->getCastKind() == CK_ToVoid) { |
| 14081 | return true; |
| 14082 | } |
| 14083 | |
| 14084 | // static_cast<void> on a dependent type will not show up as CK_ToVoid. |
| 14085 | if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && |
| 14086 | CE->getSubExpr()->getType()->isDependentType()) { |
| 14087 | return true; |
| 14088 | } |
| 14089 | } |
| 14090 | |
| 14091 | if (const auto *CE = dyn_cast<CallExpr>(Val: E)) |
| 14092 | return CE->getCallReturnType(Ctx: Context)->isVoidType(); |
| 14093 | return false; |
| 14094 | } |
| 14095 | |
| 14096 | void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { |
| 14097 | // No warnings in macros |
| 14098 | if (Loc.isMacroID()) |
| 14099 | return; |
| 14100 | |
| 14101 | // Don't warn in template instantiations. |
| 14102 | if (inTemplateInstantiation()) |
| 14103 | return; |
| 14104 | |
| 14105 | // Scope isn't fine-grained enough to explicitly list the specific cases, so |
| 14106 | // instead, skip more than needed, then call back into here with the |
| 14107 | // CommaVisitor in SemaStmt.cpp. |
| 14108 | // The listed locations are the initialization and increment portions |
| 14109 | // of a for loop. The additional checks are on the condition of |
| 14110 | // if statements, do/while loops, and for loops. |
| 14111 | // Differences in scope flags for C89 mode requires the extra logic. |
| 14112 | const unsigned ForIncrementFlags = |
| 14113 | getLangOpts().C99 || getLangOpts().CPlusPlus |
| 14114 | ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope |
| 14115 | : Scope::ContinueScope | Scope::BreakScope; |
| 14116 | const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; |
| 14117 | const unsigned ScopeFlags = getCurScope()->getFlags(); |
| 14118 | if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || |
| 14119 | (ScopeFlags & ForInitFlags) == ForInitFlags) |
| 14120 | return; |
| 14121 | |
| 14122 | // If there are multiple comma operators used together, get the RHS of the |
| 14123 | // of the comma operator as the LHS. |
| 14124 | while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) { |
| 14125 | if (BO->getOpcode() != BO_Comma) |
| 14126 | break; |
| 14127 | LHS = BO->getRHS(); |
| 14128 | } |
| 14129 | |
| 14130 | // Only allow some expressions on LHS to not warn. |
| 14131 | if (IgnoreCommaOperand(E: LHS, Context)) |
| 14132 | return; |
| 14133 | |
| 14134 | Diag(Loc, DiagID: diag::warn_comma_operator); |
| 14135 | Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_cast_to_void) |
| 14136 | << LHS->getSourceRange() |
| 14137 | << FixItHint::CreateInsertion(InsertionLoc: LHS->getBeginLoc(), |
| 14138 | Code: LangOpts.CPlusPlus ? "static_cast<void>(" |
| 14139 | : "(void)(" ) |
| 14140 | << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: LHS->getEndLoc()), |
| 14141 | Code: ")" ); |
| 14142 | } |
| 14143 | |
| 14144 | // C99 6.5.17 |
| 14145 | static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, |
| 14146 | SourceLocation Loc) { |
| 14147 | LHS = S.CheckPlaceholderExpr(E: LHS.get()); |
| 14148 | RHS = S.CheckPlaceholderExpr(E: RHS.get()); |
| 14149 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 14150 | return QualType(); |
| 14151 | |
| 14152 | // C's comma performs lvalue conversion (C99 6.3.2.1) on both its |
| 14153 | // operands, but not unary promotions. |
| 14154 | // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). |
| 14155 | |
| 14156 | // So we treat the LHS as a ignored value, and in C++ we allow the |
| 14157 | // containing site to determine what should be done with the RHS. |
| 14158 | LHS = S.IgnoredValueConversions(E: LHS.get()); |
| 14159 | if (LHS.isInvalid()) |
| 14160 | return QualType(); |
| 14161 | |
| 14162 | S.DiagnoseUnusedExprResult(S: LHS.get(), DiagID: diag::warn_unused_comma_left_operand); |
| 14163 | |
| 14164 | if (!S.getLangOpts().CPlusPlus) { |
| 14165 | RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
| 14166 | if (RHS.isInvalid()) |
| 14167 | return QualType(); |
| 14168 | if (!RHS.get()->getType()->isVoidType()) |
| 14169 | S.RequireCompleteType(Loc, T: RHS.get()->getType(), |
| 14170 | DiagID: diag::err_incomplete_type); |
| 14171 | } |
| 14172 | |
| 14173 | if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_comma_operator, Loc)) |
| 14174 | S.DiagnoseCommaOperator(LHS: LHS.get(), Loc); |
| 14175 | |
| 14176 | return RHS.get()->getType(); |
| 14177 | } |
| 14178 | |
| 14179 | /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine |
| 14180 | /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. |
| 14181 | static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, |
| 14182 | ExprValueKind &VK, |
| 14183 | ExprObjectKind &OK, |
| 14184 | SourceLocation OpLoc, bool IsInc, |
| 14185 | bool IsPrefix) { |
| 14186 | QualType ResType = Op->getType(); |
| 14187 | // Atomic types can be used for increment / decrement where the non-atomic |
| 14188 | // versions can, so ignore the _Atomic() specifier for the purpose of |
| 14189 | // checking. |
| 14190 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) |
| 14191 | ResType = ResAtomicType->getValueType(); |
| 14192 | |
| 14193 | assert(!ResType.isNull() && "no type for increment/decrement expression" ); |
| 14194 | |
| 14195 | if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { |
| 14196 | // Decrement of bool is not allowed. |
| 14197 | if (!IsInc) { |
| 14198 | S.Diag(Loc: OpLoc, DiagID: diag::err_decrement_bool) << Op->getSourceRange(); |
| 14199 | return QualType(); |
| 14200 | } |
| 14201 | // Increment of bool sets it to true, but is deprecated. |
| 14202 | S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool |
| 14203 | : diag::warn_increment_bool) |
| 14204 | << Op->getSourceRange(); |
| 14205 | } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { |
| 14206 | // Error on enum increments and decrements in C++ mode |
| 14207 | S.Diag(Loc: OpLoc, DiagID: diag::err_increment_decrement_enum) << IsInc << ResType; |
| 14208 | return QualType(); |
| 14209 | } else if (ResType->isRealType()) { |
| 14210 | // OK! |
| 14211 | } else if (ResType->isPointerType()) { |
| 14212 | // C99 6.5.2.4p2, 6.5.6p2 |
| 14213 | if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op)) |
| 14214 | return QualType(); |
| 14215 | } else if (ResType->isObjCObjectPointerType()) { |
| 14216 | // On modern runtimes, ObjC pointer arithmetic is forbidden. |
| 14217 | // Otherwise, we just need a complete type. |
| 14218 | if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) || |
| 14219 | checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op)) |
| 14220 | return QualType(); |
| 14221 | } else if (ResType->isAnyComplexType()) { |
| 14222 | // C99 does not support ++/-- on complex types, we allow as an extension. |
| 14223 | S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex |
| 14224 | : diag::ext_c2y_increment_complex) |
| 14225 | << IsInc << Op->getSourceRange(); |
| 14226 | } else if (ResType->isPlaceholderType()) { |
| 14227 | ExprResult PR = S.CheckPlaceholderExpr(E: Op); |
| 14228 | if (PR.isInvalid()) return QualType(); |
| 14229 | return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc, |
| 14230 | IsInc, IsPrefix); |
| 14231 | } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { |
| 14232 | // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) |
| 14233 | } else if (S.getLangOpts().ZVector && ResType->isVectorType() && |
| 14234 | (ResType->castAs<VectorType>()->getVectorKind() != |
| 14235 | VectorKind::AltiVecBool)) { |
| 14236 | // The z vector extensions allow ++ and -- for non-bool vectors. |
| 14237 | } else if (S.getLangOpts().OpenCL && ResType->isVectorType() && |
| 14238 | ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { |
| 14239 | // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. |
| 14240 | } else { |
| 14241 | S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_illegal_increment_decrement) |
| 14242 | << ResType << int(IsInc) << Op->getSourceRange(); |
| 14243 | return QualType(); |
| 14244 | } |
| 14245 | // At this point, we know we have a real, complex or pointer type. |
| 14246 | // Now make sure the operand is a modifiable lvalue. |
| 14247 | if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S)) |
| 14248 | return QualType(); |
| 14249 | if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { |
| 14250 | // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: |
| 14251 | // An operand with volatile-qualified type is deprecated |
| 14252 | S.Diag(Loc: OpLoc, DiagID: diag::warn_deprecated_increment_decrement_volatile) |
| 14253 | << IsInc << ResType; |
| 14254 | } |
| 14255 | // In C++, a prefix increment is the same type as the operand. Otherwise |
| 14256 | // (in C or with postfix), the increment is the unqualified type of the |
| 14257 | // operand. |
| 14258 | if (IsPrefix && S.getLangOpts().CPlusPlus) { |
| 14259 | VK = VK_LValue; |
| 14260 | OK = Op->getObjectKind(); |
| 14261 | return ResType; |
| 14262 | } else { |
| 14263 | VK = VK_PRValue; |
| 14264 | return ResType.getUnqualifiedType(); |
| 14265 | } |
| 14266 | } |
| 14267 | |
| 14268 | /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). |
| 14269 | /// This routine allows us to typecheck complex/recursive expressions |
| 14270 | /// where the declaration is needed for type checking. We only need to |
| 14271 | /// handle cases when the expression references a function designator |
| 14272 | /// or is an lvalue. Here are some examples: |
| 14273 | /// - &(x) => x |
| 14274 | /// - &*****f => f for f a function designator. |
| 14275 | /// - &s.xx => s |
| 14276 | /// - &s.zz[1].yy -> s, if zz is an array |
| 14277 | /// - *(x + 1) -> x, if x is an array |
| 14278 | /// - &"123"[2] -> 0 |
| 14279 | /// - & __real__ x -> x |
| 14280 | /// |
| 14281 | /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to |
| 14282 | /// members. |
| 14283 | static ValueDecl *getPrimaryDecl(Expr *E) { |
| 14284 | switch (E->getStmtClass()) { |
| 14285 | case Stmt::DeclRefExprClass: |
| 14286 | return cast<DeclRefExpr>(Val: E)->getDecl(); |
| 14287 | case Stmt::MemberExprClass: |
| 14288 | // If this is an arrow operator, the address is an offset from |
| 14289 | // the base's value, so the object the base refers to is |
| 14290 | // irrelevant. |
| 14291 | if (cast<MemberExpr>(Val: E)->isArrow()) |
| 14292 | return nullptr; |
| 14293 | // Otherwise, the expression refers to a part of the base |
| 14294 | return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase()); |
| 14295 | case Stmt::ArraySubscriptExprClass: { |
| 14296 | // FIXME: This code shouldn't be necessary! We should catch the implicit |
| 14297 | // promotion of register arrays earlier. |
| 14298 | Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase(); |
| 14299 | if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) { |
| 14300 | if (ICE->getSubExpr()->getType()->isArrayType()) |
| 14301 | return getPrimaryDecl(E: ICE->getSubExpr()); |
| 14302 | } |
| 14303 | return nullptr; |
| 14304 | } |
| 14305 | case Stmt::UnaryOperatorClass: { |
| 14306 | UnaryOperator *UO = cast<UnaryOperator>(Val: E); |
| 14307 | |
| 14308 | switch(UO->getOpcode()) { |
| 14309 | case UO_Real: |
| 14310 | case UO_Imag: |
| 14311 | case UO_Extension: |
| 14312 | return getPrimaryDecl(E: UO->getSubExpr()); |
| 14313 | default: |
| 14314 | return nullptr; |
| 14315 | } |
| 14316 | } |
| 14317 | case Stmt::ParenExprClass: |
| 14318 | return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr()); |
| 14319 | case Stmt::ImplicitCastExprClass: |
| 14320 | // If the result of an implicit cast is an l-value, we care about |
| 14321 | // the sub-expression; otherwise, the result here doesn't matter. |
| 14322 | return getPrimaryDecl(E: cast<ImplicitCastExpr>(Val: E)->getSubExpr()); |
| 14323 | case Stmt::CXXUuidofExprClass: |
| 14324 | return cast<CXXUuidofExpr>(Val: E)->getGuidDecl(); |
| 14325 | default: |
| 14326 | return nullptr; |
| 14327 | } |
| 14328 | } |
| 14329 | |
| 14330 | namespace { |
| 14331 | enum { |
| 14332 | AO_Bit_Field = 0, |
| 14333 | AO_Vector_Element = 1, |
| 14334 | AO_Property_Expansion = 2, |
| 14335 | AO_Register_Variable = 3, |
| 14336 | AO_Matrix_Element = 4, |
| 14337 | AO_No_Error = 5 |
| 14338 | }; |
| 14339 | } |
| 14340 | /// Diagnose invalid operand for address of operations. |
| 14341 | /// |
| 14342 | /// \param Type The type of operand which cannot have its address taken. |
| 14343 | static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, |
| 14344 | Expr *E, unsigned Type) { |
| 14345 | S.Diag(Loc, DiagID: diag::err_typecheck_address_of) << Type << E->getSourceRange(); |
| 14346 | } |
| 14347 | |
| 14348 | bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, |
| 14349 | const Expr *Op, |
| 14350 | const CXXMethodDecl *MD) { |
| 14351 | const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens()); |
| 14352 | |
| 14353 | if (Op != DRE) |
| 14354 | return Diag(Loc: OpLoc, DiagID: diag::err_parens_pointer_member_function) |
| 14355 | << Op->getSourceRange(); |
| 14356 | |
| 14357 | // Taking the address of a dtor is illegal per C++ [class.dtor]p2. |
| 14358 | if (isa<CXXDestructorDecl>(Val: MD)) |
| 14359 | return Diag(Loc: OpLoc, DiagID: diag::err_typecheck_addrof_dtor) |
| 14360 | << DRE->getSourceRange(); |
| 14361 | |
| 14362 | if (DRE->getQualifier()) |
| 14363 | return false; |
| 14364 | |
| 14365 | if (MD->getParent()->getName().empty()) |
| 14366 | return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function) |
| 14367 | << DRE->getSourceRange(); |
| 14368 | |
| 14369 | SmallString<32> Str; |
| 14370 | StringRef Qual = (MD->getParent()->getName() + "::" ).toStringRef(Out&: Str); |
| 14371 | return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function) |
| 14372 | << DRE->getSourceRange() |
| 14373 | << FixItHint::CreateInsertion(InsertionLoc: DRE->getSourceRange().getBegin(), Code: Qual); |
| 14374 | } |
| 14375 | |
| 14376 | QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { |
| 14377 | if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ |
| 14378 | if (PTy->getKind() == BuiltinType::Overload) { |
| 14379 | Expr *E = OrigOp.get()->IgnoreParens(); |
| 14380 | if (!isa<OverloadExpr>(Val: E)) { |
| 14381 | assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); |
| 14382 | Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof_addrof_function) |
| 14383 | << OrigOp.get()->getSourceRange(); |
| 14384 | return QualType(); |
| 14385 | } |
| 14386 | |
| 14387 | OverloadExpr *Ovl = cast<OverloadExpr>(Val: E); |
| 14388 | if (isa<UnresolvedMemberExpr>(Val: Ovl)) |
| 14389 | if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) { |
| 14390 | Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function) |
| 14391 | << OrigOp.get()->getSourceRange(); |
| 14392 | return QualType(); |
| 14393 | } |
| 14394 | |
| 14395 | return Context.OverloadTy; |
| 14396 | } |
| 14397 | |
| 14398 | if (PTy->getKind() == BuiltinType::UnknownAny) |
| 14399 | return Context.UnknownAnyTy; |
| 14400 | |
| 14401 | if (PTy->getKind() == BuiltinType::BoundMember) { |
| 14402 | Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function) |
| 14403 | << OrigOp.get()->getSourceRange(); |
| 14404 | return QualType(); |
| 14405 | } |
| 14406 | |
| 14407 | OrigOp = CheckPlaceholderExpr(E: OrigOp.get()); |
| 14408 | if (OrigOp.isInvalid()) return QualType(); |
| 14409 | } |
| 14410 | |
| 14411 | if (OrigOp.get()->isTypeDependent()) |
| 14412 | return Context.DependentTy; |
| 14413 | |
| 14414 | assert(!OrigOp.get()->hasPlaceholderType()); |
| 14415 | |
| 14416 | // Make sure to ignore parentheses in subsequent checks |
| 14417 | Expr *op = OrigOp.get()->IgnoreParens(); |
| 14418 | |
| 14419 | // In OpenCL captures for blocks called as lambda functions |
| 14420 | // are located in the private address space. Blocks used in |
| 14421 | // enqueue_kernel can be located in a different address space |
| 14422 | // depending on a vendor implementation. Thus preventing |
| 14423 | // taking an address of the capture to avoid invalid AS casts. |
| 14424 | if (LangOpts.OpenCL) { |
| 14425 | auto* VarRef = dyn_cast<DeclRefExpr>(Val: op); |
| 14426 | if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { |
| 14427 | Diag(Loc: op->getExprLoc(), DiagID: diag::err_opencl_taking_address_capture); |
| 14428 | return QualType(); |
| 14429 | } |
| 14430 | } |
| 14431 | |
| 14432 | if (getLangOpts().C99) { |
| 14433 | // Implement C99-only parts of addressof rules. |
| 14434 | if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) { |
| 14435 | if (uOp->getOpcode() == UO_Deref) |
| 14436 | // Per C99 6.5.3.2, the address of a deref always returns a valid result |
| 14437 | // (assuming the deref expression is valid). |
| 14438 | return uOp->getSubExpr()->getType(); |
| 14439 | } |
| 14440 | // Technically, there should be a check for array subscript |
| 14441 | // expressions here, but the result of one is always an lvalue anyway. |
| 14442 | } |
| 14443 | ValueDecl *dcl = getPrimaryDecl(E: op); |
| 14444 | |
| 14445 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl)) |
| 14446 | if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true, |
| 14447 | Loc: op->getBeginLoc())) |
| 14448 | return QualType(); |
| 14449 | |
| 14450 | Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context); |
| 14451 | unsigned AddressOfError = AO_No_Error; |
| 14452 | |
| 14453 | if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { |
| 14454 | bool sfinae = (bool)isSFINAEContext(); |
| 14455 | Diag(Loc: OpLoc, DiagID: isSFINAEContext() ? diag::err_typecheck_addrof_temporary |
| 14456 | : diag::ext_typecheck_addrof_temporary) |
| 14457 | << op->getType() << op->getSourceRange(); |
| 14458 | if (sfinae) |
| 14459 | return QualType(); |
| 14460 | // Materialize the temporary as an lvalue so that we can take its address. |
| 14461 | OrigOp = op = |
| 14462 | CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true); |
| 14463 | } else if (isa<ObjCSelectorExpr>(Val: op)) { |
| 14464 | return Context.getPointerType(T: op->getType()); |
| 14465 | } else if (lval == Expr::LV_MemberFunction) { |
| 14466 | // If it's an instance method, make a member pointer. |
| 14467 | // The expression must have exactly the form &A::foo. |
| 14468 | |
| 14469 | // If the underlying expression isn't a decl ref, give up. |
| 14470 | if (!isa<DeclRefExpr>(Val: op)) { |
| 14471 | Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function) |
| 14472 | << OrigOp.get()->getSourceRange(); |
| 14473 | return QualType(); |
| 14474 | } |
| 14475 | DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op); |
| 14476 | CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl()); |
| 14477 | |
| 14478 | CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD); |
| 14479 | QualType MPTy = Context.getMemberPointerType( |
| 14480 | T: op->getType(), Qualifier: DRE->getQualifier(), Cls: MD->getParent()); |
| 14481 | |
| 14482 | if (getLangOpts().PointerAuthCalls && MD->isVirtual() && |
| 14483 | !isUnevaluatedContext() && !MPTy->isDependentType()) { |
| 14484 | // When pointer authentication is enabled, argument and return types of |
| 14485 | // vitual member functions must be complete. This is because vitrual |
| 14486 | // member function pointers are implemented using virtual dispatch |
| 14487 | // thunks and the thunks cannot be emitted if the argument or return |
| 14488 | // types are incomplete. |
| 14489 | auto ReturnOrParamTypeIsIncomplete = [&](QualType T, |
| 14490 | SourceLocation DeclRefLoc, |
| 14491 | SourceLocation RetArgTypeLoc) { |
| 14492 | if (RequireCompleteType(Loc: DeclRefLoc, T, DiagID: diag::err_incomplete_type)) { |
| 14493 | Diag(Loc: DeclRefLoc, |
| 14494 | DiagID: diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret); |
| 14495 | Diag(Loc: RetArgTypeLoc, |
| 14496 | DiagID: diag::note_ptrauth_virtual_function_incomplete_arg_ret_type) |
| 14497 | << T; |
| 14498 | return true; |
| 14499 | } |
| 14500 | return false; |
| 14501 | }; |
| 14502 | QualType RetTy = MD->getReturnType(); |
| 14503 | bool IsIncomplete = |
| 14504 | !RetTy->isVoidType() && |
| 14505 | ReturnOrParamTypeIsIncomplete( |
| 14506 | RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin()); |
| 14507 | for (auto *PVD : MD->parameters()) |
| 14508 | IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc, |
| 14509 | PVD->getBeginLoc()); |
| 14510 | if (IsIncomplete) |
| 14511 | return QualType(); |
| 14512 | } |
| 14513 | |
| 14514 | // Under the MS ABI, lock down the inheritance model now. |
| 14515 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
| 14516 | (void)isCompleteType(Loc: OpLoc, T: MPTy); |
| 14517 | return MPTy; |
| 14518 | } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { |
| 14519 | // C99 6.5.3.2p1 |
| 14520 | // The operand must be either an l-value or a function designator |
| 14521 | if (!op->getType()->isFunctionType()) { |
| 14522 | // Use a special diagnostic for loads from property references. |
| 14523 | if (isa<PseudoObjectExpr>(Val: op)) { |
| 14524 | AddressOfError = AO_Property_Expansion; |
| 14525 | } else { |
| 14526 | Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof) |
| 14527 | << op->getType() << op->getSourceRange(); |
| 14528 | return QualType(); |
| 14529 | } |
| 14530 | } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) { |
| 14531 | if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl())) |
| 14532 | CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD); |
| 14533 | } |
| 14534 | |
| 14535 | } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 |
| 14536 | // The operand cannot be a bit-field |
| 14537 | AddressOfError = AO_Bit_Field; |
| 14538 | } else if (op->getObjectKind() == OK_VectorComponent) { |
| 14539 | // The operand cannot be an element of a vector |
| 14540 | AddressOfError = AO_Vector_Element; |
| 14541 | } else if (op->getObjectKind() == OK_MatrixComponent) { |
| 14542 | // The operand cannot be an element of a matrix. |
| 14543 | AddressOfError = AO_Matrix_Element; |
| 14544 | } else if (dcl) { // C99 6.5.3.2p1 |
| 14545 | // We have an lvalue with a decl. Make sure the decl is not declared |
| 14546 | // with the register storage-class specifier. |
| 14547 | if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) { |
| 14548 | // in C++ it is not error to take address of a register |
| 14549 | // variable (c++03 7.1.1P3) |
| 14550 | if (vd->getStorageClass() == SC_Register && |
| 14551 | !getLangOpts().CPlusPlus) { |
| 14552 | AddressOfError = AO_Register_Variable; |
| 14553 | } |
| 14554 | } else if (isa<MSPropertyDecl>(Val: dcl)) { |
| 14555 | AddressOfError = AO_Property_Expansion; |
| 14556 | } else if (isa<FunctionTemplateDecl>(Val: dcl)) { |
| 14557 | return Context.OverloadTy; |
| 14558 | } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) { |
| 14559 | // Okay: we can take the address of a field. |
| 14560 | // Could be a pointer to member, though, if there is an explicit |
| 14561 | // scope qualifier for the class. |
| 14562 | |
| 14563 | // [C++26] [expr.prim.id.general] |
| 14564 | // If an id-expression E denotes a non-static non-type member |
| 14565 | // of some class C [...] and if E is a qualified-id, E is |
| 14566 | // not the un-parenthesized operand of the unary & operator [...] |
| 14567 | // the id-expression is transformed into a class member access expression. |
| 14568 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: op); |
| 14569 | DRE && DRE->getQualifier() && !isa<ParenExpr>(Val: OrigOp.get())) { |
| 14570 | DeclContext *Ctx = dcl->getDeclContext(); |
| 14571 | if (Ctx && Ctx->isRecord()) { |
| 14572 | if (dcl->getType()->isReferenceType()) { |
| 14573 | Diag(Loc: OpLoc, |
| 14574 | DiagID: diag::err_cannot_form_pointer_to_member_of_reference_type) |
| 14575 | << dcl->getDeclName() << dcl->getType(); |
| 14576 | return QualType(); |
| 14577 | } |
| 14578 | |
| 14579 | while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion()) |
| 14580 | Ctx = Ctx->getParent(); |
| 14581 | |
| 14582 | QualType MPTy = Context.getMemberPointerType( |
| 14583 | T: op->getType(), Qualifier: DRE->getQualifier(), Cls: cast<CXXRecordDecl>(Val: Ctx)); |
| 14584 | // Under the MS ABI, lock down the inheritance model now. |
| 14585 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
| 14586 | (void)isCompleteType(Loc: OpLoc, T: MPTy); |
| 14587 | return MPTy; |
| 14588 | } |
| 14589 | } |
| 14590 | } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl, |
| 14591 | MSGuidDecl, UnnamedGlobalConstantDecl>(Val: dcl)) |
| 14592 | llvm_unreachable("Unknown/unexpected decl type" ); |
| 14593 | } |
| 14594 | |
| 14595 | if (AddressOfError != AO_No_Error) { |
| 14596 | diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError); |
| 14597 | return QualType(); |
| 14598 | } |
| 14599 | |
| 14600 | if (lval == Expr::LV_IncompleteVoidType) { |
| 14601 | // Taking the address of a void variable is technically illegal, but we |
| 14602 | // allow it in cases which are otherwise valid. |
| 14603 | // Example: "extern void x; void* y = &x;". |
| 14604 | Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_addrof_void) << op->getSourceRange(); |
| 14605 | } |
| 14606 | |
| 14607 | // If the operand has type "type", the result has type "pointer to type". |
| 14608 | if (op->getType()->isObjCObjectType()) |
| 14609 | return Context.getObjCObjectPointerType(OIT: op->getType()); |
| 14610 | |
| 14611 | // Cannot take the address of WebAssembly references or tables. |
| 14612 | if (Context.getTargetInfo().getTriple().isWasm()) { |
| 14613 | QualType OpTy = op->getType(); |
| 14614 | if (OpTy.isWebAssemblyReferenceType()) { |
| 14615 | Diag(Loc: OpLoc, DiagID: diag::err_wasm_ca_reference) |
| 14616 | << 1 << OrigOp.get()->getSourceRange(); |
| 14617 | return QualType(); |
| 14618 | } |
| 14619 | if (OpTy->isWebAssemblyTableType()) { |
| 14620 | Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_pr) |
| 14621 | << 1 << OrigOp.get()->getSourceRange(); |
| 14622 | return QualType(); |
| 14623 | } |
| 14624 | } |
| 14625 | |
| 14626 | CheckAddressOfPackedMember(rhs: op); |
| 14627 | |
| 14628 | return Context.getPointerType(T: op->getType()); |
| 14629 | } |
| 14630 | |
| 14631 | static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { |
| 14632 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp); |
| 14633 | if (!DRE) |
| 14634 | return; |
| 14635 | const Decl *D = DRE->getDecl(); |
| 14636 | if (!D) |
| 14637 | return; |
| 14638 | const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D); |
| 14639 | if (!Param) |
| 14640 | return; |
| 14641 | if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Val: Param->getDeclContext())) |
| 14642 | if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) |
| 14643 | return; |
| 14644 | if (FunctionScopeInfo *FD = S.getCurFunction()) |
| 14645 | FD->ModifiedNonNullParams.insert(Ptr: Param); |
| 14646 | } |
| 14647 | |
| 14648 | /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). |
| 14649 | static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, |
| 14650 | SourceLocation OpLoc, |
| 14651 | bool IsAfterAmp = false) { |
| 14652 | ExprResult ConvResult = S.UsualUnaryConversions(E: Op); |
| 14653 | if (ConvResult.isInvalid()) |
| 14654 | return QualType(); |
| 14655 | Op = ConvResult.get(); |
| 14656 | QualType OpTy = Op->getType(); |
| 14657 | QualType Result; |
| 14658 | |
| 14659 | if (isa<CXXReinterpretCastExpr>(Val: Op)) { |
| 14660 | QualType OpOrigType = Op->IgnoreParenCasts()->getType(); |
| 14661 | S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true, |
| 14662 | Range: Op->getSourceRange()); |
| 14663 | } |
| 14664 | |
| 14665 | if (const PointerType *PT = OpTy->getAs<PointerType>()) |
| 14666 | { |
| 14667 | Result = PT->getPointeeType(); |
| 14668 | } |
| 14669 | else if (const ObjCObjectPointerType *OPT = |
| 14670 | OpTy->getAs<ObjCObjectPointerType>()) |
| 14671 | Result = OPT->getPointeeType(); |
| 14672 | else { |
| 14673 | ExprResult PR = S.CheckPlaceholderExpr(E: Op); |
| 14674 | if (PR.isInvalid()) return QualType(); |
| 14675 | if (PR.get() != Op) |
| 14676 | return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc); |
| 14677 | } |
| 14678 | |
| 14679 | if (Result.isNull()) { |
| 14680 | S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_requires_pointer) |
| 14681 | << OpTy << Op->getSourceRange(); |
| 14682 | return QualType(); |
| 14683 | } |
| 14684 | |
| 14685 | if (Result->isVoidType()) { |
| 14686 | // C++ [expr.unary.op]p1: |
| 14687 | // [...] the expression to which [the unary * operator] is applied shall |
| 14688 | // be a pointer to an object type, or a pointer to a function type |
| 14689 | LangOptions LO = S.getLangOpts(); |
| 14690 | if (LO.CPlusPlus) |
| 14691 | S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_through_void_pointer_cpp) |
| 14692 | << OpTy << Op->getSourceRange(); |
| 14693 | else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext()) |
| 14694 | S.Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_indirection_through_void_pointer) |
| 14695 | << OpTy << Op->getSourceRange(); |
| 14696 | } |
| 14697 | |
| 14698 | // Dereferences are usually l-values... |
| 14699 | VK = VK_LValue; |
| 14700 | |
| 14701 | // ...except that certain expressions are never l-values in C. |
| 14702 | if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) |
| 14703 | VK = VK_PRValue; |
| 14704 | |
| 14705 | return Result; |
| 14706 | } |
| 14707 | |
| 14708 | BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { |
| 14709 | BinaryOperatorKind Opc; |
| 14710 | switch (Kind) { |
| 14711 | default: llvm_unreachable("Unknown binop!" ); |
| 14712 | case tok::periodstar: Opc = BO_PtrMemD; break; |
| 14713 | case tok::arrowstar: Opc = BO_PtrMemI; break; |
| 14714 | case tok::star: Opc = BO_Mul; break; |
| 14715 | case tok::slash: Opc = BO_Div; break; |
| 14716 | case tok::percent: Opc = BO_Rem; break; |
| 14717 | case tok::plus: Opc = BO_Add; break; |
| 14718 | case tok::minus: Opc = BO_Sub; break; |
| 14719 | case tok::lessless: Opc = BO_Shl; break; |
| 14720 | case tok::greatergreater: Opc = BO_Shr; break; |
| 14721 | case tok::lessequal: Opc = BO_LE; break; |
| 14722 | case tok::less: Opc = BO_LT; break; |
| 14723 | case tok::greaterequal: Opc = BO_GE; break; |
| 14724 | case tok::greater: Opc = BO_GT; break; |
| 14725 | case tok::exclaimequal: Opc = BO_NE; break; |
| 14726 | case tok::equalequal: Opc = BO_EQ; break; |
| 14727 | case tok::spaceship: Opc = BO_Cmp; break; |
| 14728 | case tok::amp: Opc = BO_And; break; |
| 14729 | case tok::caret: Opc = BO_Xor; break; |
| 14730 | case tok::pipe: Opc = BO_Or; break; |
| 14731 | case tok::ampamp: Opc = BO_LAnd; break; |
| 14732 | case tok::pipepipe: Opc = BO_LOr; break; |
| 14733 | case tok::equal: Opc = BO_Assign; break; |
| 14734 | case tok::starequal: Opc = BO_MulAssign; break; |
| 14735 | case tok::slashequal: Opc = BO_DivAssign; break; |
| 14736 | case tok::percentequal: Opc = BO_RemAssign; break; |
| 14737 | case tok::plusequal: Opc = BO_AddAssign; break; |
| 14738 | case tok::minusequal: Opc = BO_SubAssign; break; |
| 14739 | case tok::lesslessequal: Opc = BO_ShlAssign; break; |
| 14740 | case tok::greatergreaterequal: Opc = BO_ShrAssign; break; |
| 14741 | case tok::ampequal: Opc = BO_AndAssign; break; |
| 14742 | case tok::caretequal: Opc = BO_XorAssign; break; |
| 14743 | case tok::pipeequal: Opc = BO_OrAssign; break; |
| 14744 | case tok::comma: Opc = BO_Comma; break; |
| 14745 | } |
| 14746 | return Opc; |
| 14747 | } |
| 14748 | |
| 14749 | static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( |
| 14750 | tok::TokenKind Kind) { |
| 14751 | UnaryOperatorKind Opc; |
| 14752 | switch (Kind) { |
| 14753 | default: llvm_unreachable("Unknown unary op!" ); |
| 14754 | case tok::plusplus: Opc = UO_PreInc; break; |
| 14755 | case tok::minusminus: Opc = UO_PreDec; break; |
| 14756 | case tok::amp: Opc = UO_AddrOf; break; |
| 14757 | case tok::star: Opc = UO_Deref; break; |
| 14758 | case tok::plus: Opc = UO_Plus; break; |
| 14759 | case tok::minus: Opc = UO_Minus; break; |
| 14760 | case tok::tilde: Opc = UO_Not; break; |
| 14761 | case tok::exclaim: Opc = UO_LNot; break; |
| 14762 | case tok::kw___real: Opc = UO_Real; break; |
| 14763 | case tok::kw___imag: Opc = UO_Imag; break; |
| 14764 | case tok::kw___extension__: Opc = UO_Extension; break; |
| 14765 | } |
| 14766 | return Opc; |
| 14767 | } |
| 14768 | |
| 14769 | const FieldDecl * |
| 14770 | Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) { |
| 14771 | // Explore the case for adding 'this->' to the LHS of a self assignment, very |
| 14772 | // common for setters. |
| 14773 | // struct A { |
| 14774 | // int X; |
| 14775 | // -void setX(int X) { X = X; } |
| 14776 | // +void setX(int X) { this->X = X; } |
| 14777 | // }; |
| 14778 | |
| 14779 | // Only consider parameters for self assignment fixes. |
| 14780 | if (!isa<ParmVarDecl>(Val: SelfAssigned)) |
| 14781 | return nullptr; |
| 14782 | const auto *Method = |
| 14783 | dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true)); |
| 14784 | if (!Method) |
| 14785 | return nullptr; |
| 14786 | |
| 14787 | const CXXRecordDecl *Parent = Method->getParent(); |
| 14788 | // In theory this is fixable if the lambda explicitly captures this, but |
| 14789 | // that's added complexity that's rarely going to be used. |
| 14790 | if (Parent->isLambda()) |
| 14791 | return nullptr; |
| 14792 | |
| 14793 | // FIXME: Use an actual Lookup operation instead of just traversing fields |
| 14794 | // in order to get base class fields. |
| 14795 | auto Field = |
| 14796 | llvm::find_if(Range: Parent->fields(), |
| 14797 | P: [Name(SelfAssigned->getDeclName())](const FieldDecl *F) { |
| 14798 | return F->getDeclName() == Name; |
| 14799 | }); |
| 14800 | return (Field != Parent->field_end()) ? *Field : nullptr; |
| 14801 | } |
| 14802 | |
| 14803 | /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. |
| 14804 | /// This warning suppressed in the event of macro expansions. |
| 14805 | static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, |
| 14806 | SourceLocation OpLoc, bool IsBuiltin) { |
| 14807 | if (S.inTemplateInstantiation()) |
| 14808 | return; |
| 14809 | if (S.isUnevaluatedContext()) |
| 14810 | return; |
| 14811 | if (OpLoc.isInvalid() || OpLoc.isMacroID()) |
| 14812 | return; |
| 14813 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); |
| 14814 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); |
| 14815 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr); |
| 14816 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr); |
| 14817 | if (!LHSDeclRef || !RHSDeclRef || |
| 14818 | LHSDeclRef->getLocation().isMacroID() || |
| 14819 | RHSDeclRef->getLocation().isMacroID()) |
| 14820 | return; |
| 14821 | const ValueDecl *LHSDecl = |
| 14822 | cast<ValueDecl>(Val: LHSDeclRef->getDecl()->getCanonicalDecl()); |
| 14823 | const ValueDecl *RHSDecl = |
| 14824 | cast<ValueDecl>(Val: RHSDeclRef->getDecl()->getCanonicalDecl()); |
| 14825 | if (LHSDecl != RHSDecl) |
| 14826 | return; |
| 14827 | if (LHSDecl->getType().isVolatileQualified()) |
| 14828 | return; |
| 14829 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) |
| 14830 | if (RefTy->getPointeeType().isVolatileQualified()) |
| 14831 | return; |
| 14832 | |
| 14833 | auto Diag = S.Diag(Loc: OpLoc, DiagID: IsBuiltin ? diag::warn_self_assignment_builtin |
| 14834 | : diag::warn_self_assignment_overloaded) |
| 14835 | << LHSDeclRef->getType() << LHSExpr->getSourceRange() |
| 14836 | << RHSExpr->getSourceRange(); |
| 14837 | if (const FieldDecl *SelfAssignField = |
| 14838 | S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl)) |
| 14839 | Diag << 1 << SelfAssignField |
| 14840 | << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->" ); |
| 14841 | else |
| 14842 | Diag << 0; |
| 14843 | } |
| 14844 | |
| 14845 | /// Check if a bitwise-& is performed on an Objective-C pointer. This |
| 14846 | /// is usually indicative of introspection within the Objective-C pointer. |
| 14847 | static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, |
| 14848 | SourceLocation OpLoc) { |
| 14849 | if (!S.getLangOpts().ObjC) |
| 14850 | return; |
| 14851 | |
| 14852 | const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; |
| 14853 | const Expr *LHS = L.get(); |
| 14854 | const Expr *RHS = R.get(); |
| 14855 | |
| 14856 | if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { |
| 14857 | ObjCPointerExpr = LHS; |
| 14858 | OtherExpr = RHS; |
| 14859 | } |
| 14860 | else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { |
| 14861 | ObjCPointerExpr = RHS; |
| 14862 | OtherExpr = LHS; |
| 14863 | } |
| 14864 | |
| 14865 | // This warning is deliberately made very specific to reduce false |
| 14866 | // positives with logic that uses '&' for hashing. This logic mainly |
| 14867 | // looks for code trying to introspect into tagged pointers, which |
| 14868 | // code should generally never do. |
| 14869 | if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) { |
| 14870 | unsigned Diag = diag::warn_objc_pointer_masking; |
| 14871 | // Determine if we are introspecting the result of performSelectorXXX. |
| 14872 | const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); |
| 14873 | // Special case messages to -performSelector and friends, which |
| 14874 | // can return non-pointer values boxed in a pointer value. |
| 14875 | // Some clients may wish to silence warnings in this subcase. |
| 14876 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) { |
| 14877 | Selector S = ME->getSelector(); |
| 14878 | StringRef SelArg0 = S.getNameForSlot(argIndex: 0); |
| 14879 | if (SelArg0.starts_with(Prefix: "performSelector" )) |
| 14880 | Diag = diag::warn_objc_pointer_masking_performSelector; |
| 14881 | } |
| 14882 | |
| 14883 | S.Diag(Loc: OpLoc, DiagID: Diag) |
| 14884 | << ObjCPointerExpr->getSourceRange(); |
| 14885 | } |
| 14886 | } |
| 14887 | |
| 14888 | // This helper function promotes a binary operator's operands (which are of a |
| 14889 | // half vector type) to a vector of floats and then truncates the result to |
| 14890 | // a vector of either half or short. |
| 14891 | static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, |
| 14892 | BinaryOperatorKind Opc, QualType ResultTy, |
| 14893 | ExprValueKind VK, ExprObjectKind OK, |
| 14894 | bool IsCompAssign, SourceLocation OpLoc, |
| 14895 | FPOptionsOverride FPFeatures) { |
| 14896 | auto &Context = S.getASTContext(); |
| 14897 | assert((isVector(ResultTy, Context.HalfTy) || |
| 14898 | isVector(ResultTy, Context.ShortTy)) && |
| 14899 | "Result must be a vector of half or short" ); |
| 14900 | assert(isVector(LHS.get()->getType(), Context.HalfTy) && |
| 14901 | isVector(RHS.get()->getType(), Context.HalfTy) && |
| 14902 | "both operands expected to be a half vector" ); |
| 14903 | |
| 14904 | RHS = convertVector(E: RHS.get(), ElementType: Context.FloatTy, S); |
| 14905 | QualType BinOpResTy = RHS.get()->getType(); |
| 14906 | |
| 14907 | // If Opc is a comparison, ResultType is a vector of shorts. In that case, |
| 14908 | // change BinOpResTy to a vector of ints. |
| 14909 | if (isVector(QT: ResultTy, ElementType: Context.ShortTy)) |
| 14910 | BinOpResTy = S.GetSignedVectorType(V: BinOpResTy); |
| 14911 | |
| 14912 | if (IsCompAssign) |
| 14913 | return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, |
| 14914 | ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures, |
| 14915 | CompLHSType: BinOpResTy, CompResultType: BinOpResTy); |
| 14916 | |
| 14917 | LHS = convertVector(E: LHS.get(), ElementType: Context.FloatTy, S); |
| 14918 | auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, |
| 14919 | ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures); |
| 14920 | return convertVector(E: BO, ElementType: ResultTy->castAs<VectorType>()->getElementType(), S); |
| 14921 | } |
| 14922 | |
| 14923 | /// Returns true if conversion between vectors of halfs and vectors of floats |
| 14924 | /// is needed. |
| 14925 | static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, |
| 14926 | Expr *E0, Expr *E1 = nullptr) { |
| 14927 | if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || |
| 14928 | Ctx.getTargetInfo().useFP16ConversionIntrinsics()) |
| 14929 | return false; |
| 14930 | |
| 14931 | auto HasVectorOfHalfType = [&Ctx](Expr *E) { |
| 14932 | QualType Ty = E->IgnoreImplicit()->getType(); |
| 14933 | |
| 14934 | // Don't promote half precision neon vectors like float16x4_t in arm_neon.h |
| 14935 | // to vectors of floats. Although the element type of the vectors is __fp16, |
| 14936 | // the vectors shouldn't be treated as storage-only types. See the |
| 14937 | // discussion here: https://reviews.llvm.org/rG825235c140e7 |
| 14938 | if (const VectorType *VT = Ty->getAs<VectorType>()) { |
| 14939 | if (VT->getVectorKind() == VectorKind::Neon) |
| 14940 | return false; |
| 14941 | return VT->getElementType().getCanonicalType() == Ctx.HalfTy; |
| 14942 | } |
| 14943 | return false; |
| 14944 | }; |
| 14945 | |
| 14946 | return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); |
| 14947 | } |
| 14948 | |
| 14949 | ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, |
| 14950 | BinaryOperatorKind Opc, Expr *LHSExpr, |
| 14951 | Expr *RHSExpr, bool ForFoldExpression) { |
| 14952 | if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) { |
| 14953 | // The syntax only allows initializer lists on the RHS of assignment, |
| 14954 | // so we don't need to worry about accepting invalid code for |
| 14955 | // non-assignment operators. |
| 14956 | // C++11 5.17p9: |
| 14957 | // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning |
| 14958 | // of x = {} is x = T(). |
| 14959 | InitializationKind Kind = InitializationKind::CreateDirectList( |
| 14960 | InitLoc: RHSExpr->getBeginLoc(), LBraceLoc: RHSExpr->getBeginLoc(), RBraceLoc: RHSExpr->getEndLoc()); |
| 14961 | InitializedEntity Entity = |
| 14962 | InitializedEntity::InitializeTemporary(Type: LHSExpr->getType()); |
| 14963 | InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); |
| 14964 | ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr); |
| 14965 | if (Init.isInvalid()) |
| 14966 | return Init; |
| 14967 | RHSExpr = Init.get(); |
| 14968 | } |
| 14969 | |
| 14970 | ExprResult LHS = LHSExpr, RHS = RHSExpr; |
| 14971 | QualType ResultTy; // Result type of the binary operator. |
| 14972 | // The following two variables are used for compound assignment operators |
| 14973 | QualType CompLHSTy; // Type of LHS after promotions for computation |
| 14974 | QualType CompResultTy; // Type of computation result |
| 14975 | ExprValueKind VK = VK_PRValue; |
| 14976 | ExprObjectKind OK = OK_Ordinary; |
| 14977 | bool ConvertHalfVec = false; |
| 14978 | |
| 14979 | if (!LHS.isUsable() || !RHS.isUsable()) |
| 14980 | return ExprError(); |
| 14981 | |
| 14982 | if (getLangOpts().OpenCL) { |
| 14983 | QualType LHSTy = LHSExpr->getType(); |
| 14984 | QualType RHSTy = RHSExpr->getType(); |
| 14985 | // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by |
| 14986 | // the ATOMIC_VAR_INIT macro. |
| 14987 | if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { |
| 14988 | SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
| 14989 | if (BO_Assign == Opc) |
| 14990 | Diag(Loc: OpLoc, DiagID: diag::err_opencl_atomic_init) << 0 << SR; |
| 14991 | else |
| 14992 | ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS); |
| 14993 | return ExprError(); |
| 14994 | } |
| 14995 | |
| 14996 | // OpenCL special types - image, sampler, pipe, and blocks are to be used |
| 14997 | // only with a builtin functions and therefore should be disallowed here. |
| 14998 | if (LHSTy->isImageType() || RHSTy->isImageType() || |
| 14999 | LHSTy->isSamplerT() || RHSTy->isSamplerT() || |
| 15000 | LHSTy->isPipeType() || RHSTy->isPipeType() || |
| 15001 | LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { |
| 15002 | ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS); |
| 15003 | return ExprError(); |
| 15004 | } |
| 15005 | } |
| 15006 | |
| 15007 | checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr); |
| 15008 | checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr); |
| 15009 | |
| 15010 | switch (Opc) { |
| 15011 | case BO_Assign: |
| 15012 | ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc); |
| 15013 | if (getLangOpts().CPlusPlus && |
| 15014 | LHS.get()->getObjectKind() != OK_ObjCProperty) { |
| 15015 | VK = LHS.get()->getValueKind(); |
| 15016 | OK = LHS.get()->getObjectKind(); |
| 15017 | } |
| 15018 | if (!ResultTy.isNull()) { |
| 15019 | DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true); |
| 15020 | DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc); |
| 15021 | |
| 15022 | // Avoid copying a block to the heap if the block is assigned to a local |
| 15023 | // auto variable that is declared in the same scope as the block. This |
| 15024 | // optimization is unsafe if the local variable is declared in an outer |
| 15025 | // scope. For example: |
| 15026 | // |
| 15027 | // BlockTy b; |
| 15028 | // { |
| 15029 | // b = ^{...}; |
| 15030 | // } |
| 15031 | // // It is unsafe to invoke the block here if it wasn't copied to the |
| 15032 | // // heap. |
| 15033 | // b(); |
| 15034 | |
| 15035 | if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens())) |
| 15036 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens())) |
| 15037 | if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl())) |
| 15038 | if (VD->hasLocalStorage() && getCurScope()->isDeclScope(D: VD)) |
| 15039 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); |
| 15040 | |
| 15041 | if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) |
| 15042 | checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(), |
| 15043 | UseContext: NonTrivialCUnionContext::Assignment, NonTrivialKind: NTCUK_Copy); |
| 15044 | } |
| 15045 | RecordModifiableNonNullParam(S&: *this, Exp: LHS.get()); |
| 15046 | break; |
| 15047 | case BO_PtrMemD: |
| 15048 | case BO_PtrMemI: |
| 15049 | ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, |
| 15050 | isIndirect: Opc == BO_PtrMemI); |
| 15051 | break; |
| 15052 | case BO_Mul: |
| 15053 | case BO_Div: |
| 15054 | ConvertHalfVec = true; |
| 15055 | ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: false, |
| 15056 | IsDiv: Opc == BO_Div); |
| 15057 | break; |
| 15058 | case BO_Rem: |
| 15059 | ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc); |
| 15060 | break; |
| 15061 | case BO_Add: |
| 15062 | ConvertHalfVec = true; |
| 15063 | ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc); |
| 15064 | break; |
| 15065 | case BO_Sub: |
| 15066 | ConvertHalfVec = true; |
| 15067 | ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc); |
| 15068 | break; |
| 15069 | case BO_Shl: |
| 15070 | case BO_Shr: |
| 15071 | ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc); |
| 15072 | break; |
| 15073 | case BO_LE: |
| 15074 | case BO_LT: |
| 15075 | case BO_GE: |
| 15076 | case BO_GT: |
| 15077 | ConvertHalfVec = true; |
| 15078 | ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc); |
| 15079 | |
| 15080 | if (const auto *BI = dyn_cast<BinaryOperator>(Val: LHSExpr); |
| 15081 | !ForFoldExpression && BI && BI->isComparisonOp()) |
| 15082 | Diag(Loc: OpLoc, DiagID: diag::warn_consecutive_comparison) |
| 15083 | << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc); |
| 15084 | |
| 15085 | break; |
| 15086 | case BO_EQ: |
| 15087 | case BO_NE: |
| 15088 | ConvertHalfVec = true; |
| 15089 | ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc); |
| 15090 | break; |
| 15091 | case BO_Cmp: |
| 15092 | ConvertHalfVec = true; |
| 15093 | ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc); |
| 15094 | assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); |
| 15095 | break; |
| 15096 | case BO_And: |
| 15097 | checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc); |
| 15098 | [[fallthrough]]; |
| 15099 | case BO_Xor: |
| 15100 | case BO_Or: |
| 15101 | ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc); |
| 15102 | break; |
| 15103 | case BO_LAnd: |
| 15104 | case BO_LOr: |
| 15105 | ConvertHalfVec = true; |
| 15106 | ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc); |
| 15107 | break; |
| 15108 | case BO_MulAssign: |
| 15109 | case BO_DivAssign: |
| 15110 | ConvertHalfVec = true; |
| 15111 | CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true, |
| 15112 | IsDiv: Opc == BO_DivAssign); |
| 15113 | CompLHSTy = CompResultTy; |
| 15114 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
| 15115 | ResultTy = |
| 15116 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
| 15117 | break; |
| 15118 | case BO_RemAssign: |
| 15119 | CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true); |
| 15120 | CompLHSTy = CompResultTy; |
| 15121 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
| 15122 | ResultTy = |
| 15123 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
| 15124 | break; |
| 15125 | case BO_AddAssign: |
| 15126 | ConvertHalfVec = true; |
| 15127 | CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy); |
| 15128 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
| 15129 | ResultTy = |
| 15130 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
| 15131 | break; |
| 15132 | case BO_SubAssign: |
| 15133 | ConvertHalfVec = true; |
| 15134 | CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, CompLHSTy: &CompLHSTy); |
| 15135 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
| 15136 | ResultTy = |
| 15137 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
| 15138 | break; |
| 15139 | case BO_ShlAssign: |
| 15140 | case BO_ShrAssign: |
| 15141 | CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true); |
| 15142 | CompLHSTy = CompResultTy; |
| 15143 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
| 15144 | ResultTy = |
| 15145 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
| 15146 | break; |
| 15147 | case BO_AndAssign: |
| 15148 | case BO_OrAssign: // fallthrough |
| 15149 | DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true); |
| 15150 | [[fallthrough]]; |
| 15151 | case BO_XorAssign: |
| 15152 | CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc); |
| 15153 | CompLHSTy = CompResultTy; |
| 15154 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
| 15155 | ResultTy = |
| 15156 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
| 15157 | break; |
| 15158 | case BO_Comma: |
| 15159 | ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc); |
| 15160 | if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { |
| 15161 | VK = RHS.get()->getValueKind(); |
| 15162 | OK = RHS.get()->getObjectKind(); |
| 15163 | } |
| 15164 | break; |
| 15165 | } |
| 15166 | if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) |
| 15167 | return ExprError(); |
| 15168 | |
| 15169 | // Some of the binary operations require promoting operands of half vector to |
| 15170 | // float vectors and truncating the result back to half vector. For now, we do |
| 15171 | // this only when HalfArgsAndReturn is set (that is, when the target is arm or |
| 15172 | // arm64). |
| 15173 | assert( |
| 15174 | (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == |
| 15175 | isVector(LHS.get()->getType(), Context.HalfTy)) && |
| 15176 | "both sides are half vectors or neither sides are" ); |
| 15177 | ConvertHalfVec = |
| 15178 | needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, E0: LHS.get(), E1: RHS.get()); |
| 15179 | |
| 15180 | // Check for array bounds violations for both sides of the BinaryOperator |
| 15181 | CheckArrayAccess(E: LHS.get()); |
| 15182 | CheckArrayAccess(E: RHS.get()); |
| 15183 | |
| 15184 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) { |
| 15185 | NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope, |
| 15186 | Name: &Context.Idents.get(Name: "object_setClass" ), |
| 15187 | Loc: SourceLocation(), NameKind: LookupOrdinaryName); |
| 15188 | if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) { |
| 15189 | SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc()); |
| 15190 | Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign) |
| 15191 | << FixItHint::CreateInsertion(InsertionLoc: LHS.get()->getBeginLoc(), |
| 15192 | Code: "object_setClass(" ) |
| 15193 | << FixItHint::CreateReplacement(RemoveRange: SourceRange(OISA->getOpLoc(), OpLoc), |
| 15194 | Code: "," ) |
| 15195 | << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")" ); |
| 15196 | } |
| 15197 | else |
| 15198 | Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign); |
| 15199 | } |
| 15200 | else if (const ObjCIvarRefExpr *OIRE = |
| 15201 | dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts())) |
| 15202 | DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get()); |
| 15203 | |
| 15204 | // Opc is not a compound assignment if CompResultTy is null. |
| 15205 | if (CompResultTy.isNull()) { |
| 15206 | if (ConvertHalfVec) |
| 15207 | return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false, |
| 15208 | OpLoc, FPFeatures: CurFPFeatureOverrides()); |
| 15209 | return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, |
| 15210 | VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides()); |
| 15211 | } |
| 15212 | |
| 15213 | // Handle compound assignments. |
| 15214 | if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != |
| 15215 | OK_ObjCProperty) { |
| 15216 | VK = VK_LValue; |
| 15217 | OK = LHS.get()->getObjectKind(); |
| 15218 | } |
| 15219 | |
| 15220 | // The LHS is not converted to the result type for fixed-point compound |
| 15221 | // assignment as the common type is computed on demand. Reset the CompLHSTy |
| 15222 | // to the LHS type we would have gotten after unary conversions. |
| 15223 | if (CompResultTy->isFixedPointType()) |
| 15224 | CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType(); |
| 15225 | |
| 15226 | if (ConvertHalfVec) |
| 15227 | return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true, |
| 15228 | OpLoc, FPFeatures: CurFPFeatureOverrides()); |
| 15229 | |
| 15230 | return CompoundAssignOperator::Create( |
| 15231 | C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc, |
| 15232 | FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy); |
| 15233 | } |
| 15234 | |
| 15235 | /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison |
| 15236 | /// operators are mixed in a way that suggests that the programmer forgot that |
| 15237 | /// comparison operators have higher precedence. The most typical example of |
| 15238 | /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". |
| 15239 | static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, |
| 15240 | SourceLocation OpLoc, Expr *LHSExpr, |
| 15241 | Expr *RHSExpr) { |
| 15242 | BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr); |
| 15243 | BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr); |
| 15244 | |
| 15245 | // Check that one of the sides is a comparison operator and the other isn't. |
| 15246 | bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); |
| 15247 | bool isRightComp = RHSBO && RHSBO->isComparisonOp(); |
| 15248 | if (isLeftComp == isRightComp) |
| 15249 | return; |
| 15250 | |
| 15251 | // Bitwise operations are sometimes used as eager logical ops. |
| 15252 | // Don't diagnose this. |
| 15253 | bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); |
| 15254 | bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); |
| 15255 | if (isLeftBitwise || isRightBitwise) |
| 15256 | return; |
| 15257 | |
| 15258 | SourceRange DiagRange = isLeftComp |
| 15259 | ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) |
| 15260 | : SourceRange(OpLoc, RHSExpr->getEndLoc()); |
| 15261 | StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); |
| 15262 | SourceRange ParensRange = |
| 15263 | isLeftComp |
| 15264 | ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) |
| 15265 | : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); |
| 15266 | |
| 15267 | Self.Diag(Loc: OpLoc, DiagID: diag::warn_precedence_bitwise_rel) |
| 15268 | << DiagRange << BinaryOperator::getOpcodeStr(Op: Opc) << OpStr; |
| 15269 | SuggestParentheses(Self, Loc: OpLoc, |
| 15270 | Note: Self.PDiag(DiagID: diag::note_precedence_silence) << OpStr, |
| 15271 | ParenRange: (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); |
| 15272 | SuggestParentheses(Self, Loc: OpLoc, |
| 15273 | Note: Self.PDiag(DiagID: diag::note_precedence_bitwise_first) |
| 15274 | << BinaryOperator::getOpcodeStr(Op: Opc), |
| 15275 | ParenRange: ParensRange); |
| 15276 | } |
| 15277 | |
| 15278 | /// It accepts a '&&' expr that is inside a '||' one. |
| 15279 | /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression |
| 15280 | /// in parentheses. |
| 15281 | static void |
| 15282 | EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, |
| 15283 | BinaryOperator *Bop) { |
| 15284 | assert(Bop->getOpcode() == BO_LAnd); |
| 15285 | Self.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_logical_and_in_logical_or) |
| 15286 | << Bop->getSourceRange() << OpLoc; |
| 15287 | SuggestParentheses(Self, Loc: Bop->getOperatorLoc(), |
| 15288 | Note: Self.PDiag(DiagID: diag::note_precedence_silence) |
| 15289 | << Bop->getOpcodeStr(), |
| 15290 | ParenRange: Bop->getSourceRange()); |
| 15291 | } |
| 15292 | |
| 15293 | /// Look for '&&' in the left hand of a '||' expr. |
| 15294 | static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, |
| 15295 | Expr *LHSExpr, Expr *RHSExpr) { |
| 15296 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) { |
| 15297 | if (Bop->getOpcode() == BO_LAnd) { |
| 15298 | // If it's "string_literal && a || b" don't warn since the precedence |
| 15299 | // doesn't matter. |
| 15300 | if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts())) |
| 15301 | return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop); |
| 15302 | } else if (Bop->getOpcode() == BO_LOr) { |
| 15303 | if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) { |
| 15304 | // If it's "a || b && string_literal || c" we didn't warn earlier for |
| 15305 | // "a || b && string_literal", but warn now. |
| 15306 | if (RBop->getOpcode() == BO_LAnd && |
| 15307 | isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts())) |
| 15308 | return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop); |
| 15309 | } |
| 15310 | } |
| 15311 | } |
| 15312 | } |
| 15313 | |
| 15314 | /// Look for '&&' in the right hand of a '||' expr. |
| 15315 | static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, |
| 15316 | Expr *LHSExpr, Expr *RHSExpr) { |
| 15317 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) { |
| 15318 | if (Bop->getOpcode() == BO_LAnd) { |
| 15319 | // If it's "a || b && string_literal" don't warn since the precedence |
| 15320 | // doesn't matter. |
| 15321 | if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts())) |
| 15322 | return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop); |
| 15323 | } |
| 15324 | } |
| 15325 | } |
| 15326 | |
| 15327 | /// Look for bitwise op in the left or right hand of a bitwise op with |
| 15328 | /// lower precedence and emit a diagnostic together with a fixit hint that wraps |
| 15329 | /// the '&' expression in parentheses. |
| 15330 | static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, |
| 15331 | SourceLocation OpLoc, Expr *SubExpr) { |
| 15332 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) { |
| 15333 | if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { |
| 15334 | S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_bitwise_op_in_bitwise_op) |
| 15335 | << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc) |
| 15336 | << Bop->getSourceRange() << OpLoc; |
| 15337 | SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(), |
| 15338 | Note: S.PDiag(DiagID: diag::note_precedence_silence) |
| 15339 | << Bop->getOpcodeStr(), |
| 15340 | ParenRange: Bop->getSourceRange()); |
| 15341 | } |
| 15342 | } |
| 15343 | } |
| 15344 | |
| 15345 | static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, |
| 15346 | Expr *SubExpr, StringRef Shift) { |
| 15347 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) { |
| 15348 | if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { |
| 15349 | StringRef Op = Bop->getOpcodeStr(); |
| 15350 | S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_addition_in_bitshift) |
| 15351 | << Bop->getSourceRange() << OpLoc << Shift << Op; |
| 15352 | SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(), |
| 15353 | Note: S.PDiag(DiagID: diag::note_precedence_silence) << Op, |
| 15354 | ParenRange: Bop->getSourceRange()); |
| 15355 | } |
| 15356 | } |
| 15357 | } |
| 15358 | |
| 15359 | static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, |
| 15360 | Expr *LHSExpr, Expr *RHSExpr) { |
| 15361 | CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr); |
| 15362 | if (!OCE) |
| 15363 | return; |
| 15364 | |
| 15365 | FunctionDecl *FD = OCE->getDirectCallee(); |
| 15366 | if (!FD || !FD->isOverloadedOperator()) |
| 15367 | return; |
| 15368 | |
| 15369 | OverloadedOperatorKind Kind = FD->getOverloadedOperator(); |
| 15370 | if (Kind != OO_LessLess && Kind != OO_GreaterGreater) |
| 15371 | return; |
| 15372 | |
| 15373 | S.Diag(Loc: OpLoc, DiagID: diag::warn_overloaded_shift_in_comparison) |
| 15374 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() |
| 15375 | << (Kind == OO_LessLess); |
| 15376 | SuggestParentheses(Self&: S, Loc: OCE->getOperatorLoc(), |
| 15377 | Note: S.PDiag(DiagID: diag::note_precedence_silence) |
| 15378 | << (Kind == OO_LessLess ? "<<" : ">>" ), |
| 15379 | ParenRange: OCE->getSourceRange()); |
| 15380 | SuggestParentheses( |
| 15381 | Self&: S, Loc: OpLoc, Note: S.PDiag(DiagID: diag::note_evaluate_comparison_first), |
| 15382 | ParenRange: SourceRange(OCE->getArg(Arg: 1)->getBeginLoc(), RHSExpr->getEndLoc())); |
| 15383 | } |
| 15384 | |
| 15385 | /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky |
| 15386 | /// precedence. |
| 15387 | static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, |
| 15388 | SourceLocation OpLoc, Expr *LHSExpr, |
| 15389 | Expr *RHSExpr){ |
| 15390 | // Diagnose "arg1 'bitwise' arg2 'eq' arg3". |
| 15391 | if (BinaryOperator::isBitwiseOp(Opc)) |
| 15392 | DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); |
| 15393 | |
| 15394 | // Diagnose "arg1 & arg2 | arg3" |
| 15395 | if ((Opc == BO_Or || Opc == BO_Xor) && |
| 15396 | !OpLoc.isMacroID()/* Don't warn in macros. */) { |
| 15397 | DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr); |
| 15398 | DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr); |
| 15399 | } |
| 15400 | |
| 15401 | // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. |
| 15402 | // We don't warn for 'assert(a || b && "bad")' since this is safe. |
| 15403 | if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { |
| 15404 | DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr); |
| 15405 | DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr); |
| 15406 | } |
| 15407 | |
| 15408 | if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext())) |
| 15409 | || Opc == BO_Shr) { |
| 15410 | StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc); |
| 15411 | DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift); |
| 15412 | DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift); |
| 15413 | } |
| 15414 | |
| 15415 | // Warn on overloaded shift operators and comparisons, such as: |
| 15416 | // cout << 5 == 4; |
| 15417 | if (BinaryOperator::isComparisonOp(Opc)) |
| 15418 | DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr); |
| 15419 | } |
| 15420 | |
| 15421 | ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, |
| 15422 | tok::TokenKind Kind, |
| 15423 | Expr *LHSExpr, Expr *RHSExpr) { |
| 15424 | BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); |
| 15425 | assert(LHSExpr && "ActOnBinOp(): missing left expression" ); |
| 15426 | assert(RHSExpr && "ActOnBinOp(): missing right expression" ); |
| 15427 | |
| 15428 | // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" |
| 15429 | DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr); |
| 15430 | |
| 15431 | BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc) |
| 15432 | ? BuiltinCountedByRefKind::Assignment |
| 15433 | : BuiltinCountedByRefKind::BinaryExpr; |
| 15434 | |
| 15435 | CheckInvalidBuiltinCountedByRef(E: LHSExpr, K); |
| 15436 | CheckInvalidBuiltinCountedByRef(E: RHSExpr, K); |
| 15437 | |
| 15438 | return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr); |
| 15439 | } |
| 15440 | |
| 15441 | void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, |
| 15442 | UnresolvedSetImpl &Functions) { |
| 15443 | OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); |
| 15444 | if (OverOp != OO_None && OverOp != OO_Equal) |
| 15445 | LookupOverloadedOperatorName(Op: OverOp, S, Functions); |
| 15446 | |
| 15447 | // In C++20 onwards, we may have a second operator to look up. |
| 15448 | if (getLangOpts().CPlusPlus20) { |
| 15449 | if (OverloadedOperatorKind = getRewrittenOverloadedOperator(Kind: OverOp)) |
| 15450 | LookupOverloadedOperatorName(Op: ExtraOp, S, Functions); |
| 15451 | } |
| 15452 | } |
| 15453 | |
| 15454 | /// Build an overloaded binary operator expression in the given scope. |
| 15455 | static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, |
| 15456 | BinaryOperatorKind Opc, |
| 15457 | Expr *LHS, Expr *RHS) { |
| 15458 | switch (Opc) { |
| 15459 | case BO_Assign: |
| 15460 | // In the non-overloaded case, we warn about self-assignment (x = x) for |
| 15461 | // both simple assignment and certain compound assignments where algebra |
| 15462 | // tells us the operation yields a constant result. When the operator is |
| 15463 | // overloaded, we can't do the latter because we don't want to assume that |
| 15464 | // those algebraic identities still apply; for example, a path-building |
| 15465 | // library might use operator/= to append paths. But it's still reasonable |
| 15466 | // to assume that simple assignment is just moving/copying values around |
| 15467 | // and so self-assignment is likely a bug. |
| 15468 | DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false); |
| 15469 | [[fallthrough]]; |
| 15470 | case BO_DivAssign: |
| 15471 | case BO_RemAssign: |
| 15472 | case BO_SubAssign: |
| 15473 | case BO_AndAssign: |
| 15474 | case BO_OrAssign: |
| 15475 | case BO_XorAssign: |
| 15476 | CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S); |
| 15477 | break; |
| 15478 | default: |
| 15479 | break; |
| 15480 | } |
| 15481 | |
| 15482 | // Find all of the overloaded operators visible from this point. |
| 15483 | UnresolvedSet<16> Functions; |
| 15484 | S.LookupBinOp(S: Sc, OpLoc, Opc, Functions); |
| 15485 | |
| 15486 | // Build the (potentially-overloaded, potentially-dependent) |
| 15487 | // binary operation. |
| 15488 | return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS); |
| 15489 | } |
| 15490 | |
| 15491 | ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, |
| 15492 | BinaryOperatorKind Opc, Expr *LHSExpr, |
| 15493 | Expr *RHSExpr, bool ForFoldExpression) { |
| 15494 | if (!LHSExpr || !RHSExpr) |
| 15495 | return ExprError(); |
| 15496 | |
| 15497 | // We want to end up calling one of SemaPseudoObject::checkAssignment |
| 15498 | // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if |
| 15499 | // both expressions are overloadable or either is type-dependent), |
| 15500 | // or CreateBuiltinBinOp (in any other case). We also want to get |
| 15501 | // any placeholder types out of the way. |
| 15502 | |
| 15503 | // Handle pseudo-objects in the LHS. |
| 15504 | if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { |
| 15505 | // Assignments with a pseudo-object l-value need special analysis. |
| 15506 | if (pty->getKind() == BuiltinType::PseudoObject && |
| 15507 | BinaryOperator::isAssignmentOp(Opc)) |
| 15508 | return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr); |
| 15509 | |
| 15510 | // Don't resolve overloads if the other type is overloadable. |
| 15511 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { |
| 15512 | // We can't actually test that if we still have a placeholder, |
| 15513 | // though. Fortunately, none of the exceptions we see in that |
| 15514 | // code below are valid when the LHS is an overload set. Note |
| 15515 | // that an overload set can be dependently-typed, but it never |
| 15516 | // instantiates to having an overloadable type. |
| 15517 | ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr); |
| 15518 | if (resolvedRHS.isInvalid()) return ExprError(); |
| 15519 | RHSExpr = resolvedRHS.get(); |
| 15520 | |
| 15521 | if (RHSExpr->isTypeDependent() || |
| 15522 | RHSExpr->getType()->isOverloadableType()) |
| 15523 | return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr); |
| 15524 | } |
| 15525 | |
| 15526 | // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function |
| 15527 | // template, diagnose the missing 'template' keyword instead of diagnosing |
| 15528 | // an invalid use of a bound member function. |
| 15529 | // |
| 15530 | // Note that "A::x < b" might be valid if 'b' has an overloadable type due |
| 15531 | // to C++1z [over.over]/1.4, but we already checked for that case above. |
| 15532 | if (Opc == BO_LT && inTemplateInstantiation() && |
| 15533 | (pty->getKind() == BuiltinType::BoundMember || |
| 15534 | pty->getKind() == BuiltinType::Overload)) { |
| 15535 | auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr); |
| 15536 | if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && |
| 15537 | llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) { |
| 15538 | return isa<FunctionTemplateDecl>(Val: ND); |
| 15539 | })) { |
| 15540 | Diag(Loc: OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() |
| 15541 | : OE->getNameLoc(), |
| 15542 | DiagID: diag::err_template_kw_missing) |
| 15543 | << OE->getName().getAsIdentifierInfo(); |
| 15544 | return ExprError(); |
| 15545 | } |
| 15546 | } |
| 15547 | |
| 15548 | ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr); |
| 15549 | if (LHS.isInvalid()) return ExprError(); |
| 15550 | LHSExpr = LHS.get(); |
| 15551 | } |
| 15552 | |
| 15553 | // Handle pseudo-objects in the RHS. |
| 15554 | if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { |
| 15555 | // An overload in the RHS can potentially be resolved by the type |
| 15556 | // being assigned to. |
| 15557 | if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { |
| 15558 | if (getLangOpts().CPlusPlus && |
| 15559 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || |
| 15560 | LHSExpr->getType()->isOverloadableType())) |
| 15561 | return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr); |
| 15562 | |
| 15563 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, |
| 15564 | ForFoldExpression); |
| 15565 | } |
| 15566 | |
| 15567 | // Don't resolve overloads if the other type is overloadable. |
| 15568 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && |
| 15569 | LHSExpr->getType()->isOverloadableType()) |
| 15570 | return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr); |
| 15571 | |
| 15572 | ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr); |
| 15573 | if (!resolvedRHS.isUsable()) return ExprError(); |
| 15574 | RHSExpr = resolvedRHS.get(); |
| 15575 | } |
| 15576 | |
| 15577 | if (getLangOpts().CPlusPlus) { |
| 15578 | // Otherwise, build an overloaded op if either expression is type-dependent |
| 15579 | // or has an overloadable type. |
| 15580 | if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || |
| 15581 | LHSExpr->getType()->isOverloadableType() || |
| 15582 | RHSExpr->getType()->isOverloadableType()) |
| 15583 | return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr); |
| 15584 | } |
| 15585 | |
| 15586 | if (getLangOpts().RecoveryAST && |
| 15587 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { |
| 15588 | assert(!getLangOpts().CPlusPlus); |
| 15589 | assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && |
| 15590 | "Should only occur in error-recovery path." ); |
| 15591 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) |
| 15592 | // C [6.15.16] p3: |
| 15593 | // An assignment expression has the value of the left operand after the |
| 15594 | // assignment, but is not an lvalue. |
| 15595 | return CompoundAssignOperator::Create( |
| 15596 | C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, |
| 15597 | ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary, |
| 15598 | opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides()); |
| 15599 | QualType ResultType; |
| 15600 | switch (Opc) { |
| 15601 | case BO_Assign: |
| 15602 | ResultType = LHSExpr->getType().getUnqualifiedType(); |
| 15603 | break; |
| 15604 | case BO_LT: |
| 15605 | case BO_GT: |
| 15606 | case BO_LE: |
| 15607 | case BO_GE: |
| 15608 | case BO_EQ: |
| 15609 | case BO_NE: |
| 15610 | case BO_LAnd: |
| 15611 | case BO_LOr: |
| 15612 | // These operators have a fixed result type regardless of operands. |
| 15613 | ResultType = Context.IntTy; |
| 15614 | break; |
| 15615 | case BO_Comma: |
| 15616 | ResultType = RHSExpr->getType(); |
| 15617 | break; |
| 15618 | default: |
| 15619 | ResultType = Context.DependentTy; |
| 15620 | break; |
| 15621 | } |
| 15622 | return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType, |
| 15623 | VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc, |
| 15624 | FPFeatures: CurFPFeatureOverrides()); |
| 15625 | } |
| 15626 | |
| 15627 | // Build a built-in binary operation. |
| 15628 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression); |
| 15629 | } |
| 15630 | |
| 15631 | static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { |
| 15632 | if (T.isNull() || T->isDependentType()) |
| 15633 | return false; |
| 15634 | |
| 15635 | if (!Ctx.isPromotableIntegerType(T)) |
| 15636 | return true; |
| 15637 | |
| 15638 | return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy); |
| 15639 | } |
| 15640 | |
| 15641 | ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, |
| 15642 | UnaryOperatorKind Opc, Expr *InputExpr, |
| 15643 | bool IsAfterAmp) { |
| 15644 | ExprResult Input = InputExpr; |
| 15645 | ExprValueKind VK = VK_PRValue; |
| 15646 | ExprObjectKind OK = OK_Ordinary; |
| 15647 | QualType resultType; |
| 15648 | bool CanOverflow = false; |
| 15649 | |
| 15650 | bool ConvertHalfVec = false; |
| 15651 | if (getLangOpts().OpenCL) { |
| 15652 | QualType Ty = InputExpr->getType(); |
| 15653 | // The only legal unary operation for atomics is '&'. |
| 15654 | if ((Opc != UO_AddrOf && Ty->isAtomicType()) || |
| 15655 | // OpenCL special types - image, sampler, pipe, and blocks are to be used |
| 15656 | // only with a builtin functions and therefore should be disallowed here. |
| 15657 | (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() |
| 15658 | || Ty->isBlockPointerType())) { |
| 15659 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
| 15660 | << InputExpr->getType() |
| 15661 | << Input.get()->getSourceRange()); |
| 15662 | } |
| 15663 | } |
| 15664 | |
| 15665 | if (getLangOpts().HLSL && OpLoc.isValid()) { |
| 15666 | if (Opc == UO_AddrOf) |
| 15667 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 0); |
| 15668 | if (Opc == UO_Deref) |
| 15669 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 1); |
| 15670 | } |
| 15671 | |
| 15672 | if (InputExpr->isTypeDependent() && |
| 15673 | InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) { |
| 15674 | resultType = Context.DependentTy; |
| 15675 | } else { |
| 15676 | switch (Opc) { |
| 15677 | case UO_PreInc: |
| 15678 | case UO_PreDec: |
| 15679 | case UO_PostInc: |
| 15680 | case UO_PostDec: |
| 15681 | resultType = |
| 15682 | CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc, |
| 15683 | IsInc: Opc == UO_PreInc || Opc == UO_PostInc, |
| 15684 | IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec); |
| 15685 | CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType); |
| 15686 | break; |
| 15687 | case UO_AddrOf: |
| 15688 | resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc); |
| 15689 | CheckAddressOfNoDeref(E: InputExpr); |
| 15690 | RecordModifiableNonNullParam(S&: *this, Exp: InputExpr); |
| 15691 | break; |
| 15692 | case UO_Deref: { |
| 15693 | Input = DefaultFunctionArrayLvalueConversion(E: Input.get()); |
| 15694 | if (Input.isInvalid()) |
| 15695 | return ExprError(); |
| 15696 | resultType = |
| 15697 | CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp); |
| 15698 | break; |
| 15699 | } |
| 15700 | case UO_Plus: |
| 15701 | case UO_Minus: |
| 15702 | CanOverflow = Opc == UO_Minus && |
| 15703 | isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType()); |
| 15704 | Input = UsualUnaryConversions(E: Input.get()); |
| 15705 | if (Input.isInvalid()) |
| 15706 | return ExprError(); |
| 15707 | // Unary plus and minus require promoting an operand of half vector to a |
| 15708 | // float vector and truncating the result back to a half vector. For now, |
| 15709 | // we do this only when HalfArgsAndReturns is set (that is, when the |
| 15710 | // target is arm or arm64). |
| 15711 | ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: true, Ctx&: Context, E0: Input.get()); |
| 15712 | |
| 15713 | // If the operand is a half vector, promote it to a float vector. |
| 15714 | if (ConvertHalfVec) |
| 15715 | Input = convertVector(E: Input.get(), ElementType: Context.FloatTy, S&: *this); |
| 15716 | resultType = Input.get()->getType(); |
| 15717 | if (resultType->isArithmeticType()) // C99 6.5.3.3p1 |
| 15718 | break; |
| 15719 | else if (resultType->isVectorType() && |
| 15720 | // The z vector extensions don't allow + or - with bool vectors. |
| 15721 | (!Context.getLangOpts().ZVector || |
| 15722 | resultType->castAs<VectorType>()->getVectorKind() != |
| 15723 | VectorKind::AltiVecBool)) |
| 15724 | break; |
| 15725 | else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and - |
| 15726 | break; |
| 15727 | else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 |
| 15728 | Opc == UO_Plus && resultType->isPointerType()) |
| 15729 | break; |
| 15730 | |
| 15731 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
| 15732 | << resultType << Input.get()->getSourceRange()); |
| 15733 | |
| 15734 | case UO_Not: // bitwise complement |
| 15735 | Input = UsualUnaryConversions(E: Input.get()); |
| 15736 | if (Input.isInvalid()) |
| 15737 | return ExprError(); |
| 15738 | resultType = Input.get()->getType(); |
| 15739 | // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. |
| 15740 | if (resultType->isComplexType() || resultType->isComplexIntegerType()) |
| 15741 | // C99 does not support '~' for complex conjugation. |
| 15742 | Diag(Loc: OpLoc, DiagID: diag::ext_integer_complement_complex) |
| 15743 | << resultType << Input.get()->getSourceRange(); |
| 15744 | else if (resultType->hasIntegerRepresentation()) |
| 15745 | break; |
| 15746 | else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { |
| 15747 | // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate |
| 15748 | // on vector float types. |
| 15749 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); |
| 15750 | if (!T->isIntegerType()) |
| 15751 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
| 15752 | << resultType << Input.get()->getSourceRange()); |
| 15753 | } else { |
| 15754 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
| 15755 | << resultType << Input.get()->getSourceRange()); |
| 15756 | } |
| 15757 | break; |
| 15758 | |
| 15759 | case UO_LNot: // logical negation |
| 15760 | // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). |
| 15761 | Input = DefaultFunctionArrayLvalueConversion(E: Input.get()); |
| 15762 | if (Input.isInvalid()) |
| 15763 | return ExprError(); |
| 15764 | resultType = Input.get()->getType(); |
| 15765 | |
| 15766 | // Though we still have to promote half FP to float... |
| 15767 | if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { |
| 15768 | Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast) |
| 15769 | .get(); |
| 15770 | resultType = Context.FloatTy; |
| 15771 | } |
| 15772 | |
| 15773 | // WebAsembly tables can't be used in unary expressions. |
| 15774 | if (resultType->isPointerType() && |
| 15775 | resultType->getPointeeType().isWebAssemblyReferenceType()) { |
| 15776 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
| 15777 | << resultType << Input.get()->getSourceRange()); |
| 15778 | } |
| 15779 | |
| 15780 | if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType)) { |
| 15781 | // C99 6.5.3.3p1: ok, fallthrough; |
| 15782 | if (Context.getLangOpts().CPlusPlus) { |
| 15783 | // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: |
| 15784 | // operand contextually converted to bool. |
| 15785 | Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy, |
| 15786 | CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType)); |
| 15787 | } else if (Context.getLangOpts().OpenCL && |
| 15788 | Context.getLangOpts().OpenCLVersion < 120) { |
| 15789 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not |
| 15790 | // operate on scalar float types. |
| 15791 | if (!resultType->isIntegerType() && !resultType->isPointerType()) |
| 15792 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
| 15793 | << resultType << Input.get()->getSourceRange()); |
| 15794 | } |
| 15795 | } else if (resultType->isExtVectorType()) { |
| 15796 | if (Context.getLangOpts().OpenCL && |
| 15797 | Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { |
| 15798 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not |
| 15799 | // operate on vector float types. |
| 15800 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); |
| 15801 | if (!T->isIntegerType()) |
| 15802 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
| 15803 | << resultType << Input.get()->getSourceRange()); |
| 15804 | } |
| 15805 | // Vector logical not returns the signed variant of the operand type. |
| 15806 | resultType = GetSignedVectorType(V: resultType); |
| 15807 | break; |
| 15808 | } else if (Context.getLangOpts().CPlusPlus && |
| 15809 | resultType->isVectorType()) { |
| 15810 | const VectorType *VTy = resultType->castAs<VectorType>(); |
| 15811 | if (VTy->getVectorKind() != VectorKind::Generic) |
| 15812 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
| 15813 | << resultType << Input.get()->getSourceRange()); |
| 15814 | |
| 15815 | // Vector logical not returns the signed variant of the operand type. |
| 15816 | resultType = GetSignedVectorType(V: resultType); |
| 15817 | break; |
| 15818 | } else { |
| 15819 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
| 15820 | << resultType << Input.get()->getSourceRange()); |
| 15821 | } |
| 15822 | |
| 15823 | // LNot always has type int. C99 6.5.3.3p5. |
| 15824 | // In C++, it's bool. C++ 5.3.1p8 |
| 15825 | resultType = Context.getLogicalOperationType(); |
| 15826 | break; |
| 15827 | case UO_Real: |
| 15828 | case UO_Imag: |
| 15829 | resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real); |
| 15830 | // _Real maps ordinary l-values into ordinary l-values. _Imag maps |
| 15831 | // ordinary complex l-values to ordinary l-values and all other values to |
| 15832 | // r-values. |
| 15833 | if (Input.isInvalid()) |
| 15834 | return ExprError(); |
| 15835 | if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { |
| 15836 | if (Input.get()->isGLValue() && |
| 15837 | Input.get()->getObjectKind() == OK_Ordinary) |
| 15838 | VK = Input.get()->getValueKind(); |
| 15839 | } else if (!getLangOpts().CPlusPlus) { |
| 15840 | // In C, a volatile scalar is read by __imag. In C++, it is not. |
| 15841 | Input = DefaultLvalueConversion(E: Input.get()); |
| 15842 | } |
| 15843 | break; |
| 15844 | case UO_Extension: |
| 15845 | resultType = Input.get()->getType(); |
| 15846 | VK = Input.get()->getValueKind(); |
| 15847 | OK = Input.get()->getObjectKind(); |
| 15848 | break; |
| 15849 | case UO_Coawait: |
| 15850 | // It's unnecessary to represent the pass-through operator co_await in the |
| 15851 | // AST; just return the input expression instead. |
| 15852 | assert(!Input.get()->getType()->isDependentType() && |
| 15853 | "the co_await expression must be non-dependant before " |
| 15854 | "building operator co_await" ); |
| 15855 | return Input; |
| 15856 | } |
| 15857 | } |
| 15858 | if (resultType.isNull() || Input.isInvalid()) |
| 15859 | return ExprError(); |
| 15860 | |
| 15861 | // Check for array bounds violations in the operand of the UnaryOperator, |
| 15862 | // except for the '*' and '&' operators that have to be handled specially |
| 15863 | // by CheckArrayAccess (as there are special cases like &array[arraysize] |
| 15864 | // that are explicitly defined as valid by the standard). |
| 15865 | if (Opc != UO_AddrOf && Opc != UO_Deref) |
| 15866 | CheckArrayAccess(E: Input.get()); |
| 15867 | |
| 15868 | auto *UO = |
| 15869 | UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK, |
| 15870 | l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides()); |
| 15871 | |
| 15872 | if (Opc == UO_Deref && UO->getType()->hasAttr(AK: attr::NoDeref) && |
| 15873 | !isa<ArrayType>(Val: UO->getType().getDesugaredType(Context)) && |
| 15874 | !isUnevaluatedContext()) |
| 15875 | ExprEvalContexts.back().PossibleDerefs.insert(Ptr: UO); |
| 15876 | |
| 15877 | // Convert the result back to a half vector. |
| 15878 | if (ConvertHalfVec) |
| 15879 | return convertVector(E: UO, ElementType: Context.HalfTy, S&: *this); |
| 15880 | return UO; |
| 15881 | } |
| 15882 | |
| 15883 | bool Sema::isQualifiedMemberAccess(Expr *E) { |
| 15884 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) { |
| 15885 | if (!DRE->getQualifier()) |
| 15886 | return false; |
| 15887 | |
| 15888 | ValueDecl *VD = DRE->getDecl(); |
| 15889 | if (!VD->isCXXClassMember()) |
| 15890 | return false; |
| 15891 | |
| 15892 | if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD)) |
| 15893 | return true; |
| 15894 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD)) |
| 15895 | return Method->isImplicitObjectMemberFunction(); |
| 15896 | |
| 15897 | return false; |
| 15898 | } |
| 15899 | |
| 15900 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) { |
| 15901 | if (!ULE->getQualifier()) |
| 15902 | return false; |
| 15903 | |
| 15904 | for (NamedDecl *D : ULE->decls()) { |
| 15905 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) { |
| 15906 | if (Method->isImplicitObjectMemberFunction()) |
| 15907 | return true; |
| 15908 | } else { |
| 15909 | // Overload set does not contain methods. |
| 15910 | break; |
| 15911 | } |
| 15912 | } |
| 15913 | |
| 15914 | return false; |
| 15915 | } |
| 15916 | |
| 15917 | return false; |
| 15918 | } |
| 15919 | |
| 15920 | ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, |
| 15921 | UnaryOperatorKind Opc, Expr *Input, |
| 15922 | bool IsAfterAmp) { |
| 15923 | // First things first: handle placeholders so that the |
| 15924 | // overloaded-operator check considers the right type. |
| 15925 | if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { |
| 15926 | // Increment and decrement of pseudo-object references. |
| 15927 | if (pty->getKind() == BuiltinType::PseudoObject && |
| 15928 | UnaryOperator::isIncrementDecrementOp(Op: Opc)) |
| 15929 | return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input); |
| 15930 | |
| 15931 | // extension is always a builtin operator. |
| 15932 | if (Opc == UO_Extension) |
| 15933 | return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input); |
| 15934 | |
| 15935 | // & gets special logic for several kinds of placeholder. |
| 15936 | // The builtin code knows what to do. |
| 15937 | if (Opc == UO_AddrOf && |
| 15938 | (pty->getKind() == BuiltinType::Overload || |
| 15939 | pty->getKind() == BuiltinType::UnknownAny || |
| 15940 | pty->getKind() == BuiltinType::BoundMember)) |
| 15941 | return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input); |
| 15942 | |
| 15943 | // Anything else needs to be handled now. |
| 15944 | ExprResult Result = CheckPlaceholderExpr(E: Input); |
| 15945 | if (Result.isInvalid()) return ExprError(); |
| 15946 | Input = Result.get(); |
| 15947 | } |
| 15948 | |
| 15949 | if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && |
| 15950 | UnaryOperator::getOverloadedOperator(Opc) != OO_None && |
| 15951 | !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) { |
| 15952 | // Find all of the overloaded operators visible from this point. |
| 15953 | UnresolvedSet<16> Functions; |
| 15954 | OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); |
| 15955 | if (S && OverOp != OO_None) |
| 15956 | LookupOverloadedOperatorName(Op: OverOp, S, Functions); |
| 15957 | |
| 15958 | return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input); |
| 15959 | } |
| 15960 | |
| 15961 | return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp); |
| 15962 | } |
| 15963 | |
| 15964 | ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, |
| 15965 | Expr *Input, bool IsAfterAmp) { |
| 15966 | return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input, |
| 15967 | IsAfterAmp); |
| 15968 | } |
| 15969 | |
| 15970 | ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, |
| 15971 | LabelDecl *TheDecl) { |
| 15972 | TheDecl->markUsed(C&: Context); |
| 15973 | // Create the AST node. The address of a label always has type 'void*'. |
| 15974 | auto *Res = new (Context) AddrLabelExpr( |
| 15975 | OpLoc, LabLoc, TheDecl, Context.getPointerType(T: Context.VoidTy)); |
| 15976 | |
| 15977 | if (getCurFunction()) |
| 15978 | getCurFunction()->AddrLabels.push_back(Elt: Res); |
| 15979 | |
| 15980 | return Res; |
| 15981 | } |
| 15982 | |
| 15983 | void Sema::ActOnStartStmtExpr() { |
| 15984 | PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context); |
| 15985 | // Make sure we diagnose jumping into a statement expression. |
| 15986 | setFunctionHasBranchProtectedScope(); |
| 15987 | } |
| 15988 | |
| 15989 | void Sema::ActOnStmtExprError() { |
| 15990 | // Note that function is also called by TreeTransform when leaving a |
| 15991 | // StmtExpr scope without rebuilding anything. |
| 15992 | |
| 15993 | DiscardCleanupsInEvaluationContext(); |
| 15994 | PopExpressionEvaluationContext(); |
| 15995 | } |
| 15996 | |
| 15997 | ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, |
| 15998 | SourceLocation RPLoc) { |
| 15999 | return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S)); |
| 16000 | } |
| 16001 | |
| 16002 | ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, |
| 16003 | SourceLocation RPLoc, unsigned TemplateDepth) { |
| 16004 | assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!" ); |
| 16005 | CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt); |
| 16006 | |
| 16007 | if (hasAnyUnrecoverableErrorsInThisFunction()) |
| 16008 | DiscardCleanupsInEvaluationContext(); |
| 16009 | assert(!Cleanup.exprNeedsCleanups() && |
| 16010 | "cleanups within StmtExpr not correctly bound!" ); |
| 16011 | PopExpressionEvaluationContext(); |
| 16012 | |
| 16013 | // FIXME: there are a variety of strange constraints to enforce here, for |
| 16014 | // example, it is not possible to goto into a stmt expression apparently. |
| 16015 | // More semantic analysis is needed. |
| 16016 | |
| 16017 | // If there are sub-stmts in the compound stmt, take the type of the last one |
| 16018 | // as the type of the stmtexpr. |
| 16019 | QualType Ty = Context.VoidTy; |
| 16020 | bool StmtExprMayBindToTemp = false; |
| 16021 | if (!Compound->body_empty()) { |
| 16022 | // For GCC compatibility we get the last Stmt excluding trailing NullStmts. |
| 16023 | if (const auto *LastStmt = |
| 16024 | dyn_cast<ValueStmt>(Val: Compound->getStmtExprResult())) { |
| 16025 | if (const Expr *Value = LastStmt->getExprStmt()) { |
| 16026 | StmtExprMayBindToTemp = true; |
| 16027 | Ty = Value->getType(); |
| 16028 | } |
| 16029 | } |
| 16030 | } |
| 16031 | |
| 16032 | // FIXME: Check that expression type is complete/non-abstract; statement |
| 16033 | // expressions are not lvalues. |
| 16034 | Expr *ResStmtExpr = |
| 16035 | new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); |
| 16036 | if (StmtExprMayBindToTemp) |
| 16037 | return MaybeBindToTemporary(E: ResStmtExpr); |
| 16038 | return ResStmtExpr; |
| 16039 | } |
| 16040 | |
| 16041 | ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { |
| 16042 | if (ER.isInvalid()) |
| 16043 | return ExprError(); |
| 16044 | |
| 16045 | // Do function/array conversion on the last expression, but not |
| 16046 | // lvalue-to-rvalue. However, initialize an unqualified type. |
| 16047 | ER = DefaultFunctionArrayConversion(E: ER.get()); |
| 16048 | if (ER.isInvalid()) |
| 16049 | return ExprError(); |
| 16050 | Expr *E = ER.get(); |
| 16051 | |
| 16052 | if (E->isTypeDependent()) |
| 16053 | return E; |
| 16054 | |
| 16055 | // In ARC, if the final expression ends in a consume, splice |
| 16056 | // the consume out and bind it later. In the alternate case |
| 16057 | // (when dealing with a retainable type), the result |
| 16058 | // initialization will create a produce. In both cases the |
| 16059 | // result will be +1, and we'll need to balance that out with |
| 16060 | // a bind. |
| 16061 | auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E); |
| 16062 | if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) |
| 16063 | return Cast->getSubExpr(); |
| 16064 | |
| 16065 | // FIXME: Provide a better location for the initialization. |
| 16066 | return PerformCopyInitialization( |
| 16067 | Entity: InitializedEntity::InitializeStmtExprResult( |
| 16068 | ReturnLoc: E->getBeginLoc(), Type: E->getType().getAtomicUnqualifiedType()), |
| 16069 | EqualLoc: SourceLocation(), Init: E); |
| 16070 | } |
| 16071 | |
| 16072 | ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, |
| 16073 | TypeSourceInfo *TInfo, |
| 16074 | ArrayRef<OffsetOfComponent> Components, |
| 16075 | SourceLocation RParenLoc) { |
| 16076 | QualType ArgTy = TInfo->getType(); |
| 16077 | bool Dependent = ArgTy->isDependentType(); |
| 16078 | SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); |
| 16079 | |
| 16080 | // We must have at least one component that refers to the type, and the first |
| 16081 | // one is known to be a field designator. Verify that the ArgTy represents |
| 16082 | // a struct/union/class. |
| 16083 | if (!Dependent && !ArgTy->isRecordType()) |
| 16084 | return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_offsetof_record_type) |
| 16085 | << ArgTy << TypeRange); |
| 16086 | |
| 16087 | // Type must be complete per C99 7.17p3 because a declaring a variable |
| 16088 | // with an incomplete type would be ill-formed. |
| 16089 | if (!Dependent |
| 16090 | && RequireCompleteType(Loc: BuiltinLoc, T: ArgTy, |
| 16091 | DiagID: diag::err_offsetof_incomplete_type, Args: TypeRange)) |
| 16092 | return ExprError(); |
| 16093 | |
| 16094 | bool DidWarnAboutNonPOD = false; |
| 16095 | QualType CurrentType = ArgTy; |
| 16096 | SmallVector<OffsetOfNode, 4> Comps; |
| 16097 | SmallVector<Expr*, 4> Exprs; |
| 16098 | for (const OffsetOfComponent &OC : Components) { |
| 16099 | if (OC.isBrackets) { |
| 16100 | // Offset of an array sub-field. TODO: Should we allow vector elements? |
| 16101 | if (!CurrentType->isDependentType()) { |
| 16102 | const ArrayType *AT = Context.getAsArrayType(T: CurrentType); |
| 16103 | if(!AT) |
| 16104 | return ExprError(Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_array_type) |
| 16105 | << CurrentType); |
| 16106 | CurrentType = AT->getElementType(); |
| 16107 | } else |
| 16108 | CurrentType = Context.DependentTy; |
| 16109 | |
| 16110 | ExprResult IdxRval = DefaultLvalueConversion(E: static_cast<Expr*>(OC.U.E)); |
| 16111 | if (IdxRval.isInvalid()) |
| 16112 | return ExprError(); |
| 16113 | Expr *Idx = IdxRval.get(); |
| 16114 | |
| 16115 | // The expression must be an integral expression. |
| 16116 | // FIXME: An integral constant expression? |
| 16117 | if (!Idx->isTypeDependent() && !Idx->isValueDependent() && |
| 16118 | !Idx->getType()->isIntegerType()) |
| 16119 | return ExprError( |
| 16120 | Diag(Loc: Idx->getBeginLoc(), DiagID: diag::err_typecheck_subscript_not_integer) |
| 16121 | << Idx->getSourceRange()); |
| 16122 | |
| 16123 | // Record this array index. |
| 16124 | Comps.push_back(Elt: OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); |
| 16125 | Exprs.push_back(Elt: Idx); |
| 16126 | continue; |
| 16127 | } |
| 16128 | |
| 16129 | // Offset of a field. |
| 16130 | if (CurrentType->isDependentType()) { |
| 16131 | // We have the offset of a field, but we can't look into the dependent |
| 16132 | // type. Just record the identifier of the field. |
| 16133 | Comps.push_back(Elt: OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); |
| 16134 | CurrentType = Context.DependentTy; |
| 16135 | continue; |
| 16136 | } |
| 16137 | |
| 16138 | // We need to have a complete type to look into. |
| 16139 | if (RequireCompleteType(Loc: OC.LocStart, T: CurrentType, |
| 16140 | DiagID: diag::err_offsetof_incomplete_type)) |
| 16141 | return ExprError(); |
| 16142 | |
| 16143 | // Look for the designated field. |
| 16144 | const RecordType *RC = CurrentType->getAs<RecordType>(); |
| 16145 | if (!RC) |
| 16146 | return ExprError(Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_record_type) |
| 16147 | << CurrentType); |
| 16148 | RecordDecl *RD = RC->getDecl(); |
| 16149 | |
| 16150 | // C++ [lib.support.types]p5: |
| 16151 | // The macro offsetof accepts a restricted set of type arguments in this |
| 16152 | // International Standard. type shall be a POD structure or a POD union |
| 16153 | // (clause 9). |
| 16154 | // C++11 [support.types]p4: |
| 16155 | // If type is not a standard-layout class (Clause 9), the results are |
| 16156 | // undefined. |
| 16157 | if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) { |
| 16158 | bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); |
| 16159 | unsigned DiagID = |
| 16160 | LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type |
| 16161 | : diag::ext_offsetof_non_pod_type; |
| 16162 | |
| 16163 | if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) { |
| 16164 | Diag(Loc: BuiltinLoc, DiagID) |
| 16165 | << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType; |
| 16166 | DidWarnAboutNonPOD = true; |
| 16167 | } |
| 16168 | } |
| 16169 | |
| 16170 | // Look for the field. |
| 16171 | LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); |
| 16172 | LookupQualifiedName(R, LookupCtx: RD); |
| 16173 | FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); |
| 16174 | IndirectFieldDecl *IndirectMemberDecl = nullptr; |
| 16175 | if (!MemberDecl) { |
| 16176 | if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) |
| 16177 | MemberDecl = IndirectMemberDecl->getAnonField(); |
| 16178 | } |
| 16179 | |
| 16180 | if (!MemberDecl) { |
| 16181 | // Lookup could be ambiguous when looking up a placeholder variable |
| 16182 | // __builtin_offsetof(S, _). |
| 16183 | // In that case we would already have emitted a diagnostic |
| 16184 | if (!R.isAmbiguous()) |
| 16185 | Diag(Loc: BuiltinLoc, DiagID: diag::err_no_member) |
| 16186 | << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd); |
| 16187 | return ExprError(); |
| 16188 | } |
| 16189 | |
| 16190 | // C99 7.17p3: |
| 16191 | // (If the specified member is a bit-field, the behavior is undefined.) |
| 16192 | // |
| 16193 | // We diagnose this as an error. |
| 16194 | if (MemberDecl->isBitField()) { |
| 16195 | Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_bitfield) |
| 16196 | << MemberDecl->getDeclName() |
| 16197 | << SourceRange(BuiltinLoc, RParenLoc); |
| 16198 | Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_bitfield_decl); |
| 16199 | return ExprError(); |
| 16200 | } |
| 16201 | |
| 16202 | RecordDecl *Parent = MemberDecl->getParent(); |
| 16203 | if (IndirectMemberDecl) |
| 16204 | Parent = cast<RecordDecl>(Val: IndirectMemberDecl->getDeclContext()); |
| 16205 | |
| 16206 | // If the member was found in a base class, introduce OffsetOfNodes for |
| 16207 | // the base class indirections. |
| 16208 | CXXBasePaths Paths; |
| 16209 | if (IsDerivedFrom(Loc: OC.LocStart, Derived: CurrentType, Base: Context.getTypeDeclType(Decl: Parent), |
| 16210 | Paths)) { |
| 16211 | if (Paths.getDetectedVirtual()) { |
| 16212 | Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_field_of_virtual_base) |
| 16213 | << MemberDecl->getDeclName() |
| 16214 | << SourceRange(BuiltinLoc, RParenLoc); |
| 16215 | return ExprError(); |
| 16216 | } |
| 16217 | |
| 16218 | CXXBasePath &Path = Paths.front(); |
| 16219 | for (const CXXBasePathElement &B : Path) |
| 16220 | Comps.push_back(Elt: OffsetOfNode(B.Base)); |
| 16221 | } |
| 16222 | |
| 16223 | if (IndirectMemberDecl) { |
| 16224 | for (auto *FI : IndirectMemberDecl->chain()) { |
| 16225 | assert(isa<FieldDecl>(FI)); |
| 16226 | Comps.push_back(Elt: OffsetOfNode(OC.LocStart, |
| 16227 | cast<FieldDecl>(Val: FI), OC.LocEnd)); |
| 16228 | } |
| 16229 | } else |
| 16230 | Comps.push_back(Elt: OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); |
| 16231 | |
| 16232 | CurrentType = MemberDecl->getType().getNonReferenceType(); |
| 16233 | } |
| 16234 | |
| 16235 | return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo, |
| 16236 | comps: Comps, exprs: Exprs, RParenLoc); |
| 16237 | } |
| 16238 | |
| 16239 | ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, |
| 16240 | SourceLocation BuiltinLoc, |
| 16241 | SourceLocation TypeLoc, |
| 16242 | ParsedType ParsedArgTy, |
| 16243 | ArrayRef<OffsetOfComponent> Components, |
| 16244 | SourceLocation RParenLoc) { |
| 16245 | |
| 16246 | TypeSourceInfo *ArgTInfo; |
| 16247 | QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo); |
| 16248 | if (ArgTy.isNull()) |
| 16249 | return ExprError(); |
| 16250 | |
| 16251 | if (!ArgTInfo) |
| 16252 | ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc); |
| 16253 | |
| 16254 | return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Components, RParenLoc); |
| 16255 | } |
| 16256 | |
| 16257 | |
| 16258 | ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, |
| 16259 | Expr *CondExpr, |
| 16260 | Expr *LHSExpr, Expr *RHSExpr, |
| 16261 | SourceLocation RPLoc) { |
| 16262 | assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)" ); |
| 16263 | |
| 16264 | ExprValueKind VK = VK_PRValue; |
| 16265 | ExprObjectKind OK = OK_Ordinary; |
| 16266 | QualType resType; |
| 16267 | bool CondIsTrue = false; |
| 16268 | if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { |
| 16269 | resType = Context.DependentTy; |
| 16270 | } else { |
| 16271 | // The conditional expression is required to be a constant expression. |
| 16272 | llvm::APSInt condEval(32); |
| 16273 | ExprResult CondICE = VerifyIntegerConstantExpression( |
| 16274 | E: CondExpr, Result: &condEval, DiagID: diag::err_typecheck_choose_expr_requires_constant); |
| 16275 | if (CondICE.isInvalid()) |
| 16276 | return ExprError(); |
| 16277 | CondExpr = CondICE.get(); |
| 16278 | CondIsTrue = condEval.getZExtValue(); |
| 16279 | |
| 16280 | // If the condition is > zero, then the AST type is the same as the LHSExpr. |
| 16281 | Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; |
| 16282 | |
| 16283 | resType = ActiveExpr->getType(); |
| 16284 | VK = ActiveExpr->getValueKind(); |
| 16285 | OK = ActiveExpr->getObjectKind(); |
| 16286 | } |
| 16287 | |
| 16288 | return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, |
| 16289 | resType, VK, OK, RPLoc, CondIsTrue); |
| 16290 | } |
| 16291 | |
| 16292 | //===----------------------------------------------------------------------===// |
| 16293 | // Clang Extensions. |
| 16294 | //===----------------------------------------------------------------------===// |
| 16295 | |
| 16296 | void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { |
| 16297 | BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc); |
| 16298 | |
| 16299 | if (LangOpts.CPlusPlus) { |
| 16300 | MangleNumberingContext *MCtx; |
| 16301 | Decl *ManglingContextDecl; |
| 16302 | std::tie(args&: MCtx, args&: ManglingContextDecl) = |
| 16303 | getCurrentMangleNumberContext(DC: Block->getDeclContext()); |
| 16304 | if (MCtx) { |
| 16305 | unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block); |
| 16306 | Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl); |
| 16307 | } |
| 16308 | } |
| 16309 | |
| 16310 | PushBlockScope(BlockScope: CurScope, Block); |
| 16311 | CurContext->addDecl(D: Block); |
| 16312 | if (CurScope) |
| 16313 | PushDeclContext(S: CurScope, DC: Block); |
| 16314 | else |
| 16315 | CurContext = Block; |
| 16316 | |
| 16317 | getCurBlock()->HasImplicitReturnType = true; |
| 16318 | |
| 16319 | // Enter a new evaluation context to insulate the block from any |
| 16320 | // cleanups from the enclosing full-expression. |
| 16321 | PushExpressionEvaluationContext( |
| 16322 | NewContext: ExpressionEvaluationContext::PotentiallyEvaluated); |
| 16323 | } |
| 16324 | |
| 16325 | void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, |
| 16326 | Scope *CurScope) { |
| 16327 | assert(ParamInfo.getIdentifier() == nullptr && |
| 16328 | "block-id should have no identifier!" ); |
| 16329 | assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); |
| 16330 | BlockScopeInfo *CurBlock = getCurBlock(); |
| 16331 | |
| 16332 | TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo); |
| 16333 | QualType T = Sig->getType(); |
| 16334 | DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block); |
| 16335 | |
| 16336 | // GetTypeForDeclarator always produces a function type for a block |
| 16337 | // literal signature. Furthermore, it is always a FunctionProtoType |
| 16338 | // unless the function was written with a typedef. |
| 16339 | assert(T->isFunctionType() && |
| 16340 | "GetTypeForDeclarator made a non-function block signature" ); |
| 16341 | |
| 16342 | // Look for an explicit signature in that function type. |
| 16343 | FunctionProtoTypeLoc ExplicitSignature; |
| 16344 | |
| 16345 | if ((ExplicitSignature = Sig->getTypeLoc() |
| 16346 | .getAsAdjusted<FunctionProtoTypeLoc>())) { |
| 16347 | |
| 16348 | // Check whether that explicit signature was synthesized by |
| 16349 | // GetTypeForDeclarator. If so, don't save that as part of the |
| 16350 | // written signature. |
| 16351 | if (ExplicitSignature.getLocalRangeBegin() == |
| 16352 | ExplicitSignature.getLocalRangeEnd()) { |
| 16353 | // This would be much cheaper if we stored TypeLocs instead of |
| 16354 | // TypeSourceInfos. |
| 16355 | TypeLoc Result = ExplicitSignature.getReturnLoc(); |
| 16356 | unsigned Size = Result.getFullDataSize(); |
| 16357 | Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size); |
| 16358 | Sig->getTypeLoc().initializeFullCopy(Other: Result, Size); |
| 16359 | |
| 16360 | ExplicitSignature = FunctionProtoTypeLoc(); |
| 16361 | } |
| 16362 | } |
| 16363 | |
| 16364 | CurBlock->TheDecl->setSignatureAsWritten(Sig); |
| 16365 | CurBlock->FunctionType = T; |
| 16366 | |
| 16367 | const auto *Fn = T->castAs<FunctionType>(); |
| 16368 | QualType RetTy = Fn->getReturnType(); |
| 16369 | bool isVariadic = |
| 16370 | (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic()); |
| 16371 | |
| 16372 | CurBlock->TheDecl->setIsVariadic(isVariadic); |
| 16373 | |
| 16374 | // Context.DependentTy is used as a placeholder for a missing block |
| 16375 | // return type. TODO: what should we do with declarators like: |
| 16376 | // ^ * { ... } |
| 16377 | // If the answer is "apply template argument deduction".... |
| 16378 | if (RetTy != Context.DependentTy) { |
| 16379 | CurBlock->ReturnType = RetTy; |
| 16380 | CurBlock->TheDecl->setBlockMissingReturnType(false); |
| 16381 | CurBlock->HasImplicitReturnType = false; |
| 16382 | } |
| 16383 | |
| 16384 | // Push block parameters from the declarator if we had them. |
| 16385 | SmallVector<ParmVarDecl*, 8> Params; |
| 16386 | if (ExplicitSignature) { |
| 16387 | for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { |
| 16388 | ParmVarDecl *Param = ExplicitSignature.getParam(i: I); |
| 16389 | if (Param->getIdentifier() == nullptr && !Param->isImplicit() && |
| 16390 | !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { |
| 16391 | // Diagnose this as an extension in C17 and earlier. |
| 16392 | if (!getLangOpts().C23) |
| 16393 | Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23); |
| 16394 | } |
| 16395 | Params.push_back(Elt: Param); |
| 16396 | } |
| 16397 | |
| 16398 | // Fake up parameter variables if we have a typedef, like |
| 16399 | // ^ fntype { ... } |
| 16400 | } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { |
| 16401 | for (const auto &I : Fn->param_types()) { |
| 16402 | ParmVarDecl *Param = BuildParmVarDeclForTypedef( |
| 16403 | DC: CurBlock->TheDecl, Loc: ParamInfo.getBeginLoc(), T: I); |
| 16404 | Params.push_back(Elt: Param); |
| 16405 | } |
| 16406 | } |
| 16407 | |
| 16408 | // Set the parameters on the block decl. |
| 16409 | if (!Params.empty()) { |
| 16410 | CurBlock->TheDecl->setParams(Params); |
| 16411 | CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(), |
| 16412 | /*CheckParameterNames=*/false); |
| 16413 | } |
| 16414 | |
| 16415 | // Finally we can process decl attributes. |
| 16416 | ProcessDeclAttributes(S: CurScope, D: CurBlock->TheDecl, PD: ParamInfo); |
| 16417 | |
| 16418 | // Put the parameter variables in scope. |
| 16419 | for (auto *AI : CurBlock->TheDecl->parameters()) { |
| 16420 | AI->setOwningFunction(CurBlock->TheDecl); |
| 16421 | |
| 16422 | // If this has an identifier, add it to the scope stack. |
| 16423 | if (AI->getIdentifier()) { |
| 16424 | CheckShadow(S: CurBlock->TheScope, D: AI); |
| 16425 | |
| 16426 | PushOnScopeChains(D: AI, S: CurBlock->TheScope); |
| 16427 | } |
| 16428 | |
| 16429 | if (AI->isInvalidDecl()) |
| 16430 | CurBlock->TheDecl->setInvalidDecl(); |
| 16431 | } |
| 16432 | } |
| 16433 | |
| 16434 | void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { |
| 16435 | // Leave the expression-evaluation context. |
| 16436 | DiscardCleanupsInEvaluationContext(); |
| 16437 | PopExpressionEvaluationContext(); |
| 16438 | |
| 16439 | // Pop off CurBlock, handle nested blocks. |
| 16440 | PopDeclContext(); |
| 16441 | PopFunctionScopeInfo(); |
| 16442 | } |
| 16443 | |
| 16444 | ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, |
| 16445 | Stmt *Body, Scope *CurScope) { |
| 16446 | // If blocks are disabled, emit an error. |
| 16447 | if (!LangOpts.Blocks) |
| 16448 | Diag(Loc: CaretLoc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL; |
| 16449 | |
| 16450 | // Leave the expression-evaluation context. |
| 16451 | if (hasAnyUnrecoverableErrorsInThisFunction()) |
| 16452 | DiscardCleanupsInEvaluationContext(); |
| 16453 | assert(!Cleanup.exprNeedsCleanups() && |
| 16454 | "cleanups within block not correctly bound!" ); |
| 16455 | PopExpressionEvaluationContext(); |
| 16456 | |
| 16457 | BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back()); |
| 16458 | BlockDecl *BD = BSI->TheDecl; |
| 16459 | |
| 16460 | maybeAddDeclWithEffects(D: BD); |
| 16461 | |
| 16462 | if (BSI->HasImplicitReturnType) |
| 16463 | deduceClosureReturnType(CSI&: *BSI); |
| 16464 | |
| 16465 | QualType RetTy = Context.VoidTy; |
| 16466 | if (!BSI->ReturnType.isNull()) |
| 16467 | RetTy = BSI->ReturnType; |
| 16468 | |
| 16469 | bool NoReturn = BD->hasAttr<NoReturnAttr>(); |
| 16470 | QualType BlockTy; |
| 16471 | |
| 16472 | // If the user wrote a function type in some form, try to use that. |
| 16473 | if (!BSI->FunctionType.isNull()) { |
| 16474 | const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); |
| 16475 | |
| 16476 | FunctionType::ExtInfo Ext = FTy->getExtInfo(); |
| 16477 | if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true); |
| 16478 | |
| 16479 | // Turn protoless block types into nullary block types. |
| 16480 | if (isa<FunctionNoProtoType>(Val: FTy)) { |
| 16481 | FunctionProtoType::ExtProtoInfo EPI; |
| 16482 | EPI.ExtInfo = Ext; |
| 16483 | BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI); |
| 16484 | |
| 16485 | // Otherwise, if we don't need to change anything about the function type, |
| 16486 | // preserve its sugar structure. |
| 16487 | } else if (FTy->getReturnType() == RetTy && |
| 16488 | (!NoReturn || FTy->getNoReturnAttr())) { |
| 16489 | BlockTy = BSI->FunctionType; |
| 16490 | |
| 16491 | // Otherwise, make the minimal modifications to the function type. |
| 16492 | } else { |
| 16493 | const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy); |
| 16494 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
| 16495 | EPI.TypeQuals = Qualifiers(); |
| 16496 | EPI.ExtInfo = Ext; |
| 16497 | BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI); |
| 16498 | } |
| 16499 | |
| 16500 | // If we don't have a function type, just build one from nothing. |
| 16501 | } else { |
| 16502 | FunctionProtoType::ExtProtoInfo EPI; |
| 16503 | EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn); |
| 16504 | BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI); |
| 16505 | } |
| 16506 | |
| 16507 | DiagnoseUnusedParameters(Parameters: BD->parameters()); |
| 16508 | BlockTy = Context.getBlockPointerType(T: BlockTy); |
| 16509 | |
| 16510 | // If needed, diagnose invalid gotos and switches in the block. |
| 16511 | if (getCurFunction()->NeedsScopeChecking() && |
| 16512 | !PP.isCodeCompletionEnabled()) |
| 16513 | DiagnoseInvalidJumps(Body: cast<CompoundStmt>(Val: Body)); |
| 16514 | |
| 16515 | BD->setBody(cast<CompoundStmt>(Val: Body)); |
| 16516 | |
| 16517 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) |
| 16518 | DiagnoseUnguardedAvailabilityViolations(FD: BD); |
| 16519 | |
| 16520 | // Try to apply the named return value optimization. We have to check again |
| 16521 | // if we can do this, though, because blocks keep return statements around |
| 16522 | // to deduce an implicit return type. |
| 16523 | if (getLangOpts().CPlusPlus && RetTy->isRecordType() && |
| 16524 | !BD->isDependentContext()) |
| 16525 | computeNRVO(Body, Scope: BSI); |
| 16526 | |
| 16527 | if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || |
| 16528 | RetTy.hasNonTrivialToPrimitiveCopyCUnion()) |
| 16529 | checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(), |
| 16530 | UseContext: NonTrivialCUnionContext::FunctionReturn, |
| 16531 | NonTrivialKind: NTCUK_Destruct | NTCUK_Copy); |
| 16532 | |
| 16533 | PopDeclContext(); |
| 16534 | |
| 16535 | // Set the captured variables on the block. |
| 16536 | SmallVector<BlockDecl::Capture, 4> Captures; |
| 16537 | for (Capture &Cap : BSI->Captures) { |
| 16538 | if (Cap.isInvalid() || Cap.isThisCapture()) |
| 16539 | continue; |
| 16540 | // Cap.getVariable() is always a VarDecl because |
| 16541 | // blocks cannot capture structured bindings or other ValueDecl kinds. |
| 16542 | auto *Var = cast<VarDecl>(Val: Cap.getVariable()); |
| 16543 | Expr *CopyExpr = nullptr; |
| 16544 | if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { |
| 16545 | if (const RecordType *Record = |
| 16546 | Cap.getCaptureType()->getAs<RecordType>()) { |
| 16547 | // The capture logic needs the destructor, so make sure we mark it. |
| 16548 | // Usually this is unnecessary because most local variables have |
| 16549 | // their destructors marked at declaration time, but parameters are |
| 16550 | // an exception because it's technically only the call site that |
| 16551 | // actually requires the destructor. |
| 16552 | if (isa<ParmVarDecl>(Val: Var)) |
| 16553 | FinalizeVarWithDestructor(VD: Var, DeclInitType: Record); |
| 16554 | |
| 16555 | // Enter a separate potentially-evaluated context while building block |
| 16556 | // initializers to isolate their cleanups from those of the block |
| 16557 | // itself. |
| 16558 | // FIXME: Is this appropriate even when the block itself occurs in an |
| 16559 | // unevaluated operand? |
| 16560 | EnterExpressionEvaluationContext EvalContext( |
| 16561 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); |
| 16562 | |
| 16563 | SourceLocation Loc = Cap.getLocation(); |
| 16564 | |
| 16565 | ExprResult Result = BuildDeclarationNameExpr( |
| 16566 | SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var); |
| 16567 | |
| 16568 | // According to the blocks spec, the capture of a variable from |
| 16569 | // the stack requires a const copy constructor. This is not true |
| 16570 | // of the copy/move done to move a __block variable to the heap. |
| 16571 | if (!Result.isInvalid() && |
| 16572 | !Result.get()->getType().isConstQualified()) { |
| 16573 | Result = ImpCastExprToType(E: Result.get(), |
| 16574 | Type: Result.get()->getType().withConst(), |
| 16575 | CK: CK_NoOp, VK: VK_LValue); |
| 16576 | } |
| 16577 | |
| 16578 | if (!Result.isInvalid()) { |
| 16579 | Result = PerformCopyInitialization( |
| 16580 | Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(), |
| 16581 | Type: Cap.getCaptureType()), |
| 16582 | EqualLoc: Loc, Init: Result.get()); |
| 16583 | } |
| 16584 | |
| 16585 | // Build a full-expression copy expression if initialization |
| 16586 | // succeeded and used a non-trivial constructor. Recover from |
| 16587 | // errors by pretending that the copy isn't necessary. |
| 16588 | if (!Result.isInvalid() && |
| 16589 | !cast<CXXConstructExpr>(Val: Result.get())->getConstructor() |
| 16590 | ->isTrivial()) { |
| 16591 | Result = MaybeCreateExprWithCleanups(SubExpr: Result); |
| 16592 | CopyExpr = Result.get(); |
| 16593 | } |
| 16594 | } |
| 16595 | } |
| 16596 | |
| 16597 | BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), |
| 16598 | CopyExpr); |
| 16599 | Captures.push_back(Elt: NewCap); |
| 16600 | } |
| 16601 | BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0); |
| 16602 | |
| 16603 | // Pop the block scope now but keep it alive to the end of this function. |
| 16604 | AnalysisBasedWarnings::Policy WP = |
| 16605 | AnalysisWarnings.getPolicyInEffectAt(Loc: Body->getEndLoc()); |
| 16606 | PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(WP: &WP, D: BD, BlockType: BlockTy); |
| 16607 | |
| 16608 | BlockExpr *Result = new (Context) |
| 16609 | BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack); |
| 16610 | |
| 16611 | // If the block isn't obviously global, i.e. it captures anything at |
| 16612 | // all, then we need to do a few things in the surrounding context: |
| 16613 | if (Result->getBlockDecl()->hasCaptures()) { |
| 16614 | // First, this expression has a new cleanup object. |
| 16615 | ExprCleanupObjects.push_back(Elt: Result->getBlockDecl()); |
| 16616 | Cleanup.setExprNeedsCleanups(true); |
| 16617 | |
| 16618 | // It also gets a branch-protected scope if any of the captured |
| 16619 | // variables needs destruction. |
| 16620 | for (const auto &CI : Result->getBlockDecl()->captures()) { |
| 16621 | const VarDecl *var = CI.getVariable(); |
| 16622 | if (var->getType().isDestructedType() != QualType::DK_none) { |
| 16623 | setFunctionHasBranchProtectedScope(); |
| 16624 | break; |
| 16625 | } |
| 16626 | } |
| 16627 | } |
| 16628 | |
| 16629 | if (getCurFunction()) |
| 16630 | getCurFunction()->addBlock(BD); |
| 16631 | |
| 16632 | // This can happen if the block's return type is deduced, but |
| 16633 | // the return expression is invalid. |
| 16634 | if (BD->isInvalidDecl()) |
| 16635 | return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(), |
| 16636 | SubExprs: {Result}, T: Result->getType()); |
| 16637 | return Result; |
| 16638 | } |
| 16639 | |
| 16640 | ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, |
| 16641 | SourceLocation RPLoc) { |
| 16642 | TypeSourceInfo *TInfo; |
| 16643 | GetTypeFromParser(Ty, TInfo: &TInfo); |
| 16644 | return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); |
| 16645 | } |
| 16646 | |
| 16647 | ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, |
| 16648 | Expr *E, TypeSourceInfo *TInfo, |
| 16649 | SourceLocation RPLoc) { |
| 16650 | Expr *OrigExpr = E; |
| 16651 | bool IsMS = false; |
| 16652 | |
| 16653 | // CUDA device code does not support varargs. |
| 16654 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { |
| 16655 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) { |
| 16656 | CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F); |
| 16657 | if (T == CUDAFunctionTarget::Global || T == CUDAFunctionTarget::Device || |
| 16658 | T == CUDAFunctionTarget::HostDevice) |
| 16659 | return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device)); |
| 16660 | } |
| 16661 | } |
| 16662 | |
| 16663 | // NVPTX does not support va_arg expression. |
| 16664 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice && |
| 16665 | Context.getTargetInfo().getTriple().isNVPTX()) |
| 16666 | targetDiag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device); |
| 16667 | |
| 16668 | // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() |
| 16669 | // as Microsoft ABI on an actual Microsoft platform, where |
| 16670 | // __builtin_ms_va_list and __builtin_va_list are the same.) |
| 16671 | if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && |
| 16672 | Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { |
| 16673 | QualType MSVaListType = Context.getBuiltinMSVaListType(); |
| 16674 | if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) { |
| 16675 | if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this)) |
| 16676 | return ExprError(); |
| 16677 | IsMS = true; |
| 16678 | } |
| 16679 | } |
| 16680 | |
| 16681 | // Get the va_list type |
| 16682 | QualType VaListType = Context.getBuiltinVaListType(); |
| 16683 | if (!IsMS) { |
| 16684 | if (VaListType->isArrayType()) { |
| 16685 | // Deal with implicit array decay; for example, on x86-64, |
| 16686 | // va_list is an array, but it's supposed to decay to |
| 16687 | // a pointer for va_arg. |
| 16688 | VaListType = Context.getArrayDecayedType(T: VaListType); |
| 16689 | // Make sure the input expression also decays appropriately. |
| 16690 | ExprResult Result = UsualUnaryConversions(E); |
| 16691 | if (Result.isInvalid()) |
| 16692 | return ExprError(); |
| 16693 | E = Result.get(); |
| 16694 | } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { |
| 16695 | // If va_list is a record type and we are compiling in C++ mode, |
| 16696 | // check the argument using reference binding. |
| 16697 | InitializedEntity Entity = InitializedEntity::InitializeParameter( |
| 16698 | Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false); |
| 16699 | ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E); |
| 16700 | if (Init.isInvalid()) |
| 16701 | return ExprError(); |
| 16702 | E = Init.getAs<Expr>(); |
| 16703 | } else { |
| 16704 | // Otherwise, the va_list argument must be an l-value because |
| 16705 | // it is modified by va_arg. |
| 16706 | if (!E->isTypeDependent() && |
| 16707 | CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this)) |
| 16708 | return ExprError(); |
| 16709 | } |
| 16710 | } |
| 16711 | |
| 16712 | if (!IsMS && !E->isTypeDependent() && |
| 16713 | !Context.hasSameType(T1: VaListType, T2: E->getType())) |
| 16714 | return ExprError( |
| 16715 | Diag(Loc: E->getBeginLoc(), |
| 16716 | DiagID: diag::err_first_argument_to_va_arg_not_of_type_va_list) |
| 16717 | << OrigExpr->getType() << E->getSourceRange()); |
| 16718 | |
| 16719 | if (!TInfo->getType()->isDependentType()) { |
| 16720 | if (RequireCompleteType(Loc: TInfo->getTypeLoc().getBeginLoc(), T: TInfo->getType(), |
| 16721 | DiagID: diag::err_second_parameter_to_va_arg_incomplete, |
| 16722 | Args: TInfo->getTypeLoc())) |
| 16723 | return ExprError(); |
| 16724 | |
| 16725 | if (RequireNonAbstractType(Loc: TInfo->getTypeLoc().getBeginLoc(), |
| 16726 | T: TInfo->getType(), |
| 16727 | DiagID: diag::err_second_parameter_to_va_arg_abstract, |
| 16728 | Args: TInfo->getTypeLoc())) |
| 16729 | return ExprError(); |
| 16730 | |
| 16731 | if (!TInfo->getType().isPODType(Context)) { |
| 16732 | Diag(Loc: TInfo->getTypeLoc().getBeginLoc(), |
| 16733 | DiagID: TInfo->getType()->isObjCLifetimeType() |
| 16734 | ? diag::warn_second_parameter_to_va_arg_ownership_qualified |
| 16735 | : diag::warn_second_parameter_to_va_arg_not_pod) |
| 16736 | << TInfo->getType() |
| 16737 | << TInfo->getTypeLoc().getSourceRange(); |
| 16738 | } |
| 16739 | |
| 16740 | if (TInfo->getType()->isArrayType()) { |
| 16741 | DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E, |
| 16742 | PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_array) |
| 16743 | << TInfo->getType() |
| 16744 | << TInfo->getTypeLoc().getSourceRange()); |
| 16745 | } |
| 16746 | |
| 16747 | // Check for va_arg where arguments of the given type will be promoted |
| 16748 | // (i.e. this va_arg is guaranteed to have undefined behavior). |
| 16749 | QualType PromoteType; |
| 16750 | if (Context.isPromotableIntegerType(T: TInfo->getType())) { |
| 16751 | PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType()); |
| 16752 | // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, |
| 16753 | // and C23 7.16.1.1p2 says, in part: |
| 16754 | // If type is not compatible with the type of the actual next argument |
| 16755 | // (as promoted according to the default argument promotions), the |
| 16756 | // behavior is undefined, except for the following cases: |
| 16757 | // - both types are pointers to qualified or unqualified versions of |
| 16758 | // compatible types; |
| 16759 | // - one type is compatible with a signed integer type, the other |
| 16760 | // type is compatible with the corresponding unsigned integer type, |
| 16761 | // and the value is representable in both types; |
| 16762 | // - one type is pointer to qualified or unqualified void and the |
| 16763 | // other is a pointer to a qualified or unqualified character type; |
| 16764 | // - or, the type of the next argument is nullptr_t and type is a |
| 16765 | // pointer type that has the same representation and alignment |
| 16766 | // requirements as a pointer to a character type. |
| 16767 | // Given that type compatibility is the primary requirement (ignoring |
| 16768 | // qualifications), you would think we could call typesAreCompatible() |
| 16769 | // directly to test this. However, in C++, that checks for *same type*, |
| 16770 | // which causes false positives when passing an enumeration type to |
| 16771 | // va_arg. Instead, get the underlying type of the enumeration and pass |
| 16772 | // that. |
| 16773 | QualType UnderlyingType = TInfo->getType(); |
| 16774 | if (const auto *ET = UnderlyingType->getAs<EnumType>()) |
| 16775 | UnderlyingType = ET->getDecl()->getIntegerType(); |
| 16776 | if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType, |
| 16777 | /*CompareUnqualified*/ true)) |
| 16778 | PromoteType = QualType(); |
| 16779 | |
| 16780 | // If the types are still not compatible, we need to test whether the |
| 16781 | // promoted type and the underlying type are the same except for |
| 16782 | // signedness. Ask the AST for the correctly corresponding type and see |
| 16783 | // if that's compatible. |
| 16784 | if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && |
| 16785 | PromoteType->isUnsignedIntegerType() != |
| 16786 | UnderlyingType->isUnsignedIntegerType()) { |
| 16787 | UnderlyingType = |
| 16788 | UnderlyingType->isUnsignedIntegerType() |
| 16789 | ? Context.getCorrespondingSignedType(T: UnderlyingType) |
| 16790 | : Context.getCorrespondingUnsignedType(T: UnderlyingType); |
| 16791 | if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType, |
| 16792 | /*CompareUnqualified*/ true)) |
| 16793 | PromoteType = QualType(); |
| 16794 | } |
| 16795 | } |
| 16796 | if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float)) |
| 16797 | PromoteType = Context.DoubleTy; |
| 16798 | if (!PromoteType.isNull()) |
| 16799 | DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E, |
| 16800 | PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_never_compatible) |
| 16801 | << TInfo->getType() |
| 16802 | << PromoteType |
| 16803 | << TInfo->getTypeLoc().getSourceRange()); |
| 16804 | } |
| 16805 | |
| 16806 | QualType T = TInfo->getType().getNonLValueExprType(Context); |
| 16807 | return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); |
| 16808 | } |
| 16809 | |
| 16810 | ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { |
| 16811 | // The type of __null will be int or long, depending on the size of |
| 16812 | // pointers on the target. |
| 16813 | QualType Ty; |
| 16814 | unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default); |
| 16815 | if (pw == Context.getTargetInfo().getIntWidth()) |
| 16816 | Ty = Context.IntTy; |
| 16817 | else if (pw == Context.getTargetInfo().getLongWidth()) |
| 16818 | Ty = Context.LongTy; |
| 16819 | else if (pw == Context.getTargetInfo().getLongLongWidth()) |
| 16820 | Ty = Context.LongLongTy; |
| 16821 | else { |
| 16822 | llvm_unreachable("I don't know size of pointer!" ); |
| 16823 | } |
| 16824 | |
| 16825 | return new (Context) GNUNullExpr(Ty, TokenLoc); |
| 16826 | } |
| 16827 | |
| 16828 | static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) { |
| 16829 | CXXRecordDecl *ImplDecl = nullptr; |
| 16830 | |
| 16831 | // Fetch the std::source_location::__impl decl. |
| 16832 | if (NamespaceDecl *Std = S.getStdNamespace()) { |
| 16833 | LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location" ), |
| 16834 | Loc, Sema::LookupOrdinaryName); |
| 16835 | if (S.LookupQualifiedName(R&: ResultSL, LookupCtx: Std)) { |
| 16836 | if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) { |
| 16837 | LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl" ), |
| 16838 | Loc, Sema::LookupOrdinaryName); |
| 16839 | if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) && |
| 16840 | S.LookupQualifiedName(R&: ResultImpl, LookupCtx: SLDecl)) { |
| 16841 | ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>(); |
| 16842 | } |
| 16843 | } |
| 16844 | } |
| 16845 | } |
| 16846 | |
| 16847 | if (!ImplDecl || !ImplDecl->isCompleteDefinition()) { |
| 16848 | S.Diag(Loc, DiagID: diag::err_std_source_location_impl_not_found); |
| 16849 | return nullptr; |
| 16850 | } |
| 16851 | |
| 16852 | // Verify that __impl is a trivial struct type, with no base classes, and with |
| 16853 | // only the four expected fields. |
| 16854 | if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() || |
| 16855 | ImplDecl->getNumBases() != 0) { |
| 16856 | S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed); |
| 16857 | return nullptr; |
| 16858 | } |
| 16859 | |
| 16860 | unsigned Count = 0; |
| 16861 | for (FieldDecl *F : ImplDecl->fields()) { |
| 16862 | StringRef Name = F->getName(); |
| 16863 | |
| 16864 | if (Name == "_M_file_name" ) { |
| 16865 | if (F->getType() != |
| 16866 | S.Context.getPointerType(T: S.Context.CharTy.withConst())) |
| 16867 | break; |
| 16868 | Count++; |
| 16869 | } else if (Name == "_M_function_name" ) { |
| 16870 | if (F->getType() != |
| 16871 | S.Context.getPointerType(T: S.Context.CharTy.withConst())) |
| 16872 | break; |
| 16873 | Count++; |
| 16874 | } else if (Name == "_M_line" ) { |
| 16875 | if (!F->getType()->isIntegerType()) |
| 16876 | break; |
| 16877 | Count++; |
| 16878 | } else if (Name == "_M_column" ) { |
| 16879 | if (!F->getType()->isIntegerType()) |
| 16880 | break; |
| 16881 | Count++; |
| 16882 | } else { |
| 16883 | Count = 100; // invalid |
| 16884 | break; |
| 16885 | } |
| 16886 | } |
| 16887 | if (Count != 4) { |
| 16888 | S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed); |
| 16889 | return nullptr; |
| 16890 | } |
| 16891 | |
| 16892 | return ImplDecl; |
| 16893 | } |
| 16894 | |
| 16895 | ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind, |
| 16896 | SourceLocation BuiltinLoc, |
| 16897 | SourceLocation RPLoc) { |
| 16898 | QualType ResultTy; |
| 16899 | switch (Kind) { |
| 16900 | case SourceLocIdentKind::File: |
| 16901 | case SourceLocIdentKind::FileName: |
| 16902 | case SourceLocIdentKind::Function: |
| 16903 | case SourceLocIdentKind::FuncSig: { |
| 16904 | QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0); |
| 16905 | ResultTy = |
| 16906 | Context.getPointerType(T: ArrTy->getAsArrayTypeUnsafe()->getElementType()); |
| 16907 | break; |
| 16908 | } |
| 16909 | case SourceLocIdentKind::Line: |
| 16910 | case SourceLocIdentKind::Column: |
| 16911 | ResultTy = Context.UnsignedIntTy; |
| 16912 | break; |
| 16913 | case SourceLocIdentKind::SourceLocStruct: |
| 16914 | if (!StdSourceLocationImplDecl) { |
| 16915 | StdSourceLocationImplDecl = |
| 16916 | LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc); |
| 16917 | if (!StdSourceLocationImplDecl) |
| 16918 | return ExprError(); |
| 16919 | } |
| 16920 | ResultTy = Context.getPointerType( |
| 16921 | T: Context.getRecordType(Decl: StdSourceLocationImplDecl).withConst()); |
| 16922 | break; |
| 16923 | } |
| 16924 | |
| 16925 | return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext); |
| 16926 | } |
| 16927 | |
| 16928 | ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, |
| 16929 | SourceLocation BuiltinLoc, |
| 16930 | SourceLocation RPLoc, |
| 16931 | DeclContext *ParentContext) { |
| 16932 | return new (Context) |
| 16933 | SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext); |
| 16934 | } |
| 16935 | |
| 16936 | ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, |
| 16937 | StringLiteral *BinaryData, StringRef FileName) { |
| 16938 | EmbedDataStorage *Data = new (Context) EmbedDataStorage; |
| 16939 | Data->BinaryData = BinaryData; |
| 16940 | Data->FileName = FileName; |
| 16941 | return new (Context) |
| 16942 | EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0, |
| 16943 | Data->getDataElementCount()); |
| 16944 | } |
| 16945 | |
| 16946 | static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, |
| 16947 | const Expr *SrcExpr) { |
| 16948 | if (!DstType->isFunctionPointerType() || |
| 16949 | !SrcExpr->getType()->isFunctionType()) |
| 16950 | return false; |
| 16951 | |
| 16952 | auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts()); |
| 16953 | if (!DRE) |
| 16954 | return false; |
| 16955 | |
| 16956 | auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()); |
| 16957 | if (!FD) |
| 16958 | return false; |
| 16959 | |
| 16960 | return !S.checkAddressOfFunctionIsAvailable(Function: FD, |
| 16961 | /*Complain=*/true, |
| 16962 | Loc: SrcExpr->getBeginLoc()); |
| 16963 | } |
| 16964 | |
| 16965 | bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, |
| 16966 | SourceLocation Loc, |
| 16967 | QualType DstType, QualType SrcType, |
| 16968 | Expr *SrcExpr, AssignmentAction Action, |
| 16969 | bool *Complained) { |
| 16970 | if (Complained) |
| 16971 | *Complained = false; |
| 16972 | |
| 16973 | // Decode the result (notice that AST's are still created for extensions). |
| 16974 | bool CheckInferredResultType = false; |
| 16975 | bool isInvalid = false; |
| 16976 | unsigned DiagKind = 0; |
| 16977 | ConversionFixItGenerator ConvHints; |
| 16978 | bool MayHaveConvFixit = false; |
| 16979 | bool MayHaveFunctionDiff = false; |
| 16980 | const ObjCInterfaceDecl *IFace = nullptr; |
| 16981 | const ObjCProtocolDecl *PDecl = nullptr; |
| 16982 | |
| 16983 | switch (ConvTy) { |
| 16984 | case AssignConvertType::Compatible: |
| 16985 | DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); |
| 16986 | return false; |
| 16987 | case AssignConvertType::CompatibleVoidPtrToNonVoidPtr: |
| 16988 | // Still a valid conversion, but we may want to diagnose for C++ |
| 16989 | // compatibility reasons. |
| 16990 | DiagKind = diag::warn_compatible_implicit_pointer_conv; |
| 16991 | break; |
| 16992 | case AssignConvertType::PointerToInt: |
| 16993 | if (getLangOpts().CPlusPlus) { |
| 16994 | DiagKind = diag::err_typecheck_convert_pointer_int; |
| 16995 | isInvalid = true; |
| 16996 | } else { |
| 16997 | DiagKind = diag::ext_typecheck_convert_pointer_int; |
| 16998 | } |
| 16999 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
| 17000 | MayHaveConvFixit = true; |
| 17001 | break; |
| 17002 | case AssignConvertType::IntToPointer: |
| 17003 | if (getLangOpts().CPlusPlus) { |
| 17004 | DiagKind = diag::err_typecheck_convert_int_pointer; |
| 17005 | isInvalid = true; |
| 17006 | } else { |
| 17007 | DiagKind = diag::ext_typecheck_convert_int_pointer; |
| 17008 | } |
| 17009 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
| 17010 | MayHaveConvFixit = true; |
| 17011 | break; |
| 17012 | case AssignConvertType::IncompatibleFunctionPointerStrict: |
| 17013 | DiagKind = |
| 17014 | diag::warn_typecheck_convert_incompatible_function_pointer_strict; |
| 17015 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
| 17016 | MayHaveConvFixit = true; |
| 17017 | break; |
| 17018 | case AssignConvertType::IncompatibleFunctionPointer: |
| 17019 | if (getLangOpts().CPlusPlus) { |
| 17020 | DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; |
| 17021 | isInvalid = true; |
| 17022 | } else { |
| 17023 | DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; |
| 17024 | } |
| 17025 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
| 17026 | MayHaveConvFixit = true; |
| 17027 | break; |
| 17028 | case AssignConvertType::IncompatiblePointer: |
| 17029 | if (Action == AssignmentAction::Passing_CFAudited) { |
| 17030 | DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; |
| 17031 | } else if (getLangOpts().CPlusPlus) { |
| 17032 | DiagKind = diag::err_typecheck_convert_incompatible_pointer; |
| 17033 | isInvalid = true; |
| 17034 | } else { |
| 17035 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer; |
| 17036 | } |
| 17037 | CheckInferredResultType = DstType->isObjCObjectPointerType() && |
| 17038 | SrcType->isObjCObjectPointerType(); |
| 17039 | if (CheckInferredResultType) { |
| 17040 | SrcType = SrcType.getUnqualifiedType(); |
| 17041 | DstType = DstType.getUnqualifiedType(); |
| 17042 | } else { |
| 17043 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
| 17044 | } |
| 17045 | MayHaveConvFixit = true; |
| 17046 | break; |
| 17047 | case AssignConvertType::IncompatiblePointerSign: |
| 17048 | if (getLangOpts().CPlusPlus) { |
| 17049 | DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; |
| 17050 | isInvalid = true; |
| 17051 | } else { |
| 17052 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; |
| 17053 | } |
| 17054 | break; |
| 17055 | case AssignConvertType::FunctionVoidPointer: |
| 17056 | if (getLangOpts().CPlusPlus) { |
| 17057 | DiagKind = diag::err_typecheck_convert_pointer_void_func; |
| 17058 | isInvalid = true; |
| 17059 | } else { |
| 17060 | DiagKind = diag::ext_typecheck_convert_pointer_void_func; |
| 17061 | } |
| 17062 | break; |
| 17063 | case AssignConvertType::IncompatiblePointerDiscardsQualifiers: { |
| 17064 | // Perform array-to-pointer decay if necessary. |
| 17065 | if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(T: SrcType); |
| 17066 | |
| 17067 | isInvalid = true; |
| 17068 | |
| 17069 | Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); |
| 17070 | Qualifiers rhq = DstType->getPointeeType().getQualifiers(); |
| 17071 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) { |
| 17072 | DiagKind = diag::err_typecheck_incompatible_address_space; |
| 17073 | break; |
| 17074 | } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { |
| 17075 | DiagKind = diag::err_typecheck_incompatible_ownership; |
| 17076 | break; |
| 17077 | } else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) { |
| 17078 | DiagKind = diag::err_typecheck_incompatible_ptrauth; |
| 17079 | break; |
| 17080 | } |
| 17081 | |
| 17082 | llvm_unreachable("unknown error case for discarding qualifiers!" ); |
| 17083 | // fallthrough |
| 17084 | } |
| 17085 | case AssignConvertType::CompatiblePointerDiscardsQualifiers: |
| 17086 | // If the qualifiers lost were because we were applying the |
| 17087 | // (deprecated) C++ conversion from a string literal to a char* |
| 17088 | // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: |
| 17089 | // Ideally, this check would be performed in |
| 17090 | // checkPointerTypesForAssignment. However, that would require a |
| 17091 | // bit of refactoring (so that the second argument is an |
| 17092 | // expression, rather than a type), which should be done as part |
| 17093 | // of a larger effort to fix checkPointerTypesForAssignment for |
| 17094 | // C++ semantics. |
| 17095 | if (getLangOpts().CPlusPlus && |
| 17096 | IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType)) |
| 17097 | return false; |
| 17098 | if (getLangOpts().CPlusPlus) { |
| 17099 | DiagKind = diag::err_typecheck_convert_discards_qualifiers; |
| 17100 | isInvalid = true; |
| 17101 | } else { |
| 17102 | DiagKind = diag::ext_typecheck_convert_discards_qualifiers; |
| 17103 | } |
| 17104 | |
| 17105 | break; |
| 17106 | case AssignConvertType::IncompatibleNestedPointerQualifiers: |
| 17107 | if (getLangOpts().CPlusPlus) { |
| 17108 | isInvalid = true; |
| 17109 | DiagKind = diag::err_nested_pointer_qualifier_mismatch; |
| 17110 | } else { |
| 17111 | DiagKind = diag::ext_nested_pointer_qualifier_mismatch; |
| 17112 | } |
| 17113 | break; |
| 17114 | case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch: |
| 17115 | DiagKind = diag::err_typecheck_incompatible_nested_address_space; |
| 17116 | isInvalid = true; |
| 17117 | break; |
| 17118 | case AssignConvertType::IntToBlockPointer: |
| 17119 | DiagKind = diag::err_int_to_block_pointer; |
| 17120 | isInvalid = true; |
| 17121 | break; |
| 17122 | case AssignConvertType::IncompatibleBlockPointer: |
| 17123 | DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; |
| 17124 | isInvalid = true; |
| 17125 | break; |
| 17126 | case AssignConvertType::IncompatibleObjCQualifiedId: { |
| 17127 | if (SrcType->isObjCQualifiedIdType()) { |
| 17128 | const ObjCObjectPointerType *srcOPT = |
| 17129 | SrcType->castAs<ObjCObjectPointerType>(); |
| 17130 | for (auto *srcProto : srcOPT->quals()) { |
| 17131 | PDecl = srcProto; |
| 17132 | break; |
| 17133 | } |
| 17134 | if (const ObjCInterfaceType *IFaceT = |
| 17135 | DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) |
| 17136 | IFace = IFaceT->getDecl(); |
| 17137 | } |
| 17138 | else if (DstType->isObjCQualifiedIdType()) { |
| 17139 | const ObjCObjectPointerType *dstOPT = |
| 17140 | DstType->castAs<ObjCObjectPointerType>(); |
| 17141 | for (auto *dstProto : dstOPT->quals()) { |
| 17142 | PDecl = dstProto; |
| 17143 | break; |
| 17144 | } |
| 17145 | if (const ObjCInterfaceType *IFaceT = |
| 17146 | SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) |
| 17147 | IFace = IFaceT->getDecl(); |
| 17148 | } |
| 17149 | if (getLangOpts().CPlusPlus) { |
| 17150 | DiagKind = diag::err_incompatible_qualified_id; |
| 17151 | isInvalid = true; |
| 17152 | } else { |
| 17153 | DiagKind = diag::warn_incompatible_qualified_id; |
| 17154 | } |
| 17155 | break; |
| 17156 | } |
| 17157 | case AssignConvertType::IncompatibleVectors: |
| 17158 | if (getLangOpts().CPlusPlus) { |
| 17159 | DiagKind = diag::err_incompatible_vectors; |
| 17160 | isInvalid = true; |
| 17161 | } else { |
| 17162 | DiagKind = diag::warn_incompatible_vectors; |
| 17163 | } |
| 17164 | break; |
| 17165 | case AssignConvertType::IncompatibleObjCWeakRef: |
| 17166 | DiagKind = diag::err_arc_weak_unavailable_assign; |
| 17167 | isInvalid = true; |
| 17168 | break; |
| 17169 | case AssignConvertType::Incompatible: |
| 17170 | if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) { |
| 17171 | if (Complained) |
| 17172 | *Complained = true; |
| 17173 | return true; |
| 17174 | } |
| 17175 | |
| 17176 | DiagKind = diag::err_typecheck_convert_incompatible; |
| 17177 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
| 17178 | MayHaveConvFixit = true; |
| 17179 | isInvalid = true; |
| 17180 | MayHaveFunctionDiff = true; |
| 17181 | break; |
| 17182 | } |
| 17183 | |
| 17184 | QualType FirstType, SecondType; |
| 17185 | switch (Action) { |
| 17186 | case AssignmentAction::Assigning: |
| 17187 | case AssignmentAction::Initializing: |
| 17188 | // The destination type comes first. |
| 17189 | FirstType = DstType; |
| 17190 | SecondType = SrcType; |
| 17191 | break; |
| 17192 | |
| 17193 | case AssignmentAction::Returning: |
| 17194 | case AssignmentAction::Passing: |
| 17195 | case AssignmentAction::Passing_CFAudited: |
| 17196 | case AssignmentAction::Converting: |
| 17197 | case AssignmentAction::Sending: |
| 17198 | case AssignmentAction::Casting: |
| 17199 | // The source type comes first. |
| 17200 | FirstType = SrcType; |
| 17201 | SecondType = DstType; |
| 17202 | break; |
| 17203 | } |
| 17204 | |
| 17205 | PartialDiagnostic FDiag = PDiag(DiagID: DiagKind); |
| 17206 | AssignmentAction ActionForDiag = Action; |
| 17207 | if (Action == AssignmentAction::Passing_CFAudited) |
| 17208 | ActionForDiag = AssignmentAction::Passing; |
| 17209 | |
| 17210 | FDiag << FirstType << SecondType << ActionForDiag |
| 17211 | << SrcExpr->getSourceRange(); |
| 17212 | |
| 17213 | if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || |
| 17214 | DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { |
| 17215 | auto isPlainChar = [](const clang::Type *Type) { |
| 17216 | return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) || |
| 17217 | Type->isSpecificBuiltinType(K: BuiltinType::Char_U); |
| 17218 | }; |
| 17219 | FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || |
| 17220 | isPlainChar(SecondType->getPointeeOrArrayElementType())); |
| 17221 | } |
| 17222 | |
| 17223 | // If we can fix the conversion, suggest the FixIts. |
| 17224 | if (!ConvHints.isNull()) { |
| 17225 | for (FixItHint &H : ConvHints.Hints) |
| 17226 | FDiag << H; |
| 17227 | } |
| 17228 | |
| 17229 | if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } |
| 17230 | |
| 17231 | if (MayHaveFunctionDiff) |
| 17232 | HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType); |
| 17233 | |
| 17234 | Diag(Loc, PD: FDiag); |
| 17235 | if ((DiagKind == diag::warn_incompatible_qualified_id || |
| 17236 | DiagKind == diag::err_incompatible_qualified_id) && |
| 17237 | PDecl && IFace && !IFace->hasDefinition()) |
| 17238 | Diag(Loc: IFace->getLocation(), DiagID: diag::note_incomplete_class_and_qualified_id) |
| 17239 | << IFace << PDecl; |
| 17240 | |
| 17241 | if (SecondType == Context.OverloadTy) |
| 17242 | NoteAllOverloadCandidates(E: OverloadExpr::find(E: SrcExpr).Expression, |
| 17243 | DestType: FirstType, /*TakingAddress=*/true); |
| 17244 | |
| 17245 | if (CheckInferredResultType) |
| 17246 | ObjC().EmitRelatedResultTypeNote(E: SrcExpr); |
| 17247 | |
| 17248 | if (Action == AssignmentAction::Returning && |
| 17249 | ConvTy == AssignConvertType::IncompatiblePointer) |
| 17250 | ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType); |
| 17251 | |
| 17252 | if (Complained) |
| 17253 | *Complained = true; |
| 17254 | return isInvalid; |
| 17255 | } |
| 17256 | |
| 17257 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, |
| 17258 | llvm::APSInt *Result, |
| 17259 | AllowFoldKind CanFold) { |
| 17260 | class SimpleICEDiagnoser : public VerifyICEDiagnoser { |
| 17261 | public: |
| 17262 | SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, |
| 17263 | QualType T) override { |
| 17264 | return S.Diag(Loc, DiagID: diag::err_ice_not_integral) |
| 17265 | << T << S.LangOpts.CPlusPlus; |
| 17266 | } |
| 17267 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { |
| 17268 | return S.Diag(Loc, DiagID: diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; |
| 17269 | } |
| 17270 | } Diagnoser; |
| 17271 | |
| 17272 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); |
| 17273 | } |
| 17274 | |
| 17275 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, |
| 17276 | llvm::APSInt *Result, |
| 17277 | unsigned DiagID, |
| 17278 | AllowFoldKind CanFold) { |
| 17279 | class IDDiagnoser : public VerifyICEDiagnoser { |
| 17280 | unsigned DiagID; |
| 17281 | |
| 17282 | public: |
| 17283 | IDDiagnoser(unsigned DiagID) |
| 17284 | : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } |
| 17285 | |
| 17286 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { |
| 17287 | return S.Diag(Loc, DiagID); |
| 17288 | } |
| 17289 | } Diagnoser(DiagID); |
| 17290 | |
| 17291 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); |
| 17292 | } |
| 17293 | |
| 17294 | Sema::SemaDiagnosticBuilder |
| 17295 | Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, |
| 17296 | QualType T) { |
| 17297 | return diagnoseNotICE(S, Loc); |
| 17298 | } |
| 17299 | |
| 17300 | Sema::SemaDiagnosticBuilder |
| 17301 | Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { |
| 17302 | return S.Diag(Loc, DiagID: diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; |
| 17303 | } |
| 17304 | |
| 17305 | ExprResult |
| 17306 | Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, |
| 17307 | VerifyICEDiagnoser &Diagnoser, |
| 17308 | AllowFoldKind CanFold) { |
| 17309 | SourceLocation DiagLoc = E->getBeginLoc(); |
| 17310 | |
| 17311 | if (getLangOpts().CPlusPlus11) { |
| 17312 | // C++11 [expr.const]p5: |
| 17313 | // If an expression of literal class type is used in a context where an |
| 17314 | // integral constant expression is required, then that class type shall |
| 17315 | // have a single non-explicit conversion function to an integral or |
| 17316 | // unscoped enumeration type |
| 17317 | ExprResult Converted; |
| 17318 | class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { |
| 17319 | VerifyICEDiagnoser &BaseDiagnoser; |
| 17320 | public: |
| 17321 | CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) |
| 17322 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, |
| 17323 | BaseDiagnoser.Suppress, true), |
| 17324 | BaseDiagnoser(BaseDiagnoser) {} |
| 17325 | |
| 17326 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, |
| 17327 | QualType T) override { |
| 17328 | return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); |
| 17329 | } |
| 17330 | |
| 17331 | SemaDiagnosticBuilder diagnoseIncomplete( |
| 17332 | Sema &S, SourceLocation Loc, QualType T) override { |
| 17333 | return S.Diag(Loc, DiagID: diag::err_ice_incomplete_type) << T; |
| 17334 | } |
| 17335 | |
| 17336 | SemaDiagnosticBuilder diagnoseExplicitConv( |
| 17337 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { |
| 17338 | return S.Diag(Loc, DiagID: diag::err_ice_explicit_conversion) << T << ConvTy; |
| 17339 | } |
| 17340 | |
| 17341 | SemaDiagnosticBuilder noteExplicitConv( |
| 17342 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
| 17343 | return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here) |
| 17344 | << ConvTy->isEnumeralType() << ConvTy; |
| 17345 | } |
| 17346 | |
| 17347 | SemaDiagnosticBuilder diagnoseAmbiguous( |
| 17348 | Sema &S, SourceLocation Loc, QualType T) override { |
| 17349 | return S.Diag(Loc, DiagID: diag::err_ice_ambiguous_conversion) << T; |
| 17350 | } |
| 17351 | |
| 17352 | SemaDiagnosticBuilder noteAmbiguous( |
| 17353 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
| 17354 | return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here) |
| 17355 | << ConvTy->isEnumeralType() << ConvTy; |
| 17356 | } |
| 17357 | |
| 17358 | SemaDiagnosticBuilder diagnoseConversion( |
| 17359 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { |
| 17360 | llvm_unreachable("conversion functions are permitted" ); |
| 17361 | } |
| 17362 | } ConvertDiagnoser(Diagnoser); |
| 17363 | |
| 17364 | Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E, |
| 17365 | Converter&: ConvertDiagnoser); |
| 17366 | if (Converted.isInvalid()) |
| 17367 | return Converted; |
| 17368 | E = Converted.get(); |
| 17369 | // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we |
| 17370 | // don't try to evaluate it later. We also don't want to return the |
| 17371 | // RecoveryExpr here, as it results in this call succeeding, thus callers of |
| 17372 | // this function will attempt to use 'Value'. |
| 17373 | if (isa<RecoveryExpr>(Val: E)) |
| 17374 | return ExprError(); |
| 17375 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) |
| 17376 | return ExprError(); |
| 17377 | } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { |
| 17378 | // An ICE must be of integral or unscoped enumeration type. |
| 17379 | if (!Diagnoser.Suppress) |
| 17380 | Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType()) |
| 17381 | << E->getSourceRange(); |
| 17382 | return ExprError(); |
| 17383 | } |
| 17384 | |
| 17385 | ExprResult RValueExpr = DefaultLvalueConversion(E); |
| 17386 | if (RValueExpr.isInvalid()) |
| 17387 | return ExprError(); |
| 17388 | |
| 17389 | E = RValueExpr.get(); |
| 17390 | |
| 17391 | // Circumvent ICE checking in C++11 to avoid evaluating the expression twice |
| 17392 | // in the non-ICE case. |
| 17393 | if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) { |
| 17394 | SmallVector<PartialDiagnosticAt, 8> Notes; |
| 17395 | if (Result) |
| 17396 | *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes); |
| 17397 | if (!isa<ConstantExpr>(Val: E)) |
| 17398 | E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result)) |
| 17399 | : ConstantExpr::Create(Context, E); |
| 17400 | |
| 17401 | if (Notes.empty()) |
| 17402 | return E; |
| 17403 | |
| 17404 | // If our only note is the usual "invalid subexpression" note, just point |
| 17405 | // the caret at its location rather than producing an essentially |
| 17406 | // redundant note. |
| 17407 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == |
| 17408 | diag::note_invalid_subexpr_in_const_expr) { |
| 17409 | DiagLoc = Notes[0].first; |
| 17410 | Notes.clear(); |
| 17411 | } |
| 17412 | |
| 17413 | if (getLangOpts().CPlusPlus) { |
| 17414 | if (!Diagnoser.Suppress) { |
| 17415 | Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange(); |
| 17416 | for (const PartialDiagnosticAt &Note : Notes) |
| 17417 | Diag(Loc: Note.first, PD: Note.second); |
| 17418 | } |
| 17419 | return ExprError(); |
| 17420 | } |
| 17421 | |
| 17422 | Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange(); |
| 17423 | for (const PartialDiagnosticAt &Note : Notes) |
| 17424 | Diag(Loc: Note.first, PD: Note.second); |
| 17425 | |
| 17426 | return E; |
| 17427 | } |
| 17428 | |
| 17429 | Expr::EvalResult EvalResult; |
| 17430 | SmallVector<PartialDiagnosticAt, 8> Notes; |
| 17431 | EvalResult.Diag = &Notes; |
| 17432 | |
| 17433 | // Try to evaluate the expression, and produce diagnostics explaining why it's |
| 17434 | // not a constant expression as a side-effect. |
| 17435 | bool Folded = |
| 17436 | E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) && |
| 17437 | EvalResult.Val.isInt() && !EvalResult.HasSideEffects && |
| 17438 | (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior); |
| 17439 | |
| 17440 | if (!isa<ConstantExpr>(Val: E)) |
| 17441 | E = ConstantExpr::Create(Context, E, Result: EvalResult.Val); |
| 17442 | |
| 17443 | // In C++11, we can rely on diagnostics being produced for any expression |
| 17444 | // which is not a constant expression. If no diagnostics were produced, then |
| 17445 | // this is a constant expression. |
| 17446 | if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { |
| 17447 | if (Result) |
| 17448 | *Result = EvalResult.Val.getInt(); |
| 17449 | return E; |
| 17450 | } |
| 17451 | |
| 17452 | // If our only note is the usual "invalid subexpression" note, just point |
| 17453 | // the caret at its location rather than producing an essentially |
| 17454 | // redundant note. |
| 17455 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == |
| 17456 | diag::note_invalid_subexpr_in_const_expr) { |
| 17457 | DiagLoc = Notes[0].first; |
| 17458 | Notes.clear(); |
| 17459 | } |
| 17460 | |
| 17461 | if (!Folded || CanFold == AllowFoldKind::No) { |
| 17462 | if (!Diagnoser.Suppress) { |
| 17463 | Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange(); |
| 17464 | for (const PartialDiagnosticAt &Note : Notes) |
| 17465 | Diag(Loc: Note.first, PD: Note.second); |
| 17466 | } |
| 17467 | |
| 17468 | return ExprError(); |
| 17469 | } |
| 17470 | |
| 17471 | Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange(); |
| 17472 | for (const PartialDiagnosticAt &Note : Notes) |
| 17473 | Diag(Loc: Note.first, PD: Note.second); |
| 17474 | |
| 17475 | if (Result) |
| 17476 | *Result = EvalResult.Val.getInt(); |
| 17477 | return E; |
| 17478 | } |
| 17479 | |
| 17480 | namespace { |
| 17481 | // Handle the case where we conclude a expression which we speculatively |
| 17482 | // considered to be unevaluated is actually evaluated. |
| 17483 | class TransformToPE : public TreeTransform<TransformToPE> { |
| 17484 | typedef TreeTransform<TransformToPE> BaseTransform; |
| 17485 | |
| 17486 | public: |
| 17487 | TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } |
| 17488 | |
| 17489 | // Make sure we redo semantic analysis |
| 17490 | bool AlwaysRebuild() { return true; } |
| 17491 | bool ReplacingOriginal() { return true; } |
| 17492 | |
| 17493 | // We need to special-case DeclRefExprs referring to FieldDecls which |
| 17494 | // are not part of a member pointer formation; normal TreeTransforming |
| 17495 | // doesn't catch this case because of the way we represent them in the AST. |
| 17496 | // FIXME: This is a bit ugly; is it really the best way to handle this |
| 17497 | // case? |
| 17498 | // |
| 17499 | // Error on DeclRefExprs referring to FieldDecls. |
| 17500 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { |
| 17501 | if (isa<FieldDecl>(Val: E->getDecl()) && |
| 17502 | !SemaRef.isUnevaluatedContext()) |
| 17503 | return SemaRef.Diag(Loc: E->getLocation(), |
| 17504 | DiagID: diag::err_invalid_non_static_member_use) |
| 17505 | << E->getDecl() << E->getSourceRange(); |
| 17506 | |
| 17507 | return BaseTransform::TransformDeclRefExpr(E); |
| 17508 | } |
| 17509 | |
| 17510 | // Exception: filter out member pointer formation |
| 17511 | ExprResult TransformUnaryOperator(UnaryOperator *E) { |
| 17512 | if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) |
| 17513 | return E; |
| 17514 | |
| 17515 | return BaseTransform::TransformUnaryOperator(E); |
| 17516 | } |
| 17517 | |
| 17518 | // The body of a lambda-expression is in a separate expression evaluation |
| 17519 | // context so never needs to be transformed. |
| 17520 | // FIXME: Ideally we wouldn't transform the closure type either, and would |
| 17521 | // just recreate the capture expressions and lambda expression. |
| 17522 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { |
| 17523 | return SkipLambdaBody(E, S: Body); |
| 17524 | } |
| 17525 | }; |
| 17526 | } |
| 17527 | |
| 17528 | ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { |
| 17529 | assert(isUnevaluatedContext() && |
| 17530 | "Should only transform unevaluated expressions" ); |
| 17531 | ExprEvalContexts.back().Context = |
| 17532 | ExprEvalContexts[ExprEvalContexts.size()-2].Context; |
| 17533 | if (isUnevaluatedContext()) |
| 17534 | return E; |
| 17535 | return TransformToPE(*this).TransformExpr(E); |
| 17536 | } |
| 17537 | |
| 17538 | TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { |
| 17539 | assert(isUnevaluatedContext() && |
| 17540 | "Should only transform unevaluated expressions" ); |
| 17541 | ExprEvalContexts.back().Context = parentEvaluationContext().Context; |
| 17542 | if (isUnevaluatedContext()) |
| 17543 | return TInfo; |
| 17544 | return TransformToPE(*this).TransformType(DI: TInfo); |
| 17545 | } |
| 17546 | |
| 17547 | void |
| 17548 | Sema::PushExpressionEvaluationContext( |
| 17549 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, |
| 17550 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { |
| 17551 | ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup, |
| 17552 | Args&: LambdaContextDecl, Args&: ExprContext); |
| 17553 | |
| 17554 | // Discarded statements and immediate contexts nested in other |
| 17555 | // discarded statements or immediate context are themselves |
| 17556 | // a discarded statement or an immediate context, respectively. |
| 17557 | ExprEvalContexts.back().InDiscardedStatement = |
| 17558 | parentEvaluationContext().isDiscardedStatementContext(); |
| 17559 | |
| 17560 | // C++23 [expr.const]/p15 |
| 17561 | // An expression or conversion is in an immediate function context if [...] |
| 17562 | // it is a subexpression of a manifestly constant-evaluated expression or |
| 17563 | // conversion. |
| 17564 | const auto &Prev = parentEvaluationContext(); |
| 17565 | ExprEvalContexts.back().InImmediateFunctionContext = |
| 17566 | Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated(); |
| 17567 | |
| 17568 | ExprEvalContexts.back().InImmediateEscalatingFunctionContext = |
| 17569 | Prev.InImmediateEscalatingFunctionContext; |
| 17570 | |
| 17571 | Cleanup.reset(); |
| 17572 | if (!MaybeODRUseExprs.empty()) |
| 17573 | std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs); |
| 17574 | } |
| 17575 | |
| 17576 | void |
| 17577 | Sema::PushExpressionEvaluationContext( |
| 17578 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, |
| 17579 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { |
| 17580 | Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; |
| 17581 | PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext); |
| 17582 | } |
| 17583 | |
| 17584 | void Sema::PushExpressionEvaluationContextForFunction( |
| 17585 | ExpressionEvaluationContext NewContext, FunctionDecl *FD) { |
| 17586 | // [expr.const]/p14.1 |
| 17587 | // An expression or conversion is in an immediate function context if it is |
| 17588 | // potentially evaluated and either: its innermost enclosing non-block scope |
| 17589 | // is a function parameter scope of an immediate function. |
| 17590 | PushExpressionEvaluationContext( |
| 17591 | NewContext: FD && FD->isConsteval() |
| 17592 | ? ExpressionEvaluationContext::ImmediateFunctionContext |
| 17593 | : NewContext); |
| 17594 | const Sema::ExpressionEvaluationContextRecord &Parent = |
| 17595 | parentEvaluationContext(); |
| 17596 | Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext(); |
| 17597 | |
| 17598 | Current.InDiscardedStatement = false; |
| 17599 | |
| 17600 | if (FD) { |
| 17601 | |
| 17602 | // Each ExpressionEvaluationContextRecord also keeps track of whether the |
| 17603 | // context is nested in an immediate function context, so smaller contexts |
| 17604 | // that appear inside immediate functions (like variable initializers) are |
| 17605 | // considered to be inside an immediate function context even though by |
| 17606 | // themselves they are not immediate function contexts. But when a new |
| 17607 | // function is entered, we need to reset this tracking, since the entered |
| 17608 | // function might be not an immediate function. |
| 17609 | |
| 17610 | Current.InImmediateEscalatingFunctionContext = |
| 17611 | getLangOpts().CPlusPlus20 && FD->isImmediateEscalating(); |
| 17612 | |
| 17613 | if (isLambdaMethod(DC: FD)) |
| 17614 | Current.InImmediateFunctionContext = |
| 17615 | FD->isConsteval() || |
| 17616 | (isLambdaMethod(DC: FD) && (Parent.isConstantEvaluated() || |
| 17617 | Parent.isImmediateFunctionContext())); |
| 17618 | else |
| 17619 | Current.InImmediateFunctionContext = FD->isConsteval(); |
| 17620 | } |
| 17621 | } |
| 17622 | |
| 17623 | namespace { |
| 17624 | |
| 17625 | const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { |
| 17626 | PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); |
| 17627 | if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) { |
| 17628 | if (E->getOpcode() == UO_Deref) |
| 17629 | return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr()); |
| 17630 | } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) { |
| 17631 | return CheckPossibleDeref(S, PossibleDeref: E->getBase()); |
| 17632 | } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) { |
| 17633 | return CheckPossibleDeref(S, PossibleDeref: E->getBase()); |
| 17634 | } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) { |
| 17635 | QualType Inner; |
| 17636 | QualType Ty = E->getType(); |
| 17637 | if (const auto *Ptr = Ty->getAs<PointerType>()) |
| 17638 | Inner = Ptr->getPointeeType(); |
| 17639 | else if (const auto *Arr = S.Context.getAsArrayType(T: Ty)) |
| 17640 | Inner = Arr->getElementType(); |
| 17641 | else |
| 17642 | return nullptr; |
| 17643 | |
| 17644 | if (Inner->hasAttr(AK: attr::NoDeref)) |
| 17645 | return E; |
| 17646 | } |
| 17647 | return nullptr; |
| 17648 | } |
| 17649 | |
| 17650 | } // namespace |
| 17651 | |
| 17652 | void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { |
| 17653 | for (const Expr *E : Rec.PossibleDerefs) { |
| 17654 | const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E); |
| 17655 | if (DeclRef) { |
| 17656 | const ValueDecl *Decl = DeclRef->getDecl(); |
| 17657 | Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type) |
| 17658 | << Decl->getName() << E->getSourceRange(); |
| 17659 | Diag(Loc: Decl->getLocation(), DiagID: diag::note_previous_decl) << Decl->getName(); |
| 17660 | } else { |
| 17661 | Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type_no_decl) |
| 17662 | << E->getSourceRange(); |
| 17663 | } |
| 17664 | } |
| 17665 | Rec.PossibleDerefs.clear(); |
| 17666 | } |
| 17667 | |
| 17668 | void Sema::CheckUnusedVolatileAssignment(Expr *E) { |
| 17669 | if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) |
| 17670 | return; |
| 17671 | |
| 17672 | // Note: ignoring parens here is not justified by the standard rules, but |
| 17673 | // ignoring parentheses seems like a more reasonable approach, and this only |
| 17674 | // drives a deprecation warning so doesn't affect conformance. |
| 17675 | if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) { |
| 17676 | if (BO->getOpcode() == BO_Assign) { |
| 17677 | auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; |
| 17678 | llvm::erase(C&: LHSs, V: BO->getLHS()); |
| 17679 | } |
| 17680 | } |
| 17681 | } |
| 17682 | |
| 17683 | void Sema::MarkExpressionAsImmediateEscalating(Expr *E) { |
| 17684 | assert(getLangOpts().CPlusPlus20 && |
| 17685 | ExprEvalContexts.back().InImmediateEscalatingFunctionContext && |
| 17686 | "Cannot mark an immediate escalating expression outside of an " |
| 17687 | "immediate escalating context" ); |
| 17688 | if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit()); |
| 17689 | Call && Call->getCallee()) { |
| 17690 | if (auto *DeclRef = |
| 17691 | dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit())) |
| 17692 | DeclRef->setIsImmediateEscalating(true); |
| 17693 | } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) { |
| 17694 | Ctr->setIsImmediateEscalating(true); |
| 17695 | } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) { |
| 17696 | DeclRef->setIsImmediateEscalating(true); |
| 17697 | } else { |
| 17698 | assert(false && "expected an immediately escalating expression" ); |
| 17699 | } |
| 17700 | if (FunctionScopeInfo *FI = getCurFunction()) |
| 17701 | FI->FoundImmediateEscalatingExpression = true; |
| 17702 | } |
| 17703 | |
| 17704 | ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { |
| 17705 | if (isUnevaluatedContext() || !E.isUsable() || !Decl || |
| 17706 | !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() || |
| 17707 | isCheckingDefaultArgumentOrInitializer() || |
| 17708 | RebuildingImmediateInvocation || isImmediateFunctionContext()) |
| 17709 | return E; |
| 17710 | |
| 17711 | /// Opportunistically remove the callee from ReferencesToConsteval if we can. |
| 17712 | /// It's OK if this fails; we'll also remove this in |
| 17713 | /// HandleImmediateInvocations, but catching it here allows us to avoid |
| 17714 | /// walking the AST looking for it in simple cases. |
| 17715 | if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit())) |
| 17716 | if (auto *DeclRef = |
| 17717 | dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit())) |
| 17718 | ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef); |
| 17719 | |
| 17720 | // C++23 [expr.const]/p16 |
| 17721 | // An expression or conversion is immediate-escalating if it is not initially |
| 17722 | // in an immediate function context and it is [...] an immediate invocation |
| 17723 | // that is not a constant expression and is not a subexpression of an |
| 17724 | // immediate invocation. |
| 17725 | APValue Cached; |
| 17726 | auto CheckConstantExpressionAndKeepResult = [&]() { |
| 17727 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; |
| 17728 | Expr::EvalResult Eval; |
| 17729 | Eval.Diag = &Notes; |
| 17730 | bool Res = E.get()->EvaluateAsConstantExpr( |
| 17731 | Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation); |
| 17732 | if (Res && Notes.empty()) { |
| 17733 | Cached = std::move(Eval.Val); |
| 17734 | return true; |
| 17735 | } |
| 17736 | return false; |
| 17737 | }; |
| 17738 | |
| 17739 | if (!E.get()->isValueDependent() && |
| 17740 | ExprEvalContexts.back().InImmediateEscalatingFunctionContext && |
| 17741 | !CheckConstantExpressionAndKeepResult()) { |
| 17742 | MarkExpressionAsImmediateEscalating(E: E.get()); |
| 17743 | return E; |
| 17744 | } |
| 17745 | |
| 17746 | if (Cleanup.exprNeedsCleanups()) { |
| 17747 | // Since an immediate invocation is a full expression itself - it requires |
| 17748 | // an additional ExprWithCleanups node, but it can participate to a bigger |
| 17749 | // full expression which actually requires cleanups to be run after so |
| 17750 | // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it |
| 17751 | // may discard cleanups for outer expression too early. |
| 17752 | |
| 17753 | // Note that ExprWithCleanups created here must always have empty cleanup |
| 17754 | // objects: |
| 17755 | // - compound literals do not create cleanup objects in C++ and immediate |
| 17756 | // invocations are C++-only. |
| 17757 | // - blocks are not allowed inside constant expressions and compiler will |
| 17758 | // issue an error if they appear there. |
| 17759 | // |
| 17760 | // Hence, in correct code any cleanup objects created inside current |
| 17761 | // evaluation context must be outside the immediate invocation. |
| 17762 | E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(), |
| 17763 | CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {}); |
| 17764 | } |
| 17765 | |
| 17766 | ConstantExpr *Res = ConstantExpr::Create( |
| 17767 | Context: getASTContext(), E: E.get(), |
| 17768 | Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(), |
| 17769 | Context: getASTContext()), |
| 17770 | /*IsImmediateInvocation*/ true); |
| 17771 | if (Cached.hasValue()) |
| 17772 | Res->MoveIntoResult(Value&: Cached, Context: getASTContext()); |
| 17773 | /// Value-dependent constant expressions should not be immediately |
| 17774 | /// evaluated until they are instantiated. |
| 17775 | if (!Res->isValueDependent()) |
| 17776 | ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0); |
| 17777 | return Res; |
| 17778 | } |
| 17779 | |
| 17780 | static void EvaluateAndDiagnoseImmediateInvocation( |
| 17781 | Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { |
| 17782 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; |
| 17783 | Expr::EvalResult Eval; |
| 17784 | Eval.Diag = &Notes; |
| 17785 | ConstantExpr *CE = Candidate.getPointer(); |
| 17786 | bool Result = CE->EvaluateAsConstantExpr( |
| 17787 | Result&: Eval, Ctx: SemaRef.getASTContext(), Kind: ConstantExprKind::ImmediateInvocation); |
| 17788 | if (!Result || !Notes.empty()) { |
| 17789 | SemaRef.FailedImmediateInvocations.insert(Ptr: CE); |
| 17790 | Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); |
| 17791 | if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(Val: InnerExpr)) |
| 17792 | InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit(); |
| 17793 | FunctionDecl *FD = nullptr; |
| 17794 | if (auto *Call = dyn_cast<CallExpr>(Val: InnerExpr)) |
| 17795 | FD = cast<FunctionDecl>(Val: Call->getCalleeDecl()); |
| 17796 | else if (auto *Call = dyn_cast<CXXConstructExpr>(Val: InnerExpr)) |
| 17797 | FD = Call->getConstructor(); |
| 17798 | else if (auto *Cast = dyn_cast<CastExpr>(Val: InnerExpr)) |
| 17799 | FD = dyn_cast_or_null<FunctionDecl>(Val: Cast->getConversionFunction()); |
| 17800 | |
| 17801 | assert(FD && FD->isImmediateFunction() && |
| 17802 | "could not find an immediate function in this expression" ); |
| 17803 | if (FD->isInvalidDecl()) |
| 17804 | return; |
| 17805 | SemaRef.Diag(Loc: CE->getBeginLoc(), DiagID: diag::err_invalid_consteval_call) |
| 17806 | << FD << FD->isConsteval(); |
| 17807 | if (auto Context = |
| 17808 | SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) { |
| 17809 | SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer) |
| 17810 | << Context->Decl; |
| 17811 | SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at); |
| 17812 | } |
| 17813 | if (!FD->isConsteval()) |
| 17814 | SemaRef.DiagnoseImmediateEscalatingReason(FD); |
| 17815 | for (auto &Note : Notes) |
| 17816 | SemaRef.Diag(Loc: Note.first, PD: Note.second); |
| 17817 | return; |
| 17818 | } |
| 17819 | CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext()); |
| 17820 | } |
| 17821 | |
| 17822 | static void RemoveNestedImmediateInvocation( |
| 17823 | Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, |
| 17824 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { |
| 17825 | struct ComplexRemove : TreeTransform<ComplexRemove> { |
| 17826 | using Base = TreeTransform<ComplexRemove>; |
| 17827 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; |
| 17828 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; |
| 17829 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator |
| 17830 | CurrentII; |
| 17831 | ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, |
| 17832 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, |
| 17833 | SmallVector<Sema::ImmediateInvocationCandidate, |
| 17834 | 4>::reverse_iterator Current) |
| 17835 | : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} |
| 17836 | void RemoveImmediateInvocation(ConstantExpr* E) { |
| 17837 | auto It = std::find_if(first: CurrentII, last: IISet.rend(), |
| 17838 | pred: [E](Sema::ImmediateInvocationCandidate Elem) { |
| 17839 | return Elem.getPointer() == E; |
| 17840 | }); |
| 17841 | // It is possible that some subexpression of the current immediate |
| 17842 | // invocation was handled from another expression evaluation context. Do |
| 17843 | // not handle the current immediate invocation if some of its |
| 17844 | // subexpressions failed before. |
| 17845 | if (It == IISet.rend()) { |
| 17846 | if (SemaRef.FailedImmediateInvocations.contains(Ptr: E)) |
| 17847 | CurrentII->setInt(1); |
| 17848 | } else { |
| 17849 | It->setInt(1); // Mark as deleted |
| 17850 | } |
| 17851 | } |
| 17852 | ExprResult TransformConstantExpr(ConstantExpr *E) { |
| 17853 | if (!E->isImmediateInvocation()) |
| 17854 | return Base::TransformConstantExpr(E); |
| 17855 | RemoveImmediateInvocation(E); |
| 17856 | return Base::TransformExpr(E: E->getSubExpr()); |
| 17857 | } |
| 17858 | /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so |
| 17859 | /// we need to remove its DeclRefExpr from the DRSet. |
| 17860 | ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { |
| 17861 | DRSet.erase(Ptr: cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit())); |
| 17862 | return Base::TransformCXXOperatorCallExpr(E); |
| 17863 | } |
| 17864 | /// Base::TransformUserDefinedLiteral doesn't preserve the |
| 17865 | /// UserDefinedLiteral node. |
| 17866 | ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; } |
| 17867 | /// Base::TransformInitializer skips ConstantExpr so we need to visit them |
| 17868 | /// here. |
| 17869 | ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { |
| 17870 | if (!Init) |
| 17871 | return Init; |
| 17872 | |
| 17873 | // We cannot use IgnoreImpCasts because we need to preserve |
| 17874 | // full expressions. |
| 17875 | while (true) { |
| 17876 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init)) |
| 17877 | Init = ICE->getSubExpr(); |
| 17878 | else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Val: Init)) |
| 17879 | Init = ICE->getSubExpr(); |
| 17880 | else |
| 17881 | break; |
| 17882 | } |
| 17883 | /// ConstantExprs are the first layer of implicit node to be removed so if |
| 17884 | /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. |
| 17885 | if (auto *CE = dyn_cast<ConstantExpr>(Val: Init); |
| 17886 | CE && CE->isImmediateInvocation()) |
| 17887 | RemoveImmediateInvocation(E: CE); |
| 17888 | return Base::TransformInitializer(Init, NotCopyInit); |
| 17889 | } |
| 17890 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { |
| 17891 | DRSet.erase(Ptr: E); |
| 17892 | return E; |
| 17893 | } |
| 17894 | ExprResult TransformLambdaExpr(LambdaExpr *E) { |
| 17895 | // Do not rebuild lambdas to avoid creating a new type. |
| 17896 | // Lambdas have already been processed inside their eval contexts. |
| 17897 | return E; |
| 17898 | } |
| 17899 | bool AlwaysRebuild() { return false; } |
| 17900 | bool ReplacingOriginal() { return true; } |
| 17901 | bool AllowSkippingCXXConstructExpr() { |
| 17902 | bool Res = AllowSkippingFirstCXXConstructExpr; |
| 17903 | AllowSkippingFirstCXXConstructExpr = true; |
| 17904 | return Res; |
| 17905 | } |
| 17906 | bool AllowSkippingFirstCXXConstructExpr = true; |
| 17907 | } Transformer(SemaRef, Rec.ReferenceToConsteval, |
| 17908 | Rec.ImmediateInvocationCandidates, It); |
| 17909 | |
| 17910 | /// CXXConstructExpr with a single argument are getting skipped by |
| 17911 | /// TreeTransform in some situtation because they could be implicit. This |
| 17912 | /// can only occur for the top-level CXXConstructExpr because it is used |
| 17913 | /// nowhere in the expression being transformed therefore will not be rebuilt. |
| 17914 | /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from |
| 17915 | /// skipping the first CXXConstructExpr. |
| 17916 | if (isa<CXXConstructExpr>(Val: It->getPointer()->IgnoreImplicit())) |
| 17917 | Transformer.AllowSkippingFirstCXXConstructExpr = false; |
| 17918 | |
| 17919 | ExprResult Res = Transformer.TransformExpr(E: It->getPointer()->getSubExpr()); |
| 17920 | // The result may not be usable in case of previous compilation errors. |
| 17921 | // In this case evaluation of the expression may result in crash so just |
| 17922 | // don't do anything further with the result. |
| 17923 | if (Res.isUsable()) { |
| 17924 | Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res); |
| 17925 | It->getPointer()->setSubExpr(Res.get()); |
| 17926 | } |
| 17927 | } |
| 17928 | |
| 17929 | static void |
| 17930 | HandleImmediateInvocations(Sema &SemaRef, |
| 17931 | Sema::ExpressionEvaluationContextRecord &Rec) { |
| 17932 | if ((Rec.ImmediateInvocationCandidates.size() == 0 && |
| 17933 | Rec.ReferenceToConsteval.size() == 0) || |
| 17934 | Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation) |
| 17935 | return; |
| 17936 | |
| 17937 | /// When we have more than 1 ImmediateInvocationCandidates or previously |
| 17938 | /// failed immediate invocations, we need to check for nested |
| 17939 | /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics. |
| 17940 | /// Otherwise we only need to remove ReferenceToConsteval in the immediate |
| 17941 | /// invocation. |
| 17942 | if (Rec.ImmediateInvocationCandidates.size() > 1 || |
| 17943 | !SemaRef.FailedImmediateInvocations.empty()) { |
| 17944 | |
| 17945 | /// Prevent sema calls during the tree transform from adding pointers that |
| 17946 | /// are already in the sets. |
| 17947 | llvm::SaveAndRestore DisableIITracking( |
| 17948 | SemaRef.RebuildingImmediateInvocation, true); |
| 17949 | |
| 17950 | /// Prevent diagnostic during tree transfrom as they are duplicates |
| 17951 | Sema::TentativeAnalysisScope DisableDiag(SemaRef); |
| 17952 | |
| 17953 | for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); |
| 17954 | It != Rec.ImmediateInvocationCandidates.rend(); It++) |
| 17955 | if (!It->getInt()) |
| 17956 | RemoveNestedImmediateInvocation(SemaRef, Rec, It); |
| 17957 | } else if (Rec.ImmediateInvocationCandidates.size() == 1 && |
| 17958 | Rec.ReferenceToConsteval.size()) { |
| 17959 | struct SimpleRemove : DynamicRecursiveASTVisitor { |
| 17960 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; |
| 17961 | SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} |
| 17962 | bool VisitDeclRefExpr(DeclRefExpr *E) override { |
| 17963 | DRSet.erase(Ptr: E); |
| 17964 | return DRSet.size(); |
| 17965 | } |
| 17966 | } Visitor(Rec.ReferenceToConsteval); |
| 17967 | Visitor.TraverseStmt( |
| 17968 | S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); |
| 17969 | } |
| 17970 | for (auto CE : Rec.ImmediateInvocationCandidates) |
| 17971 | if (!CE.getInt()) |
| 17972 | EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE); |
| 17973 | for (auto *DR : Rec.ReferenceToConsteval) { |
| 17974 | // If the expression is immediate escalating, it is not an error; |
| 17975 | // The outer context itself becomes immediate and further errors, |
| 17976 | // if any, will be handled by DiagnoseImmediateEscalatingReason. |
| 17977 | if (DR->isImmediateEscalating()) |
| 17978 | continue; |
| 17979 | auto *FD = cast<FunctionDecl>(Val: DR->getDecl()); |
| 17980 | const NamedDecl *ND = FD; |
| 17981 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND); |
| 17982 | MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD))) |
| 17983 | ND = MD->getParent(); |
| 17984 | |
| 17985 | // C++23 [expr.const]/p16 |
| 17986 | // An expression or conversion is immediate-escalating if it is not |
| 17987 | // initially in an immediate function context and it is [...] a |
| 17988 | // potentially-evaluated id-expression that denotes an immediate function |
| 17989 | // that is not a subexpression of an immediate invocation. |
| 17990 | bool ImmediateEscalating = false; |
| 17991 | bool IsPotentiallyEvaluated = |
| 17992 | Rec.Context == |
| 17993 | Sema::ExpressionEvaluationContext::PotentiallyEvaluated || |
| 17994 | Rec.Context == |
| 17995 | Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed; |
| 17996 | if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated) |
| 17997 | ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext; |
| 17998 | |
| 17999 | if (!Rec.InImmediateEscalatingFunctionContext || |
| 18000 | (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) { |
| 18001 | SemaRef.Diag(Loc: DR->getBeginLoc(), DiagID: diag::err_invalid_consteval_take_address) |
| 18002 | << ND << isa<CXXRecordDecl>(Val: ND) << FD->isConsteval(); |
| 18003 | if (!FD->getBuiltinID()) |
| 18004 | SemaRef.Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at); |
| 18005 | if (auto Context = |
| 18006 | SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) { |
| 18007 | SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer) |
| 18008 | << Context->Decl; |
| 18009 | SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at); |
| 18010 | } |
| 18011 | if (FD->isImmediateEscalating() && !FD->isConsteval()) |
| 18012 | SemaRef.DiagnoseImmediateEscalatingReason(FD); |
| 18013 | |
| 18014 | } else { |
| 18015 | SemaRef.MarkExpressionAsImmediateEscalating(E: DR); |
| 18016 | } |
| 18017 | } |
| 18018 | } |
| 18019 | |
| 18020 | void Sema::PopExpressionEvaluationContext() { |
| 18021 | ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); |
| 18022 | if (!Rec.Lambdas.empty()) { |
| 18023 | using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; |
| 18024 | if (!getLangOpts().CPlusPlus20 && |
| 18025 | (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || |
| 18026 | Rec.isUnevaluated() || |
| 18027 | (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { |
| 18028 | unsigned D; |
| 18029 | if (Rec.isUnevaluated()) { |
| 18030 | // C++11 [expr.prim.lambda]p2: |
| 18031 | // A lambda-expression shall not appear in an unevaluated operand |
| 18032 | // (Clause 5). |
| 18033 | D = diag::err_lambda_unevaluated_operand; |
| 18034 | } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { |
| 18035 | // C++1y [expr.const]p2: |
| 18036 | // A conditional-expression e is a core constant expression unless the |
| 18037 | // evaluation of e, following the rules of the abstract machine, would |
| 18038 | // evaluate [...] a lambda-expression. |
| 18039 | D = diag::err_lambda_in_constant_expression; |
| 18040 | } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { |
| 18041 | // C++17 [expr.prim.lamda]p2: |
| 18042 | // A lambda-expression shall not appear [...] in a template-argument. |
| 18043 | D = diag::err_lambda_in_invalid_context; |
| 18044 | } else |
| 18045 | llvm_unreachable("Couldn't infer lambda error message." ); |
| 18046 | |
| 18047 | for (const auto *L : Rec.Lambdas) |
| 18048 | Diag(Loc: L->getBeginLoc(), DiagID: D); |
| 18049 | } |
| 18050 | } |
| 18051 | |
| 18052 | // Append the collected materialized temporaries into previous context before |
| 18053 | // exit if the previous also is a lifetime extending context. |
| 18054 | if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext && |
| 18055 | parentEvaluationContext().InLifetimeExtendingContext && |
| 18056 | !Rec.ForRangeLifetimeExtendTemps.empty()) { |
| 18057 | parentEvaluationContext().ForRangeLifetimeExtendTemps.append( |
| 18058 | RHS: Rec.ForRangeLifetimeExtendTemps); |
| 18059 | } |
| 18060 | |
| 18061 | WarnOnPendingNoDerefs(Rec); |
| 18062 | HandleImmediateInvocations(SemaRef&: *this, Rec); |
| 18063 | |
| 18064 | // Warn on any volatile-qualified simple-assignments that are not discarded- |
| 18065 | // value expressions nor unevaluated operands (those cases get removed from |
| 18066 | // this list by CheckUnusedVolatileAssignment). |
| 18067 | for (auto *BO : Rec.VolatileAssignmentLHSs) |
| 18068 | Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_deprecated_simple_assign_volatile) |
| 18069 | << BO->getType(); |
| 18070 | |
| 18071 | // When are coming out of an unevaluated context, clear out any |
| 18072 | // temporaries that we may have created as part of the evaluation of |
| 18073 | // the expression in that context: they aren't relevant because they |
| 18074 | // will never be constructed. |
| 18075 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { |
| 18076 | ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects, |
| 18077 | CE: ExprCleanupObjects.end()); |
| 18078 | Cleanup = Rec.ParentCleanup; |
| 18079 | CleanupVarDeclMarking(); |
| 18080 | std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs); |
| 18081 | // Otherwise, merge the contexts together. |
| 18082 | } else { |
| 18083 | Cleanup.mergeFrom(Rhs: Rec.ParentCleanup); |
| 18084 | MaybeODRUseExprs.insert_range(R&: Rec.SavedMaybeODRUseExprs); |
| 18085 | } |
| 18086 | |
| 18087 | // Pop the current expression evaluation context off the stack. |
| 18088 | ExprEvalContexts.pop_back(); |
| 18089 | } |
| 18090 | |
| 18091 | void Sema::DiscardCleanupsInEvaluationContext() { |
| 18092 | ExprCleanupObjects.erase( |
| 18093 | CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, |
| 18094 | CE: ExprCleanupObjects.end()); |
| 18095 | Cleanup.reset(); |
| 18096 | MaybeODRUseExprs.clear(); |
| 18097 | } |
| 18098 | |
| 18099 | ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { |
| 18100 | ExprResult Result = CheckPlaceholderExpr(E); |
| 18101 | if (Result.isInvalid()) |
| 18102 | return ExprError(); |
| 18103 | E = Result.get(); |
| 18104 | if (!E->getType()->isVariablyModifiedType()) |
| 18105 | return E; |
| 18106 | return TransformToPotentiallyEvaluated(E); |
| 18107 | } |
| 18108 | |
| 18109 | /// Are we in a context that is potentially constant evaluated per C++20 |
| 18110 | /// [expr.const]p12? |
| 18111 | static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { |
| 18112 | /// C++2a [expr.const]p12: |
| 18113 | // An expression or conversion is potentially constant evaluated if it is |
| 18114 | switch (SemaRef.ExprEvalContexts.back().Context) { |
| 18115 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: |
| 18116 | case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: |
| 18117 | |
| 18118 | // -- a manifestly constant-evaluated expression, |
| 18119 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: |
| 18120 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: |
| 18121 | case Sema::ExpressionEvaluationContext::DiscardedStatement: |
| 18122 | // -- a potentially-evaluated expression, |
| 18123 | case Sema::ExpressionEvaluationContext::UnevaluatedList: |
| 18124 | // -- an immediate subexpression of a braced-init-list, |
| 18125 | |
| 18126 | // -- [FIXME] an expression of the form & cast-expression that occurs |
| 18127 | // within a templated entity |
| 18128 | // -- a subexpression of one of the above that is not a subexpression of |
| 18129 | // a nested unevaluated operand. |
| 18130 | return true; |
| 18131 | |
| 18132 | case Sema::ExpressionEvaluationContext::Unevaluated: |
| 18133 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: |
| 18134 | // Expressions in this context are never evaluated. |
| 18135 | return false; |
| 18136 | } |
| 18137 | llvm_unreachable("Invalid context" ); |
| 18138 | } |
| 18139 | |
| 18140 | /// Return true if this function has a calling convention that requires mangling |
| 18141 | /// in the size of the parameter pack. |
| 18142 | static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { |
| 18143 | // These manglings are only applicable for targets whcih use Microsoft |
| 18144 | // mangling scheme for C. |
| 18145 | if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling()) |
| 18146 | return false; |
| 18147 | |
| 18148 | // If this is C++ and this isn't an extern "C" function, parameters do not |
| 18149 | // need to be complete. In this case, C++ mangling will apply, which doesn't |
| 18150 | // use the size of the parameters. |
| 18151 | if (S.getLangOpts().CPlusPlus && !FD->isExternC()) |
| 18152 | return false; |
| 18153 | |
| 18154 | // Stdcall, fastcall, and vectorcall need this special treatment. |
| 18155 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); |
| 18156 | switch (CC) { |
| 18157 | case CC_X86StdCall: |
| 18158 | case CC_X86FastCall: |
| 18159 | case CC_X86VectorCall: |
| 18160 | return true; |
| 18161 | default: |
| 18162 | break; |
| 18163 | } |
| 18164 | return false; |
| 18165 | } |
| 18166 | |
| 18167 | /// Require that all of the parameter types of function be complete. Normally, |
| 18168 | /// parameter types are only required to be complete when a function is called |
| 18169 | /// or defined, but to mangle functions with certain calling conventions, the |
| 18170 | /// mangler needs to know the size of the parameter list. In this situation, |
| 18171 | /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles |
| 18172 | /// the function as _foo@0, i.e. zero bytes of parameters, which will usually |
| 18173 | /// result in a linker error. Clang doesn't implement this behavior, and instead |
| 18174 | /// attempts to error at compile time. |
| 18175 | static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, |
| 18176 | SourceLocation Loc) { |
| 18177 | class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { |
| 18178 | FunctionDecl *FD; |
| 18179 | ParmVarDecl *Param; |
| 18180 | |
| 18181 | public: |
| 18182 | ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) |
| 18183 | : FD(FD), Param(Param) {} |
| 18184 | |
| 18185 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
| 18186 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); |
| 18187 | StringRef CCName; |
| 18188 | switch (CC) { |
| 18189 | case CC_X86StdCall: |
| 18190 | CCName = "stdcall" ; |
| 18191 | break; |
| 18192 | case CC_X86FastCall: |
| 18193 | CCName = "fastcall" ; |
| 18194 | break; |
| 18195 | case CC_X86VectorCall: |
| 18196 | CCName = "vectorcall" ; |
| 18197 | break; |
| 18198 | default: |
| 18199 | llvm_unreachable("CC does not need mangling" ); |
| 18200 | } |
| 18201 | |
| 18202 | S.Diag(Loc, DiagID: diag::err_cconv_incomplete_param_type) |
| 18203 | << Param->getDeclName() << FD->getDeclName() << CCName; |
| 18204 | } |
| 18205 | }; |
| 18206 | |
| 18207 | for (ParmVarDecl *Param : FD->parameters()) { |
| 18208 | ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); |
| 18209 | S.RequireCompleteType(Loc, T: Param->getType(), Diagnoser); |
| 18210 | } |
| 18211 | } |
| 18212 | |
| 18213 | namespace { |
| 18214 | enum class OdrUseContext { |
| 18215 | /// Declarations in this context are not odr-used. |
| 18216 | None, |
| 18217 | /// Declarations in this context are formally odr-used, but this is a |
| 18218 | /// dependent context. |
| 18219 | Dependent, |
| 18220 | /// Declarations in this context are odr-used but not actually used (yet). |
| 18221 | FormallyOdrUsed, |
| 18222 | /// Declarations in this context are used. |
| 18223 | Used |
| 18224 | }; |
| 18225 | } |
| 18226 | |
| 18227 | /// Are we within a context in which references to resolved functions or to |
| 18228 | /// variables result in odr-use? |
| 18229 | static OdrUseContext isOdrUseContext(Sema &SemaRef) { |
| 18230 | const Sema::ExpressionEvaluationContextRecord &Context = |
| 18231 | SemaRef.currentEvaluationContext(); |
| 18232 | |
| 18233 | if (Context.isUnevaluated()) |
| 18234 | return OdrUseContext::None; |
| 18235 | |
| 18236 | if (SemaRef.CurContext->isDependentContext()) |
| 18237 | return OdrUseContext::Dependent; |
| 18238 | |
| 18239 | if (Context.isDiscardedStatementContext()) |
| 18240 | return OdrUseContext::FormallyOdrUsed; |
| 18241 | |
| 18242 | else if (Context.Context == |
| 18243 | Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) |
| 18244 | return OdrUseContext::FormallyOdrUsed; |
| 18245 | |
| 18246 | return OdrUseContext::Used; |
| 18247 | } |
| 18248 | |
| 18249 | static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { |
| 18250 | if (!Func->isConstexpr()) |
| 18251 | return false; |
| 18252 | |
| 18253 | if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) |
| 18254 | return true; |
| 18255 | |
| 18256 | // Lambda conversion operators are never user provided. |
| 18257 | if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: Func)) |
| 18258 | return isLambdaConversionOperator(C: Conv); |
| 18259 | |
| 18260 | auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func); |
| 18261 | return CCD && CCD->getInheritedConstructor(); |
| 18262 | } |
| 18263 | |
| 18264 | void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, |
| 18265 | bool MightBeOdrUse) { |
| 18266 | assert(Func && "No function?" ); |
| 18267 | |
| 18268 | Func->setReferenced(); |
| 18269 | |
| 18270 | // Recursive functions aren't really used until they're used from some other |
| 18271 | // context. |
| 18272 | bool IsRecursiveCall = CurContext == Func; |
| 18273 | |
| 18274 | // C++11 [basic.def.odr]p3: |
| 18275 | // A function whose name appears as a potentially-evaluated expression is |
| 18276 | // odr-used if it is the unique lookup result or the selected member of a |
| 18277 | // set of overloaded functions [...]. |
| 18278 | // |
| 18279 | // We (incorrectly) mark overload resolution as an unevaluated context, so we |
| 18280 | // can just check that here. |
| 18281 | OdrUseContext OdrUse = |
| 18282 | MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None; |
| 18283 | if (IsRecursiveCall && OdrUse == OdrUseContext::Used) |
| 18284 | OdrUse = OdrUseContext::FormallyOdrUsed; |
| 18285 | |
| 18286 | // Trivial default constructors and destructors are never actually used. |
| 18287 | // FIXME: What about other special members? |
| 18288 | if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && |
| 18289 | OdrUse == OdrUseContext::Used) { |
| 18290 | if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) |
| 18291 | if (Constructor->isDefaultConstructor()) |
| 18292 | OdrUse = OdrUseContext::FormallyOdrUsed; |
| 18293 | if (isa<CXXDestructorDecl>(Val: Func)) |
| 18294 | OdrUse = OdrUseContext::FormallyOdrUsed; |
| 18295 | } |
| 18296 | |
| 18297 | // C++20 [expr.const]p12: |
| 18298 | // A function [...] is needed for constant evaluation if it is [...] a |
| 18299 | // constexpr function that is named by an expression that is potentially |
| 18300 | // constant evaluated |
| 18301 | bool NeededForConstantEvaluation = |
| 18302 | isPotentiallyConstantEvaluatedContext(SemaRef&: *this) && |
| 18303 | isImplicitlyDefinableConstexprFunction(Func); |
| 18304 | |
| 18305 | // Determine whether we require a function definition to exist, per |
| 18306 | // C++11 [temp.inst]p3: |
| 18307 | // Unless a function template specialization has been explicitly |
| 18308 | // instantiated or explicitly specialized, the function template |
| 18309 | // specialization is implicitly instantiated when the specialization is |
| 18310 | // referenced in a context that requires a function definition to exist. |
| 18311 | // C++20 [temp.inst]p7: |
| 18312 | // The existence of a definition of a [...] function is considered to |
| 18313 | // affect the semantics of the program if the [...] function is needed for |
| 18314 | // constant evaluation by an expression |
| 18315 | // C++20 [basic.def.odr]p10: |
| 18316 | // Every program shall contain exactly one definition of every non-inline |
| 18317 | // function or variable that is odr-used in that program outside of a |
| 18318 | // discarded statement |
| 18319 | // C++20 [special]p1: |
| 18320 | // The implementation will implicitly define [defaulted special members] |
| 18321 | // if they are odr-used or needed for constant evaluation. |
| 18322 | // |
| 18323 | // Note that we skip the implicit instantiation of templates that are only |
| 18324 | // used in unused default arguments or by recursive calls to themselves. |
| 18325 | // This is formally non-conforming, but seems reasonable in practice. |
| 18326 | bool NeedDefinition = |
| 18327 | !IsRecursiveCall && |
| 18328 | (OdrUse == OdrUseContext::Used || |
| 18329 | (NeededForConstantEvaluation && !Func->isPureVirtual())); |
| 18330 | |
| 18331 | // C++14 [temp.expl.spec]p6: |
| 18332 | // If a template [...] is explicitly specialized then that specialization |
| 18333 | // shall be declared before the first use of that specialization that would |
| 18334 | // cause an implicit instantiation to take place, in every translation unit |
| 18335 | // in which such a use occurs |
| 18336 | if (NeedDefinition && |
| 18337 | (Func->getTemplateSpecializationKind() != TSK_Undeclared || |
| 18338 | Func->getMemberSpecializationInfo())) |
| 18339 | checkSpecializationReachability(Loc, Spec: Func); |
| 18340 | |
| 18341 | if (getLangOpts().CUDA) |
| 18342 | CUDA().CheckCall(Loc, Callee: Func); |
| 18343 | |
| 18344 | // If we need a definition, try to create one. |
| 18345 | if (NeedDefinition && !Func->getBody()) { |
| 18346 | runWithSufficientStackSpace(Loc, Fn: [&] { |
| 18347 | if (CXXConstructorDecl *Constructor = |
| 18348 | dyn_cast<CXXConstructorDecl>(Val: Func)) { |
| 18349 | Constructor = cast<CXXConstructorDecl>(Val: Constructor->getFirstDecl()); |
| 18350 | if (Constructor->isDefaulted() && !Constructor->isDeleted()) { |
| 18351 | if (Constructor->isDefaultConstructor()) { |
| 18352 | if (Constructor->isTrivial() && |
| 18353 | !Constructor->hasAttr<DLLExportAttr>()) |
| 18354 | return; |
| 18355 | DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor); |
| 18356 | } else if (Constructor->isCopyConstructor()) { |
| 18357 | DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor); |
| 18358 | } else if (Constructor->isMoveConstructor()) { |
| 18359 | DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor); |
| 18360 | } |
| 18361 | } else if (Constructor->getInheritedConstructor()) { |
| 18362 | DefineInheritingConstructor(UseLoc: Loc, Constructor); |
| 18363 | } |
| 18364 | } else if (CXXDestructorDecl *Destructor = |
| 18365 | dyn_cast<CXXDestructorDecl>(Val: Func)) { |
| 18366 | Destructor = cast<CXXDestructorDecl>(Val: Destructor->getFirstDecl()); |
| 18367 | if (Destructor->isDefaulted() && !Destructor->isDeleted()) { |
| 18368 | if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) |
| 18369 | return; |
| 18370 | DefineImplicitDestructor(CurrentLocation: Loc, Destructor); |
| 18371 | } |
| 18372 | if (Destructor->isVirtual() && getLangOpts().AppleKext) |
| 18373 | MarkVTableUsed(Loc, Class: Destructor->getParent()); |
| 18374 | } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) { |
| 18375 | if (MethodDecl->isOverloadedOperator() && |
| 18376 | MethodDecl->getOverloadedOperator() == OO_Equal) { |
| 18377 | MethodDecl = cast<CXXMethodDecl>(Val: MethodDecl->getFirstDecl()); |
| 18378 | if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { |
| 18379 | if (MethodDecl->isCopyAssignmentOperator()) |
| 18380 | DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl); |
| 18381 | else if (MethodDecl->isMoveAssignmentOperator()) |
| 18382 | DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl); |
| 18383 | } |
| 18384 | } else if (isa<CXXConversionDecl>(Val: MethodDecl) && |
| 18385 | MethodDecl->getParent()->isLambda()) { |
| 18386 | CXXConversionDecl *Conversion = |
| 18387 | cast<CXXConversionDecl>(Val: MethodDecl->getFirstDecl()); |
| 18388 | if (Conversion->isLambdaToBlockPointerConversion()) |
| 18389 | DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion); |
| 18390 | else |
| 18391 | DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion); |
| 18392 | } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) |
| 18393 | MarkVTableUsed(Loc, Class: MethodDecl->getParent()); |
| 18394 | } |
| 18395 | |
| 18396 | if (Func->isDefaulted() && !Func->isDeleted()) { |
| 18397 | DefaultedComparisonKind DCK = getDefaultedComparisonKind(FD: Func); |
| 18398 | if (DCK != DefaultedComparisonKind::None) |
| 18399 | DefineDefaultedComparison(Loc, FD: Func, DCK); |
| 18400 | } |
| 18401 | |
| 18402 | // Implicit instantiation of function templates and member functions of |
| 18403 | // class templates. |
| 18404 | if (Func->isImplicitlyInstantiable()) { |
| 18405 | TemplateSpecializationKind TSK = |
| 18406 | Func->getTemplateSpecializationKindForInstantiation(); |
| 18407 | SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); |
| 18408 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); |
| 18409 | if (FirstInstantiation) { |
| 18410 | PointOfInstantiation = Loc; |
| 18411 | if (auto *MSI = Func->getMemberSpecializationInfo()) |
| 18412 | MSI->setPointOfInstantiation(Loc); |
| 18413 | // FIXME: Notify listener. |
| 18414 | else |
| 18415 | Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
| 18416 | } else if (TSK != TSK_ImplicitInstantiation) { |
| 18417 | // Use the point of use as the point of instantiation, instead of the |
| 18418 | // point of explicit instantiation (which we track as the actual point |
| 18419 | // of instantiation). This gives better backtraces in diagnostics. |
| 18420 | PointOfInstantiation = Loc; |
| 18421 | } |
| 18422 | |
| 18423 | if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || |
| 18424 | Func->isConstexpr()) { |
| 18425 | if (isa<CXXRecordDecl>(Val: Func->getDeclContext()) && |
| 18426 | cast<CXXRecordDecl>(Val: Func->getDeclContext())->isLocalClass() && |
| 18427 | CodeSynthesisContexts.size()) |
| 18428 | PendingLocalImplicitInstantiations.push_back( |
| 18429 | x: std::make_pair(x&: Func, y&: PointOfInstantiation)); |
| 18430 | else if (Func->isConstexpr()) |
| 18431 | // Do not defer instantiations of constexpr functions, to avoid the |
| 18432 | // expression evaluator needing to call back into Sema if it sees a |
| 18433 | // call to such a function. |
| 18434 | InstantiateFunctionDefinition(PointOfInstantiation, Function: Func); |
| 18435 | else { |
| 18436 | Func->setInstantiationIsPending(true); |
| 18437 | PendingInstantiations.push_back( |
| 18438 | x: std::make_pair(x&: Func, y&: PointOfInstantiation)); |
| 18439 | if (llvm::isTimeTraceVerbose()) { |
| 18440 | llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation" , Detail: [&] { |
| 18441 | std::string Name; |
| 18442 | llvm::raw_string_ostream OS(Name); |
| 18443 | Func->getNameForDiagnostic(OS, Policy: getPrintingPolicy(), |
| 18444 | /*Qualified=*/true); |
| 18445 | return Name; |
| 18446 | }); |
| 18447 | } |
| 18448 | // Notify the consumer that a function was implicitly instantiated. |
| 18449 | Consumer.HandleCXXImplicitFunctionInstantiation(D: Func); |
| 18450 | } |
| 18451 | } |
| 18452 | } else { |
| 18453 | // Walk redefinitions, as some of them may be instantiable. |
| 18454 | for (auto *i : Func->redecls()) { |
| 18455 | if (!i->isUsed(CheckUsedAttr: false) && i->isImplicitlyInstantiable()) |
| 18456 | MarkFunctionReferenced(Loc, Func: i, MightBeOdrUse); |
| 18457 | } |
| 18458 | } |
| 18459 | }); |
| 18460 | } |
| 18461 | |
| 18462 | // If a constructor was defined in the context of a default parameter |
| 18463 | // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed |
| 18464 | // context), its initializers may not be referenced yet. |
| 18465 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) { |
| 18466 | EnterExpressionEvaluationContext EvalContext( |
| 18467 | *this, |
| 18468 | Constructor->isImmediateFunction() |
| 18469 | ? ExpressionEvaluationContext::ImmediateFunctionContext |
| 18470 | : ExpressionEvaluationContext::PotentiallyEvaluated, |
| 18471 | Constructor); |
| 18472 | for (CXXCtorInitializer *Init : Constructor->inits()) { |
| 18473 | if (Init->isInClassMemberInitializer()) |
| 18474 | runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() { |
| 18475 | MarkDeclarationsReferencedInExpr(E: Init->getInit()); |
| 18476 | }); |
| 18477 | } |
| 18478 | } |
| 18479 | |
| 18480 | // C++14 [except.spec]p17: |
| 18481 | // An exception-specification is considered to be needed when: |
| 18482 | // - the function is odr-used or, if it appears in an unevaluated operand, |
| 18483 | // would be odr-used if the expression were potentially-evaluated; |
| 18484 | // |
| 18485 | // Note, we do this even if MightBeOdrUse is false. That indicates that the |
| 18486 | // function is a pure virtual function we're calling, and in that case the |
| 18487 | // function was selected by overload resolution and we need to resolve its |
| 18488 | // exception specification for a different reason. |
| 18489 | const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); |
| 18490 | if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) |
| 18491 | ResolveExceptionSpec(Loc, FPT); |
| 18492 | |
| 18493 | // A callee could be called by a host function then by a device function. |
| 18494 | // If we only try recording once, we will miss recording the use on device |
| 18495 | // side. Therefore keep trying until it is recorded. |
| 18496 | if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice && |
| 18497 | !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func)) |
| 18498 | CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func); |
| 18499 | |
| 18500 | // If this is the first "real" use, act on that. |
| 18501 | if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { |
| 18502 | // Keep track of used but undefined functions. |
| 18503 | if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) { |
| 18504 | if (mightHaveNonExternalLinkage(FD: Func)) |
| 18505 | UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc)); |
| 18506 | else if (Func->getMostRecentDecl()->isInlined() && |
| 18507 | !LangOpts.GNUInline && |
| 18508 | !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) |
| 18509 | UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc)); |
| 18510 | else if (isExternalWithNoLinkageType(VD: Func)) |
| 18511 | UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc)); |
| 18512 | } |
| 18513 | |
| 18514 | // Some x86 Windows calling conventions mangle the size of the parameter |
| 18515 | // pack into the name. Computing the size of the parameters requires the |
| 18516 | // parameter types to be complete. Check that now. |
| 18517 | if (funcHasParameterSizeMangling(S&: *this, FD: Func)) |
| 18518 | CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc); |
| 18519 | |
| 18520 | // In the MS C++ ABI, the compiler emits destructor variants where they are |
| 18521 | // used. If the destructor is used here but defined elsewhere, mark the |
| 18522 | // virtual base destructors referenced. If those virtual base destructors |
| 18523 | // are inline, this will ensure they are defined when emitting the complete |
| 18524 | // destructor variant. This checking may be redundant if the destructor is |
| 18525 | // provided later in this TU. |
| 18526 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
| 18527 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) { |
| 18528 | CXXRecordDecl *Parent = Dtor->getParent(); |
| 18529 | if (Parent->getNumVBases() > 0 && !Dtor->getBody()) |
| 18530 | CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor); |
| 18531 | } |
| 18532 | } |
| 18533 | |
| 18534 | Func->markUsed(C&: Context); |
| 18535 | } |
| 18536 | } |
| 18537 | |
| 18538 | /// Directly mark a variable odr-used. Given a choice, prefer to use |
| 18539 | /// MarkVariableReferenced since it does additional checks and then |
| 18540 | /// calls MarkVarDeclODRUsed. |
| 18541 | /// If the variable must be captured: |
| 18542 | /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext |
| 18543 | /// - else capture it in the DeclContext that maps to the |
| 18544 | /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. |
| 18545 | static void |
| 18546 | MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, |
| 18547 | const unsigned *const FunctionScopeIndexToStopAt = nullptr) { |
| 18548 | // Keep track of used but undefined variables. |
| 18549 | // FIXME: We shouldn't suppress this warning for static data members. |
| 18550 | VarDecl *Var = V->getPotentiallyDecomposedVarDecl(); |
| 18551 | assert(Var && "expected a capturable variable" ); |
| 18552 | |
| 18553 | if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && |
| 18554 | (!Var->isExternallyVisible() || Var->isInline() || |
| 18555 | SemaRef.isExternalWithNoLinkageType(VD: Var)) && |
| 18556 | !(Var->isStaticDataMember() && Var->hasInit())) { |
| 18557 | SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; |
| 18558 | if (old.isInvalid()) |
| 18559 | old = Loc; |
| 18560 | } |
| 18561 | QualType CaptureType, DeclRefType; |
| 18562 | if (SemaRef.LangOpts.OpenMP) |
| 18563 | SemaRef.OpenMP().tryCaptureOpenMPLambdas(V); |
| 18564 | SemaRef.tryCaptureVariable(Var: V, Loc, Kind: TryCaptureKind::Implicit, |
| 18565 | /*EllipsisLoc*/ SourceLocation(), |
| 18566 | /*BuildAndDiagnose*/ true, CaptureType, |
| 18567 | DeclRefType, FunctionScopeIndexToStopAt); |
| 18568 | |
| 18569 | if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) { |
| 18570 | auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext); |
| 18571 | auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var); |
| 18572 | auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD); |
| 18573 | if (VarTarget == SemaCUDA::CVT_Host && |
| 18574 | (UserTarget == CUDAFunctionTarget::Device || |
| 18575 | UserTarget == CUDAFunctionTarget::HostDevice || |
| 18576 | UserTarget == CUDAFunctionTarget::Global)) { |
| 18577 | // Diagnose ODR-use of host global variables in device functions. |
| 18578 | // Reference of device global variables in host functions is allowed |
| 18579 | // through shadow variables therefore it is not diagnosed. |
| 18580 | if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) { |
| 18581 | SemaRef.targetDiag(Loc, DiagID: diag::err_ref_bad_target) |
| 18582 | << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; |
| 18583 | SemaRef.targetDiag(Loc: Var->getLocation(), |
| 18584 | DiagID: Var->getType().isConstQualified() |
| 18585 | ? diag::note_cuda_const_var_unpromoted |
| 18586 | : diag::note_cuda_host_var); |
| 18587 | } |
| 18588 | } else if (VarTarget == SemaCUDA::CVT_Device && |
| 18589 | !Var->hasAttr<CUDASharedAttr>() && |
| 18590 | (UserTarget == CUDAFunctionTarget::Host || |
| 18591 | UserTarget == CUDAFunctionTarget::HostDevice)) { |
| 18592 | // Record a CUDA/HIP device side variable if it is ODR-used |
| 18593 | // by host code. This is done conservatively, when the variable is |
| 18594 | // referenced in any of the following contexts: |
| 18595 | // - a non-function context |
| 18596 | // - a host function |
| 18597 | // - a host device function |
| 18598 | // This makes the ODR-use of the device side variable by host code to |
| 18599 | // be visible in the device compilation for the compiler to be able to |
| 18600 | // emit template variables instantiated by host code only and to |
| 18601 | // externalize the static device side variable ODR-used by host code. |
| 18602 | if (!Var->hasExternalStorage()) |
| 18603 | SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(V: Var); |
| 18604 | else if (SemaRef.LangOpts.GPURelocatableDeviceCode && |
| 18605 | (!FD || (!FD->getDescribedFunctionTemplate() && |
| 18606 | SemaRef.getASTContext().GetGVALinkageForFunction(FD) == |
| 18607 | GVA_StrongExternal))) |
| 18608 | SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Var); |
| 18609 | } |
| 18610 | } |
| 18611 | |
| 18612 | V->markUsed(C&: SemaRef.Context); |
| 18613 | } |
| 18614 | |
| 18615 | void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, |
| 18616 | SourceLocation Loc, |
| 18617 | unsigned CapturingScopeIndex) { |
| 18618 | MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex); |
| 18619 | } |
| 18620 | |
| 18621 | void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, |
| 18622 | ValueDecl *var) { |
| 18623 | DeclContext *VarDC = var->getDeclContext(); |
| 18624 | |
| 18625 | // If the parameter still belongs to the translation unit, then |
| 18626 | // we're actually just using one parameter in the declaration of |
| 18627 | // the next. |
| 18628 | if (isa<ParmVarDecl>(Val: var) && |
| 18629 | isa<TranslationUnitDecl>(Val: VarDC)) |
| 18630 | return; |
| 18631 | |
| 18632 | // For C code, don't diagnose about capture if we're not actually in code |
| 18633 | // right now; it's impossible to write a non-constant expression outside of |
| 18634 | // function context, so we'll get other (more useful) diagnostics later. |
| 18635 | // |
| 18636 | // For C++, things get a bit more nasty... it would be nice to suppress this |
| 18637 | // diagnostic for certain cases like using a local variable in an array bound |
| 18638 | // for a member of a local class, but the correct predicate is not obvious. |
| 18639 | if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) |
| 18640 | return; |
| 18641 | |
| 18642 | unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0; |
| 18643 | unsigned ContextKind = 3; // unknown |
| 18644 | if (isa<CXXMethodDecl>(Val: VarDC) && |
| 18645 | cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) { |
| 18646 | ContextKind = 2; |
| 18647 | } else if (isa<FunctionDecl>(Val: VarDC)) { |
| 18648 | ContextKind = 0; |
| 18649 | } else if (isa<BlockDecl>(Val: VarDC)) { |
| 18650 | ContextKind = 1; |
| 18651 | } |
| 18652 | |
| 18653 | S.Diag(Loc: loc, DiagID: diag::err_reference_to_local_in_enclosing_context) |
| 18654 | << var << ValueKind << ContextKind << VarDC; |
| 18655 | S.Diag(Loc: var->getLocation(), DiagID: diag::note_entity_declared_at) |
| 18656 | << var; |
| 18657 | |
| 18658 | // FIXME: Add additional diagnostic info about class etc. which prevents |
| 18659 | // capture. |
| 18660 | } |
| 18661 | |
| 18662 | static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, |
| 18663 | ValueDecl *Var, |
| 18664 | bool &SubCapturesAreNested, |
| 18665 | QualType &CaptureType, |
| 18666 | QualType &DeclRefType) { |
| 18667 | // Check whether we've already captured it. |
| 18668 | if (CSI->CaptureMap.count(Val: Var)) { |
| 18669 | // If we found a capture, any subcaptures are nested. |
| 18670 | SubCapturesAreNested = true; |
| 18671 | |
| 18672 | // Retrieve the capture type for this variable. |
| 18673 | CaptureType = CSI->getCapture(Var).getCaptureType(); |
| 18674 | |
| 18675 | // Compute the type of an expression that refers to this variable. |
| 18676 | DeclRefType = CaptureType.getNonReferenceType(); |
| 18677 | |
| 18678 | // Similarly to mutable captures in lambda, all the OpenMP captures by copy |
| 18679 | // are mutable in the sense that user can change their value - they are |
| 18680 | // private instances of the captured declarations. |
| 18681 | const Capture &Cap = CSI->getCapture(Var); |
| 18682 | // C++ [expr.prim.lambda]p10: |
| 18683 | // The type of such a data member is [...] an lvalue reference to the |
| 18684 | // referenced function type if the entity is a reference to a function. |
| 18685 | // [...] |
| 18686 | if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() && |
| 18687 | !(isa<LambdaScopeInfo>(Val: CSI) && |
| 18688 | !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) && |
| 18689 | !(isa<CapturedRegionScopeInfo>(Val: CSI) && |
| 18690 | cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP)) |
| 18691 | DeclRefType.addConst(); |
| 18692 | return true; |
| 18693 | } |
| 18694 | return false; |
| 18695 | } |
| 18696 | |
| 18697 | // Only block literals, captured statements, and lambda expressions can |
| 18698 | // capture; other scopes don't work. |
| 18699 | static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, |
| 18700 | ValueDecl *Var, |
| 18701 | SourceLocation Loc, |
| 18702 | const bool Diagnose, |
| 18703 | Sema &S) { |
| 18704 | if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC)) |
| 18705 | return getLambdaAwareParentOfDeclContext(DC); |
| 18706 | |
| 18707 | VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl(); |
| 18708 | if (Underlying) { |
| 18709 | if (Underlying->hasLocalStorage() && Diagnose) |
| 18710 | diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var); |
| 18711 | } |
| 18712 | return nullptr; |
| 18713 | } |
| 18714 | |
| 18715 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture |
| 18716 | // certain types of variables (unnamed, variably modified types etc.) |
| 18717 | // so check for eligibility. |
| 18718 | static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, |
| 18719 | SourceLocation Loc, const bool Diagnose, |
| 18720 | Sema &S) { |
| 18721 | |
| 18722 | assert((isa<VarDecl, BindingDecl>(Var)) && |
| 18723 | "Only variables and structured bindings can be captured" ); |
| 18724 | |
| 18725 | bool IsBlock = isa<BlockScopeInfo>(Val: CSI); |
| 18726 | bool IsLambda = isa<LambdaScopeInfo>(Val: CSI); |
| 18727 | |
| 18728 | // Lambdas are not allowed to capture unnamed variables |
| 18729 | // (e.g. anonymous unions). |
| 18730 | // FIXME: The C++11 rule don't actually state this explicitly, but I'm |
| 18731 | // assuming that's the intent. |
| 18732 | if (IsLambda && !Var->getDeclName()) { |
| 18733 | if (Diagnose) { |
| 18734 | S.Diag(Loc, DiagID: diag::err_lambda_capture_anonymous_var); |
| 18735 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_declared_at); |
| 18736 | } |
| 18737 | return false; |
| 18738 | } |
| 18739 | |
| 18740 | // Prohibit variably-modified types in blocks; they're difficult to deal with. |
| 18741 | if (Var->getType()->isVariablyModifiedType() && IsBlock) { |
| 18742 | if (Diagnose) { |
| 18743 | S.Diag(Loc, DiagID: diag::err_ref_vm_type); |
| 18744 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
| 18745 | } |
| 18746 | return false; |
| 18747 | } |
| 18748 | // Prohibit structs with flexible array members too. |
| 18749 | // We cannot capture what is in the tail end of the struct. |
| 18750 | if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { |
| 18751 | if (VTTy->getDecl()->hasFlexibleArrayMember()) { |
| 18752 | if (Diagnose) { |
| 18753 | if (IsBlock) |
| 18754 | S.Diag(Loc, DiagID: diag::err_ref_flexarray_type); |
| 18755 | else |
| 18756 | S.Diag(Loc, DiagID: diag::err_lambda_capture_flexarray_type) << Var; |
| 18757 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
| 18758 | } |
| 18759 | return false; |
| 18760 | } |
| 18761 | } |
| 18762 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); |
| 18763 | // Lambdas and captured statements are not allowed to capture __block |
| 18764 | // variables; they don't support the expected semantics. |
| 18765 | if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) { |
| 18766 | if (Diagnose) { |
| 18767 | S.Diag(Loc, DiagID: diag::err_capture_block_variable) << Var << !IsLambda; |
| 18768 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
| 18769 | } |
| 18770 | return false; |
| 18771 | } |
| 18772 | // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks |
| 18773 | if (S.getLangOpts().OpenCL && IsBlock && |
| 18774 | Var->getType()->isBlockPointerType()) { |
| 18775 | if (Diagnose) |
| 18776 | S.Diag(Loc, DiagID: diag::err_opencl_block_ref_block); |
| 18777 | return false; |
| 18778 | } |
| 18779 | |
| 18780 | if (isa<BindingDecl>(Val: Var)) { |
| 18781 | if (!IsLambda || !S.getLangOpts().CPlusPlus) { |
| 18782 | if (Diagnose) |
| 18783 | diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var); |
| 18784 | return false; |
| 18785 | } else if (Diagnose && S.getLangOpts().CPlusPlus) { |
| 18786 | S.Diag(Loc, DiagID: S.LangOpts.CPlusPlus20 |
| 18787 | ? diag::warn_cxx17_compat_capture_binding |
| 18788 | : diag::ext_capture_binding) |
| 18789 | << Var; |
| 18790 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var; |
| 18791 | } |
| 18792 | } |
| 18793 | |
| 18794 | return true; |
| 18795 | } |
| 18796 | |
| 18797 | // Returns true if the capture by block was successful. |
| 18798 | static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, |
| 18799 | SourceLocation Loc, const bool BuildAndDiagnose, |
| 18800 | QualType &CaptureType, QualType &DeclRefType, |
| 18801 | const bool Nested, Sema &S, bool Invalid) { |
| 18802 | bool ByRef = false; |
| 18803 | |
| 18804 | // Blocks are not allowed to capture arrays, excepting OpenCL. |
| 18805 | // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference |
| 18806 | // (decayed to pointers). |
| 18807 | if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { |
| 18808 | if (BuildAndDiagnose) { |
| 18809 | S.Diag(Loc, DiagID: diag::err_ref_array_type); |
| 18810 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
| 18811 | Invalid = true; |
| 18812 | } else { |
| 18813 | return false; |
| 18814 | } |
| 18815 | } |
| 18816 | |
| 18817 | // Forbid the block-capture of autoreleasing variables. |
| 18818 | if (!Invalid && |
| 18819 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { |
| 18820 | if (BuildAndDiagnose) { |
| 18821 | S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) |
| 18822 | << /*block*/ 0; |
| 18823 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
| 18824 | Invalid = true; |
| 18825 | } else { |
| 18826 | return false; |
| 18827 | } |
| 18828 | } |
| 18829 | |
| 18830 | // Warn about implicitly autoreleasing indirect parameters captured by blocks. |
| 18831 | if (const auto *PT = CaptureType->getAs<PointerType>()) { |
| 18832 | QualType PointeeTy = PT->getPointeeType(); |
| 18833 | |
| 18834 | if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && |
| 18835 | PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && |
| 18836 | !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) { |
| 18837 | if (BuildAndDiagnose) { |
| 18838 | SourceLocation VarLoc = Var->getLocation(); |
| 18839 | S.Diag(Loc, DiagID: diag::warn_block_capture_autoreleasing); |
| 18840 | S.Diag(Loc: VarLoc, DiagID: diag::note_declare_parameter_strong); |
| 18841 | } |
| 18842 | } |
| 18843 | } |
| 18844 | |
| 18845 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); |
| 18846 | if (HasBlocksAttr || CaptureType->isReferenceType() || |
| 18847 | (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) { |
| 18848 | // Block capture by reference does not change the capture or |
| 18849 | // declaration reference types. |
| 18850 | ByRef = true; |
| 18851 | } else { |
| 18852 | // Block capture by copy introduces 'const'. |
| 18853 | CaptureType = CaptureType.getNonReferenceType().withConst(); |
| 18854 | DeclRefType = CaptureType; |
| 18855 | } |
| 18856 | |
| 18857 | // Actually capture the variable. |
| 18858 | if (BuildAndDiagnose) |
| 18859 | BSI->addCapture(Var, isBlock: HasBlocksAttr, isByref: ByRef, isNested: Nested, Loc, EllipsisLoc: SourceLocation(), |
| 18860 | CaptureType, Invalid); |
| 18861 | |
| 18862 | return !Invalid; |
| 18863 | } |
| 18864 | |
| 18865 | /// Capture the given variable in the captured region. |
| 18866 | static bool captureInCapturedRegion( |
| 18867 | CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, |
| 18868 | const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, |
| 18869 | const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope, |
| 18870 | Sema &S, bool Invalid) { |
| 18871 | // By default, capture variables by reference. |
| 18872 | bool ByRef = true; |
| 18873 | if (IsTopScope && Kind != TryCaptureKind::Implicit) { |
| 18874 | ByRef = (Kind == TryCaptureKind::ExplicitByRef); |
| 18875 | } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { |
| 18876 | // Using an LValue reference type is consistent with Lambdas (see below). |
| 18877 | if (S.OpenMP().isOpenMPCapturedDecl(D: Var)) { |
| 18878 | bool HasConst = DeclRefType.isConstQualified(); |
| 18879 | DeclRefType = DeclRefType.getUnqualifiedType(); |
| 18880 | // Don't lose diagnostics about assignments to const. |
| 18881 | if (HasConst) |
| 18882 | DeclRefType.addConst(); |
| 18883 | } |
| 18884 | // Do not capture firstprivates in tasks. |
| 18885 | if (S.OpenMP().isOpenMPPrivateDecl(D: Var, Level: RSI->OpenMPLevel, |
| 18886 | CapLevel: RSI->OpenMPCaptureLevel) != OMPC_unknown) |
| 18887 | return true; |
| 18888 | ByRef = S.OpenMP().isOpenMPCapturedByRef(D: Var, Level: RSI->OpenMPLevel, |
| 18889 | OpenMPCaptureLevel: RSI->OpenMPCaptureLevel); |
| 18890 | } |
| 18891 | |
| 18892 | if (ByRef) |
| 18893 | CaptureType = S.Context.getLValueReferenceType(T: DeclRefType); |
| 18894 | else |
| 18895 | CaptureType = DeclRefType; |
| 18896 | |
| 18897 | // Actually capture the variable. |
| 18898 | if (BuildAndDiagnose) |
| 18899 | RSI->addCapture(Var, /*isBlock*/ false, isByref: ByRef, isNested: RefersToCapturedVariable, |
| 18900 | Loc, EllipsisLoc: SourceLocation(), CaptureType, Invalid); |
| 18901 | |
| 18902 | return !Invalid; |
| 18903 | } |
| 18904 | |
| 18905 | /// Capture the given variable in the lambda. |
| 18906 | static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, |
| 18907 | SourceLocation Loc, const bool BuildAndDiagnose, |
| 18908 | QualType &CaptureType, QualType &DeclRefType, |
| 18909 | const bool RefersToCapturedVariable, |
| 18910 | const TryCaptureKind Kind, |
| 18911 | SourceLocation EllipsisLoc, const bool IsTopScope, |
| 18912 | Sema &S, bool Invalid) { |
| 18913 | // Determine whether we are capturing by reference or by value. |
| 18914 | bool ByRef = false; |
| 18915 | if (IsTopScope && Kind != TryCaptureKind::Implicit) { |
| 18916 | ByRef = (Kind == TryCaptureKind::ExplicitByRef); |
| 18917 | } else { |
| 18918 | ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); |
| 18919 | } |
| 18920 | |
| 18921 | if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() && |
| 18922 | CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) { |
| 18923 | S.Diag(Loc, DiagID: diag::err_wasm_ca_reference) << 0; |
| 18924 | Invalid = true; |
| 18925 | } |
| 18926 | |
| 18927 | // Compute the type of the field that will capture this variable. |
| 18928 | if (ByRef) { |
| 18929 | // C++11 [expr.prim.lambda]p15: |
| 18930 | // An entity is captured by reference if it is implicitly or |
| 18931 | // explicitly captured but not captured by copy. It is |
| 18932 | // unspecified whether additional unnamed non-static data |
| 18933 | // members are declared in the closure type for entities |
| 18934 | // captured by reference. |
| 18935 | // |
| 18936 | // FIXME: It is not clear whether we want to build an lvalue reference |
| 18937 | // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears |
| 18938 | // to do the former, while EDG does the latter. Core issue 1249 will |
| 18939 | // clarify, but for now we follow GCC because it's a more permissive and |
| 18940 | // easily defensible position. |
| 18941 | CaptureType = S.Context.getLValueReferenceType(T: DeclRefType); |
| 18942 | } else { |
| 18943 | // C++11 [expr.prim.lambda]p14: |
| 18944 | // For each entity captured by copy, an unnamed non-static |
| 18945 | // data member is declared in the closure type. The |
| 18946 | // declaration order of these members is unspecified. The type |
| 18947 | // of such a data member is the type of the corresponding |
| 18948 | // captured entity if the entity is not a reference to an |
| 18949 | // object, or the referenced type otherwise. [Note: If the |
| 18950 | // captured entity is a reference to a function, the |
| 18951 | // corresponding data member is also a reference to a |
| 18952 | // function. - end note ] |
| 18953 | if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ |
| 18954 | if (!RefType->getPointeeType()->isFunctionType()) |
| 18955 | CaptureType = RefType->getPointeeType(); |
| 18956 | } |
| 18957 | |
| 18958 | // Forbid the lambda copy-capture of autoreleasing variables. |
| 18959 | if (!Invalid && |
| 18960 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { |
| 18961 | if (BuildAndDiagnose) { |
| 18962 | S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; |
| 18963 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) |
| 18964 | << Var->getDeclName(); |
| 18965 | Invalid = true; |
| 18966 | } else { |
| 18967 | return false; |
| 18968 | } |
| 18969 | } |
| 18970 | |
| 18971 | // Make sure that by-copy captures are of a complete and non-abstract type. |
| 18972 | if (!Invalid && BuildAndDiagnose) { |
| 18973 | if (!CaptureType->isDependentType() && |
| 18974 | S.RequireCompleteSizedType( |
| 18975 | Loc, T: CaptureType, |
| 18976 | DiagID: diag::err_capture_of_incomplete_or_sizeless_type, |
| 18977 | Args: Var->getDeclName())) |
| 18978 | Invalid = true; |
| 18979 | else if (S.RequireNonAbstractType(Loc, T: CaptureType, |
| 18980 | DiagID: diag::err_capture_of_abstract_type)) |
| 18981 | Invalid = true; |
| 18982 | } |
| 18983 | } |
| 18984 | |
| 18985 | // Compute the type of a reference to this captured variable. |
| 18986 | if (ByRef) |
| 18987 | DeclRefType = CaptureType.getNonReferenceType(); |
| 18988 | else { |
| 18989 | // C++ [expr.prim.lambda]p5: |
| 18990 | // The closure type for a lambda-expression has a public inline |
| 18991 | // function call operator [...]. This function call operator is |
| 18992 | // declared const (9.3.1) if and only if the lambda-expression's |
| 18993 | // parameter-declaration-clause is not followed by mutable. |
| 18994 | DeclRefType = CaptureType.getNonReferenceType(); |
| 18995 | bool Const = LSI->lambdaCaptureShouldBeConst(); |
| 18996 | // C++ [expr.prim.lambda]p10: |
| 18997 | // The type of such a data member is [...] an lvalue reference to the |
| 18998 | // referenced function type if the entity is a reference to a function. |
| 18999 | // [...] |
| 19000 | if (Const && !CaptureType->isReferenceType() && |
| 19001 | !DeclRefType->isFunctionType()) |
| 19002 | DeclRefType.addConst(); |
| 19003 | } |
| 19004 | |
| 19005 | // Add the capture. |
| 19006 | if (BuildAndDiagnose) |
| 19007 | LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef, isNested: RefersToCapturedVariable, |
| 19008 | Loc, EllipsisLoc, CaptureType, Invalid); |
| 19009 | |
| 19010 | return !Invalid; |
| 19011 | } |
| 19012 | |
| 19013 | static bool canCaptureVariableByCopy(ValueDecl *Var, |
| 19014 | const ASTContext &Context) { |
| 19015 | // Offer a Copy fix even if the type is dependent. |
| 19016 | if (Var->getType()->isDependentType()) |
| 19017 | return true; |
| 19018 | QualType T = Var->getType().getNonReferenceType(); |
| 19019 | if (T.isTriviallyCopyableType(Context)) |
| 19020 | return true; |
| 19021 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { |
| 19022 | |
| 19023 | if (!(RD = RD->getDefinition())) |
| 19024 | return false; |
| 19025 | if (RD->hasSimpleCopyConstructor()) |
| 19026 | return true; |
| 19027 | if (RD->hasUserDeclaredCopyConstructor()) |
| 19028 | for (CXXConstructorDecl *Ctor : RD->ctors()) |
| 19029 | if (Ctor->isCopyConstructor()) |
| 19030 | return !Ctor->isDeleted(); |
| 19031 | } |
| 19032 | return false; |
| 19033 | } |
| 19034 | |
| 19035 | /// Create up to 4 fix-its for explicit reference and value capture of \p Var or |
| 19036 | /// default capture. Fixes may be omitted if they aren't allowed by the |
| 19037 | /// standard, for example we can't emit a default copy capture fix-it if we |
| 19038 | /// already explicitly copy capture capture another variable. |
| 19039 | static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, |
| 19040 | ValueDecl *Var) { |
| 19041 | assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); |
| 19042 | // Don't offer Capture by copy of default capture by copy fixes if Var is |
| 19043 | // known not to be copy constructible. |
| 19044 | bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext()); |
| 19045 | |
| 19046 | SmallString<32> FixBuffer; |
| 19047 | StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "" ; |
| 19048 | if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { |
| 19049 | SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); |
| 19050 | if (ShouldOfferCopyFix) { |
| 19051 | // Offer fixes to insert an explicit capture for the variable. |
| 19052 | // [] -> [VarName] |
| 19053 | // [OtherCapture] -> [OtherCapture, VarName] |
| 19054 | FixBuffer.assign(Refs: {Separator, Var->getName()}); |
| 19055 | Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit) |
| 19056 | << Var << /*value*/ 0 |
| 19057 | << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer); |
| 19058 | } |
| 19059 | // As above but capture by reference. |
| 19060 | FixBuffer.assign(Refs: {Separator, "&" , Var->getName()}); |
| 19061 | Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit) |
| 19062 | << Var << /*reference*/ 1 |
| 19063 | << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer); |
| 19064 | } |
| 19065 | |
| 19066 | // Only try to offer default capture if there are no captures excluding this |
| 19067 | // and init captures. |
| 19068 | // [this]: OK. |
| 19069 | // [X = Y]: OK. |
| 19070 | // [&A, &B]: Don't offer. |
| 19071 | // [A, B]: Don't offer. |
| 19072 | if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) { |
| 19073 | return !C.isThisCapture() && !C.isInitCapture(); |
| 19074 | })) |
| 19075 | return; |
| 19076 | |
| 19077 | // The default capture specifiers, '=' or '&', must appear first in the |
| 19078 | // capture body. |
| 19079 | SourceLocation DefaultInsertLoc = |
| 19080 | LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1); |
| 19081 | |
| 19082 | if (ShouldOfferCopyFix) { |
| 19083 | bool CanDefaultCopyCapture = true; |
| 19084 | // [=, *this] OK since c++17 |
| 19085 | // [=, this] OK since c++20 |
| 19086 | if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) |
| 19087 | CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 |
| 19088 | ? LSI->getCXXThisCapture().isCopyCapture() |
| 19089 | : false; |
| 19090 | // We can't use default capture by copy if any captures already specified |
| 19091 | // capture by copy. |
| 19092 | if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) { |
| 19093 | return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); |
| 19094 | })) { |
| 19095 | FixBuffer.assign(Refs: {"=" , Separator}); |
| 19096 | Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit) |
| 19097 | << /*value*/ 0 |
| 19098 | << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer); |
| 19099 | } |
| 19100 | } |
| 19101 | |
| 19102 | // We can't use default capture by reference if any captures already specified |
| 19103 | // capture by reference. |
| 19104 | if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) { |
| 19105 | return !C.isInitCapture() && C.isReferenceCapture() && |
| 19106 | !C.isThisCapture(); |
| 19107 | })) { |
| 19108 | FixBuffer.assign(Refs: {"&" , Separator}); |
| 19109 | Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit) |
| 19110 | << /*reference*/ 1 |
| 19111 | << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer); |
| 19112 | } |
| 19113 | } |
| 19114 | |
| 19115 | bool Sema::tryCaptureVariable( |
| 19116 | ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, |
| 19117 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, |
| 19118 | QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { |
| 19119 | // An init-capture is notionally from the context surrounding its |
| 19120 | // declaration, but its parent DC is the lambda class. |
| 19121 | DeclContext *VarDC = Var->getDeclContext(); |
| 19122 | DeclContext *DC = CurContext; |
| 19123 | |
| 19124 | // Skip past RequiresExprBodys because they don't constitute function scopes. |
| 19125 | while (DC->isRequiresExprBody()) |
| 19126 | DC = DC->getParent(); |
| 19127 | |
| 19128 | // tryCaptureVariable is called every time a DeclRef is formed, |
| 19129 | // it can therefore have non-negigible impact on performances. |
| 19130 | // For local variables and when there is no capturing scope, |
| 19131 | // we can bailout early. |
| 19132 | if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC)) |
| 19133 | return true; |
| 19134 | |
| 19135 | // Exception: Function parameters are not tied to the function's DeclContext |
| 19136 | // until we enter the function definition. Capturing them anyway would result |
| 19137 | // in an out-of-bounds error while traversing DC and its parents. |
| 19138 | if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod()) |
| 19139 | return true; |
| 19140 | |
| 19141 | const auto *VD = dyn_cast<VarDecl>(Val: Var); |
| 19142 | if (VD) { |
| 19143 | if (VD->isInitCapture()) |
| 19144 | VarDC = VarDC->getParent(); |
| 19145 | } else { |
| 19146 | VD = Var->getPotentiallyDecomposedVarDecl(); |
| 19147 | } |
| 19148 | assert(VD && "Cannot capture a null variable" ); |
| 19149 | |
| 19150 | const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt |
| 19151 | ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; |
| 19152 | // We need to sync up the Declaration Context with the |
| 19153 | // FunctionScopeIndexToStopAt |
| 19154 | if (FunctionScopeIndexToStopAt) { |
| 19155 | assert(!FunctionScopes.empty() && "No function scopes to stop at?" ); |
| 19156 | unsigned FSIndex = FunctionScopes.size() - 1; |
| 19157 | // When we're parsing the lambda parameter list, the current DeclContext is |
| 19158 | // NOT the lambda but its parent. So move away the current LSI before |
| 19159 | // aligning DC and FunctionScopeIndexToStopAt. |
| 19160 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FunctionScopes[FSIndex]); |
| 19161 | FSIndex && LSI && !LSI->AfterParameterList) |
| 19162 | --FSIndex; |
| 19163 | assert(MaxFunctionScopesIndex <= FSIndex && |
| 19164 | "FunctionScopeIndexToStopAt should be no greater than FSIndex into " |
| 19165 | "FunctionScopes." ); |
| 19166 | while (FSIndex != MaxFunctionScopesIndex) { |
| 19167 | DC = getLambdaAwareParentOfDeclContext(DC); |
| 19168 | --FSIndex; |
| 19169 | } |
| 19170 | } |
| 19171 | |
| 19172 | // Capture global variables if it is required to use private copy of this |
| 19173 | // variable. |
| 19174 | bool IsGlobal = !VD->hasLocalStorage(); |
| 19175 | if (IsGlobal && !(LangOpts.OpenMP && |
| 19176 | OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true, |
| 19177 | StopAt: MaxFunctionScopesIndex))) |
| 19178 | return true; |
| 19179 | |
| 19180 | if (isa<VarDecl>(Val: Var)) |
| 19181 | Var = cast<VarDecl>(Val: Var->getCanonicalDecl()); |
| 19182 | |
| 19183 | // Walk up the stack to determine whether we can capture the variable, |
| 19184 | // performing the "simple" checks that don't depend on type. We stop when |
| 19185 | // we've either hit the declared scope of the variable or find an existing |
| 19186 | // capture of that variable. We start from the innermost capturing-entity |
| 19187 | // (the DC) and ensure that all intervening capturing-entities |
| 19188 | // (blocks/lambdas etc.) between the innermost capturer and the variable`s |
| 19189 | // declcontext can either capture the variable or have already captured |
| 19190 | // the variable. |
| 19191 | CaptureType = Var->getType(); |
| 19192 | DeclRefType = CaptureType.getNonReferenceType(); |
| 19193 | bool Nested = false; |
| 19194 | bool Explicit = (Kind != TryCaptureKind::Implicit); |
| 19195 | unsigned FunctionScopesIndex = MaxFunctionScopesIndex; |
| 19196 | do { |
| 19197 | |
| 19198 | LambdaScopeInfo *LSI = nullptr; |
| 19199 | if (!FunctionScopes.empty()) |
| 19200 | LSI = dyn_cast_or_null<LambdaScopeInfo>( |
| 19201 | Val: FunctionScopes[FunctionScopesIndex]); |
| 19202 | |
| 19203 | bool IsInScopeDeclarationContext = |
| 19204 | !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator; |
| 19205 | |
| 19206 | if (LSI && !LSI->AfterParameterList) { |
| 19207 | // This allows capturing parameters from a default value which does not |
| 19208 | // seems correct |
| 19209 | if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod()) |
| 19210 | return true; |
| 19211 | } |
| 19212 | // If the variable is declared in the current context, there is no need to |
| 19213 | // capture it. |
| 19214 | if (IsInScopeDeclarationContext && |
| 19215 | FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC) |
| 19216 | return true; |
| 19217 | |
| 19218 | // Only block literals, captured statements, and lambda expressions can |
| 19219 | // capture; other scopes don't work. |
| 19220 | DeclContext *ParentDC = |
| 19221 | !IsInScopeDeclarationContext |
| 19222 | ? DC->getParent() |
| 19223 | : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc, |
| 19224 | Diagnose: BuildAndDiagnose, S&: *this); |
| 19225 | // We need to check for the parent *first* because, if we *have* |
| 19226 | // private-captured a global variable, we need to recursively capture it in |
| 19227 | // intermediate blocks, lambdas, etc. |
| 19228 | if (!ParentDC) { |
| 19229 | if (IsGlobal) { |
| 19230 | FunctionScopesIndex = MaxFunctionScopesIndex - 1; |
| 19231 | break; |
| 19232 | } |
| 19233 | return true; |
| 19234 | } |
| 19235 | |
| 19236 | FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; |
| 19237 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI); |
| 19238 | |
| 19239 | // Check whether we've already captured it. |
| 19240 | if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType, |
| 19241 | DeclRefType)) { |
| 19242 | CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose); |
| 19243 | break; |
| 19244 | } |
| 19245 | |
| 19246 | // When evaluating some attributes (like enable_if) we might refer to a |
| 19247 | // function parameter appertaining to the same declaration as that |
| 19248 | // attribute. |
| 19249 | if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var); |
| 19250 | Parm && Parm->getDeclContext() == DC) |
| 19251 | return true; |
| 19252 | |
| 19253 | // If we are instantiating a generic lambda call operator body, |
| 19254 | // we do not want to capture new variables. What was captured |
| 19255 | // during either a lambdas transformation or initial parsing |
| 19256 | // should be used. |
| 19257 | if (isGenericLambdaCallOperatorSpecialization(DC)) { |
| 19258 | if (BuildAndDiagnose) { |
| 19259 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI); |
| 19260 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { |
| 19261 | Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var; |
| 19262 | Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
| 19263 | Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl); |
| 19264 | buildLambdaCaptureFixit(Sema&: *this, LSI, Var); |
| 19265 | } else |
| 19266 | diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var); |
| 19267 | } |
| 19268 | return true; |
| 19269 | } |
| 19270 | |
| 19271 | // Try to capture variable-length arrays types. |
| 19272 | if (Var->getType()->isVariablyModifiedType()) { |
| 19273 | // We're going to walk down into the type and look for VLA |
| 19274 | // expressions. |
| 19275 | QualType QTy = Var->getType(); |
| 19276 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var)) |
| 19277 | QTy = PVD->getOriginalType(); |
| 19278 | captureVariablyModifiedType(Context, T: QTy, CSI); |
| 19279 | } |
| 19280 | |
| 19281 | if (getLangOpts().OpenMP) { |
| 19282 | if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) { |
| 19283 | // OpenMP private variables should not be captured in outer scope, so |
| 19284 | // just break here. Similarly, global variables that are captured in a |
| 19285 | // target region should not be captured outside the scope of the region. |
| 19286 | if (RSI->CapRegionKind == CR_OpenMP) { |
| 19287 | // FIXME: We should support capturing structured bindings in OpenMP. |
| 19288 | if (isa<BindingDecl>(Val: Var)) { |
| 19289 | if (BuildAndDiagnose) { |
| 19290 | Diag(Loc: ExprLoc, DiagID: diag::err_capture_binding_openmp) << Var; |
| 19291 | Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var; |
| 19292 | } |
| 19293 | return true; |
| 19294 | } |
| 19295 | OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl( |
| 19296 | D: Var, Level: RSI->OpenMPLevel, CapLevel: RSI->OpenMPCaptureLevel); |
| 19297 | // If the variable is private (i.e. not captured) and has variably |
| 19298 | // modified type, we still need to capture the type for correct |
| 19299 | // codegen in all regions, associated with the construct. Currently, |
| 19300 | // it is captured in the innermost captured region only. |
| 19301 | if (IsOpenMPPrivateDecl != OMPC_unknown && |
| 19302 | Var->getType()->isVariablyModifiedType()) { |
| 19303 | QualType QTy = Var->getType(); |
| 19304 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var)) |
| 19305 | QTy = PVD->getOriginalType(); |
| 19306 | for (int I = 1, |
| 19307 | E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel); |
| 19308 | I < E; ++I) { |
| 19309 | auto *OuterRSI = cast<CapturedRegionScopeInfo>( |
| 19310 | Val: FunctionScopes[FunctionScopesIndex - I]); |
| 19311 | assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && |
| 19312 | "Wrong number of captured regions associated with the " |
| 19313 | "OpenMP construct." ); |
| 19314 | captureVariablyModifiedType(Context, T: QTy, CSI: OuterRSI); |
| 19315 | } |
| 19316 | } |
| 19317 | bool IsTargetCap = |
| 19318 | IsOpenMPPrivateDecl != OMPC_private && |
| 19319 | OpenMP().isOpenMPTargetCapturedDecl(D: Var, Level: RSI->OpenMPLevel, |
| 19320 | CaptureLevel: RSI->OpenMPCaptureLevel); |
| 19321 | // Do not capture global if it is not privatized in outer regions. |
| 19322 | bool IsGlobalCap = |
| 19323 | IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl( |
| 19324 | D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel); |
| 19325 | |
| 19326 | // When we detect target captures we are looking from inside the |
| 19327 | // target region, therefore we need to propagate the capture from the |
| 19328 | // enclosing region. Therefore, the capture is not initially nested. |
| 19329 | if (IsTargetCap) |
| 19330 | OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex, |
| 19331 | Level: RSI->OpenMPLevel); |
| 19332 | |
| 19333 | if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || |
| 19334 | (IsGlobal && !IsGlobalCap)) { |
| 19335 | Nested = !IsTargetCap; |
| 19336 | bool HasConst = DeclRefType.isConstQualified(); |
| 19337 | DeclRefType = DeclRefType.getUnqualifiedType(); |
| 19338 | // Don't lose diagnostics about assignments to const. |
| 19339 | if (HasConst) |
| 19340 | DeclRefType.addConst(); |
| 19341 | CaptureType = Context.getLValueReferenceType(T: DeclRefType); |
| 19342 | break; |
| 19343 | } |
| 19344 | } |
| 19345 | } |
| 19346 | } |
| 19347 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { |
| 19348 | // No capture-default, and this is not an explicit capture |
| 19349 | // so cannot capture this variable. |
| 19350 | if (BuildAndDiagnose) { |
| 19351 | Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var; |
| 19352 | Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
| 19353 | auto *LSI = cast<LambdaScopeInfo>(Val: CSI); |
| 19354 | if (LSI->Lambda) { |
| 19355 | Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl); |
| 19356 | buildLambdaCaptureFixit(Sema&: *this, LSI, Var); |
| 19357 | } |
| 19358 | // FIXME: If we error out because an outer lambda can not implicitly |
| 19359 | // capture a variable that an inner lambda explicitly captures, we |
| 19360 | // should have the inner lambda do the explicit capture - because |
| 19361 | // it makes for cleaner diagnostics later. This would purely be done |
| 19362 | // so that the diagnostic does not misleadingly claim that a variable |
| 19363 | // can not be captured by a lambda implicitly even though it is captured |
| 19364 | // explicitly. Suggestion: |
| 19365 | // - create const bool VariableCaptureWasInitiallyExplicit = Explicit |
| 19366 | // at the function head |
| 19367 | // - cache the StartingDeclContext - this must be a lambda |
| 19368 | // - captureInLambda in the innermost lambda the variable. |
| 19369 | } |
| 19370 | return true; |
| 19371 | } |
| 19372 | Explicit = false; |
| 19373 | FunctionScopesIndex--; |
| 19374 | if (IsInScopeDeclarationContext) |
| 19375 | DC = ParentDC; |
| 19376 | } while (!VarDC->Equals(DC)); |
| 19377 | |
| 19378 | // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) |
| 19379 | // computing the type of the capture at each step, checking type-specific |
| 19380 | // requirements, and adding captures if requested. |
| 19381 | // If the variable had already been captured previously, we start capturing |
| 19382 | // at the lambda nested within that one. |
| 19383 | bool Invalid = false; |
| 19384 | for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; |
| 19385 | ++I) { |
| 19386 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]); |
| 19387 | |
| 19388 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture |
| 19389 | // certain types of variables (unnamed, variably modified types etc.) |
| 19390 | // so check for eligibility. |
| 19391 | if (!Invalid) |
| 19392 | Invalid = |
| 19393 | !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this); |
| 19394 | |
| 19395 | // After encountering an error, if we're actually supposed to capture, keep |
| 19396 | // capturing in nested contexts to suppress any follow-on diagnostics. |
| 19397 | if (Invalid && !BuildAndDiagnose) |
| 19398 | return true; |
| 19399 | |
| 19400 | if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) { |
| 19401 | Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, |
| 19402 | DeclRefType, Nested, S&: *this, Invalid); |
| 19403 | Nested = true; |
| 19404 | } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) { |
| 19405 | Invalid = !captureInCapturedRegion( |
| 19406 | RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested, |
| 19407 | Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid); |
| 19408 | Nested = true; |
| 19409 | } else { |
| 19410 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI); |
| 19411 | Invalid = |
| 19412 | !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, |
| 19413 | DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc, |
| 19414 | /*IsTopScope*/ I == N - 1, S&: *this, Invalid); |
| 19415 | Nested = true; |
| 19416 | } |
| 19417 | |
| 19418 | if (Invalid && !BuildAndDiagnose) |
| 19419 | return true; |
| 19420 | } |
| 19421 | return Invalid; |
| 19422 | } |
| 19423 | |
| 19424 | bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, |
| 19425 | TryCaptureKind Kind, SourceLocation EllipsisLoc) { |
| 19426 | QualType CaptureType; |
| 19427 | QualType DeclRefType; |
| 19428 | return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc, |
| 19429 | /*BuildAndDiagnose=*/true, CaptureType, |
| 19430 | DeclRefType, FunctionScopeIndexToStopAt: nullptr); |
| 19431 | } |
| 19432 | |
| 19433 | bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) { |
| 19434 | QualType CaptureType; |
| 19435 | QualType DeclRefType; |
| 19436 | return !tryCaptureVariable( |
| 19437 | Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(), |
| 19438 | /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, FunctionScopeIndexToStopAt: nullptr); |
| 19439 | } |
| 19440 | |
| 19441 | QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) { |
| 19442 | assert(Var && "Null value cannot be captured" ); |
| 19443 | |
| 19444 | QualType CaptureType; |
| 19445 | QualType DeclRefType; |
| 19446 | |
| 19447 | // Determine whether we can capture this variable. |
| 19448 | if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(), |
| 19449 | /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, |
| 19450 | FunctionScopeIndexToStopAt: nullptr)) |
| 19451 | return QualType(); |
| 19452 | |
| 19453 | return DeclRefType; |
| 19454 | } |
| 19455 | |
| 19456 | namespace { |
| 19457 | // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. |
| 19458 | // The produced TemplateArgumentListInfo* points to data stored within this |
| 19459 | // object, so should only be used in contexts where the pointer will not be |
| 19460 | // used after the CopiedTemplateArgs object is destroyed. |
| 19461 | class CopiedTemplateArgs { |
| 19462 | bool HasArgs; |
| 19463 | TemplateArgumentListInfo TemplateArgStorage; |
| 19464 | public: |
| 19465 | template<typename RefExpr> |
| 19466 | CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { |
| 19467 | if (HasArgs) |
| 19468 | E->copyTemplateArgumentsInto(TemplateArgStorage); |
| 19469 | } |
| 19470 | operator TemplateArgumentListInfo*() |
| 19471 | #ifdef __has_cpp_attribute |
| 19472 | #if __has_cpp_attribute(clang::lifetimebound) |
| 19473 | [[clang::lifetimebound]] |
| 19474 | #endif |
| 19475 | #endif |
| 19476 | { |
| 19477 | return HasArgs ? &TemplateArgStorage : nullptr; |
| 19478 | } |
| 19479 | }; |
| 19480 | } |
| 19481 | |
| 19482 | /// Walk the set of potential results of an expression and mark them all as |
| 19483 | /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. |
| 19484 | /// |
| 19485 | /// \return A new expression if we found any potential results, ExprEmpty() if |
| 19486 | /// not, and ExprError() if we diagnosed an error. |
| 19487 | static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, |
| 19488 | NonOdrUseReason NOUR) { |
| 19489 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it is |
| 19490 | // an object that satisfies the requirements for appearing in a |
| 19491 | // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) |
| 19492 | // is immediately applied." This function handles the lvalue-to-rvalue |
| 19493 | // conversion part. |
| 19494 | // |
| 19495 | // If we encounter a node that claims to be an odr-use but shouldn't be, we |
| 19496 | // transform it into the relevant kind of non-odr-use node and rebuild the |
| 19497 | // tree of nodes leading to it. |
| 19498 | // |
| 19499 | // This is a mini-TreeTransform that only transforms a restricted subset of |
| 19500 | // nodes (and only certain operands of them). |
| 19501 | |
| 19502 | // Rebuild a subexpression. |
| 19503 | auto Rebuild = [&](Expr *Sub) { |
| 19504 | return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR); |
| 19505 | }; |
| 19506 | |
| 19507 | // Check whether a potential result satisfies the requirements of NOUR. |
| 19508 | auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { |
| 19509 | // Any entity other than a VarDecl is always odr-used whenever it's named |
| 19510 | // in a potentially-evaluated expression. |
| 19511 | auto *VD = dyn_cast<VarDecl>(Val: D); |
| 19512 | if (!VD) |
| 19513 | return true; |
| 19514 | |
| 19515 | // C++2a [basic.def.odr]p4: |
| 19516 | // A variable x whose name appears as a potentially-evalauted expression |
| 19517 | // e is odr-used by e unless |
| 19518 | // -- x is a reference that is usable in constant expressions, or |
| 19519 | // -- x is a variable of non-reference type that is usable in constant |
| 19520 | // expressions and has no mutable subobjects, and e is an element of |
| 19521 | // the set of potential results of an expression of |
| 19522 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue |
| 19523 | // conversion is applied, or |
| 19524 | // -- x is a variable of non-reference type, and e is an element of the |
| 19525 | // set of potential results of a discarded-value expression to which |
| 19526 | // the lvalue-to-rvalue conversion is not applied |
| 19527 | // |
| 19528 | // We check the first bullet and the "potentially-evaluated" condition in |
| 19529 | // BuildDeclRefExpr. We check the type requirements in the second bullet |
| 19530 | // in CheckLValueToRValueConversionOperand below. |
| 19531 | switch (NOUR) { |
| 19532 | case NOUR_None: |
| 19533 | case NOUR_Unevaluated: |
| 19534 | llvm_unreachable("unexpected non-odr-use-reason" ); |
| 19535 | |
| 19536 | case NOUR_Constant: |
| 19537 | // Constant references were handled when they were built. |
| 19538 | if (VD->getType()->isReferenceType()) |
| 19539 | return true; |
| 19540 | if (auto *RD = VD->getType()->getAsCXXRecordDecl()) |
| 19541 | if (RD->hasDefinition() && RD->hasMutableFields()) |
| 19542 | return true; |
| 19543 | if (!VD->isUsableInConstantExpressions(C: S.Context)) |
| 19544 | return true; |
| 19545 | break; |
| 19546 | |
| 19547 | case NOUR_Discarded: |
| 19548 | if (VD->getType()->isReferenceType()) |
| 19549 | return true; |
| 19550 | break; |
| 19551 | } |
| 19552 | return false; |
| 19553 | }; |
| 19554 | |
| 19555 | // Check whether this expression may be odr-used in CUDA/HIP. |
| 19556 | auto MaybeCUDAODRUsed = [&]() -> bool { |
| 19557 | if (!S.LangOpts.CUDA) |
| 19558 | return false; |
| 19559 | LambdaScopeInfo *LSI = S.getCurLambda(); |
| 19560 | if (!LSI) |
| 19561 | return false; |
| 19562 | auto *DRE = dyn_cast<DeclRefExpr>(Val: E); |
| 19563 | if (!DRE) |
| 19564 | return false; |
| 19565 | auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
| 19566 | if (!VD) |
| 19567 | return false; |
| 19568 | return LSI->CUDAPotentialODRUsedVars.count(Ptr: VD); |
| 19569 | }; |
| 19570 | |
| 19571 | // Mark that this expression does not constitute an odr-use. |
| 19572 | auto MarkNotOdrUsed = [&] { |
| 19573 | if (!MaybeCUDAODRUsed()) { |
| 19574 | S.MaybeODRUseExprs.remove(X: E); |
| 19575 | if (LambdaScopeInfo *LSI = S.getCurLambda()) |
| 19576 | LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E); |
| 19577 | } |
| 19578 | }; |
| 19579 | |
| 19580 | // C++2a [basic.def.odr]p2: |
| 19581 | // The set of potential results of an expression e is defined as follows: |
| 19582 | switch (E->getStmtClass()) { |
| 19583 | // -- If e is an id-expression, ... |
| 19584 | case Expr::DeclRefExprClass: { |
| 19585 | auto *DRE = cast<DeclRefExpr>(Val: E); |
| 19586 | if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) |
| 19587 | break; |
| 19588 | |
| 19589 | // Rebuild as a non-odr-use DeclRefExpr. |
| 19590 | MarkNotOdrUsed(); |
| 19591 | return DeclRefExpr::Create( |
| 19592 | Context: S.Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: DRE->getTemplateKeywordLoc(), |
| 19593 | D: DRE->getDecl(), RefersToEnclosingVariableOrCapture: DRE->refersToEnclosingVariableOrCapture(), |
| 19594 | NameInfo: DRE->getNameInfo(), T: DRE->getType(), VK: DRE->getValueKind(), |
| 19595 | FoundD: DRE->getFoundDecl(), TemplateArgs: CopiedTemplateArgs(DRE), NOUR); |
| 19596 | } |
| 19597 | |
| 19598 | case Expr::FunctionParmPackExprClass: { |
| 19599 | auto *FPPE = cast<FunctionParmPackExpr>(Val: E); |
| 19600 | // If any of the declarations in the pack is odr-used, then the expression |
| 19601 | // as a whole constitutes an odr-use. |
| 19602 | for (ValueDecl *D : *FPPE) |
| 19603 | if (IsPotentialResultOdrUsed(D)) |
| 19604 | return ExprEmpty(); |
| 19605 | |
| 19606 | // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, |
| 19607 | // nothing cares about whether we marked this as an odr-use, but it might |
| 19608 | // be useful for non-compiler tools. |
| 19609 | MarkNotOdrUsed(); |
| 19610 | break; |
| 19611 | } |
| 19612 | |
| 19613 | // -- If e is a subscripting operation with an array operand... |
| 19614 | case Expr::ArraySubscriptExprClass: { |
| 19615 | auto *ASE = cast<ArraySubscriptExpr>(Val: E); |
| 19616 | Expr *OldBase = ASE->getBase()->IgnoreImplicit(); |
| 19617 | if (!OldBase->getType()->isArrayType()) |
| 19618 | break; |
| 19619 | ExprResult Base = Rebuild(OldBase); |
| 19620 | if (!Base.isUsable()) |
| 19621 | return Base; |
| 19622 | Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); |
| 19623 | Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); |
| 19624 | SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. |
| 19625 | return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS, |
| 19626 | rbLoc: ASE->getRBracketLoc()); |
| 19627 | } |
| 19628 | |
| 19629 | case Expr::MemberExprClass: { |
| 19630 | auto *ME = cast<MemberExpr>(Val: E); |
| 19631 | // -- If e is a class member access expression [...] naming a non-static |
| 19632 | // data member... |
| 19633 | if (isa<FieldDecl>(Val: ME->getMemberDecl())) { |
| 19634 | ExprResult Base = Rebuild(ME->getBase()); |
| 19635 | if (!Base.isUsable()) |
| 19636 | return Base; |
| 19637 | return MemberExpr::Create( |
| 19638 | C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(), |
| 19639 | QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), |
| 19640 | MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), |
| 19641 | TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(), |
| 19642 | OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse()); |
| 19643 | } |
| 19644 | |
| 19645 | if (ME->getMemberDecl()->isCXXInstanceMember()) |
| 19646 | break; |
| 19647 | |
| 19648 | // -- If e is a class member access expression naming a static data member, |
| 19649 | // ... |
| 19650 | if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) |
| 19651 | break; |
| 19652 | |
| 19653 | // Rebuild as a non-odr-use MemberExpr. |
| 19654 | MarkNotOdrUsed(); |
| 19655 | return MemberExpr::Create( |
| 19656 | C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(), |
| 19657 | QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(), |
| 19658 | FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME), |
| 19659 | T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR); |
| 19660 | } |
| 19661 | |
| 19662 | case Expr::BinaryOperatorClass: { |
| 19663 | auto *BO = cast<BinaryOperator>(Val: E); |
| 19664 | Expr *LHS = BO->getLHS(); |
| 19665 | Expr *RHS = BO->getRHS(); |
| 19666 | // -- If e is a pointer-to-member expression of the form e1 .* e2 ... |
| 19667 | if (BO->getOpcode() == BO_PtrMemD) { |
| 19668 | ExprResult Sub = Rebuild(LHS); |
| 19669 | if (!Sub.isUsable()) |
| 19670 | return Sub; |
| 19671 | BO->setLHS(Sub.get()); |
| 19672 | // -- If e is a comma expression, ... |
| 19673 | } else if (BO->getOpcode() == BO_Comma) { |
| 19674 | ExprResult Sub = Rebuild(RHS); |
| 19675 | if (!Sub.isUsable()) |
| 19676 | return Sub; |
| 19677 | BO->setRHS(Sub.get()); |
| 19678 | } else { |
| 19679 | break; |
| 19680 | } |
| 19681 | return ExprResult(BO); |
| 19682 | } |
| 19683 | |
| 19684 | // -- If e has the form (e1)... |
| 19685 | case Expr::ParenExprClass: { |
| 19686 | auto *PE = cast<ParenExpr>(Val: E); |
| 19687 | ExprResult Sub = Rebuild(PE->getSubExpr()); |
| 19688 | if (!Sub.isUsable()) |
| 19689 | return Sub; |
| 19690 | return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get()); |
| 19691 | } |
| 19692 | |
| 19693 | // -- If e is a glvalue conditional expression, ... |
| 19694 | // We don't apply this to a binary conditional operator. FIXME: Should we? |
| 19695 | case Expr::ConditionalOperatorClass: { |
| 19696 | auto *CO = cast<ConditionalOperator>(Val: E); |
| 19697 | ExprResult LHS = Rebuild(CO->getLHS()); |
| 19698 | if (LHS.isInvalid()) |
| 19699 | return ExprError(); |
| 19700 | ExprResult RHS = Rebuild(CO->getRHS()); |
| 19701 | if (RHS.isInvalid()) |
| 19702 | return ExprError(); |
| 19703 | if (!LHS.isUsable() && !RHS.isUsable()) |
| 19704 | return ExprEmpty(); |
| 19705 | if (!LHS.isUsable()) |
| 19706 | LHS = CO->getLHS(); |
| 19707 | if (!RHS.isUsable()) |
| 19708 | RHS = CO->getRHS(); |
| 19709 | return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(), |
| 19710 | CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
| 19711 | } |
| 19712 | |
| 19713 | // [Clang extension] |
| 19714 | // -- If e has the form __extension__ e1... |
| 19715 | case Expr::UnaryOperatorClass: { |
| 19716 | auto *UO = cast<UnaryOperator>(Val: E); |
| 19717 | if (UO->getOpcode() != UO_Extension) |
| 19718 | break; |
| 19719 | ExprResult Sub = Rebuild(UO->getSubExpr()); |
| 19720 | if (!Sub.isUsable()) |
| 19721 | return Sub; |
| 19722 | return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension, |
| 19723 | Input: Sub.get()); |
| 19724 | } |
| 19725 | |
| 19726 | // [Clang extension] |
| 19727 | // -- If e has the form _Generic(...), the set of potential results is the |
| 19728 | // union of the sets of potential results of the associated expressions. |
| 19729 | case Expr::GenericSelectionExprClass: { |
| 19730 | auto *GSE = cast<GenericSelectionExpr>(Val: E); |
| 19731 | |
| 19732 | SmallVector<Expr *, 4> AssocExprs; |
| 19733 | bool AnyChanged = false; |
| 19734 | for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { |
| 19735 | ExprResult AssocExpr = Rebuild(OrigAssocExpr); |
| 19736 | if (AssocExpr.isInvalid()) |
| 19737 | return ExprError(); |
| 19738 | if (AssocExpr.isUsable()) { |
| 19739 | AssocExprs.push_back(Elt: AssocExpr.get()); |
| 19740 | AnyChanged = true; |
| 19741 | } else { |
| 19742 | AssocExprs.push_back(Elt: OrigAssocExpr); |
| 19743 | } |
| 19744 | } |
| 19745 | |
| 19746 | void *ExOrTy = nullptr; |
| 19747 | bool IsExpr = GSE->isExprPredicate(); |
| 19748 | if (IsExpr) |
| 19749 | ExOrTy = GSE->getControllingExpr(); |
| 19750 | else |
| 19751 | ExOrTy = GSE->getControllingType(); |
| 19752 | return AnyChanged ? S.CreateGenericSelectionExpr( |
| 19753 | KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(), |
| 19754 | RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy, |
| 19755 | Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs) |
| 19756 | : ExprEmpty(); |
| 19757 | } |
| 19758 | |
| 19759 | // [Clang extension] |
| 19760 | // -- If e has the form __builtin_choose_expr(...), the set of potential |
| 19761 | // results is the union of the sets of potential results of the |
| 19762 | // second and third subexpressions. |
| 19763 | case Expr::ChooseExprClass: { |
| 19764 | auto *CE = cast<ChooseExpr>(Val: E); |
| 19765 | |
| 19766 | ExprResult LHS = Rebuild(CE->getLHS()); |
| 19767 | if (LHS.isInvalid()) |
| 19768 | return ExprError(); |
| 19769 | |
| 19770 | ExprResult RHS = Rebuild(CE->getLHS()); |
| 19771 | if (RHS.isInvalid()) |
| 19772 | return ExprError(); |
| 19773 | |
| 19774 | if (!LHS.get() && !RHS.get()) |
| 19775 | return ExprEmpty(); |
| 19776 | if (!LHS.isUsable()) |
| 19777 | LHS = CE->getLHS(); |
| 19778 | if (!RHS.isUsable()) |
| 19779 | RHS = CE->getRHS(); |
| 19780 | |
| 19781 | return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(), |
| 19782 | RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc()); |
| 19783 | } |
| 19784 | |
| 19785 | // Step through non-syntactic nodes. |
| 19786 | case Expr::ConstantExprClass: { |
| 19787 | auto *CE = cast<ConstantExpr>(Val: E); |
| 19788 | ExprResult Sub = Rebuild(CE->getSubExpr()); |
| 19789 | if (!Sub.isUsable()) |
| 19790 | return Sub; |
| 19791 | return ConstantExpr::Create(Context: S.Context, E: Sub.get()); |
| 19792 | } |
| 19793 | |
| 19794 | // We could mostly rely on the recursive rebuilding to rebuild implicit |
| 19795 | // casts, but not at the top level, so rebuild them here. |
| 19796 | case Expr::ImplicitCastExprClass: { |
| 19797 | auto *ICE = cast<ImplicitCastExpr>(Val: E); |
| 19798 | // Only step through the narrow set of cast kinds we expect to encounter. |
| 19799 | // Anything else suggests we've left the region in which potential results |
| 19800 | // can be found. |
| 19801 | switch (ICE->getCastKind()) { |
| 19802 | case CK_NoOp: |
| 19803 | case CK_DerivedToBase: |
| 19804 | case CK_UncheckedDerivedToBase: { |
| 19805 | ExprResult Sub = Rebuild(ICE->getSubExpr()); |
| 19806 | if (!Sub.isUsable()) |
| 19807 | return Sub; |
| 19808 | CXXCastPath Path(ICE->path()); |
| 19809 | return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(), |
| 19810 | VK: ICE->getValueKind(), BasePath: &Path); |
| 19811 | } |
| 19812 | |
| 19813 | default: |
| 19814 | break; |
| 19815 | } |
| 19816 | break; |
| 19817 | } |
| 19818 | |
| 19819 | default: |
| 19820 | break; |
| 19821 | } |
| 19822 | |
| 19823 | // Can't traverse through this node. Nothing to do. |
| 19824 | return ExprEmpty(); |
| 19825 | } |
| 19826 | |
| 19827 | ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { |
| 19828 | // Check whether the operand is or contains an object of non-trivial C union |
| 19829 | // type. |
| 19830 | if (E->getType().isVolatileQualified() && |
| 19831 | (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || |
| 19832 | E->getType().hasNonTrivialToPrimitiveCopyCUnion())) |
| 19833 | checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(), |
| 19834 | UseContext: NonTrivialCUnionContext::LValueToRValueVolatile, |
| 19835 | NonTrivialKind: NTCUK_Destruct | NTCUK_Copy); |
| 19836 | |
| 19837 | // C++2a [basic.def.odr]p4: |
| 19838 | // [...] an expression of non-volatile-qualified non-class type to which |
| 19839 | // the lvalue-to-rvalue conversion is applied [...] |
| 19840 | if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) |
| 19841 | return E; |
| 19842 | |
| 19843 | ExprResult Result = |
| 19844 | rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant); |
| 19845 | if (Result.isInvalid()) |
| 19846 | return ExprError(); |
| 19847 | return Result.get() ? Result : E; |
| 19848 | } |
| 19849 | |
| 19850 | ExprResult Sema::ActOnConstantExpression(ExprResult Res) { |
| 19851 | if (!Res.isUsable()) |
| 19852 | return Res; |
| 19853 | |
| 19854 | // If a constant-expression is a reference to a variable where we delay |
| 19855 | // deciding whether it is an odr-use, just assume we will apply the |
| 19856 | // lvalue-to-rvalue conversion. In the one case where this doesn't happen |
| 19857 | // (a non-type template argument), we have special handling anyway. |
| 19858 | return CheckLValueToRValueConversionOperand(E: Res.get()); |
| 19859 | } |
| 19860 | |
| 19861 | void Sema::CleanupVarDeclMarking() { |
| 19862 | // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive |
| 19863 | // call. |
| 19864 | MaybeODRUseExprSet LocalMaybeODRUseExprs; |
| 19865 | std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs); |
| 19866 | |
| 19867 | for (Expr *E : LocalMaybeODRUseExprs) { |
| 19868 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) { |
| 19869 | MarkVarDeclODRUsed(V: cast<VarDecl>(Val: DRE->getDecl()), |
| 19870 | Loc: DRE->getLocation(), SemaRef&: *this); |
| 19871 | } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) { |
| 19872 | MarkVarDeclODRUsed(V: cast<VarDecl>(Val: ME->getMemberDecl()), Loc: ME->getMemberLoc(), |
| 19873 | SemaRef&: *this); |
| 19874 | } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) { |
| 19875 | for (ValueDecl *VD : *FP) |
| 19876 | MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this); |
| 19877 | } else { |
| 19878 | llvm_unreachable("Unexpected expression" ); |
| 19879 | } |
| 19880 | } |
| 19881 | |
| 19882 | assert(MaybeODRUseExprs.empty() && |
| 19883 | "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?" ); |
| 19884 | } |
| 19885 | |
| 19886 | static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, |
| 19887 | ValueDecl *Var, Expr *E) { |
| 19888 | VarDecl *VD = Var->getPotentiallyDecomposedVarDecl(); |
| 19889 | if (!VD) |
| 19890 | return; |
| 19891 | |
| 19892 | const bool RefersToEnclosingScope = |
| 19893 | (SemaRef.CurContext != VD->getDeclContext() && |
| 19894 | VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage()); |
| 19895 | if (RefersToEnclosingScope) { |
| 19896 | LambdaScopeInfo *const LSI = |
| 19897 | SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); |
| 19898 | if (LSI && (!LSI->CallOperator || |
| 19899 | !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) { |
| 19900 | // If a variable could potentially be odr-used, defer marking it so |
| 19901 | // until we finish analyzing the full expression for any |
| 19902 | // lvalue-to-rvalue |
| 19903 | // or discarded value conversions that would obviate odr-use. |
| 19904 | // Add it to the list of potential captures that will be analyzed |
| 19905 | // later (ActOnFinishFullExpr) for eventual capture and odr-use marking |
| 19906 | // unless the variable is a reference that was initialized by a constant |
| 19907 | // expression (this will never need to be captured or odr-used). |
| 19908 | // |
| 19909 | // FIXME: We can simplify this a lot after implementing P0588R1. |
| 19910 | assert(E && "Capture variable should be used in an expression." ); |
| 19911 | if (!Var->getType()->isReferenceType() || |
| 19912 | !VD->isUsableInConstantExpressions(C: SemaRef.Context)) |
| 19913 | LSI->addPotentialCapture(VarExpr: E->IgnoreParens()); |
| 19914 | } |
| 19915 | } |
| 19916 | } |
| 19917 | |
| 19918 | static void DoMarkVarDeclReferenced( |
| 19919 | Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, |
| 19920 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { |
| 19921 | assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || |
| 19922 | isa<FunctionParmPackExpr>(E)) && |
| 19923 | "Invalid Expr argument to DoMarkVarDeclReferenced" ); |
| 19924 | Var->setReferenced(); |
| 19925 | |
| 19926 | if (Var->isInvalidDecl()) |
| 19927 | return; |
| 19928 | |
| 19929 | auto *MSI = Var->getMemberSpecializationInfo(); |
| 19930 | TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() |
| 19931 | : Var->getTemplateSpecializationKind(); |
| 19932 | |
| 19933 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); |
| 19934 | bool UsableInConstantExpr = |
| 19935 | Var->mightBeUsableInConstantExpressions(C: SemaRef.Context); |
| 19936 | |
| 19937 | if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { |
| 19938 | RefsMinusAssignments.insert(KV: {Var, 0}).first->getSecond()++; |
| 19939 | } |
| 19940 | |
| 19941 | // C++20 [expr.const]p12: |
| 19942 | // A variable [...] is needed for constant evaluation if it is [...] a |
| 19943 | // variable whose name appears as a potentially constant evaluated |
| 19944 | // expression that is either a contexpr variable or is of non-volatile |
| 19945 | // const-qualified integral type or of reference type |
| 19946 | bool NeededForConstantEvaluation = |
| 19947 | isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; |
| 19948 | |
| 19949 | bool NeedDefinition = |
| 19950 | OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; |
| 19951 | |
| 19952 | assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && |
| 19953 | "Can't instantiate a partial template specialization." ); |
| 19954 | |
| 19955 | // If this might be a member specialization of a static data member, check |
| 19956 | // the specialization is visible. We already did the checks for variable |
| 19957 | // template specializations when we created them. |
| 19958 | if (NeedDefinition && TSK != TSK_Undeclared && |
| 19959 | !isa<VarTemplateSpecializationDecl>(Val: Var)) |
| 19960 | SemaRef.checkSpecializationVisibility(Loc, Spec: Var); |
| 19961 | |
| 19962 | // Perform implicit instantiation of static data members, static data member |
| 19963 | // templates of class templates, and variable template specializations. Delay |
| 19964 | // instantiations of variable templates, except for those that could be used |
| 19965 | // in a constant expression. |
| 19966 | if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) { |
| 19967 | // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit |
| 19968 | // instantiation declaration if a variable is usable in a constant |
| 19969 | // expression (among other cases). |
| 19970 | bool TryInstantiating = |
| 19971 | TSK == TSK_ImplicitInstantiation || |
| 19972 | (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); |
| 19973 | |
| 19974 | if (TryInstantiating) { |
| 19975 | SourceLocation PointOfInstantiation = |
| 19976 | MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); |
| 19977 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); |
| 19978 | if (FirstInstantiation) { |
| 19979 | PointOfInstantiation = Loc; |
| 19980 | if (MSI) |
| 19981 | MSI->setPointOfInstantiation(PointOfInstantiation); |
| 19982 | // FIXME: Notify listener. |
| 19983 | else |
| 19984 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
| 19985 | } |
| 19986 | |
| 19987 | if (UsableInConstantExpr || Var->getType()->isUndeducedType()) { |
| 19988 | // Do not defer instantiations of variables that could be used in a |
| 19989 | // constant expression. |
| 19990 | // The type deduction also needs a complete initializer. |
| 19991 | SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] { |
| 19992 | SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); |
| 19993 | }); |
| 19994 | |
| 19995 | // The size of an incomplete array type can be updated by |
| 19996 | // instantiating the initializer. The DeclRefExpr's type should be |
| 19997 | // updated accordingly too, or users of it would be confused! |
| 19998 | if (E) |
| 19999 | SemaRef.getCompletedType(E); |
| 20000 | |
| 20001 | // Re-set the member to trigger a recomputation of the dependence bits |
| 20002 | // for the expression. |
| 20003 | if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E)) |
| 20004 | DRE->setDecl(DRE->getDecl()); |
| 20005 | else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E)) |
| 20006 | ME->setMemberDecl(ME->getMemberDecl()); |
| 20007 | } else if (FirstInstantiation) { |
| 20008 | SemaRef.PendingInstantiations |
| 20009 | .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation)); |
| 20010 | } else { |
| 20011 | bool Inserted = false; |
| 20012 | for (auto &I : SemaRef.SavedPendingInstantiations) { |
| 20013 | auto Iter = llvm::find_if( |
| 20014 | Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) { |
| 20015 | return P.first == Var; |
| 20016 | }); |
| 20017 | if (Iter != I.end()) { |
| 20018 | SemaRef.PendingInstantiations.push_back(x: *Iter); |
| 20019 | I.erase(position: Iter); |
| 20020 | Inserted = true; |
| 20021 | break; |
| 20022 | } |
| 20023 | } |
| 20024 | |
| 20025 | // FIXME: For a specialization of a variable template, we don't |
| 20026 | // distinguish between "declaration and type implicitly instantiated" |
| 20027 | // and "implicit instantiation of definition requested", so we have |
| 20028 | // no direct way to avoid enqueueing the pending instantiation |
| 20029 | // multiple times. |
| 20030 | if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted) |
| 20031 | SemaRef.PendingInstantiations |
| 20032 | .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation)); |
| 20033 | } |
| 20034 | } |
| 20035 | } |
| 20036 | |
| 20037 | // C++2a [basic.def.odr]p4: |
| 20038 | // A variable x whose name appears as a potentially-evaluated expression e |
| 20039 | // is odr-used by e unless |
| 20040 | // -- x is a reference that is usable in constant expressions |
| 20041 | // -- x is a variable of non-reference type that is usable in constant |
| 20042 | // expressions and has no mutable subobjects [FIXME], and e is an |
| 20043 | // element of the set of potential results of an expression of |
| 20044 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue |
| 20045 | // conversion is applied |
| 20046 | // -- x is a variable of non-reference type, and e is an element of the set |
| 20047 | // of potential results of a discarded-value expression to which the |
| 20048 | // lvalue-to-rvalue conversion is not applied [FIXME] |
| 20049 | // |
| 20050 | // We check the first part of the second bullet here, and |
| 20051 | // Sema::CheckLValueToRValueConversionOperand deals with the second part. |
| 20052 | // FIXME: To get the third bullet right, we need to delay this even for |
| 20053 | // variables that are not usable in constant expressions. |
| 20054 | |
| 20055 | // If we already know this isn't an odr-use, there's nothing more to do. |
| 20056 | if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E)) |
| 20057 | if (DRE->isNonOdrUse()) |
| 20058 | return; |
| 20059 | if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E)) |
| 20060 | if (ME->isNonOdrUse()) |
| 20061 | return; |
| 20062 | |
| 20063 | switch (OdrUse) { |
| 20064 | case OdrUseContext::None: |
| 20065 | // In some cases, a variable may not have been marked unevaluated, if it |
| 20066 | // appears in a defaukt initializer. |
| 20067 | assert((!E || isa<FunctionParmPackExpr>(E) || |
| 20068 | SemaRef.isUnevaluatedContext()) && |
| 20069 | "missing non-odr-use marking for unevaluated decl ref" ); |
| 20070 | break; |
| 20071 | |
| 20072 | case OdrUseContext::FormallyOdrUsed: |
| 20073 | // FIXME: Ignoring formal odr-uses results in incorrect lambda capture |
| 20074 | // behavior. |
| 20075 | break; |
| 20076 | |
| 20077 | case OdrUseContext::Used: |
| 20078 | // If we might later find that this expression isn't actually an odr-use, |
| 20079 | // delay the marking. |
| 20080 | if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context)) |
| 20081 | SemaRef.MaybeODRUseExprs.insert(X: E); |
| 20082 | else |
| 20083 | MarkVarDeclODRUsed(V: Var, Loc, SemaRef); |
| 20084 | break; |
| 20085 | |
| 20086 | case OdrUseContext::Dependent: |
| 20087 | // If this is a dependent context, we don't need to mark variables as |
| 20088 | // odr-used, but we may still need to track them for lambda capture. |
| 20089 | // FIXME: Do we also need to do this inside dependent typeid expressions |
| 20090 | // (which are modeled as unevaluated at this point)? |
| 20091 | DoMarkPotentialCapture(SemaRef, Loc, Var, E); |
| 20092 | break; |
| 20093 | } |
| 20094 | } |
| 20095 | |
| 20096 | static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, |
| 20097 | BindingDecl *BD, Expr *E) { |
| 20098 | BD->setReferenced(); |
| 20099 | |
| 20100 | if (BD->isInvalidDecl()) |
| 20101 | return; |
| 20102 | |
| 20103 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); |
| 20104 | if (OdrUse == OdrUseContext::Used) { |
| 20105 | QualType CaptureType, DeclRefType; |
| 20106 | SemaRef.tryCaptureVariable(Var: BD, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, |
| 20107 | /*EllipsisLoc*/ SourceLocation(), |
| 20108 | /*BuildAndDiagnose*/ true, CaptureType, |
| 20109 | DeclRefType, |
| 20110 | /*FunctionScopeIndexToStopAt*/ nullptr); |
| 20111 | } else if (OdrUse == OdrUseContext::Dependent) { |
| 20112 | DoMarkPotentialCapture(SemaRef, Loc, Var: BD, E); |
| 20113 | } |
| 20114 | } |
| 20115 | |
| 20116 | void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { |
| 20117 | DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments); |
| 20118 | } |
| 20119 | |
| 20120 | // C++ [temp.dep.expr]p3: |
| 20121 | // An id-expression is type-dependent if it contains: |
| 20122 | // - an identifier associated by name lookup with an entity captured by copy |
| 20123 | // in a lambda-expression that has an explicit object parameter whose type |
| 20124 | // is dependent ([dcl.fct]), |
| 20125 | static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter( |
| 20126 | Sema &SemaRef, ValueDecl *D, Expr *E) { |
| 20127 | auto *ID = dyn_cast<DeclRefExpr>(Val: E); |
| 20128 | if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture()) |
| 20129 | return; |
| 20130 | |
| 20131 | // If any enclosing lambda with a dependent explicit object parameter either |
| 20132 | // explicitly captures the variable by value, or has a capture default of '=' |
| 20133 | // and does not capture the variable by reference, then the type of the DRE |
| 20134 | // is dependent on the type of that lambda's explicit object parameter. |
| 20135 | auto IsDependent = [&]() { |
| 20136 | for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) { |
| 20137 | auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope); |
| 20138 | if (!LSI) |
| 20139 | continue; |
| 20140 | |
| 20141 | if (LSI->Lambda && !LSI->Lambda->Encloses(DC: SemaRef.CurContext) && |
| 20142 | LSI->AfterParameterList) |
| 20143 | return false; |
| 20144 | |
| 20145 | const auto *MD = LSI->CallOperator; |
| 20146 | if (MD->getType().isNull()) |
| 20147 | continue; |
| 20148 | |
| 20149 | const auto *Ty = MD->getType()->getAs<FunctionProtoType>(); |
| 20150 | if (!Ty || !MD->isExplicitObjectMemberFunction() || |
| 20151 | !Ty->getParamType(i: 0)->isDependentType()) |
| 20152 | continue; |
| 20153 | |
| 20154 | if (auto *C = LSI->CaptureMap.count(Val: D) ? &LSI->getCapture(Var: D) : nullptr) { |
| 20155 | if (C->isCopyCapture()) |
| 20156 | return true; |
| 20157 | continue; |
| 20158 | } |
| 20159 | |
| 20160 | if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval) |
| 20161 | return true; |
| 20162 | } |
| 20163 | return false; |
| 20164 | }(); |
| 20165 | |
| 20166 | ID->setCapturedByCopyInLambdaWithExplicitObjectParameter( |
| 20167 | Set: IsDependent, Context: SemaRef.getASTContext()); |
| 20168 | } |
| 20169 | |
| 20170 | static void |
| 20171 | MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, |
| 20172 | bool MightBeOdrUse, |
| 20173 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { |
| 20174 | if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext()) |
| 20175 | SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D); |
| 20176 | |
| 20177 | if (SemaRef.getLangOpts().OpenACC) |
| 20178 | SemaRef.OpenACC().CheckDeclReference(Loc, E, D); |
| 20179 | |
| 20180 | if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) { |
| 20181 | DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); |
| 20182 | if (SemaRef.getLangOpts().CPlusPlus) |
| 20183 | FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef, |
| 20184 | D: Var, E); |
| 20185 | return; |
| 20186 | } |
| 20187 | |
| 20188 | if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) { |
| 20189 | DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E); |
| 20190 | if (SemaRef.getLangOpts().CPlusPlus) |
| 20191 | FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef, |
| 20192 | D: Decl, E); |
| 20193 | return; |
| 20194 | } |
| 20195 | SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); |
| 20196 | |
| 20197 | // If this is a call to a method via a cast, also mark the method in the |
| 20198 | // derived class used in case codegen can devirtualize the call. |
| 20199 | const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E); |
| 20200 | if (!ME) |
| 20201 | return; |
| 20202 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl()); |
| 20203 | if (!MD) |
| 20204 | return; |
| 20205 | // Only attempt to devirtualize if this is truly a virtual call. |
| 20206 | bool IsVirtualCall = MD->isVirtual() && |
| 20207 | ME->performsVirtualDispatch(LO: SemaRef.getLangOpts()); |
| 20208 | if (!IsVirtualCall) |
| 20209 | return; |
| 20210 | |
| 20211 | // If it's possible to devirtualize the call, mark the called function |
| 20212 | // referenced. |
| 20213 | CXXMethodDecl *DM = MD->getDevirtualizedMethod( |
| 20214 | Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext); |
| 20215 | if (DM) |
| 20216 | SemaRef.MarkAnyDeclReferenced(Loc, D: DM, MightBeOdrUse); |
| 20217 | } |
| 20218 | |
| 20219 | void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { |
| 20220 | // [basic.def.odr] (CWG 1614) |
| 20221 | // A function is named by an expression or conversion [...] |
| 20222 | // unless it is a pure virtual function and either the expression is not an |
| 20223 | // id-expression naming the function with an explicitly qualified name or |
| 20224 | // the expression forms a pointer to member |
| 20225 | bool OdrUse = true; |
| 20226 | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl())) |
| 20227 | if (Method->isVirtual() && |
| 20228 | !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext)) |
| 20229 | OdrUse = false; |
| 20230 | |
| 20231 | if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) { |
| 20232 | if (!isUnevaluatedContext() && !isConstantEvaluatedContext() && |
| 20233 | !isImmediateFunctionContext() && |
| 20234 | !isCheckingDefaultArgumentOrInitializer() && |
| 20235 | FD->isImmediateFunction() && !RebuildingImmediateInvocation && |
| 20236 | !FD->isDependentContext()) |
| 20237 | ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E); |
| 20238 | } |
| 20239 | MarkExprReferenced(SemaRef&: *this, Loc: E->getLocation(), D: E->getDecl(), E, MightBeOdrUse: OdrUse, |
| 20240 | RefsMinusAssignments); |
| 20241 | } |
| 20242 | |
| 20243 | void Sema::MarkMemberReferenced(MemberExpr *E) { |
| 20244 | // C++11 [basic.def.odr]p2: |
| 20245 | // A non-overloaded function whose name appears as a potentially-evaluated |
| 20246 | // expression or a member of a set of candidate functions, if selected by |
| 20247 | // overload resolution when referred to from a potentially-evaluated |
| 20248 | // expression, is odr-used, unless it is a pure virtual function and its |
| 20249 | // name is not explicitly qualified. |
| 20250 | bool MightBeOdrUse = true; |
| 20251 | if (E->performsVirtualDispatch(LO: getLangOpts())) { |
| 20252 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl())) |
| 20253 | if (Method->isPureVirtual()) |
| 20254 | MightBeOdrUse = false; |
| 20255 | } |
| 20256 | SourceLocation Loc = |
| 20257 | E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); |
| 20258 | MarkExprReferenced(SemaRef&: *this, Loc, D: E->getMemberDecl(), E, MightBeOdrUse, |
| 20259 | RefsMinusAssignments); |
| 20260 | } |
| 20261 | |
| 20262 | void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { |
| 20263 | for (ValueDecl *VD : *E) |
| 20264 | MarkExprReferenced(SemaRef&: *this, Loc: E->getParameterPackLocation(), D: VD, E, MightBeOdrUse: true, |
| 20265 | RefsMinusAssignments); |
| 20266 | } |
| 20267 | |
| 20268 | /// Perform marking for a reference to an arbitrary declaration. It |
| 20269 | /// marks the declaration referenced, and performs odr-use checking for |
| 20270 | /// functions and variables. This method should not be used when building a |
| 20271 | /// normal expression which refers to a variable. |
| 20272 | void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, |
| 20273 | bool MightBeOdrUse) { |
| 20274 | if (MightBeOdrUse) { |
| 20275 | if (auto *VD = dyn_cast<VarDecl>(Val: D)) { |
| 20276 | MarkVariableReferenced(Loc, Var: VD); |
| 20277 | return; |
| 20278 | } |
| 20279 | } |
| 20280 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
| 20281 | MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse); |
| 20282 | return; |
| 20283 | } |
| 20284 | D->setReferenced(); |
| 20285 | } |
| 20286 | |
| 20287 | namespace { |
| 20288 | // Mark all of the declarations used by a type as referenced. |
| 20289 | // FIXME: Not fully implemented yet! We need to have a better understanding |
| 20290 | // of when we're entering a context we should not recurse into. |
| 20291 | // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to |
| 20292 | // TreeTransforms rebuilding the type in a new context. Rather than |
| 20293 | // duplicating the TreeTransform logic, we should consider reusing it here. |
| 20294 | // Currently that causes problems when rebuilding LambdaExprs. |
| 20295 | class MarkReferencedDecls : public DynamicRecursiveASTVisitor { |
| 20296 | Sema &S; |
| 20297 | SourceLocation Loc; |
| 20298 | |
| 20299 | public: |
| 20300 | MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {} |
| 20301 | |
| 20302 | bool TraverseTemplateArgument(const TemplateArgument &Arg) override; |
| 20303 | }; |
| 20304 | } |
| 20305 | |
| 20306 | bool MarkReferencedDecls::TraverseTemplateArgument( |
| 20307 | const TemplateArgument &Arg) { |
| 20308 | { |
| 20309 | // A non-type template argument is a constant-evaluated context. |
| 20310 | EnterExpressionEvaluationContext Evaluated( |
| 20311 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
| 20312 | if (Arg.getKind() == TemplateArgument::Declaration) { |
| 20313 | if (Decl *D = Arg.getAsDecl()) |
| 20314 | S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true); |
| 20315 | } else if (Arg.getKind() == TemplateArgument::Expression) { |
| 20316 | S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false); |
| 20317 | } |
| 20318 | } |
| 20319 | |
| 20320 | return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg); |
| 20321 | } |
| 20322 | |
| 20323 | void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { |
| 20324 | MarkReferencedDecls Marker(*this, Loc); |
| 20325 | Marker.TraverseType(T); |
| 20326 | } |
| 20327 | |
| 20328 | namespace { |
| 20329 | /// Helper class that marks all of the declarations referenced by |
| 20330 | /// potentially-evaluated subexpressions as "referenced". |
| 20331 | class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { |
| 20332 | public: |
| 20333 | typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; |
| 20334 | bool SkipLocalVariables; |
| 20335 | ArrayRef<const Expr *> StopAt; |
| 20336 | |
| 20337 | EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, |
| 20338 | ArrayRef<const Expr *> StopAt) |
| 20339 | : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} |
| 20340 | |
| 20341 | void visitUsedDecl(SourceLocation Loc, Decl *D) { |
| 20342 | S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D)); |
| 20343 | } |
| 20344 | |
| 20345 | void Visit(Expr *E) { |
| 20346 | if (llvm::is_contained(Range&: StopAt, Element: E)) |
| 20347 | return; |
| 20348 | Inherited::Visit(S: E); |
| 20349 | } |
| 20350 | |
| 20351 | void VisitConstantExpr(ConstantExpr *E) { |
| 20352 | // Don't mark declarations within a ConstantExpression, as this expression |
| 20353 | // will be evaluated and folded to a value. |
| 20354 | } |
| 20355 | |
| 20356 | void VisitDeclRefExpr(DeclRefExpr *E) { |
| 20357 | // If we were asked not to visit local variables, don't. |
| 20358 | if (SkipLocalVariables) { |
| 20359 | if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl())) |
| 20360 | if (VD->hasLocalStorage()) |
| 20361 | return; |
| 20362 | } |
| 20363 | |
| 20364 | // FIXME: This can trigger the instantiation of the initializer of a |
| 20365 | // variable, which can cause the expression to become value-dependent |
| 20366 | // or error-dependent. Do we need to propagate the new dependence bits? |
| 20367 | S.MarkDeclRefReferenced(E); |
| 20368 | } |
| 20369 | |
| 20370 | void VisitMemberExpr(MemberExpr *E) { |
| 20371 | S.MarkMemberReferenced(E); |
| 20372 | Visit(E: E->getBase()); |
| 20373 | } |
| 20374 | }; |
| 20375 | } // namespace |
| 20376 | |
| 20377 | void Sema::MarkDeclarationsReferencedInExpr(Expr *E, |
| 20378 | bool SkipLocalVariables, |
| 20379 | ArrayRef<const Expr*> StopAt) { |
| 20380 | EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); |
| 20381 | } |
| 20382 | |
| 20383 | /// Emit a diagnostic when statements are reachable. |
| 20384 | /// FIXME: check for reachability even in expressions for which we don't build a |
| 20385 | /// CFG (eg, in the initializer of a global or in a constant expression). |
| 20386 | /// For example, |
| 20387 | /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } |
| 20388 | bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, |
| 20389 | const PartialDiagnostic &PD) { |
| 20390 | if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { |
| 20391 | if (!FunctionScopes.empty()) |
| 20392 | FunctionScopes.back()->PossiblyUnreachableDiags.push_back( |
| 20393 | Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); |
| 20394 | return true; |
| 20395 | } |
| 20396 | |
| 20397 | // The initializer of a constexpr variable or of the first declaration of a |
| 20398 | // static data member is not syntactically a constant evaluated constant, |
| 20399 | // but nonetheless is always required to be a constant expression, so we |
| 20400 | // can skip diagnosing. |
| 20401 | // FIXME: Using the mangling context here is a hack. |
| 20402 | if (auto *VD = dyn_cast_or_null<VarDecl>( |
| 20403 | Val: ExprEvalContexts.back().ManglingContextDecl)) { |
| 20404 | if (VD->isConstexpr() || |
| 20405 | (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) |
| 20406 | return false; |
| 20407 | // FIXME: For any other kind of variable, we should build a CFG for its |
| 20408 | // initializer and check whether the context in question is reachable. |
| 20409 | } |
| 20410 | |
| 20411 | Diag(Loc, PD); |
| 20412 | return true; |
| 20413 | } |
| 20414 | |
| 20415 | /// Emit a diagnostic that describes an effect on the run-time behavior |
| 20416 | /// of the program being compiled. |
| 20417 | /// |
| 20418 | /// This routine emits the given diagnostic when the code currently being |
| 20419 | /// type-checked is "potentially evaluated", meaning that there is a |
| 20420 | /// possibility that the code will actually be executable. Code in sizeof() |
| 20421 | /// expressions, code used only during overload resolution, etc., are not |
| 20422 | /// potentially evaluated. This routine will suppress such diagnostics or, |
| 20423 | /// in the absolutely nutty case of potentially potentially evaluated |
| 20424 | /// expressions (C++ typeid), queue the diagnostic to potentially emit it |
| 20425 | /// later. |
| 20426 | /// |
| 20427 | /// This routine should be used for all diagnostics that describe the run-time |
| 20428 | /// behavior of a program, such as passing a non-POD value through an ellipsis. |
| 20429 | /// Failure to do so will likely result in spurious diagnostics or failures |
| 20430 | /// during overload resolution or within sizeof/alignof/typeof/typeid. |
| 20431 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, |
| 20432 | const PartialDiagnostic &PD) { |
| 20433 | |
| 20434 | if (ExprEvalContexts.back().isDiscardedStatementContext()) |
| 20435 | return false; |
| 20436 | |
| 20437 | switch (ExprEvalContexts.back().Context) { |
| 20438 | case ExpressionEvaluationContext::Unevaluated: |
| 20439 | case ExpressionEvaluationContext::UnevaluatedList: |
| 20440 | case ExpressionEvaluationContext::UnevaluatedAbstract: |
| 20441 | case ExpressionEvaluationContext::DiscardedStatement: |
| 20442 | // The argument will never be evaluated, so don't complain. |
| 20443 | break; |
| 20444 | |
| 20445 | case ExpressionEvaluationContext::ConstantEvaluated: |
| 20446 | case ExpressionEvaluationContext::ImmediateFunctionContext: |
| 20447 | // Relevant diagnostics should be produced by constant evaluation. |
| 20448 | break; |
| 20449 | |
| 20450 | case ExpressionEvaluationContext::PotentiallyEvaluated: |
| 20451 | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: |
| 20452 | return DiagIfReachable(Loc, Stmts, PD); |
| 20453 | } |
| 20454 | |
| 20455 | return false; |
| 20456 | } |
| 20457 | |
| 20458 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, |
| 20459 | const PartialDiagnostic &PD) { |
| 20460 | return DiagRuntimeBehavior( |
| 20461 | Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(), |
| 20462 | PD); |
| 20463 | } |
| 20464 | |
| 20465 | bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, |
| 20466 | CallExpr *CE, FunctionDecl *FD) { |
| 20467 | if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) |
| 20468 | return false; |
| 20469 | |
| 20470 | // If we're inside a decltype's expression, don't check for a valid return |
| 20471 | // type or construct temporaries until we know whether this is the last call. |
| 20472 | if (ExprEvalContexts.back().ExprContext == |
| 20473 | ExpressionEvaluationContextRecord::EK_Decltype) { |
| 20474 | ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE); |
| 20475 | return false; |
| 20476 | } |
| 20477 | |
| 20478 | class CallReturnIncompleteDiagnoser : public TypeDiagnoser { |
| 20479 | FunctionDecl *FD; |
| 20480 | CallExpr *CE; |
| 20481 | |
| 20482 | public: |
| 20483 | CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) |
| 20484 | : FD(FD), CE(CE) { } |
| 20485 | |
| 20486 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
| 20487 | if (!FD) { |
| 20488 | S.Diag(Loc, DiagID: diag::err_call_incomplete_return) |
| 20489 | << T << CE->getSourceRange(); |
| 20490 | return; |
| 20491 | } |
| 20492 | |
| 20493 | S.Diag(Loc, DiagID: diag::err_call_function_incomplete_return) |
| 20494 | << CE->getSourceRange() << FD << T; |
| 20495 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at) |
| 20496 | << FD->getDeclName(); |
| 20497 | } |
| 20498 | } Diagnoser(FD, CE); |
| 20499 | |
| 20500 | if (RequireCompleteType(Loc, T: ReturnType, Diagnoser)) |
| 20501 | return true; |
| 20502 | |
| 20503 | return false; |
| 20504 | } |
| 20505 | |
| 20506 | // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses |
| 20507 | // will prevent this condition from triggering, which is what we want. |
| 20508 | void Sema::DiagnoseAssignmentAsCondition(Expr *E) { |
| 20509 | SourceLocation Loc; |
| 20510 | |
| 20511 | unsigned diagnostic = diag::warn_condition_is_assignment; |
| 20512 | bool IsOrAssign = false; |
| 20513 | |
| 20514 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) { |
| 20515 | if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) |
| 20516 | return; |
| 20517 | |
| 20518 | IsOrAssign = Op->getOpcode() == BO_OrAssign; |
| 20519 | |
| 20520 | // Greylist some idioms by putting them into a warning subcategory. |
| 20521 | if (ObjCMessageExpr *ME |
| 20522 | = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) { |
| 20523 | Selector Sel = ME->getSelector(); |
| 20524 | |
| 20525 | // self = [<foo> init...] |
| 20526 | if (ObjC().isSelfExpr(RExpr: Op->getLHS()) && ME->getMethodFamily() == OMF_init) |
| 20527 | diagnostic = diag::warn_condition_is_idiomatic_assignment; |
| 20528 | |
| 20529 | // <foo> = [<bar> nextObject] |
| 20530 | else if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "nextObject" ) |
| 20531 | diagnostic = diag::warn_condition_is_idiomatic_assignment; |
| 20532 | } |
| 20533 | |
| 20534 | Loc = Op->getOperatorLoc(); |
| 20535 | } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) { |
| 20536 | if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) |
| 20537 | return; |
| 20538 | |
| 20539 | IsOrAssign = Op->getOperator() == OO_PipeEqual; |
| 20540 | Loc = Op->getOperatorLoc(); |
| 20541 | } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) |
| 20542 | return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm()); |
| 20543 | else { |
| 20544 | // Not an assignment. |
| 20545 | return; |
| 20546 | } |
| 20547 | |
| 20548 | Diag(Loc, DiagID: diagnostic) << E->getSourceRange(); |
| 20549 | |
| 20550 | SourceLocation Open = E->getBeginLoc(); |
| 20551 | SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd()); |
| 20552 | Diag(Loc, DiagID: diag::note_condition_assign_silence) |
| 20553 | << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "(" ) |
| 20554 | << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")" ); |
| 20555 | |
| 20556 | if (IsOrAssign) |
| 20557 | Diag(Loc, DiagID: diag::note_condition_or_assign_to_comparison) |
| 20558 | << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "!=" ); |
| 20559 | else |
| 20560 | Diag(Loc, DiagID: diag::note_condition_assign_to_comparison) |
| 20561 | << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "==" ); |
| 20562 | } |
| 20563 | |
| 20564 | void Sema::(ParenExpr *ParenE) { |
| 20565 | // Don't warn if the parens came from a macro. |
| 20566 | SourceLocation parenLoc = ParenE->getBeginLoc(); |
| 20567 | if (parenLoc.isInvalid() || parenLoc.isMacroID()) |
| 20568 | return; |
| 20569 | // Don't warn for dependent expressions. |
| 20570 | if (ParenE->isTypeDependent()) |
| 20571 | return; |
| 20572 | |
| 20573 | Expr *E = ParenE->IgnoreParens(); |
| 20574 | if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E) |
| 20575 | return; |
| 20576 | |
| 20577 | if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E)) |
| 20578 | if (opE->getOpcode() == BO_EQ && |
| 20579 | opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context) |
| 20580 | == Expr::MLV_Valid) { |
| 20581 | SourceLocation Loc = opE->getOperatorLoc(); |
| 20582 | |
| 20583 | Diag(Loc, DiagID: diag::warn_equality_with_extra_parens) << E->getSourceRange(); |
| 20584 | SourceRange ParenERange = ParenE->getSourceRange(); |
| 20585 | Diag(Loc, DiagID: diag::note_equality_comparison_silence) |
| 20586 | << FixItHint::CreateRemoval(RemoveRange: ParenERange.getBegin()) |
| 20587 | << FixItHint::CreateRemoval(RemoveRange: ParenERange.getEnd()); |
| 20588 | Diag(Loc, DiagID: diag::note_equality_comparison_to_assign) |
| 20589 | << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=" ); |
| 20590 | } |
| 20591 | } |
| 20592 | |
| 20593 | ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, |
| 20594 | bool IsConstexpr) { |
| 20595 | DiagnoseAssignmentAsCondition(E); |
| 20596 | if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E)) |
| 20597 | DiagnoseEqualityWithExtraParens(ParenE: parenE); |
| 20598 | |
| 20599 | ExprResult result = CheckPlaceholderExpr(E); |
| 20600 | if (result.isInvalid()) return ExprError(); |
| 20601 | E = result.get(); |
| 20602 | |
| 20603 | if (!E->isTypeDependent()) { |
| 20604 | if (getLangOpts().CPlusPlus) |
| 20605 | return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4 |
| 20606 | |
| 20607 | ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); |
| 20608 | if (ERes.isInvalid()) |
| 20609 | return ExprError(); |
| 20610 | E = ERes.get(); |
| 20611 | |
| 20612 | QualType T = E->getType(); |
| 20613 | if (!T->isScalarType()) { // C99 6.8.4.1p1 |
| 20614 | Diag(Loc, DiagID: diag::err_typecheck_statement_requires_scalar) |
| 20615 | << T << E->getSourceRange(); |
| 20616 | return ExprError(); |
| 20617 | } |
| 20618 | CheckBoolLikeConversion(E, CC: Loc); |
| 20619 | } |
| 20620 | |
| 20621 | return E; |
| 20622 | } |
| 20623 | |
| 20624 | Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, |
| 20625 | Expr *SubExpr, ConditionKind CK, |
| 20626 | bool MissingOK) { |
| 20627 | // MissingOK indicates whether having no condition expression is valid |
| 20628 | // (for loop) or invalid (e.g. while loop). |
| 20629 | if (!SubExpr) |
| 20630 | return MissingOK ? ConditionResult() : ConditionError(); |
| 20631 | |
| 20632 | ExprResult Cond; |
| 20633 | switch (CK) { |
| 20634 | case ConditionKind::Boolean: |
| 20635 | Cond = CheckBooleanCondition(Loc, E: SubExpr); |
| 20636 | break; |
| 20637 | |
| 20638 | case ConditionKind::ConstexprIf: |
| 20639 | Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true); |
| 20640 | break; |
| 20641 | |
| 20642 | case ConditionKind::Switch: |
| 20643 | Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr); |
| 20644 | break; |
| 20645 | } |
| 20646 | if (Cond.isInvalid()) { |
| 20647 | Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(), |
| 20648 | SubExprs: {SubExpr}, T: PreferredConditionType(K: CK)); |
| 20649 | if (!Cond.get()) |
| 20650 | return ConditionError(); |
| 20651 | } |
| 20652 | // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. |
| 20653 | FullExprArg FullExpr = MakeFullExpr(Arg: Cond.get(), CC: Loc); |
| 20654 | if (!FullExpr.get()) |
| 20655 | return ConditionError(); |
| 20656 | |
| 20657 | return ConditionResult(*this, nullptr, FullExpr, |
| 20658 | CK == ConditionKind::ConstexprIf); |
| 20659 | } |
| 20660 | |
| 20661 | namespace { |
| 20662 | /// A visitor for rebuilding a call to an __unknown_any expression |
| 20663 | /// to have an appropriate type. |
| 20664 | struct RebuildUnknownAnyFunction |
| 20665 | : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { |
| 20666 | |
| 20667 | Sema &S; |
| 20668 | |
| 20669 | RebuildUnknownAnyFunction(Sema &S) : S(S) {} |
| 20670 | |
| 20671 | ExprResult VisitStmt(Stmt *S) { |
| 20672 | llvm_unreachable("unexpected statement!" ); |
| 20673 | } |
| 20674 | |
| 20675 | ExprResult VisitExpr(Expr *E) { |
| 20676 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_call) |
| 20677 | << E->getSourceRange(); |
| 20678 | return ExprError(); |
| 20679 | } |
| 20680 | |
| 20681 | /// Rebuild an expression which simply semantically wraps another |
| 20682 | /// expression which it shares the type and value kind of. |
| 20683 | template <class T> ExprResult rebuildSugarExpr(T *E) { |
| 20684 | ExprResult SubResult = Visit(S: E->getSubExpr()); |
| 20685 | if (SubResult.isInvalid()) return ExprError(); |
| 20686 | |
| 20687 | Expr *SubExpr = SubResult.get(); |
| 20688 | E->setSubExpr(SubExpr); |
| 20689 | E->setType(SubExpr->getType()); |
| 20690 | E->setValueKind(SubExpr->getValueKind()); |
| 20691 | assert(E->getObjectKind() == OK_Ordinary); |
| 20692 | return E; |
| 20693 | } |
| 20694 | |
| 20695 | ExprResult VisitParenExpr(ParenExpr *E) { |
| 20696 | return rebuildSugarExpr(E); |
| 20697 | } |
| 20698 | |
| 20699 | ExprResult VisitUnaryExtension(UnaryOperator *E) { |
| 20700 | return rebuildSugarExpr(E); |
| 20701 | } |
| 20702 | |
| 20703 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { |
| 20704 | ExprResult SubResult = Visit(S: E->getSubExpr()); |
| 20705 | if (SubResult.isInvalid()) return ExprError(); |
| 20706 | |
| 20707 | Expr *SubExpr = SubResult.get(); |
| 20708 | E->setSubExpr(SubExpr); |
| 20709 | E->setType(S.Context.getPointerType(T: SubExpr->getType())); |
| 20710 | assert(E->isPRValue()); |
| 20711 | assert(E->getObjectKind() == OK_Ordinary); |
| 20712 | return E; |
| 20713 | } |
| 20714 | |
| 20715 | ExprResult resolveDecl(Expr *E, ValueDecl *VD) { |
| 20716 | if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E); |
| 20717 | |
| 20718 | E->setType(VD->getType()); |
| 20719 | |
| 20720 | assert(E->isPRValue()); |
| 20721 | if (S.getLangOpts().CPlusPlus && |
| 20722 | !(isa<CXXMethodDecl>(Val: VD) && |
| 20723 | cast<CXXMethodDecl>(Val: VD)->isInstance())) |
| 20724 | E->setValueKind(VK_LValue); |
| 20725 | |
| 20726 | return E; |
| 20727 | } |
| 20728 | |
| 20729 | ExprResult VisitMemberExpr(MemberExpr *E) { |
| 20730 | return resolveDecl(E, VD: E->getMemberDecl()); |
| 20731 | } |
| 20732 | |
| 20733 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { |
| 20734 | return resolveDecl(E, VD: E->getDecl()); |
| 20735 | } |
| 20736 | }; |
| 20737 | } |
| 20738 | |
| 20739 | /// Given a function expression of unknown-any type, try to rebuild it |
| 20740 | /// to have a function type. |
| 20741 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { |
| 20742 | ExprResult Result = RebuildUnknownAnyFunction(S).Visit(S: FunctionExpr); |
| 20743 | if (Result.isInvalid()) return ExprError(); |
| 20744 | return S.DefaultFunctionArrayConversion(E: Result.get()); |
| 20745 | } |
| 20746 | |
| 20747 | namespace { |
| 20748 | /// A visitor for rebuilding an expression of type __unknown_anytype |
| 20749 | /// into one which resolves the type directly on the referring |
| 20750 | /// expression. Strict preservation of the original source |
| 20751 | /// structure is not a goal. |
| 20752 | struct RebuildUnknownAnyExpr |
| 20753 | : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { |
| 20754 | |
| 20755 | Sema &S; |
| 20756 | |
| 20757 | /// The current destination type. |
| 20758 | QualType DestType; |
| 20759 | |
| 20760 | RebuildUnknownAnyExpr(Sema &S, QualType CastType) |
| 20761 | : S(S), DestType(CastType) {} |
| 20762 | |
| 20763 | ExprResult VisitStmt(Stmt *S) { |
| 20764 | llvm_unreachable("unexpected statement!" ); |
| 20765 | } |
| 20766 | |
| 20767 | ExprResult VisitExpr(Expr *E) { |
| 20768 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr) |
| 20769 | << E->getSourceRange(); |
| 20770 | return ExprError(); |
| 20771 | } |
| 20772 | |
| 20773 | ExprResult VisitCallExpr(CallExpr *E); |
| 20774 | ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); |
| 20775 | |
| 20776 | /// Rebuild an expression which simply semantically wraps another |
| 20777 | /// expression which it shares the type and value kind of. |
| 20778 | template <class T> ExprResult rebuildSugarExpr(T *E) { |
| 20779 | ExprResult SubResult = Visit(S: E->getSubExpr()); |
| 20780 | if (SubResult.isInvalid()) return ExprError(); |
| 20781 | Expr *SubExpr = SubResult.get(); |
| 20782 | E->setSubExpr(SubExpr); |
| 20783 | E->setType(SubExpr->getType()); |
| 20784 | E->setValueKind(SubExpr->getValueKind()); |
| 20785 | assert(E->getObjectKind() == OK_Ordinary); |
| 20786 | return E; |
| 20787 | } |
| 20788 | |
| 20789 | ExprResult VisitParenExpr(ParenExpr *E) { |
| 20790 | return rebuildSugarExpr(E); |
| 20791 | } |
| 20792 | |
| 20793 | ExprResult VisitUnaryExtension(UnaryOperator *E) { |
| 20794 | return rebuildSugarExpr(E); |
| 20795 | } |
| 20796 | |
| 20797 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { |
| 20798 | const PointerType *Ptr = DestType->getAs<PointerType>(); |
| 20799 | if (!Ptr) { |
| 20800 | S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof) |
| 20801 | << E->getSourceRange(); |
| 20802 | return ExprError(); |
| 20803 | } |
| 20804 | |
| 20805 | if (isa<CallExpr>(Val: E->getSubExpr())) { |
| 20806 | S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof_call) |
| 20807 | << E->getSourceRange(); |
| 20808 | return ExprError(); |
| 20809 | } |
| 20810 | |
| 20811 | assert(E->isPRValue()); |
| 20812 | assert(E->getObjectKind() == OK_Ordinary); |
| 20813 | E->setType(DestType); |
| 20814 | |
| 20815 | // Build the sub-expression as if it were an object of the pointee type. |
| 20816 | DestType = Ptr->getPointeeType(); |
| 20817 | ExprResult SubResult = Visit(S: E->getSubExpr()); |
| 20818 | if (SubResult.isInvalid()) return ExprError(); |
| 20819 | E->setSubExpr(SubResult.get()); |
| 20820 | return E; |
| 20821 | } |
| 20822 | |
| 20823 | ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); |
| 20824 | |
| 20825 | ExprResult resolveDecl(Expr *E, ValueDecl *VD); |
| 20826 | |
| 20827 | ExprResult VisitMemberExpr(MemberExpr *E) { |
| 20828 | return resolveDecl(E, VD: E->getMemberDecl()); |
| 20829 | } |
| 20830 | |
| 20831 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { |
| 20832 | return resolveDecl(E, VD: E->getDecl()); |
| 20833 | } |
| 20834 | }; |
| 20835 | } |
| 20836 | |
| 20837 | /// Rebuilds a call expression which yielded __unknown_anytype. |
| 20838 | ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { |
| 20839 | Expr *CalleeExpr = E->getCallee(); |
| 20840 | |
| 20841 | enum FnKind { |
| 20842 | FK_MemberFunction, |
| 20843 | FK_FunctionPointer, |
| 20844 | FK_BlockPointer |
| 20845 | }; |
| 20846 | |
| 20847 | FnKind Kind; |
| 20848 | QualType CalleeType = CalleeExpr->getType(); |
| 20849 | if (CalleeType == S.Context.BoundMemberTy) { |
| 20850 | assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); |
| 20851 | Kind = FK_MemberFunction; |
| 20852 | CalleeType = Expr::findBoundMemberType(expr: CalleeExpr); |
| 20853 | } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { |
| 20854 | CalleeType = Ptr->getPointeeType(); |
| 20855 | Kind = FK_FunctionPointer; |
| 20856 | } else { |
| 20857 | CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); |
| 20858 | Kind = FK_BlockPointer; |
| 20859 | } |
| 20860 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); |
| 20861 | |
| 20862 | // Verify that this is a legal result type of a function. |
| 20863 | if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) || |
| 20864 | DestType->isFunctionType()) { |
| 20865 | unsigned diagID = diag::err_func_returning_array_function; |
| 20866 | if (Kind == FK_BlockPointer) |
| 20867 | diagID = diag::err_block_returning_array_function; |
| 20868 | |
| 20869 | S.Diag(Loc: E->getExprLoc(), DiagID: diagID) |
| 20870 | << DestType->isFunctionType() << DestType; |
| 20871 | return ExprError(); |
| 20872 | } |
| 20873 | |
| 20874 | // Otherwise, go ahead and set DestType as the call's result. |
| 20875 | E->setType(DestType.getNonLValueExprType(Context: S.Context)); |
| 20876 | E->setValueKind(Expr::getValueKindForType(T: DestType)); |
| 20877 | assert(E->getObjectKind() == OK_Ordinary); |
| 20878 | |
| 20879 | // Rebuild the function type, replacing the result type with DestType. |
| 20880 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType); |
| 20881 | if (Proto) { |
| 20882 | // __unknown_anytype(...) is a special case used by the debugger when |
| 20883 | // it has no idea what a function's signature is. |
| 20884 | // |
| 20885 | // We want to build this call essentially under the K&R |
| 20886 | // unprototyped rules, but making a FunctionNoProtoType in C++ |
| 20887 | // would foul up all sorts of assumptions. However, we cannot |
| 20888 | // simply pass all arguments as variadic arguments, nor can we |
| 20889 | // portably just call the function under a non-variadic type; see |
| 20890 | // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. |
| 20891 | // However, it turns out that in practice it is generally safe to |
| 20892 | // call a function declared as "A foo(B,C,D);" under the prototype |
| 20893 | // "A foo(B,C,D,...);". The only known exception is with the |
| 20894 | // Windows ABI, where any variadic function is implicitly cdecl |
| 20895 | // regardless of its normal CC. Therefore we change the parameter |
| 20896 | // types to match the types of the arguments. |
| 20897 | // |
| 20898 | // This is a hack, but it is far superior to moving the |
| 20899 | // corresponding target-specific code from IR-gen to Sema/AST. |
| 20900 | |
| 20901 | ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); |
| 20902 | SmallVector<QualType, 8> ArgTypes; |
| 20903 | if (ParamTypes.empty() && Proto->isVariadic()) { // the special case |
| 20904 | ArgTypes.reserve(N: E->getNumArgs()); |
| 20905 | for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { |
| 20906 | ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i))); |
| 20907 | } |
| 20908 | ParamTypes = ArgTypes; |
| 20909 | } |
| 20910 | DestType = S.Context.getFunctionType(ResultTy: DestType, Args: ParamTypes, |
| 20911 | EPI: Proto->getExtProtoInfo()); |
| 20912 | } else { |
| 20913 | DestType = S.Context.getFunctionNoProtoType(ResultTy: DestType, |
| 20914 | Info: FnType->getExtInfo()); |
| 20915 | } |
| 20916 | |
| 20917 | // Rebuild the appropriate pointer-to-function type. |
| 20918 | switch (Kind) { |
| 20919 | case FK_MemberFunction: |
| 20920 | // Nothing to do. |
| 20921 | break; |
| 20922 | |
| 20923 | case FK_FunctionPointer: |
| 20924 | DestType = S.Context.getPointerType(T: DestType); |
| 20925 | break; |
| 20926 | |
| 20927 | case FK_BlockPointer: |
| 20928 | DestType = S.Context.getBlockPointerType(T: DestType); |
| 20929 | break; |
| 20930 | } |
| 20931 | |
| 20932 | // Finally, we can recurse. |
| 20933 | ExprResult CalleeResult = Visit(S: CalleeExpr); |
| 20934 | if (!CalleeResult.isUsable()) return ExprError(); |
| 20935 | E->setCallee(CalleeResult.get()); |
| 20936 | |
| 20937 | // Bind a temporary if necessary. |
| 20938 | return S.MaybeBindToTemporary(E); |
| 20939 | } |
| 20940 | |
| 20941 | ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { |
| 20942 | // Verify that this is a legal result type of a call. |
| 20943 | if (DestType->isArrayType() || DestType->isFunctionType()) { |
| 20944 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_func_returning_array_function) |
| 20945 | << DestType->isFunctionType() << DestType; |
| 20946 | return ExprError(); |
| 20947 | } |
| 20948 | |
| 20949 | // Rewrite the method result type if available. |
| 20950 | if (ObjCMethodDecl *Method = E->getMethodDecl()) { |
| 20951 | assert(Method->getReturnType() == S.Context.UnknownAnyTy); |
| 20952 | Method->setReturnType(DestType); |
| 20953 | } |
| 20954 | |
| 20955 | // Change the type of the message. |
| 20956 | E->setType(DestType.getNonReferenceType()); |
| 20957 | E->setValueKind(Expr::getValueKindForType(T: DestType)); |
| 20958 | |
| 20959 | return S.MaybeBindToTemporary(E); |
| 20960 | } |
| 20961 | |
| 20962 | ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { |
| 20963 | // The only case we should ever see here is a function-to-pointer decay. |
| 20964 | if (E->getCastKind() == CK_FunctionToPointerDecay) { |
| 20965 | assert(E->isPRValue()); |
| 20966 | assert(E->getObjectKind() == OK_Ordinary); |
| 20967 | |
| 20968 | E->setType(DestType); |
| 20969 | |
| 20970 | // Rebuild the sub-expression as the pointee (function) type. |
| 20971 | DestType = DestType->castAs<PointerType>()->getPointeeType(); |
| 20972 | |
| 20973 | ExprResult Result = Visit(S: E->getSubExpr()); |
| 20974 | if (!Result.isUsable()) return ExprError(); |
| 20975 | |
| 20976 | E->setSubExpr(Result.get()); |
| 20977 | return E; |
| 20978 | } else if (E->getCastKind() == CK_LValueToRValue) { |
| 20979 | assert(E->isPRValue()); |
| 20980 | assert(E->getObjectKind() == OK_Ordinary); |
| 20981 | |
| 20982 | assert(isa<BlockPointerType>(E->getType())); |
| 20983 | |
| 20984 | E->setType(DestType); |
| 20985 | |
| 20986 | // The sub-expression has to be a lvalue reference, so rebuild it as such. |
| 20987 | DestType = S.Context.getLValueReferenceType(T: DestType); |
| 20988 | |
| 20989 | ExprResult Result = Visit(S: E->getSubExpr()); |
| 20990 | if (!Result.isUsable()) return ExprError(); |
| 20991 | |
| 20992 | E->setSubExpr(Result.get()); |
| 20993 | return E; |
| 20994 | } else { |
| 20995 | llvm_unreachable("Unhandled cast type!" ); |
| 20996 | } |
| 20997 | } |
| 20998 | |
| 20999 | ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { |
| 21000 | ExprValueKind ValueKind = VK_LValue; |
| 21001 | QualType Type = DestType; |
| 21002 | |
| 21003 | // We know how to make this work for certain kinds of decls: |
| 21004 | |
| 21005 | // - functions |
| 21006 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) { |
| 21007 | if (const PointerType *Ptr = Type->getAs<PointerType>()) { |
| 21008 | DestType = Ptr->getPointeeType(); |
| 21009 | ExprResult Result = resolveDecl(E, VD); |
| 21010 | if (Result.isInvalid()) return ExprError(); |
| 21011 | return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay, |
| 21012 | VK: VK_PRValue); |
| 21013 | } |
| 21014 | |
| 21015 | if (!Type->isFunctionType()) { |
| 21016 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_function) |
| 21017 | << VD << E->getSourceRange(); |
| 21018 | return ExprError(); |
| 21019 | } |
| 21020 | if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { |
| 21021 | // We must match the FunctionDecl's type to the hack introduced in |
| 21022 | // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown |
| 21023 | // type. See the lengthy commentary in that routine. |
| 21024 | QualType FDT = FD->getType(); |
| 21025 | const FunctionType *FnType = FDT->castAs<FunctionType>(); |
| 21026 | const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType); |
| 21027 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E); |
| 21028 | if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { |
| 21029 | SourceLocation Loc = FD->getLocation(); |
| 21030 | FunctionDecl *NewFD = FunctionDecl::Create( |
| 21031 | C&: S.Context, DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc, |
| 21032 | N: FD->getNameInfo().getName(), T: DestType, TInfo: FD->getTypeSourceInfo(), |
| 21033 | SC: SC_None, UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(), |
| 21034 | isInlineSpecified: false /*isInlineSpecified*/, hasWrittenPrototype: FD->hasPrototype(), |
| 21035 | /*ConstexprKind*/ ConstexprSpecKind::Unspecified); |
| 21036 | |
| 21037 | if (FD->getQualifier()) |
| 21038 | NewFD->setQualifierInfo(FD->getQualifierLoc()); |
| 21039 | |
| 21040 | SmallVector<ParmVarDecl*, 16> Params; |
| 21041 | for (const auto &AI : FT->param_types()) { |
| 21042 | ParmVarDecl *Param = |
| 21043 | S.BuildParmVarDeclForTypedef(DC: FD, Loc, T: AI); |
| 21044 | Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size()); |
| 21045 | Params.push_back(Elt: Param); |
| 21046 | } |
| 21047 | NewFD->setParams(Params); |
| 21048 | DRE->setDecl(NewFD); |
| 21049 | VD = DRE->getDecl(); |
| 21050 | } |
| 21051 | } |
| 21052 | |
| 21053 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) |
| 21054 | if (MD->isInstance()) { |
| 21055 | ValueKind = VK_PRValue; |
| 21056 | Type = S.Context.BoundMemberTy; |
| 21057 | } |
| 21058 | |
| 21059 | // Function references aren't l-values in C. |
| 21060 | if (!S.getLangOpts().CPlusPlus) |
| 21061 | ValueKind = VK_PRValue; |
| 21062 | |
| 21063 | // - variables |
| 21064 | } else if (isa<VarDecl>(Val: VD)) { |
| 21065 | if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { |
| 21066 | Type = RefTy->getPointeeType(); |
| 21067 | } else if (Type->isFunctionType()) { |
| 21068 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_var_function_type) |
| 21069 | << VD << E->getSourceRange(); |
| 21070 | return ExprError(); |
| 21071 | } |
| 21072 | |
| 21073 | // - nothing else |
| 21074 | } else { |
| 21075 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_decl) |
| 21076 | << VD << E->getSourceRange(); |
| 21077 | return ExprError(); |
| 21078 | } |
| 21079 | |
| 21080 | // Modifying the declaration like this is friendly to IR-gen but |
| 21081 | // also really dangerous. |
| 21082 | VD->setType(DestType); |
| 21083 | E->setType(Type); |
| 21084 | E->setValueKind(ValueKind); |
| 21085 | return E; |
| 21086 | } |
| 21087 | |
| 21088 | ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, |
| 21089 | Expr *CastExpr, CastKind &CastKind, |
| 21090 | ExprValueKind &VK, CXXCastPath &Path) { |
| 21091 | // The type we're casting to must be either void or complete. |
| 21092 | if (!CastType->isVoidType() && |
| 21093 | RequireCompleteType(Loc: TypeRange.getBegin(), T: CastType, |
| 21094 | DiagID: diag::err_typecheck_cast_to_incomplete)) |
| 21095 | return ExprError(); |
| 21096 | |
| 21097 | // Rewrite the casted expression from scratch. |
| 21098 | ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(S: CastExpr); |
| 21099 | if (!result.isUsable()) return ExprError(); |
| 21100 | |
| 21101 | CastExpr = result.get(); |
| 21102 | VK = CastExpr->getValueKind(); |
| 21103 | CastKind = CK_NoOp; |
| 21104 | |
| 21105 | return CastExpr; |
| 21106 | } |
| 21107 | |
| 21108 | ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { |
| 21109 | return RebuildUnknownAnyExpr(*this, ToType).Visit(S: E); |
| 21110 | } |
| 21111 | |
| 21112 | ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, |
| 21113 | Expr *arg, QualType ¶mType) { |
| 21114 | // If the syntactic form of the argument is not an explicit cast of |
| 21115 | // any sort, just do default argument promotion. |
| 21116 | ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens()); |
| 21117 | if (!castArg) { |
| 21118 | ExprResult result = DefaultArgumentPromotion(E: arg); |
| 21119 | if (result.isInvalid()) return ExprError(); |
| 21120 | paramType = result.get()->getType(); |
| 21121 | return result; |
| 21122 | } |
| 21123 | |
| 21124 | // Otherwise, use the type that was written in the explicit cast. |
| 21125 | assert(!arg->hasPlaceholderType()); |
| 21126 | paramType = castArg->getTypeAsWritten(); |
| 21127 | |
| 21128 | // Copy-initialize a parameter of that type. |
| 21129 | InitializedEntity entity = |
| 21130 | InitializedEntity::InitializeParameter(Context, Type: paramType, |
| 21131 | /*consumed*/ Consumed: false); |
| 21132 | return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg); |
| 21133 | } |
| 21134 | |
| 21135 | static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { |
| 21136 | Expr *orig = E; |
| 21137 | unsigned diagID = diag::err_uncasted_use_of_unknown_any; |
| 21138 | while (true) { |
| 21139 | E = E->IgnoreParenImpCasts(); |
| 21140 | if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) { |
| 21141 | E = call->getCallee(); |
| 21142 | diagID = diag::err_uncasted_call_of_unknown_any; |
| 21143 | } else { |
| 21144 | break; |
| 21145 | } |
| 21146 | } |
| 21147 | |
| 21148 | SourceLocation loc; |
| 21149 | NamedDecl *d; |
| 21150 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) { |
| 21151 | loc = ref->getLocation(); |
| 21152 | d = ref->getDecl(); |
| 21153 | } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) { |
| 21154 | loc = mem->getMemberLoc(); |
| 21155 | d = mem->getMemberDecl(); |
| 21156 | } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) { |
| 21157 | diagID = diag::err_uncasted_call_of_unknown_any; |
| 21158 | loc = msg->getSelectorStartLoc(); |
| 21159 | d = msg->getMethodDecl(); |
| 21160 | if (!d) { |
| 21161 | S.Diag(Loc: loc, DiagID: diag::err_uncasted_send_to_unknown_any_method) |
| 21162 | << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() |
| 21163 | << orig->getSourceRange(); |
| 21164 | return ExprError(); |
| 21165 | } |
| 21166 | } else { |
| 21167 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr) |
| 21168 | << E->getSourceRange(); |
| 21169 | return ExprError(); |
| 21170 | } |
| 21171 | |
| 21172 | S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange(); |
| 21173 | |
| 21174 | // Never recoverable. |
| 21175 | return ExprError(); |
| 21176 | } |
| 21177 | |
| 21178 | ExprResult Sema::CheckPlaceholderExpr(Expr *E) { |
| 21179 | const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); |
| 21180 | if (!placeholderType) return E; |
| 21181 | |
| 21182 | switch (placeholderType->getKind()) { |
| 21183 | case BuiltinType::UnresolvedTemplate: { |
| 21184 | auto *ULE = cast<UnresolvedLookupExpr>(Val: E); |
| 21185 | const DeclarationNameInfo &NameInfo = ULE->getNameInfo(); |
| 21186 | // There's only one FoundDecl for UnresolvedTemplate type. See |
| 21187 | // BuildTemplateIdExpr. |
| 21188 | NamedDecl *Temp = *ULE->decls_begin(); |
| 21189 | const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp); |
| 21190 | |
| 21191 | NestedNameSpecifier *NNS = ULE->getQualifierLoc().getNestedNameSpecifier(); |
| 21192 | // FIXME: AssumedTemplate is not very appropriate for error recovery here, |
| 21193 | // as it models only the unqualified-id case, where this case can clearly be |
| 21194 | // qualified. Thus we can't just qualify an assumed template. |
| 21195 | TemplateName TN; |
| 21196 | if (auto *TD = dyn_cast<TemplateDecl>(Val: Temp)) |
| 21197 | TN = Context.getQualifiedTemplateName(NNS, TemplateKeyword: ULE->hasTemplateKeyword(), |
| 21198 | Template: TemplateName(TD)); |
| 21199 | else |
| 21200 | TN = Context.getAssumedTemplateName(Name: NameInfo.getName()); |
| 21201 | |
| 21202 | Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template) |
| 21203 | << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl; |
| 21204 | Diag(Loc: Temp->getLocation(), DiagID: diag::note_referenced_type_template) |
| 21205 | << IsTypeAliasTemplateDecl; |
| 21206 | |
| 21207 | TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc()); |
| 21208 | bool HasAnyDependentTA = false; |
| 21209 | for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) { |
| 21210 | HasAnyDependentTA |= Arg.getArgument().isDependent(); |
| 21211 | TAL.addArgument(Loc: Arg); |
| 21212 | } |
| 21213 | |
| 21214 | QualType TST; |
| 21215 | { |
| 21216 | SFINAETrap Trap(*this); |
| 21217 | TST = CheckTemplateIdType(Template: TN, TemplateLoc: NameInfo.getBeginLoc(), TemplateArgs&: TAL); |
| 21218 | } |
| 21219 | if (TST.isNull()) |
| 21220 | TST = Context.getTemplateSpecializationType( |
| 21221 | T: TN, SpecifiedArgs: ULE->template_arguments(), /*CanonicalArgs=*/{}, |
| 21222 | Canon: HasAnyDependentTA ? Context.DependentTy : Context.IntTy); |
| 21223 | QualType ET = |
| 21224 | Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS, NamedType: TST); |
| 21225 | return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {}, |
| 21226 | T: ET); |
| 21227 | } |
| 21228 | |
| 21229 | // Overloaded expressions. |
| 21230 | case BuiltinType::Overload: { |
| 21231 | // Try to resolve a single function template specialization. |
| 21232 | // This is obligatory. |
| 21233 | ExprResult Result = E; |
| 21234 | if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false)) |
| 21235 | return Result; |
| 21236 | |
| 21237 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization |
| 21238 | // leaves Result unchanged on failure. |
| 21239 | Result = E; |
| 21240 | if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result)) |
| 21241 | return Result; |
| 21242 | |
| 21243 | // If that failed, try to recover with a call. |
| 21244 | tryToRecoverWithCall(E&: Result, PD: PDiag(DiagID: diag::err_ovl_unresolvable), |
| 21245 | /*complain*/ ForceComplain: true); |
| 21246 | return Result; |
| 21247 | } |
| 21248 | |
| 21249 | // Bound member functions. |
| 21250 | case BuiltinType::BoundMember: { |
| 21251 | ExprResult result = E; |
| 21252 | const Expr *BME = E->IgnoreParens(); |
| 21253 | PartialDiagnostic PD = PDiag(DiagID: diag::err_bound_member_function); |
| 21254 | // Try to give a nicer diagnostic if it is a bound member that we recognize. |
| 21255 | if (isa<CXXPseudoDestructorExpr>(Val: BME)) { |
| 21256 | PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; |
| 21257 | } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) { |
| 21258 | if (ME->getMemberNameInfo().getName().getNameKind() == |
| 21259 | DeclarationName::CXXDestructorName) |
| 21260 | PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*destructor*/ 0; |
| 21261 | } |
| 21262 | tryToRecoverWithCall(E&: result, PD, |
| 21263 | /*complain*/ ForceComplain: true); |
| 21264 | return result; |
| 21265 | } |
| 21266 | |
| 21267 | // ARC unbridged casts. |
| 21268 | case BuiltinType::ARCUnbridgedCast: { |
| 21269 | Expr *realCast = ObjC().stripARCUnbridgedCast(e: E); |
| 21270 | ObjC().diagnoseARCUnbridgedCast(e: realCast); |
| 21271 | return realCast; |
| 21272 | } |
| 21273 | |
| 21274 | // Expressions of unknown type. |
| 21275 | case BuiltinType::UnknownAny: |
| 21276 | return diagnoseUnknownAnyExpr(S&: *this, E); |
| 21277 | |
| 21278 | // Pseudo-objects. |
| 21279 | case BuiltinType::PseudoObject: |
| 21280 | return PseudoObject().checkRValue(E); |
| 21281 | |
| 21282 | case BuiltinType::BuiltinFn: { |
| 21283 | // Accept __noop without parens by implicitly converting it to a call expr. |
| 21284 | auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()); |
| 21285 | if (DRE) { |
| 21286 | auto *FD = cast<FunctionDecl>(Val: DRE->getDecl()); |
| 21287 | unsigned BuiltinID = FD->getBuiltinID(); |
| 21288 | if (BuiltinID == Builtin::BI__noop) { |
| 21289 | E = ImpCastExprToType(E, Type: Context.getPointerType(T: FD->getType()), |
| 21290 | CK: CK_BuiltinFnToFnPtr) |
| 21291 | .get(); |
| 21292 | return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy, |
| 21293 | VK: VK_PRValue, RParenLoc: SourceLocation(), |
| 21294 | FPFeatures: FPOptionsOverride()); |
| 21295 | } |
| 21296 | |
| 21297 | if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) { |
| 21298 | // Any use of these other than a direct call is ill-formed as of C++20, |
| 21299 | // because they are not addressable functions. In earlier language |
| 21300 | // modes, warn and force an instantiation of the real body. |
| 21301 | Diag(Loc: E->getBeginLoc(), |
| 21302 | DiagID: getLangOpts().CPlusPlus20 |
| 21303 | ? diag::err_use_of_unaddressable_function |
| 21304 | : diag::warn_cxx20_compat_use_of_unaddressable_function); |
| 21305 | if (FD->isImplicitlyInstantiable()) { |
| 21306 | // Require a definition here because a normal attempt at |
| 21307 | // instantiation for a builtin will be ignored, and we won't try |
| 21308 | // again later. We assume that the definition of the template |
| 21309 | // precedes this use. |
| 21310 | InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD, |
| 21311 | /*Recursive=*/false, |
| 21312 | /*DefinitionRequired=*/true, |
| 21313 | /*AtEndOfTU=*/false); |
| 21314 | } |
| 21315 | // Produce a properly-typed reference to the function. |
| 21316 | CXXScopeSpec SS; |
| 21317 | SS.Adopt(Other: DRE->getQualifierLoc()); |
| 21318 | TemplateArgumentListInfo TemplateArgs; |
| 21319 | DRE->copyTemplateArgumentsInto(List&: TemplateArgs); |
| 21320 | return BuildDeclRefExpr( |
| 21321 | D: FD, Ty: FD->getType(), VK: VK_LValue, NameInfo: DRE->getNameInfo(), |
| 21322 | SS: DRE->hasQualifier() ? &SS : nullptr, FoundD: DRE->getFoundDecl(), |
| 21323 | TemplateKWLoc: DRE->getTemplateKeywordLoc(), |
| 21324 | TemplateArgs: DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr); |
| 21325 | } |
| 21326 | } |
| 21327 | |
| 21328 | Diag(Loc: E->getBeginLoc(), DiagID: diag::err_builtin_fn_use); |
| 21329 | return ExprError(); |
| 21330 | } |
| 21331 | |
| 21332 | case BuiltinType::IncompleteMatrixIdx: |
| 21333 | Diag(Loc: cast<MatrixSubscriptExpr>(Val: E->IgnoreParens()) |
| 21334 | ->getRowIdx() |
| 21335 | ->getBeginLoc(), |
| 21336 | DiagID: diag::err_matrix_incomplete_index); |
| 21337 | return ExprError(); |
| 21338 | |
| 21339 | // Expressions of unknown type. |
| 21340 | case BuiltinType::ArraySection: |
| 21341 | Diag(Loc: E->getBeginLoc(), DiagID: diag::err_array_section_use) |
| 21342 | << cast<ArraySectionExpr>(Val: E)->isOMPArraySection(); |
| 21343 | return ExprError(); |
| 21344 | |
| 21345 | // Expressions of unknown type. |
| 21346 | case BuiltinType::OMPArrayShaping: |
| 21347 | return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_array_shaping_use)); |
| 21348 | |
| 21349 | case BuiltinType::OMPIterator: |
| 21350 | return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_iterator_use)); |
| 21351 | |
| 21352 | // Everything else should be impossible. |
| 21353 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
| 21354 | case BuiltinType::Id: |
| 21355 | #include "clang/Basic/OpenCLImageTypes.def" |
| 21356 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
| 21357 | case BuiltinType::Id: |
| 21358 | #include "clang/Basic/OpenCLExtensionTypes.def" |
| 21359 | #define SVE_TYPE(Name, Id, SingletonId) \ |
| 21360 | case BuiltinType::Id: |
| 21361 | #include "clang/Basic/AArch64ACLETypes.def" |
| 21362 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ |
| 21363 | case BuiltinType::Id: |
| 21364 | #include "clang/Basic/PPCTypes.def" |
| 21365 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
| 21366 | #include "clang/Basic/RISCVVTypes.def" |
| 21367 | #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
| 21368 | #include "clang/Basic/WebAssemblyReferenceTypes.def" |
| 21369 | #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id: |
| 21370 | #include "clang/Basic/AMDGPUTypes.def" |
| 21371 | #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
| 21372 | #include "clang/Basic/HLSLIntangibleTypes.def" |
| 21373 | #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: |
| 21374 | #define PLACEHOLDER_TYPE(Id, SingletonId) |
| 21375 | #include "clang/AST/BuiltinTypes.def" |
| 21376 | break; |
| 21377 | } |
| 21378 | |
| 21379 | llvm_unreachable("invalid placeholder type!" ); |
| 21380 | } |
| 21381 | |
| 21382 | bool Sema::CheckCaseExpression(Expr *E) { |
| 21383 | if (E->isTypeDependent()) |
| 21384 | return true; |
| 21385 | if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context)) |
| 21386 | return E->getType()->isIntegralOrEnumerationType(); |
| 21387 | return false; |
| 21388 | } |
| 21389 | |
| 21390 | ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, |
| 21391 | ArrayRef<Expr *> SubExprs, QualType T) { |
| 21392 | if (!Context.getLangOpts().RecoveryAST) |
| 21393 | return ExprError(); |
| 21394 | |
| 21395 | if (isSFINAEContext()) |
| 21396 | return ExprError(); |
| 21397 | |
| 21398 | if (T.isNull() || T->isUndeducedType() || |
| 21399 | !Context.getLangOpts().RecoveryASTType) |
| 21400 | // We don't know the concrete type, fallback to dependent type. |
| 21401 | T = Context.DependentTy; |
| 21402 | |
| 21403 | return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs); |
| 21404 | } |
| 21405 | |