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