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