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