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