File: | clang/lib/Sema/SemaExpr.cpp |
Warning: | line 10043, column 26 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/TypeLoc.h" | |||
31 | #include "clang/Basic/Builtins.h" | |||
32 | #include "clang/Basic/DiagnosticSema.h" | |||
33 | #include "clang/Basic/PartialDiagnostic.h" | |||
34 | #include "clang/Basic/SourceManager.h" | |||
35 | #include "clang/Basic/TargetInfo.h" | |||
36 | #include "clang/Lex/LiteralSupport.h" | |||
37 | #include "clang/Lex/Preprocessor.h" | |||
38 | #include "clang/Sema/AnalysisBasedWarnings.h" | |||
39 | #include "clang/Sema/DeclSpec.h" | |||
40 | #include "clang/Sema/DelayedDiagnostic.h" | |||
41 | #include "clang/Sema/Designator.h" | |||
42 | #include "clang/Sema/Initialization.h" | |||
43 | #include "clang/Sema/Lookup.h" | |||
44 | #include "clang/Sema/Overload.h" | |||
45 | #include "clang/Sema/ParsedTemplate.h" | |||
46 | #include "clang/Sema/Scope.h" | |||
47 | #include "clang/Sema/ScopeInfo.h" | |||
48 | #include "clang/Sema/SemaFixItUtils.h" | |||
49 | #include "clang/Sema/SemaInternal.h" | |||
50 | #include "clang/Sema/Template.h" | |||
51 | #include "llvm/ADT/STLExtras.h" | |||
52 | #include "llvm/ADT/StringExtras.h" | |||
53 | #include "llvm/Support/ConvertUTF.h" | |||
54 | #include "llvm/Support/SaveAndRestore.h" | |||
55 | ||||
56 | using namespace clang; | |||
57 | using namespace sema; | |||
58 | ||||
59 | /// Determine whether the use of this declaration is valid, without | |||
60 | /// emitting diagnostics. | |||
61 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { | |||
62 | // See if this is an auto-typed variable whose initializer we are parsing. | |||
63 | if (ParsingInitForAutoVars.count(D)) | |||
64 | return false; | |||
65 | ||||
66 | // See if this is a deleted function. | |||
67 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
68 | if (FD->isDeleted()) | |||
69 | return false; | |||
70 | ||||
71 | // If the function has a deduced return type, and we can't deduce it, | |||
72 | // then we can't use it either. | |||
73 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | |||
74 | DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) | |||
75 | return false; | |||
76 | ||||
77 | // See if this is an aligned allocation/deallocation function that is | |||
78 | // unavailable. | |||
79 | if (TreatUnavailableAsInvalid && | |||
80 | isUnavailableAlignedAllocationFunction(*FD)) | |||
81 | return false; | |||
82 | } | |||
83 | ||||
84 | // See if this function is unavailable. | |||
85 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && | |||
86 | cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) | |||
87 | return false; | |||
88 | ||||
89 | if (isa<UnresolvedUsingIfExistsDecl>(D)) | |||
90 | return false; | |||
91 | ||||
92 | return true; | |||
93 | } | |||
94 | ||||
95 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { | |||
96 | // Warn if this is used but marked unused. | |||
97 | if (const auto *A = D->getAttr<UnusedAttr>()) { | |||
98 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) | |||
99 | // should diagnose them. | |||
100 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && | |||
101 | A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { | |||
102 | const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); | |||
103 | if (DC && !DC->hasAttr<UnusedAttr>()) | |||
104 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D; | |||
105 | } | |||
106 | } | |||
107 | } | |||
108 | ||||
109 | /// Emit a note explaining that this function is deleted. | |||
110 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { | |||
111 | assert(Decl && Decl->isDeleted())(static_cast <bool> (Decl && Decl->isDeleted ()) ? void (0) : __assert_fail ("Decl && Decl->isDeleted()" , "clang/lib/Sema/SemaExpr.cpp", 111, __extension__ __PRETTY_FUNCTION__ )); | |||
112 | ||||
113 | if (Decl->isDefaulted()) { | |||
114 | // If the method was explicitly defaulted, point at that declaration. | |||
115 | if (!Decl->isImplicit()) | |||
116 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); | |||
117 | ||||
118 | // Try to diagnose why this special member function was implicitly | |||
119 | // deleted. This might fail, if that reason no longer applies. | |||
120 | DiagnoseDeletedDefaultedFunction(Decl); | |||
121 | return; | |||
122 | } | |||
123 | ||||
124 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); | |||
125 | if (Ctor && Ctor->isInheritingConstructor()) | |||
126 | return NoteDeletedInheritingConstructor(Ctor); | |||
127 | ||||
128 | Diag(Decl->getLocation(), diag::note_availability_specified_here) | |||
129 | << Decl << 1; | |||
130 | } | |||
131 | ||||
132 | /// Determine whether a FunctionDecl was ever declared with an | |||
133 | /// explicit storage class. | |||
134 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { | |||
135 | for (auto I : D->redecls()) { | |||
136 | if (I->getStorageClass() != SC_None) | |||
137 | return true; | |||
138 | } | |||
139 | return false; | |||
140 | } | |||
141 | ||||
142 | /// Check whether we're in an extern inline function and referring to a | |||
143 | /// variable or function with internal linkage (C11 6.7.4p3). | |||
144 | /// | |||
145 | /// This is only a warning because we used to silently accept this code, but | |||
146 | /// in many cases it will not behave correctly. This is not enabled in C++ mode | |||
147 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) | |||
148 | /// and so while there may still be user mistakes, most of the time we can't | |||
149 | /// prove that there are errors. | |||
150 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, | |||
151 | const NamedDecl *D, | |||
152 | SourceLocation Loc) { | |||
153 | // This is disabled under C++; there are too many ways for this to fire in | |||
154 | // contexts where the warning is a false positive, or where it is technically | |||
155 | // correct but benign. | |||
156 | if (S.getLangOpts().CPlusPlus) | |||
157 | return; | |||
158 | ||||
159 | // Check if this is an inlined function or method. | |||
160 | FunctionDecl *Current = S.getCurFunctionDecl(); | |||
161 | if (!Current) | |||
162 | return; | |||
163 | if (!Current->isInlined()) | |||
164 | return; | |||
165 | if (!Current->isExternallyVisible()) | |||
166 | return; | |||
167 | ||||
168 | // Check if the decl has internal linkage. | |||
169 | if (D->getFormalLinkage() != InternalLinkage) | |||
170 | return; | |||
171 | ||||
172 | // Downgrade from ExtWarn to Extension if | |||
173 | // (1) the supposedly external inline function is in the main file, | |||
174 | // and probably won't be included anywhere else. | |||
175 | // (2) the thing we're referencing is a pure function. | |||
176 | // (3) the thing we're referencing is another inline function. | |||
177 | // This last can give us false negatives, but it's better than warning on | |||
178 | // wrappers for simple C library functions. | |||
179 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); | |||
180 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); | |||
181 | if (!DowngradeWarning && UsedFn) | |||
182 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); | |||
183 | ||||
184 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet | |||
185 | : diag::ext_internal_in_extern_inline) | |||
186 | << /*IsVar=*/!UsedFn << D; | |||
187 | ||||
188 | S.MaybeSuggestAddingStaticToDecl(Current); | |||
189 | ||||
190 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) | |||
191 | << D; | |||
192 | } | |||
193 | ||||
194 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { | |||
195 | const FunctionDecl *First = Cur->getFirstDecl(); | |||
196 | ||||
197 | // Suggest "static" on the function, if possible. | |||
198 | if (!hasAnyExplicitStorageClass(First)) { | |||
199 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); | |||
200 | Diag(DeclBegin, diag::note_convert_inline_to_static) | |||
201 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); | |||
202 | } | |||
203 | } | |||
204 | ||||
205 | /// Determine whether the use of this declaration is valid, and | |||
206 | /// emit any corresponding diagnostics. | |||
207 | /// | |||
208 | /// This routine diagnoses various problems with referencing | |||
209 | /// declarations that can occur when using a declaration. For example, | |||
210 | /// it might warn if a deprecated or unavailable declaration is being | |||
211 | /// used, or produce an error (and return true) if a C++0x deleted | |||
212 | /// function is being used. | |||
213 | /// | |||
214 | /// \returns true if there was an error (this declaration cannot be | |||
215 | /// referenced), false otherwise. | |||
216 | /// | |||
217 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | |||
218 | const ObjCInterfaceDecl *UnknownObjCClass, | |||
219 | bool ObjCPropertyAccess, | |||
220 | bool AvoidPartialAvailabilityChecks, | |||
221 | ObjCInterfaceDecl *ClassReceiver) { | |||
222 | SourceLocation Loc = Locs.front(); | |||
223 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { | |||
224 | // If there were any diagnostics suppressed by template argument deduction, | |||
225 | // emit them now. | |||
226 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); | |||
227 | if (Pos != SuppressedDiagnostics.end()) { | |||
228 | for (const PartialDiagnosticAt &Suppressed : Pos->second) | |||
229 | Diag(Suppressed.first, Suppressed.second); | |||
230 | ||||
231 | // Clear out the list of suppressed diagnostics, so that we don't emit | |||
232 | // them again for this specialization. However, we don't obsolete this | |||
233 | // entry from the table, because we want to avoid ever emitting these | |||
234 | // diagnostics again. | |||
235 | Pos->second.clear(); | |||
236 | } | |||
237 | ||||
238 | // C++ [basic.start.main]p3: | |||
239 | // The function 'main' shall not be used within a program. | |||
240 | if (cast<FunctionDecl>(D)->isMain()) | |||
241 | Diag(Loc, diag::ext_main_used); | |||
242 | ||||
243 | diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); | |||
244 | } | |||
245 | ||||
246 | // See if this is an auto-typed variable whose initializer we are parsing. | |||
247 | if (ParsingInitForAutoVars.count(D)) { | |||
248 | if (isa<BindingDecl>(D)) { | |||
249 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) | |||
250 | << D->getDeclName(); | |||
251 | } else { | |||
252 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) | |||
253 | << D->getDeclName() << cast<VarDecl>(D)->getType(); | |||
254 | } | |||
255 | return true; | |||
256 | } | |||
257 | ||||
258 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
259 | // See if this is a deleted function. | |||
260 | if (FD->isDeleted()) { | |||
261 | auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); | |||
262 | if (Ctor && Ctor->isInheritingConstructor()) | |||
263 | Diag(Loc, diag::err_deleted_inherited_ctor_use) | |||
264 | << Ctor->getParent() | |||
265 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); | |||
266 | else | |||
267 | Diag(Loc, diag::err_deleted_function_use); | |||
268 | NoteDeletedFunction(FD); | |||
269 | return true; | |||
270 | } | |||
271 | ||||
272 | // [expr.prim.id]p4 | |||
273 | // A program that refers explicitly or implicitly to a function with a | |||
274 | // trailing requires-clause whose constraint-expression is not satisfied, | |||
275 | // other than to declare it, is ill-formed. [...] | |||
276 | // | |||
277 | // See if this is a function with constraints that need to be satisfied. | |||
278 | // Check this before deducing the return type, as it might instantiate the | |||
279 | // definition. | |||
280 | if (FD->getTrailingRequiresClause()) { | |||
281 | ConstraintSatisfaction Satisfaction; | |||
282 | if (CheckFunctionConstraints(FD, Satisfaction, Loc)) | |||
283 | // A diagnostic will have already been generated (non-constant | |||
284 | // constraint expression, for example) | |||
285 | return true; | |||
286 | if (!Satisfaction.IsSatisfied) { | |||
287 | Diag(Loc, | |||
288 | diag::err_reference_to_function_with_unsatisfied_constraints) | |||
289 | << D; | |||
290 | DiagnoseUnsatisfiedConstraint(Satisfaction); | |||
291 | return true; | |||
292 | } | |||
293 | } | |||
294 | ||||
295 | // If the function has a deduced return type, and we can't deduce it, | |||
296 | // then we can't use it either. | |||
297 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | |||
298 | DeduceReturnType(FD, Loc)) | |||
299 | return true; | |||
300 | ||||
301 | if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) | |||
302 | return true; | |||
303 | ||||
304 | if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) | |||
305 | return true; | |||
306 | } | |||
307 | ||||
308 | if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { | |||
309 | // Lambdas are only default-constructible or assignable in C++2a onwards. | |||
310 | if (MD->getParent()->isLambda() && | |||
311 | ((isa<CXXConstructorDecl>(MD) && | |||
312 | cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || | |||
313 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { | |||
314 | Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) | |||
315 | << !isa<CXXConstructorDecl>(MD); | |||
316 | } | |||
317 | } | |||
318 | ||||
319 | auto getReferencedObjCProp = [](const NamedDecl *D) -> | |||
320 | const ObjCPropertyDecl * { | |||
321 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) | |||
322 | return MD->findPropertyDecl(); | |||
323 | return nullptr; | |||
324 | }; | |||
325 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { | |||
326 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) | |||
327 | return true; | |||
328 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { | |||
329 | return true; | |||
330 | } | |||
331 | ||||
332 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions | |||
333 | // Only the variables omp_in and omp_out are allowed in the combiner. | |||
334 | // Only the variables omp_priv and omp_orig are allowed in the | |||
335 | // initializer-clause. | |||
336 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); | |||
337 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && | |||
338 | isa<VarDecl>(D)) { | |||
339 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) | |||
340 | << getCurFunction()->HasOMPDeclareReductionCombiner; | |||
341 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | |||
342 | return true; | |||
343 | } | |||
344 | ||||
345 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions | |||
346 | // List-items in map clauses on this construct may only refer to the declared | |||
347 | // variable var and entities that could be referenced by a procedure defined | |||
348 | // at the same location | |||
349 | if (LangOpts.OpenMP && isa<VarDecl>(D) && | |||
350 | !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { | |||
351 | Diag(Loc, diag::err_omp_declare_mapper_wrong_var) | |||
352 | << getOpenMPDeclareMapperVarName(); | |||
353 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | |||
354 | return true; | |||
355 | } | |||
356 | ||||
357 | if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { | |||
358 | Diag(Loc, diag::err_use_of_empty_using_if_exists); | |||
359 | Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); | |||
360 | return true; | |||
361 | } | |||
362 | ||||
363 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, | |||
364 | AvoidPartialAvailabilityChecks, ClassReceiver); | |||
365 | ||||
366 | DiagnoseUnusedOfDecl(*this, D, Loc); | |||
367 | ||||
368 | diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); | |||
369 | ||||
370 | if (auto *VD = dyn_cast<ValueDecl>(D)) | |||
371 | checkTypeSupport(VD->getType(), Loc, VD); | |||
372 | ||||
373 | if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { | |||
374 | if (!Context.getTargetInfo().isTLSSupported()) | |||
375 | if (const auto *VD = dyn_cast<VarDecl>(D)) | |||
376 | if (VD->getTLSKind() != VarDecl::TLS_None) | |||
377 | targetDiag(*Locs.begin(), diag::err_thread_unsupported); | |||
378 | } | |||
379 | ||||
380 | if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && | |||
381 | !isUnevaluatedContext()) { | |||
382 | // C++ [expr.prim.req.nested] p3 | |||
383 | // A local parameter shall only appear as an unevaluated operand | |||
384 | // (Clause 8) within the constraint-expression. | |||
385 | Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) | |||
386 | << D; | |||
387 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | |||
388 | return true; | |||
389 | } | |||
390 | ||||
391 | return false; | |||
392 | } | |||
393 | ||||
394 | /// DiagnoseSentinelCalls - This routine checks whether a call or | |||
395 | /// message-send is to a declaration with the sentinel attribute, and | |||
396 | /// if so, it checks that the requirements of the sentinel are | |||
397 | /// satisfied. | |||
398 | void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, | |||
399 | ArrayRef<Expr *> Args) { | |||
400 | const SentinelAttr *attr = D->getAttr<SentinelAttr>(); | |||
401 | if (!attr) | |||
402 | return; | |||
403 | ||||
404 | // The number of formal parameters of the declaration. | |||
405 | unsigned numFormalParams; | |||
406 | ||||
407 | // The kind of declaration. This is also an index into a %select in | |||
408 | // the diagnostic. | |||
409 | enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; | |||
410 | ||||
411 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { | |||
412 | numFormalParams = MD->param_size(); | |||
413 | calleeType = CT_Method; | |||
414 | } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
415 | numFormalParams = FD->param_size(); | |||
416 | calleeType = CT_Function; | |||
417 | } else if (isa<VarDecl>(D)) { | |||
418 | QualType type = cast<ValueDecl>(D)->getType(); | |||
419 | const FunctionType *fn = nullptr; | |||
420 | if (const PointerType *ptr = type->getAs<PointerType>()) { | |||
421 | fn = ptr->getPointeeType()->getAs<FunctionType>(); | |||
422 | if (!fn) return; | |||
423 | calleeType = CT_Function; | |||
424 | } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { | |||
425 | fn = ptr->getPointeeType()->castAs<FunctionType>(); | |||
426 | calleeType = CT_Block; | |||
427 | } else { | |||
428 | return; | |||
429 | } | |||
430 | ||||
431 | if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { | |||
432 | numFormalParams = proto->getNumParams(); | |||
433 | } else { | |||
434 | numFormalParams = 0; | |||
435 | } | |||
436 | } else { | |||
437 | return; | |||
438 | } | |||
439 | ||||
440 | // "nullPos" is the number of formal parameters at the end which | |||
441 | // effectively count as part of the variadic arguments. This is | |||
442 | // useful if you would prefer to not have *any* formal parameters, | |||
443 | // but the language forces you to have at least one. | |||
444 | unsigned nullPos = attr->getNullPos(); | |||
445 | 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", 445, __extension__ __PRETTY_FUNCTION__ )); | |||
446 | numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); | |||
447 | ||||
448 | // The number of arguments which should follow the sentinel. | |||
449 | unsigned numArgsAfterSentinel = attr->getSentinel(); | |||
450 | ||||
451 | // If there aren't enough arguments for all the formal parameters, | |||
452 | // the sentinel, and the args after the sentinel, complain. | |||
453 | if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { | |||
454 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); | |||
455 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | |||
456 | return; | |||
457 | } | |||
458 | ||||
459 | // Otherwise, find the sentinel expression. | |||
460 | Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; | |||
461 | if (!sentinelExpr) return; | |||
462 | if (sentinelExpr->isValueDependent()) return; | |||
463 | if (Context.isSentinelNullExpr(sentinelExpr)) return; | |||
464 | ||||
465 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', | |||
466 | // or 'NULL' if those are actually defined in the context. Only use | |||
467 | // 'nil' for ObjC methods, where it's much more likely that the | |||
468 | // variadic arguments form a list of object pointers. | |||
469 | SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); | |||
470 | std::string NullValue; | |||
471 | if (calleeType == CT_Method && PP.isMacroDefined("nil")) | |||
472 | NullValue = "nil"; | |||
473 | else if (getLangOpts().CPlusPlus11) | |||
474 | NullValue = "nullptr"; | |||
475 | else if (PP.isMacroDefined("NULL")) | |||
476 | NullValue = "NULL"; | |||
477 | else | |||
478 | NullValue = "(void*) 0"; | |||
479 | ||||
480 | if (MissingNilLoc.isInvalid()) | |||
481 | Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); | |||
482 | else | |||
483 | Diag(MissingNilLoc, diag::warn_missing_sentinel) | |||
484 | << int(calleeType) | |||
485 | << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); | |||
486 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | |||
487 | } | |||
488 | ||||
489 | SourceRange Sema::getExprRange(Expr *E) const { | |||
490 | return E ? E->getSourceRange() : SourceRange(); | |||
491 | } | |||
492 | ||||
493 | //===----------------------------------------------------------------------===// | |||
494 | // Standard Promotions and Conversions | |||
495 | //===----------------------------------------------------------------------===// | |||
496 | ||||
497 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). | |||
498 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { | |||
499 | // Handle any placeholder expressions which made it here. | |||
500 | if (E->hasPlaceholderType()) { | |||
501 | ExprResult result = CheckPlaceholderExpr(E); | |||
502 | if (result.isInvalid()) return ExprError(); | |||
503 | E = result.get(); | |||
504 | } | |||
505 | ||||
506 | QualType Ty = E->getType(); | |||
507 | 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", 507, __extension__ __PRETTY_FUNCTION__ )); | |||
508 | ||||
509 | if (Ty->isFunctionType()) { | |||
510 | if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) | |||
511 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | |||
512 | if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) | |||
513 | return ExprError(); | |||
514 | ||||
515 | E = ImpCastExprToType(E, Context.getPointerType(Ty), | |||
516 | CK_FunctionToPointerDecay).get(); | |||
517 | } else if (Ty->isArrayType()) { | |||
518 | // In C90 mode, arrays only promote to pointers if the array expression is | |||
519 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has | |||
520 | // type 'array of type' is converted to an expression that has type 'pointer | |||
521 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression | |||
522 | // that has type 'array of type' ...". The relevant change is "an lvalue" | |||
523 | // (C90) to "an expression" (C99). | |||
524 | // | |||
525 | // C++ 4.2p1: | |||
526 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of | |||
527 | // T" can be converted to an rvalue of type "pointer to T". | |||
528 | // | |||
529 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { | |||
530 | ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), | |||
531 | CK_ArrayToPointerDecay); | |||
532 | if (Res.isInvalid()) | |||
533 | return ExprError(); | |||
534 | E = Res.get(); | |||
535 | } | |||
536 | } | |||
537 | return E; | |||
538 | } | |||
539 | ||||
540 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { | |||
541 | // Check to see if we are dereferencing a null pointer. If so, | |||
542 | // and if not volatile-qualified, this is undefined behavior that the | |||
543 | // optimizer will delete, so warn about it. People sometimes try to use this | |||
544 | // to get a deterministic trap and are surprised by clang's behavior. This | |||
545 | // only handles the pattern "*null", which is a very syntactic check. | |||
546 | const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); | |||
547 | if (UO && UO->getOpcode() == UO_Deref && | |||
548 | UO->getSubExpr()->getType()->isPointerType()) { | |||
549 | const LangAS AS = | |||
550 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); | |||
551 | if ((!isTargetAddressSpace(AS) || | |||
552 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && | |||
553 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( | |||
554 | S.Context, Expr::NPC_ValueDependentIsNotNull) && | |||
555 | !UO->getType().isVolatileQualified()) { | |||
556 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | |||
557 | S.PDiag(diag::warn_indirection_through_null) | |||
558 | << UO->getSubExpr()->getSourceRange()); | |||
559 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | |||
560 | S.PDiag(diag::note_indirection_through_null)); | |||
561 | } | |||
562 | } | |||
563 | } | |||
564 | ||||
565 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, | |||
566 | SourceLocation AssignLoc, | |||
567 | const Expr* RHS) { | |||
568 | const ObjCIvarDecl *IV = OIRE->getDecl(); | |||
569 | if (!IV) | |||
570 | return; | |||
571 | ||||
572 | DeclarationName MemberName = IV->getDeclName(); | |||
573 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); | |||
574 | if (!Member || !Member->isStr("isa")) | |||
575 | return; | |||
576 | ||||
577 | const Expr *Base = OIRE->getBase(); | |||
578 | QualType BaseType = Base->getType(); | |||
579 | if (OIRE->isArrow()) | |||
580 | BaseType = BaseType->getPointeeType(); | |||
581 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) | |||
582 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { | |||
583 | ObjCInterfaceDecl *ClassDeclared = nullptr; | |||
584 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); | |||
585 | if (!ClassDeclared->getSuperClass() | |||
586 | && (*ClassDeclared->ivar_begin()) == IV) { | |||
587 | if (RHS) { | |||
588 | NamedDecl *ObjectSetClass = | |||
589 | S.LookupSingleName(S.TUScope, | |||
590 | &S.Context.Idents.get("object_setClass"), | |||
591 | SourceLocation(), S.LookupOrdinaryName); | |||
592 | if (ObjectSetClass) { | |||
593 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); | |||
594 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) | |||
595 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | |||
596 | "object_setClass(") | |||
597 | << FixItHint::CreateReplacement( | |||
598 | SourceRange(OIRE->getOpLoc(), AssignLoc), ",") | |||
599 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | |||
600 | } | |||
601 | else | |||
602 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); | |||
603 | } else { | |||
604 | NamedDecl *ObjectGetClass = | |||
605 | S.LookupSingleName(S.TUScope, | |||
606 | &S.Context.Idents.get("object_getClass"), | |||
607 | SourceLocation(), S.LookupOrdinaryName); | |||
608 | if (ObjectGetClass) | |||
609 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) | |||
610 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | |||
611 | "object_getClass(") | |||
612 | << FixItHint::CreateReplacement( | |||
613 | SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); | |||
614 | else | |||
615 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); | |||
616 | } | |||
617 | S.Diag(IV->getLocation(), diag::note_ivar_decl); | |||
618 | } | |||
619 | } | |||
620 | } | |||
621 | ||||
622 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { | |||
623 | // Handle any placeholder expressions which made it here. | |||
624 | if (E->hasPlaceholderType()) { | |||
625 | ExprResult result = CheckPlaceholderExpr(E); | |||
626 | if (result.isInvalid()) return ExprError(); | |||
627 | E = result.get(); | |||
628 | } | |||
629 | ||||
630 | // C++ [conv.lval]p1: | |||
631 | // A glvalue of a non-function, non-array type T can be | |||
632 | // converted to a prvalue. | |||
633 | if (!E->isGLValue()) return E; | |||
634 | ||||
635 | QualType T = E->getType(); | |||
636 | 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", 636, __extension__ __PRETTY_FUNCTION__ )); | |||
637 | ||||
638 | // lvalue-to-rvalue conversion cannot be applied to function or array types. | |||
639 | if (T->isFunctionType() || T->isArrayType()) | |||
640 | return E; | |||
641 | ||||
642 | // We don't want to throw lvalue-to-rvalue casts on top of | |||
643 | // expressions of certain types in C++. | |||
644 | if (getLangOpts().CPlusPlus && | |||
645 | (E->getType() == Context.OverloadTy || | |||
646 | T->isDependentType() || | |||
647 | T->isRecordType())) | |||
648 | return E; | |||
649 | ||||
650 | // The C standard is actually really unclear on this point, and | |||
651 | // DR106 tells us what the result should be but not why. It's | |||
652 | // generally best to say that void types just doesn't undergo | |||
653 | // lvalue-to-rvalue at all. Note that expressions of unqualified | |||
654 | // 'void' type are never l-values, but qualified void can be. | |||
655 | if (T->isVoidType()) | |||
656 | return E; | |||
657 | ||||
658 | // OpenCL usually rejects direct accesses to values of 'half' type. | |||
659 | if (getLangOpts().OpenCL && | |||
660 | !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && | |||
661 | T->isHalfType()) { | |||
662 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) | |||
663 | << 0 << T; | |||
664 | return ExprError(); | |||
665 | } | |||
666 | ||||
667 | CheckForNullPointerDereference(*this, E); | |||
668 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { | |||
669 | NamedDecl *ObjectGetClass = LookupSingleName(TUScope, | |||
670 | &Context.Idents.get("object_getClass"), | |||
671 | SourceLocation(), LookupOrdinaryName); | |||
672 | if (ObjectGetClass) | |||
673 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) | |||
674 | << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") | |||
675 | << FixItHint::CreateReplacement( | |||
676 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); | |||
677 | else | |||
678 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); | |||
679 | } | |||
680 | else if (const ObjCIvarRefExpr *OIRE = | |||
681 | dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) | |||
682 | DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); | |||
683 | ||||
684 | // C++ [conv.lval]p1: | |||
685 | // [...] If T is a non-class type, the type of the prvalue is the | |||
686 | // cv-unqualified version of T. Otherwise, the type of the | |||
687 | // rvalue is T. | |||
688 | // | |||
689 | // C99 6.3.2.1p2: | |||
690 | // If the lvalue has qualified type, the value has the unqualified | |||
691 | // version of the type of the lvalue; otherwise, the value has the | |||
692 | // type of the lvalue. | |||
693 | if (T.hasQualifiers()) | |||
694 | T = T.getUnqualifiedType(); | |||
695 | ||||
696 | // Under the MS ABI, lock down the inheritance model now. | |||
697 | if (T->isMemberPointerType() && | |||
698 | Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
699 | (void)isCompleteType(E->getExprLoc(), T); | |||
700 | ||||
701 | ExprResult Res = CheckLValueToRValueConversionOperand(E); | |||
702 | if (Res.isInvalid()) | |||
703 | return Res; | |||
704 | E = Res.get(); | |||
705 | ||||
706 | // Loading a __weak object implicitly retains the value, so we need a cleanup to | |||
707 | // balance that. | |||
708 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | |||
709 | Cleanup.setExprNeedsCleanups(true); | |||
710 | ||||
711 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
712 | Cleanup.setExprNeedsCleanups(true); | |||
713 | ||||
714 | // C++ [conv.lval]p3: | |||
715 | // If T is cv std::nullptr_t, the result is a null pointer constant. | |||
716 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; | |||
717 | Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, | |||
718 | CurFPFeatureOverrides()); | |||
719 | ||||
720 | // C11 6.3.2.1p2: | |||
721 | // ... if the lvalue has atomic type, the value has the non-atomic version | |||
722 | // of the type of the lvalue ... | |||
723 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { | |||
724 | T = Atomic->getValueType().getUnqualifiedType(); | |||
725 | Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), | |||
726 | nullptr, VK_PRValue, FPOptionsOverride()); | |||
727 | } | |||
728 | ||||
729 | return Res; | |||
730 | } | |||
731 | ||||
732 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { | |||
733 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); | |||
734 | if (Res.isInvalid()) | |||
735 | return ExprError(); | |||
736 | Res = DefaultLvalueConversion(Res.get()); | |||
737 | if (Res.isInvalid()) | |||
738 | return ExprError(); | |||
739 | return Res; | |||
740 | } | |||
741 | ||||
742 | /// CallExprUnaryConversions - a special case of an unary conversion | |||
743 | /// performed on a function designator of a call expression. | |||
744 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { | |||
745 | QualType Ty = E->getType(); | |||
746 | ExprResult Res = E; | |||
747 | // Only do implicit cast for a function type, but not for a pointer | |||
748 | // to function type. | |||
749 | if (Ty->isFunctionType()) { | |||
750 | Res = ImpCastExprToType(E, Context.getPointerType(Ty), | |||
751 | CK_FunctionToPointerDecay); | |||
752 | if (Res.isInvalid()) | |||
753 | return ExprError(); | |||
754 | } | |||
755 | Res = DefaultLvalueConversion(Res.get()); | |||
756 | if (Res.isInvalid()) | |||
757 | return ExprError(); | |||
758 | return Res.get(); | |||
759 | } | |||
760 | ||||
761 | /// UsualUnaryConversions - Performs various conversions that are common to most | |||
762 | /// operators (C99 6.3). The conversions of array and function types are | |||
763 | /// sometimes suppressed. For example, the array->pointer conversion doesn't | |||
764 | /// apply if the array is an argument to the sizeof or address (&) operators. | |||
765 | /// In these instances, this routine should *not* be called. | |||
766 | ExprResult Sema::UsualUnaryConversions(Expr *E) { | |||
767 | // First, convert to an r-value. | |||
768 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | |||
769 | if (Res.isInvalid()) | |||
770 | return ExprError(); | |||
771 | E = Res.get(); | |||
772 | ||||
773 | QualType Ty = E->getType(); | |||
774 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type")(static_cast <bool> (!Ty.isNull() && "UsualUnaryConversions - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\"" , "clang/lib/Sema/SemaExpr.cpp", 774, __extension__ __PRETTY_FUNCTION__ )); | |||
775 | ||||
776 | // Half FP have to be promoted to float unless it is natively supported | |||
777 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) | |||
778 | return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); | |||
779 | ||||
780 | // Try to perform integral promotions if the object has a theoretically | |||
781 | // promotable type. | |||
782 | if (Ty->isIntegralOrUnscopedEnumerationType()) { | |||
783 | // C99 6.3.1.1p2: | |||
784 | // | |||
785 | // The following may be used in an expression wherever an int or | |||
786 | // unsigned int may be used: | |||
787 | // - an object or expression with an integer type whose integer | |||
788 | // conversion rank is less than or equal to the rank of int | |||
789 | // and unsigned int. | |||
790 | // - A bit-field of type _Bool, int, signed int, or unsigned int. | |||
791 | // | |||
792 | // If an int can represent all values of the original type, the | |||
793 | // value is converted to an int; otherwise, it is converted to an | |||
794 | // unsigned int. These are called the integer promotions. All | |||
795 | // other types are unchanged by the integer promotions. | |||
796 | ||||
797 | QualType PTy = Context.isPromotableBitField(E); | |||
798 | if (!PTy.isNull()) { | |||
799 | E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); | |||
800 | return E; | |||
801 | } | |||
802 | if (Ty->isPromotableIntegerType()) { | |||
803 | QualType PT = Context.getPromotedIntegerType(Ty); | |||
804 | E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); | |||
805 | return E; | |||
806 | } | |||
807 | } | |||
808 | return E; | |||
809 | } | |||
810 | ||||
811 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that | |||
812 | /// do not have a prototype. Arguments that have type float or __fp16 | |||
813 | /// are promoted to double. All other argument types are converted by | |||
814 | /// UsualUnaryConversions(). | |||
815 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { | |||
816 | QualType Ty = E->getType(); | |||
817 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultArgumentPromotion - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\"" , "clang/lib/Sema/SemaExpr.cpp", 817, __extension__ __PRETTY_FUNCTION__ )); | |||
818 | ||||
819 | ExprResult Res = UsualUnaryConversions(E); | |||
820 | if (Res.isInvalid()) | |||
821 | return ExprError(); | |||
822 | E = Res.get(); | |||
823 | ||||
824 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) | |||
825 | // promote to double. | |||
826 | // Note that default argument promotion applies only to float (and | |||
827 | // half/fp16); it does not apply to _Float16. | |||
828 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | |||
829 | if (BTy && (BTy->getKind() == BuiltinType::Half || | |||
830 | BTy->getKind() == BuiltinType::Float)) { | |||
831 | if (getLangOpts().OpenCL && | |||
832 | !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { | |||
833 | if (BTy->getKind() == BuiltinType::Half) { | |||
834 | E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); | |||
835 | } | |||
836 | } else { | |||
837 | E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); | |||
838 | } | |||
839 | } | |||
840 | if (BTy && | |||
841 | getLangOpts().getExtendIntArgs() == | |||
842 | LangOptions::ExtendArgsKind::ExtendTo64 && | |||
843 | Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && | |||
844 | Context.getTypeSizeInChars(BTy) < | |||
845 | Context.getTypeSizeInChars(Context.LongLongTy)) { | |||
846 | E = (Ty->isUnsignedIntegerType()) | |||
847 | ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) | |||
848 | .get() | |||
849 | : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); | |||
850 | 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", 851, __extension__ __PRETTY_FUNCTION__ )) | |||
851 | "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", 851, __extension__ __PRETTY_FUNCTION__ )); | |||
852 | } | |||
853 | ||||
854 | // C++ performs lvalue-to-rvalue conversion as a default argument | |||
855 | // promotion, even on class types, but note: | |||
856 | // C++11 [conv.lval]p2: | |||
857 | // When an lvalue-to-rvalue conversion occurs in an unevaluated | |||
858 | // operand or a subexpression thereof the value contained in the | |||
859 | // referenced object is not accessed. Otherwise, if the glvalue | |||
860 | // has a class type, the conversion copy-initializes a temporary | |||
861 | // of type T from the glvalue and the result of the conversion | |||
862 | // is a prvalue for the temporary. | |||
863 | // FIXME: add some way to gate this entire thing for correctness in | |||
864 | // potentially potentially evaluated contexts. | |||
865 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { | |||
866 | ExprResult Temp = PerformCopyInitialization( | |||
867 | InitializedEntity::InitializeTemporary(E->getType()), | |||
868 | E->getExprLoc(), E); | |||
869 | if (Temp.isInvalid()) | |||
870 | return ExprError(); | |||
871 | E = Temp.get(); | |||
872 | } | |||
873 | ||||
874 | return E; | |||
875 | } | |||
876 | ||||
877 | /// Determine the degree of POD-ness for an expression. | |||
878 | /// Incomplete types are considered POD, since this check can be performed | |||
879 | /// when we're in an unevaluated context. | |||
880 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { | |||
881 | if (Ty->isIncompleteType()) { | |||
882 | // C++11 [expr.call]p7: | |||
883 | // After these conversions, if the argument does not have arithmetic, | |||
884 | // enumeration, pointer, pointer to member, or class type, the program | |||
885 | // is ill-formed. | |||
886 | // | |||
887 | // Since we've already performed array-to-pointer and function-to-pointer | |||
888 | // decay, the only such type in C++ is cv void. This also handles | |||
889 | // initializer lists as variadic arguments. | |||
890 | if (Ty->isVoidType()) | |||
891 | return VAK_Invalid; | |||
892 | ||||
893 | if (Ty->isObjCObjectType()) | |||
894 | return VAK_Invalid; | |||
895 | return VAK_Valid; | |||
896 | } | |||
897 | ||||
898 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
899 | return VAK_Invalid; | |||
900 | ||||
901 | if (Ty.isCXX98PODType(Context)) | |||
902 | return VAK_Valid; | |||
903 | ||||
904 | // C++11 [expr.call]p7: | |||
905 | // Passing a potentially-evaluated argument of class type (Clause 9) | |||
906 | // having a non-trivial copy constructor, a non-trivial move constructor, | |||
907 | // or a non-trivial destructor, with no corresponding parameter, | |||
908 | // is conditionally-supported with implementation-defined semantics. | |||
909 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) | |||
910 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) | |||
911 | if (!Record->hasNonTrivialCopyConstructor() && | |||
912 | !Record->hasNonTrivialMoveConstructor() && | |||
913 | !Record->hasNonTrivialDestructor()) | |||
914 | return VAK_ValidInCXX11; | |||
915 | ||||
916 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) | |||
917 | return VAK_Valid; | |||
918 | ||||
919 | if (Ty->isObjCObjectType()) | |||
920 | return VAK_Invalid; | |||
921 | ||||
922 | if (getLangOpts().MSVCCompat) | |||
923 | return VAK_MSVCUndefined; | |||
924 | ||||
925 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're | |||
926 | // permitted to reject them. We should consider doing so. | |||
927 | return VAK_Undefined; | |||
928 | } | |||
929 | ||||
930 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { | |||
931 | // Don't allow one to pass an Objective-C interface to a vararg. | |||
932 | const QualType &Ty = E->getType(); | |||
933 | VarArgKind VAK = isValidVarArgType(Ty); | |||
934 | ||||
935 | // Complain about passing non-POD types through varargs. | |||
936 | switch (VAK) { | |||
937 | case VAK_ValidInCXX11: | |||
938 | DiagRuntimeBehavior( | |||
939 | E->getBeginLoc(), nullptr, | |||
940 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); | |||
941 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
942 | case VAK_Valid: | |||
943 | if (Ty->isRecordType()) { | |||
944 | // This is unlikely to be what the user intended. If the class has a | |||
945 | // 'c_str' member function, the user probably meant to call that. | |||
946 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | |||
947 | PDiag(diag::warn_pass_class_arg_to_vararg) | |||
948 | << Ty << CT << hasCStrMethod(E) << ".c_str()"); | |||
949 | } | |||
950 | break; | |||
951 | ||||
952 | case VAK_Undefined: | |||
953 | case VAK_MSVCUndefined: | |||
954 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | |||
955 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) | |||
956 | << getLangOpts().CPlusPlus11 << Ty << CT); | |||
957 | break; | |||
958 | ||||
959 | case VAK_Invalid: | |||
960 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
961 | Diag(E->getBeginLoc(), | |||
962 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) | |||
963 | << Ty << CT; | |||
964 | else if (Ty->isObjCObjectType()) | |||
965 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | |||
966 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) | |||
967 | << Ty << CT); | |||
968 | else | |||
969 | Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) | |||
970 | << isa<InitListExpr>(E) << Ty << CT; | |||
971 | break; | |||
972 | } | |||
973 | } | |||
974 | ||||
975 | /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but | |||
976 | /// will create a trap if the resulting type is not a POD type. | |||
977 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, | |||
978 | FunctionDecl *FDecl) { | |||
979 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { | |||
980 | // Strip the unbridged-cast placeholder expression off, if applicable. | |||
981 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && | |||
982 | (CT == VariadicMethod || | |||
983 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { | |||
984 | E = stripARCUnbridgedCast(E); | |||
985 | ||||
986 | // Otherwise, do normal placeholder checking. | |||
987 | } else { | |||
988 | ExprResult ExprRes = CheckPlaceholderExpr(E); | |||
989 | if (ExprRes.isInvalid()) | |||
990 | return ExprError(); | |||
991 | E = ExprRes.get(); | |||
992 | } | |||
993 | } | |||
994 | ||||
995 | ExprResult ExprRes = DefaultArgumentPromotion(E); | |||
996 | if (ExprRes.isInvalid()) | |||
997 | return ExprError(); | |||
998 | ||||
999 | // Copy blocks to the heap. | |||
1000 | if (ExprRes.get()->getType()->isBlockPointerType()) | |||
1001 | maybeExtendBlockObject(ExprRes); | |||
1002 | ||||
1003 | E = ExprRes.get(); | |||
1004 | ||||
1005 | // Diagnostics regarding non-POD argument types are | |||
1006 | // emitted along with format string checking in Sema::CheckFunctionCall(). | |||
1007 | if (isValidVarArgType(E->getType()) == VAK_Undefined) { | |||
1008 | // Turn this into a trap. | |||
1009 | CXXScopeSpec SS; | |||
1010 | SourceLocation TemplateKWLoc; | |||
1011 | UnqualifiedId Name; | |||
1012 | Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), | |||
1013 | E->getBeginLoc()); | |||
1014 | ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, | |||
1015 | /*HasTrailingLParen=*/true, | |||
1016 | /*IsAddressOfOperand=*/false); | |||
1017 | if (TrapFn.isInvalid()) | |||
1018 | return ExprError(); | |||
1019 | ||||
1020 | ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), | |||
1021 | None, E->getEndLoc()); | |||
1022 | if (Call.isInvalid()) | |||
1023 | return ExprError(); | |||
1024 | ||||
1025 | ExprResult Comma = | |||
1026 | ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); | |||
1027 | if (Comma.isInvalid()) | |||
1028 | return ExprError(); | |||
1029 | return Comma.get(); | |||
1030 | } | |||
1031 | ||||
1032 | if (!getLangOpts().CPlusPlus && | |||
1033 | RequireCompleteType(E->getExprLoc(), E->getType(), | |||
1034 | diag::err_call_incomplete_argument)) | |||
1035 | return ExprError(); | |||
1036 | ||||
1037 | return E; | |||
1038 | } | |||
1039 | ||||
1040 | /// Converts an integer to complex float type. Helper function of | |||
1041 | /// UsualArithmeticConversions() | |||
1042 | /// | |||
1043 | /// \return false if the integer expression is an integer type and is | |||
1044 | /// successfully converted to the complex type. | |||
1045 | static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, | |||
1046 | ExprResult &ComplexExpr, | |||
1047 | QualType IntTy, | |||
1048 | QualType ComplexTy, | |||
1049 | bool SkipCast) { | |||
1050 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; | |||
1051 | if (SkipCast) return false; | |||
1052 | if (IntTy->isIntegerType()) { | |||
1053 | QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); | |||
1054 | IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); | |||
1055 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | |||
1056 | CK_FloatingRealToComplex); | |||
1057 | } else { | |||
1058 | assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ? void (0) : __assert_fail ("IntTy->isComplexIntegerType()" , "clang/lib/Sema/SemaExpr.cpp", 1058, __extension__ __PRETTY_FUNCTION__ )); | |||
1059 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | |||
1060 | CK_IntegralComplexToFloatingComplex); | |||
1061 | } | |||
1062 | return false; | |||
1063 | } | |||
1064 | ||||
1065 | /// Handle arithmetic conversion with complex types. Helper function of | |||
1066 | /// UsualArithmeticConversions() | |||
1067 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, | |||
1068 | ExprResult &RHS, QualType LHSType, | |||
1069 | QualType RHSType, | |||
1070 | bool IsCompAssign) { | |||
1071 | // if we have an integer operand, the result is the complex type. | |||
1072 | if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, | |||
1073 | /*skipCast*/false)) | |||
1074 | return LHSType; | |||
1075 | if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, | |||
1076 | /*skipCast*/IsCompAssign)) | |||
1077 | return RHSType; | |||
1078 | ||||
1079 | // This handles complex/complex, complex/float, or float/complex. | |||
1080 | // When both operands are complex, the shorter operand is converted to the | |||
1081 | // type of the longer, and that is the type of the result. This corresponds | |||
1082 | // to what is done when combining two real floating-point operands. | |||
1083 | // The fun begins when size promotion occur across type domains. | |||
1084 | // From H&S 6.3.4: When one operand is complex and the other is a real | |||
1085 | // floating-point type, the less precise type is converted, within it's | |||
1086 | // real or complex domain, to the precision of the other type. For example, | |||
1087 | // when combining a "long double" with a "double _Complex", the | |||
1088 | // "double _Complex" is promoted to "long double _Complex". | |||
1089 | ||||
1090 | // Compute the rank of the two types, regardless of whether they are complex. | |||
1091 | int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | |||
1092 | ||||
1093 | auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); | |||
1094 | auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); | |||
1095 | QualType LHSElementType = | |||
1096 | LHSComplexType ? LHSComplexType->getElementType() : LHSType; | |||
1097 | QualType RHSElementType = | |||
1098 | RHSComplexType ? RHSComplexType->getElementType() : RHSType; | |||
1099 | ||||
1100 | QualType ResultType = S.Context.getComplexType(LHSElementType); | |||
1101 | if (Order < 0) { | |||
1102 | // Promote the precision of the LHS if not an assignment. | |||
1103 | ResultType = S.Context.getComplexType(RHSElementType); | |||
1104 | if (!IsCompAssign) { | |||
1105 | if (LHSComplexType) | |||
1106 | LHS = | |||
1107 | S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); | |||
1108 | else | |||
1109 | LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); | |||
1110 | } | |||
1111 | } else if (Order > 0) { | |||
1112 | // Promote the precision of the RHS. | |||
1113 | if (RHSComplexType) | |||
1114 | RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); | |||
1115 | else | |||
1116 | RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); | |||
1117 | } | |||
1118 | return ResultType; | |||
1119 | } | |||
1120 | ||||
1121 | /// Handle arithmetic conversion from integer to float. Helper function | |||
1122 | /// of UsualArithmeticConversions() | |||
1123 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, | |||
1124 | ExprResult &IntExpr, | |||
1125 | QualType FloatTy, QualType IntTy, | |||
1126 | bool ConvertFloat, bool ConvertInt) { | |||
1127 | if (IntTy->isIntegerType()) { | |||
1128 | if (ConvertInt) | |||
1129 | // Convert intExpr to the lhs floating point type. | |||
1130 | IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, | |||
1131 | CK_IntegralToFloating); | |||
1132 | return FloatTy; | |||
1133 | } | |||
1134 | ||||
1135 | // Convert both sides to the appropriate complex float. | |||
1136 | assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ? void (0) : __assert_fail ("IntTy->isComplexIntegerType()" , "clang/lib/Sema/SemaExpr.cpp", 1136, __extension__ __PRETTY_FUNCTION__ )); | |||
1137 | QualType result = S.Context.getComplexType(FloatTy); | |||
1138 | ||||
1139 | // _Complex int -> _Complex float | |||
1140 | if (ConvertInt) | |||
1141 | IntExpr = S.ImpCastExprToType(IntExpr.get(), result, | |||
1142 | CK_IntegralComplexToFloatingComplex); | |||
1143 | ||||
1144 | // float -> _Complex float | |||
1145 | if (ConvertFloat) | |||
1146 | FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, | |||
1147 | CK_FloatingRealToComplex); | |||
1148 | ||||
1149 | return result; | |||
1150 | } | |||
1151 | ||||
1152 | /// Handle arithmethic conversion with floating point types. Helper | |||
1153 | /// function of UsualArithmeticConversions() | |||
1154 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, | |||
1155 | ExprResult &RHS, QualType LHSType, | |||
1156 | QualType RHSType, bool IsCompAssign) { | |||
1157 | bool LHSFloat = LHSType->isRealFloatingType(); | |||
1158 | bool RHSFloat = RHSType->isRealFloatingType(); | |||
1159 | ||||
1160 | // N1169 4.1.4: If one of the operands has a floating type and the other | |||
1161 | // operand has a fixed-point type, the fixed-point operand | |||
1162 | // is converted to the floating type [...] | |||
1163 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { | |||
1164 | if (LHSFloat) | |||
1165 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); | |||
1166 | else if (!IsCompAssign) | |||
1167 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); | |||
1168 | return LHSFloat ? LHSType : RHSType; | |||
1169 | } | |||
1170 | ||||
1171 | // If we have two real floating types, convert the smaller operand | |||
1172 | // to the bigger result. | |||
1173 | if (LHSFloat && RHSFloat) { | |||
1174 | int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | |||
1175 | if (order > 0) { | |||
1176 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); | |||
1177 | return LHSType; | |||
1178 | } | |||
1179 | ||||
1180 | 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", 1180, __extension__ __PRETTY_FUNCTION__ )); | |||
1181 | if (!IsCompAssign) | |||
1182 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); | |||
1183 | return RHSType; | |||
1184 | } | |||
1185 | ||||
1186 | if (LHSFloat) { | |||
1187 | // Half FP has to be promoted to float unless it is natively supported | |||
1188 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) | |||
1189 | LHSType = S.Context.FloatTy; | |||
1190 | ||||
1191 | return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, | |||
1192 | /*ConvertFloat=*/!IsCompAssign, | |||
1193 | /*ConvertInt=*/ true); | |||
1194 | } | |||
1195 | assert(RHSFloat)(static_cast <bool> (RHSFloat) ? void (0) : __assert_fail ("RHSFloat", "clang/lib/Sema/SemaExpr.cpp", 1195, __extension__ __PRETTY_FUNCTION__)); | |||
1196 | return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, | |||
1197 | /*ConvertFloat=*/ true, | |||
1198 | /*ConvertInt=*/!IsCompAssign); | |||
1199 | } | |||
1200 | ||||
1201 | /// Diagnose attempts to convert between __float128, __ibm128 and | |||
1202 | /// long double if there is no support for such conversion. | |||
1203 | /// Helper function of UsualArithmeticConversions(). | |||
1204 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, | |||
1205 | QualType RHSType) { | |||
1206 | // No issue if either is not a floating point type. | |||
1207 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) | |||
1208 | return false; | |||
1209 | ||||
1210 | // No issue if both have the same 128-bit float semantics. | |||
1211 | auto *LHSComplex = LHSType->getAs<ComplexType>(); | |||
1212 | auto *RHSComplex = RHSType->getAs<ComplexType>(); | |||
1213 | ||||
1214 | QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; | |||
1215 | QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; | |||
1216 | ||||
1217 | const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); | |||
1218 | const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); | |||
1219 | ||||
1220 | if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || | |||
1221 | &RHSSem != &llvm::APFloat::IEEEquad()) && | |||
1222 | (&LHSSem != &llvm::APFloat::IEEEquad() || | |||
1223 | &RHSSem != &llvm::APFloat::PPCDoubleDouble())) | |||
1224 | return false; | |||
1225 | ||||
1226 | return true; | |||
1227 | } | |||
1228 | ||||
1229 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); | |||
1230 | ||||
1231 | namespace { | |||
1232 | /// These helper callbacks are placed in an anonymous namespace to | |||
1233 | /// permit their use as function template parameters. | |||
1234 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { | |||
1235 | return S.ImpCastExprToType(op, toType, CK_IntegralCast); | |||
1236 | } | |||
1237 | ||||
1238 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { | |||
1239 | return S.ImpCastExprToType(op, S.Context.getComplexType(toType), | |||
1240 | CK_IntegralComplexCast); | |||
1241 | } | |||
1242 | } | |||
1243 | ||||
1244 | /// Handle integer arithmetic conversions. Helper function of | |||
1245 | /// UsualArithmeticConversions() | |||
1246 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> | |||
1247 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, | |||
1248 | ExprResult &RHS, QualType LHSType, | |||
1249 | QualType RHSType, bool IsCompAssign) { | |||
1250 | // The rules for this case are in C99 6.3.1.8 | |||
1251 | int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); | |||
1252 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); | |||
1253 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); | |||
1254 | if (LHSSigned == RHSSigned) { | |||
1255 | // Same signedness; use the higher-ranked type | |||
1256 | if (order >= 0) { | |||
1257 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | |||
1258 | return LHSType; | |||
1259 | } else if (!IsCompAssign) | |||
1260 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | |||
1261 | return RHSType; | |||
1262 | } else if (order != (LHSSigned ? 1 : -1)) { | |||
1263 | // The unsigned type has greater than or equal rank to the | |||
1264 | // signed type, so use the unsigned type | |||
1265 | if (RHSSigned) { | |||
1266 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | |||
1267 | return LHSType; | |||
1268 | } else if (!IsCompAssign) | |||
1269 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | |||
1270 | return RHSType; | |||
1271 | } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { | |||
1272 | // The two types are different widths; if we are here, that | |||
1273 | // means the signed type is larger than the unsigned type, so | |||
1274 | // use the signed type. | |||
1275 | if (LHSSigned) { | |||
1276 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | |||
1277 | return LHSType; | |||
1278 | } else if (!IsCompAssign) | |||
1279 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | |||
1280 | return RHSType; | |||
1281 | } else { | |||
1282 | // The signed type is higher-ranked than the unsigned type, | |||
1283 | // but isn't actually any bigger (like unsigned int and long | |||
1284 | // on most 32-bit systems). Use the unsigned type corresponding | |||
1285 | // to the signed type. | |||
1286 | QualType result = | |||
1287 | S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); | |||
1288 | RHS = (*doRHSCast)(S, RHS.get(), result); | |||
1289 | if (!IsCompAssign) | |||
1290 | LHS = (*doLHSCast)(S, LHS.get(), result); | |||
1291 | return result; | |||
1292 | } | |||
1293 | } | |||
1294 | ||||
1295 | /// Handle conversions with GCC complex int extension. Helper function | |||
1296 | /// of UsualArithmeticConversions() | |||
1297 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, | |||
1298 | ExprResult &RHS, QualType LHSType, | |||
1299 | QualType RHSType, | |||
1300 | bool IsCompAssign) { | |||
1301 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); | |||
1302 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); | |||
1303 | ||||
1304 | if (LHSComplexInt && RHSComplexInt) { | |||
1305 | QualType LHSEltType = LHSComplexInt->getElementType(); | |||
1306 | QualType RHSEltType = RHSComplexInt->getElementType(); | |||
1307 | QualType ScalarType = | |||
1308 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> | |||
1309 | (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); | |||
1310 | ||||
1311 | return S.Context.getComplexType(ScalarType); | |||
1312 | } | |||
1313 | ||||
1314 | if (LHSComplexInt) { | |||
1315 | QualType LHSEltType = LHSComplexInt->getElementType(); | |||
1316 | QualType ScalarType = | |||
1317 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> | |||
1318 | (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); | |||
1319 | QualType ComplexType = S.Context.getComplexType(ScalarType); | |||
1320 | RHS = S.ImpCastExprToType(RHS.get(), ComplexType, | |||
1321 | CK_IntegralRealToComplex); | |||
1322 | ||||
1323 | return ComplexType; | |||
1324 | } | |||
1325 | ||||
1326 | assert(RHSComplexInt)(static_cast <bool> (RHSComplexInt) ? void (0) : __assert_fail ("RHSComplexInt", "clang/lib/Sema/SemaExpr.cpp", 1326, __extension__ __PRETTY_FUNCTION__)); | |||
1327 | ||||
1328 | QualType RHSEltType = RHSComplexInt->getElementType(); | |||
1329 | QualType ScalarType = | |||
1330 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> | |||
1331 | (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); | |||
1332 | QualType ComplexType = S.Context.getComplexType(ScalarType); | |||
1333 | ||||
1334 | if (!IsCompAssign) | |||
1335 | LHS = S.ImpCastExprToType(LHS.get(), ComplexType, | |||
1336 | CK_IntegralRealToComplex); | |||
1337 | return ComplexType; | |||
1338 | } | |||
1339 | ||||
1340 | /// Return the rank of a given fixed point or integer type. The value itself | |||
1341 | /// doesn't matter, but the values must be increasing with proper increasing | |||
1342 | /// rank as described in N1169 4.1.1. | |||
1343 | static unsigned GetFixedPointRank(QualType Ty) { | |||
1344 | const auto *BTy = Ty->getAs<BuiltinType>(); | |||
1345 | assert(BTy && "Expected a builtin type.")(static_cast <bool> (BTy && "Expected a builtin type." ) ? void (0) : __assert_fail ("BTy && \"Expected a builtin type.\"" , "clang/lib/Sema/SemaExpr.cpp", 1345, __extension__ __PRETTY_FUNCTION__ )); | |||
1346 | ||||
1347 | switch (BTy->getKind()) { | |||
1348 | case BuiltinType::ShortFract: | |||
1349 | case BuiltinType::UShortFract: | |||
1350 | case BuiltinType::SatShortFract: | |||
1351 | case BuiltinType::SatUShortFract: | |||
1352 | return 1; | |||
1353 | case BuiltinType::Fract: | |||
1354 | case BuiltinType::UFract: | |||
1355 | case BuiltinType::SatFract: | |||
1356 | case BuiltinType::SatUFract: | |||
1357 | return 2; | |||
1358 | case BuiltinType::LongFract: | |||
1359 | case BuiltinType::ULongFract: | |||
1360 | case BuiltinType::SatLongFract: | |||
1361 | case BuiltinType::SatULongFract: | |||
1362 | return 3; | |||
1363 | case BuiltinType::ShortAccum: | |||
1364 | case BuiltinType::UShortAccum: | |||
1365 | case BuiltinType::SatShortAccum: | |||
1366 | case BuiltinType::SatUShortAccum: | |||
1367 | return 4; | |||
1368 | case BuiltinType::Accum: | |||
1369 | case BuiltinType::UAccum: | |||
1370 | case BuiltinType::SatAccum: | |||
1371 | case BuiltinType::SatUAccum: | |||
1372 | return 5; | |||
1373 | case BuiltinType::LongAccum: | |||
1374 | case BuiltinType::ULongAccum: | |||
1375 | case BuiltinType::SatLongAccum: | |||
1376 | case BuiltinType::SatULongAccum: | |||
1377 | return 6; | |||
1378 | default: | |||
1379 | if (BTy->isInteger()) | |||
1380 | return 0; | |||
1381 | llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type" , "clang/lib/Sema/SemaExpr.cpp", 1381); | |||
1382 | } | |||
1383 | } | |||
1384 | ||||
1385 | /// handleFixedPointConversion - Fixed point operations between fixed | |||
1386 | /// point types and integers or other fixed point types do not fall under | |||
1387 | /// usual arithmetic conversion since these conversions could result in loss | |||
1388 | /// of precsision (N1169 4.1.4). These operations should be calculated with | |||
1389 | /// the full precision of their result type (N1169 4.1.6.2.1). | |||
1390 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, | |||
1391 | QualType RHSTy) { | |||
1392 | assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(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", 1393, __extension__ __PRETTY_FUNCTION__ )) | |||
1393 | "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", 1393, __extension__ __PRETTY_FUNCTION__ )); | |||
1394 | 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", 1397, __extension__ __PRETTY_FUNCTION__ )) | |||
1395 | 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", 1397, __extension__ __PRETTY_FUNCTION__ )) | |||
1396 | "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", 1397, __extension__ __PRETTY_FUNCTION__ )) | |||
1397 | "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", 1397, __extension__ __PRETTY_FUNCTION__ )); | |||
1398 | ||||
1399 | // If one operand has signed fixed-point type and the other operand has | |||
1400 | // unsigned fixed-point type, then the unsigned fixed-point operand is | |||
1401 | // converted to its corresponding signed fixed-point type and the resulting | |||
1402 | // type is the type of the converted operand. | |||
1403 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) | |||
1404 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); | |||
1405 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) | |||
1406 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); | |||
1407 | ||||
1408 | // The result type is the type with the highest rank, whereby a fixed-point | |||
1409 | // conversion rank is always greater than an integer conversion rank; if the | |||
1410 | // type of either of the operands is a saturating fixedpoint type, the result | |||
1411 | // type shall be the saturating fixed-point type corresponding to the type | |||
1412 | // with the highest rank; the resulting value is converted (taking into | |||
1413 | // account rounding and overflow) to the precision of the resulting type. | |||
1414 | // Same ranks between signed and unsigned types are resolved earlier, so both | |||
1415 | // types are either signed or both unsigned at this point. | |||
1416 | unsigned LHSTyRank = GetFixedPointRank(LHSTy); | |||
1417 | unsigned RHSTyRank = GetFixedPointRank(RHSTy); | |||
1418 | ||||
1419 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; | |||
1420 | ||||
1421 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) | |||
1422 | ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); | |||
1423 | ||||
1424 | return ResultTy; | |||
1425 | } | |||
1426 | ||||
1427 | /// Check that the usual arithmetic conversions can be performed on this pair of | |||
1428 | /// expressions that might be of enumeration type. | |||
1429 | static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, | |||
1430 | SourceLocation Loc, | |||
1431 | Sema::ArithConvKind ACK) { | |||
1432 | // C++2a [expr.arith.conv]p1: | |||
1433 | // If one operand is of enumeration type and the other operand is of a | |||
1434 | // different enumeration type or a floating-point type, this behavior is | |||
1435 | // deprecated ([depr.arith.conv.enum]). | |||
1436 | // | |||
1437 | // Warn on this in all language modes. Produce a deprecation warning in C++20. | |||
1438 | // Eventually we will presumably reject these cases (in C++23 onwards?). | |||
1439 | QualType L = LHS->getType(), R = RHS->getType(); | |||
1440 | bool LEnum = L->isUnscopedEnumerationType(), | |||
1441 | REnum = R->isUnscopedEnumerationType(); | |||
1442 | bool IsCompAssign = ACK == Sema::ACK_CompAssign; | |||
1443 | if ((!IsCompAssign && LEnum && R->isFloatingType()) || | |||
1444 | (REnum && L->isFloatingType())) { | |||
1445 | S.Diag(Loc, S.getLangOpts().CPlusPlus20 | |||
1446 | ? diag::warn_arith_conv_enum_float_cxx20 | |||
1447 | : diag::warn_arith_conv_enum_float) | |||
1448 | << LHS->getSourceRange() << RHS->getSourceRange() | |||
1449 | << (int)ACK << LEnum << L << R; | |||
1450 | } else if (!IsCompAssign && LEnum && REnum && | |||
1451 | !S.Context.hasSameUnqualifiedType(L, R)) { | |||
1452 | unsigned DiagID; | |||
1453 | if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || | |||
1454 | !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { | |||
1455 | // If either enumeration type is unnamed, it's less likely that the | |||
1456 | // user cares about this, but this situation is still deprecated in | |||
1457 | // C++2a. Use a different warning group. | |||
1458 | DiagID = S.getLangOpts().CPlusPlus20 | |||
1459 | ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 | |||
1460 | : diag::warn_arith_conv_mixed_anon_enum_types; | |||
1461 | } else if (ACK == Sema::ACK_Conditional) { | |||
1462 | // Conditional expressions are separated out because they have | |||
1463 | // historically had a different warning flag. | |||
1464 | DiagID = S.getLangOpts().CPlusPlus20 | |||
1465 | ? diag::warn_conditional_mixed_enum_types_cxx20 | |||
1466 | : diag::warn_conditional_mixed_enum_types; | |||
1467 | } else if (ACK == Sema::ACK_Comparison) { | |||
1468 | // Comparison expressions are separated out because they have | |||
1469 | // historically had a different warning flag. | |||
1470 | DiagID = S.getLangOpts().CPlusPlus20 | |||
1471 | ? diag::warn_comparison_mixed_enum_types_cxx20 | |||
1472 | : diag::warn_comparison_mixed_enum_types; | |||
1473 | } else { | |||
1474 | DiagID = S.getLangOpts().CPlusPlus20 | |||
1475 | ? diag::warn_arith_conv_mixed_enum_types_cxx20 | |||
1476 | : diag::warn_arith_conv_mixed_enum_types; | |||
1477 | } | |||
1478 | S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() | |||
1479 | << (int)ACK << L << R; | |||
1480 | } | |||
1481 | } | |||
1482 | ||||
1483 | /// UsualArithmeticConversions - Performs various conversions that are common to | |||
1484 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this | |||
1485 | /// routine returns the first non-arithmetic type found. The client is | |||
1486 | /// responsible for emitting appropriate error diagnostics. | |||
1487 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, | |||
1488 | SourceLocation Loc, | |||
1489 | ArithConvKind ACK) { | |||
1490 | checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); | |||
1491 | ||||
1492 | if (ACK != ACK_CompAssign) { | |||
1493 | LHS = UsualUnaryConversions(LHS.get()); | |||
1494 | if (LHS.isInvalid()) | |||
1495 | return QualType(); | |||
1496 | } | |||
1497 | ||||
1498 | RHS = UsualUnaryConversions(RHS.get()); | |||
1499 | if (RHS.isInvalid()) | |||
1500 | return QualType(); | |||
1501 | ||||
1502 | // For conversion purposes, we ignore any qualifiers. | |||
1503 | // For example, "const float" and "float" are equivalent. | |||
1504 | QualType LHSType = | |||
1505 | Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | |||
1506 | QualType RHSType = | |||
1507 | Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | |||
1508 | ||||
1509 | // For conversion purposes, we ignore any atomic qualifier on the LHS. | |||
1510 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) | |||
1511 | LHSType = AtomicLHS->getValueType(); | |||
1512 | ||||
1513 | // If both types are identical, no conversion is needed. | |||
1514 | if (LHSType == RHSType) | |||
1515 | return LHSType; | |||
1516 | ||||
1517 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. | |||
1518 | // The caller can deal with this (e.g. pointer + int). | |||
1519 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) | |||
1520 | return QualType(); | |||
1521 | ||||
1522 | // Apply unary and bitfield promotions to the LHS's type. | |||
1523 | QualType LHSUnpromotedType = LHSType; | |||
1524 | if (LHSType->isPromotableIntegerType()) | |||
1525 | LHSType = Context.getPromotedIntegerType(LHSType); | |||
1526 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); | |||
1527 | if (!LHSBitfieldPromoteTy.isNull()) | |||
1528 | LHSType = LHSBitfieldPromoteTy; | |||
1529 | if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) | |||
1530 | LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); | |||
1531 | ||||
1532 | // If both types are identical, no conversion is needed. | |||
1533 | if (LHSType == RHSType) | |||
1534 | return LHSType; | |||
1535 | ||||
1536 | // At this point, we have two different arithmetic types. | |||
1537 | ||||
1538 | // Diagnose attempts to convert between __ibm128, __float128 and long double | |||
1539 | // where such conversions currently can't be handled. | |||
1540 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | |||
1541 | return QualType(); | |||
1542 | ||||
1543 | // Handle complex types first (C99 6.3.1.8p1). | |||
1544 | if (LHSType->isComplexType() || RHSType->isComplexType()) | |||
1545 | return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, | |||
1546 | ACK == ACK_CompAssign); | |||
1547 | ||||
1548 | // Now handle "real" floating types (i.e. float, double, long double). | |||
1549 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | |||
1550 | return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, | |||
1551 | ACK == ACK_CompAssign); | |||
1552 | ||||
1553 | // Handle GCC complex int extension. | |||
1554 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) | |||
1555 | return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, | |||
1556 | ACK == ACK_CompAssign); | |||
1557 | ||||
1558 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) | |||
1559 | return handleFixedPointConversion(*this, LHSType, RHSType); | |||
1560 | ||||
1561 | // Finally, we have two differing integer types. | |||
1562 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | |||
1563 | (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); | |||
1564 | } | |||
1565 | ||||
1566 | //===----------------------------------------------------------------------===// | |||
1567 | // Semantic Analysis for various Expression Types | |||
1568 | //===----------------------------------------------------------------------===// | |||
1569 | ||||
1570 | ||||
1571 | ExprResult | |||
1572 | Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, | |||
1573 | SourceLocation DefaultLoc, | |||
1574 | SourceLocation RParenLoc, | |||
1575 | Expr *ControllingExpr, | |||
1576 | ArrayRef<ParsedType> ArgTypes, | |||
1577 | ArrayRef<Expr *> ArgExprs) { | |||
1578 | unsigned NumAssocs = ArgTypes.size(); | |||
1579 | assert(NumAssocs == ArgExprs.size())(static_cast <bool> (NumAssocs == ArgExprs.size()) ? void (0) : __assert_fail ("NumAssocs == ArgExprs.size()", "clang/lib/Sema/SemaExpr.cpp" , 1579, __extension__ __PRETTY_FUNCTION__)); | |||
1580 | ||||
1581 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; | |||
1582 | for (unsigned i = 0; i < NumAssocs; ++i) { | |||
1583 | if (ArgTypes[i]) | |||
1584 | (void) GetTypeFromParser(ArgTypes[i], &Types[i]); | |||
1585 | else | |||
1586 | Types[i] = nullptr; | |||
1587 | } | |||
1588 | ||||
1589 | ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, | |||
1590 | ControllingExpr, | |||
1591 | llvm::makeArrayRef(Types, NumAssocs), | |||
1592 | ArgExprs); | |||
1593 | delete [] Types; | |||
1594 | return ER; | |||
1595 | } | |||
1596 | ||||
1597 | ExprResult | |||
1598 | Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, | |||
1599 | SourceLocation DefaultLoc, | |||
1600 | SourceLocation RParenLoc, | |||
1601 | Expr *ControllingExpr, | |||
1602 | ArrayRef<TypeSourceInfo *> Types, | |||
1603 | ArrayRef<Expr *> Exprs) { | |||
1604 | unsigned NumAssocs = Types.size(); | |||
1605 | assert(NumAssocs == Exprs.size())(static_cast <bool> (NumAssocs == Exprs.size()) ? void ( 0) : __assert_fail ("NumAssocs == Exprs.size()", "clang/lib/Sema/SemaExpr.cpp" , 1605, __extension__ __PRETTY_FUNCTION__)); | |||
1606 | ||||
1607 | // Decay and strip qualifiers for the controlling expression type, and handle | |||
1608 | // placeholder type replacement. See committee discussion from WG14 DR423. | |||
1609 | { | |||
1610 | EnterExpressionEvaluationContext Unevaluated( | |||
1611 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
1612 | ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); | |||
1613 | if (R.isInvalid()) | |||
1614 | return ExprError(); | |||
1615 | ControllingExpr = R.get(); | |||
1616 | } | |||
1617 | ||||
1618 | // The controlling expression is an unevaluated operand, so side effects are | |||
1619 | // likely unintended. | |||
1620 | if (!inTemplateInstantiation() && | |||
1621 | ControllingExpr->HasSideEffects(Context, false)) | |||
1622 | Diag(ControllingExpr->getExprLoc(), | |||
1623 | diag::warn_side_effects_unevaluated_context); | |||
1624 | ||||
1625 | bool TypeErrorFound = false, | |||
1626 | IsResultDependent = ControllingExpr->isTypeDependent(), | |||
1627 | ContainsUnexpandedParameterPack | |||
1628 | = ControllingExpr->containsUnexpandedParameterPack(); | |||
1629 | ||||
1630 | for (unsigned i = 0; i < NumAssocs; ++i) { | |||
1631 | if (Exprs[i]->containsUnexpandedParameterPack()) | |||
1632 | ContainsUnexpandedParameterPack = true; | |||
1633 | ||||
1634 | if (Types[i]) { | |||
1635 | if (Types[i]->getType()->containsUnexpandedParameterPack()) | |||
1636 | ContainsUnexpandedParameterPack = true; | |||
1637 | ||||
1638 | if (Types[i]->getType()->isDependentType()) { | |||
1639 | IsResultDependent = true; | |||
1640 | } else { | |||
1641 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a | |||
1642 | // complete object type other than a variably modified type." | |||
1643 | unsigned D = 0; | |||
1644 | if (Types[i]->getType()->isIncompleteType()) | |||
1645 | D = diag::err_assoc_type_incomplete; | |||
1646 | else if (!Types[i]->getType()->isObjectType()) | |||
1647 | D = diag::err_assoc_type_nonobject; | |||
1648 | else if (Types[i]->getType()->isVariablyModifiedType()) | |||
1649 | D = diag::err_assoc_type_variably_modified; | |||
1650 | ||||
1651 | if (D != 0) { | |||
1652 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) | |||
1653 | << Types[i]->getTypeLoc().getSourceRange() | |||
1654 | << Types[i]->getType(); | |||
1655 | TypeErrorFound = true; | |||
1656 | } | |||
1657 | ||||
1658 | // C11 6.5.1.1p2 "No two generic associations in the same generic | |||
1659 | // selection shall specify compatible types." | |||
1660 | for (unsigned j = i+1; j < NumAssocs; ++j) | |||
1661 | if (Types[j] && !Types[j]->getType()->isDependentType() && | |||
1662 | Context.typesAreCompatible(Types[i]->getType(), | |||
1663 | Types[j]->getType())) { | |||
1664 | Diag(Types[j]->getTypeLoc().getBeginLoc(), | |||
1665 | diag::err_assoc_compatible_types) | |||
1666 | << Types[j]->getTypeLoc().getSourceRange() | |||
1667 | << Types[j]->getType() | |||
1668 | << Types[i]->getType(); | |||
1669 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | |||
1670 | diag::note_compat_assoc) | |||
1671 | << Types[i]->getTypeLoc().getSourceRange() | |||
1672 | << Types[i]->getType(); | |||
1673 | TypeErrorFound = true; | |||
1674 | } | |||
1675 | } | |||
1676 | } | |||
1677 | } | |||
1678 | if (TypeErrorFound) | |||
1679 | return ExprError(); | |||
1680 | ||||
1681 | // If we determined that the generic selection is result-dependent, don't | |||
1682 | // try to compute the result expression. | |||
1683 | if (IsResultDependent) | |||
1684 | return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, | |||
1685 | Exprs, DefaultLoc, RParenLoc, | |||
1686 | ContainsUnexpandedParameterPack); | |||
1687 | ||||
1688 | SmallVector<unsigned, 1> CompatIndices; | |||
1689 | unsigned DefaultIndex = -1U; | |||
1690 | for (unsigned i = 0; i < NumAssocs; ++i) { | |||
1691 | if (!Types[i]) | |||
1692 | DefaultIndex = i; | |||
1693 | else if (Context.typesAreCompatible(ControllingExpr->getType(), | |||
1694 | Types[i]->getType())) | |||
1695 | CompatIndices.push_back(i); | |||
1696 | } | |||
1697 | ||||
1698 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have | |||
1699 | // type compatible with at most one of the types named in its generic | |||
1700 | // association list." | |||
1701 | if (CompatIndices.size() > 1) { | |||
1702 | // We strip parens here because the controlling expression is typically | |||
1703 | // parenthesized in macro definitions. | |||
1704 | ControllingExpr = ControllingExpr->IgnoreParens(); | |||
1705 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) | |||
1706 | << ControllingExpr->getSourceRange() << ControllingExpr->getType() | |||
1707 | << (unsigned)CompatIndices.size(); | |||
1708 | for (unsigned I : CompatIndices) { | |||
1709 | Diag(Types[I]->getTypeLoc().getBeginLoc(), | |||
1710 | diag::note_compat_assoc) | |||
1711 | << Types[I]->getTypeLoc().getSourceRange() | |||
1712 | << Types[I]->getType(); | |||
1713 | } | |||
1714 | return ExprError(); | |||
1715 | } | |||
1716 | ||||
1717 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, | |||
1718 | // its controlling expression shall have type compatible with exactly one of | |||
1719 | // the types named in its generic association list." | |||
1720 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { | |||
1721 | // We strip parens here because the controlling expression is typically | |||
1722 | // parenthesized in macro definitions. | |||
1723 | ControllingExpr = ControllingExpr->IgnoreParens(); | |||
1724 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) | |||
1725 | << ControllingExpr->getSourceRange() << ControllingExpr->getType(); | |||
1726 | return ExprError(); | |||
1727 | } | |||
1728 | ||||
1729 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a | |||
1730 | // type name that is compatible with the type of the controlling expression, | |||
1731 | // then the result expression of the generic selection is the expression | |||
1732 | // in that generic association. Otherwise, the result expression of the | |||
1733 | // generic selection is the expression in the default generic association." | |||
1734 | unsigned ResultIndex = | |||
1735 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; | |||
1736 | ||||
1737 | return GenericSelectionExpr::Create( | |||
1738 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, | |||
1739 | ContainsUnexpandedParameterPack, ResultIndex); | |||
1740 | } | |||
1741 | ||||
1742 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the | |||
1743 | /// location of the token and the offset of the ud-suffix within it. | |||
1744 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, | |||
1745 | unsigned Offset) { | |||
1746 | return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), | |||
1747 | S.getLangOpts()); | |||
1748 | } | |||
1749 | ||||
1750 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up | |||
1751 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. | |||
1752 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, | |||
1753 | IdentifierInfo *UDSuffix, | |||
1754 | SourceLocation UDSuffixLoc, | |||
1755 | ArrayRef<Expr*> Args, | |||
1756 | SourceLocation LitEndLoc) { | |||
1757 | 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", 1757, __extension__ __PRETTY_FUNCTION__ )); | |||
1758 | ||||
1759 | QualType ArgTy[2]; | |||
1760 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { | |||
1761 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); | |||
1762 | if (ArgTy[ArgIdx]->isArrayType()) | |||
1763 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); | |||
1764 | } | |||
1765 | ||||
1766 | DeclarationName OpName = | |||
1767 | S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | |||
1768 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | |||
1769 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | |||
1770 | ||||
1771 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); | |||
1772 | if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), | |||
1773 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | |||
1774 | /*AllowStringTemplatePack*/ false, | |||
1775 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) | |||
1776 | return ExprError(); | |||
1777 | ||||
1778 | return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); | |||
1779 | } | |||
1780 | ||||
1781 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string | |||
1782 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string | |||
1783 | /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from | |||
1784 | /// multiple tokens. However, the common case is that StringToks points to one | |||
1785 | /// string. | |||
1786 | /// | |||
1787 | ExprResult | |||
1788 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { | |||
1789 | 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", 1789, __extension__ __PRETTY_FUNCTION__ )); | |||
1790 | ||||
1791 | StringLiteralParser Literal(StringToks, PP); | |||
1792 | if (Literal.hadError) | |||
1793 | return ExprError(); | |||
1794 | ||||
1795 | SmallVector<SourceLocation, 4> StringTokLocs; | |||
1796 | for (const Token &Tok : StringToks) | |||
1797 | StringTokLocs.push_back(Tok.getLocation()); | |||
1798 | ||||
1799 | QualType CharTy = Context.CharTy; | |||
1800 | StringLiteral::StringKind Kind = StringLiteral::Ascii; | |||
1801 | if (Literal.isWide()) { | |||
1802 | CharTy = Context.getWideCharType(); | |||
1803 | Kind = StringLiteral::Wide; | |||
1804 | } else if (Literal.isUTF8()) { | |||
1805 | if (getLangOpts().Char8) | |||
1806 | CharTy = Context.Char8Ty; | |||
1807 | Kind = StringLiteral::UTF8; | |||
1808 | } else if (Literal.isUTF16()) { | |||
1809 | CharTy = Context.Char16Ty; | |||
1810 | Kind = StringLiteral::UTF16; | |||
1811 | } else if (Literal.isUTF32()) { | |||
1812 | CharTy = Context.Char32Ty; | |||
1813 | Kind = StringLiteral::UTF32; | |||
1814 | } else if (Literal.isPascal()) { | |||
1815 | CharTy = Context.UnsignedCharTy; | |||
1816 | } | |||
1817 | ||||
1818 | // Warn on initializing an array of char from a u8 string literal; this | |||
1819 | // becomes ill-formed in C++2a. | |||
1820 | if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && | |||
1821 | !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { | |||
1822 | Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); | |||
1823 | ||||
1824 | // Create removals for all 'u8' prefixes in the string literal(s). This | |||
1825 | // ensures C++2a compatibility (but may change the program behavior when | |||
1826 | // built by non-Clang compilers for which the execution character set is | |||
1827 | // not always UTF-8). | |||
1828 | auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); | |||
1829 | SourceLocation RemovalDiagLoc; | |||
1830 | for (const Token &Tok : StringToks) { | |||
1831 | if (Tok.getKind() == tok::utf8_string_literal) { | |||
1832 | if (RemovalDiagLoc.isInvalid()) | |||
1833 | RemovalDiagLoc = Tok.getLocation(); | |||
1834 | RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( | |||
1835 | Tok.getLocation(), | |||
1836 | Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, | |||
1837 | getSourceManager(), getLangOpts()))); | |||
1838 | } | |||
1839 | } | |||
1840 | Diag(RemovalDiagLoc, RemovalDiag); | |||
1841 | } | |||
1842 | ||||
1843 | QualType StrTy = | |||
1844 | Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); | |||
1845 | ||||
1846 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! | |||
1847 | StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), | |||
1848 | Kind, Literal.Pascal, StrTy, | |||
1849 | &StringTokLocs[0], | |||
1850 | StringTokLocs.size()); | |||
1851 | if (Literal.getUDSuffix().empty()) | |||
1852 | return Lit; | |||
1853 | ||||
1854 | // We're building a user-defined literal. | |||
1855 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | |||
1856 | SourceLocation UDSuffixLoc = | |||
1857 | getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], | |||
1858 | Literal.getUDSuffixOffset()); | |||
1859 | ||||
1860 | // Make sure we're allowed user-defined literals here. | |||
1861 | if (!UDLScope) | |||
1862 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); | |||
1863 | ||||
1864 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form | |||
1865 | // operator "" X (str, len) | |||
1866 | QualType SizeType = Context.getSizeType(); | |||
1867 | ||||
1868 | DeclarationName OpName = | |||
1869 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | |||
1870 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | |||
1871 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | |||
1872 | ||||
1873 | QualType ArgTy[] = { | |||
1874 | Context.getArrayDecayedType(StrTy), SizeType | |||
1875 | }; | |||
1876 | ||||
1877 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | |||
1878 | switch (LookupLiteralOperator(UDLScope, R, ArgTy, | |||
1879 | /*AllowRaw*/ false, /*AllowTemplate*/ true, | |||
1880 | /*AllowStringTemplatePack*/ true, | |||
1881 | /*DiagnoseMissing*/ true, Lit)) { | |||
1882 | ||||
1883 | case LOLR_Cooked: { | |||
1884 | llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); | |||
1885 | IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, | |||
1886 | StringTokLocs[0]); | |||
1887 | Expr *Args[] = { Lit, LenArg }; | |||
1888 | ||||
1889 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); | |||
1890 | } | |||
1891 | ||||
1892 | case LOLR_Template: { | |||
1893 | TemplateArgumentListInfo ExplicitArgs; | |||
1894 | TemplateArgument Arg(Lit); | |||
1895 | TemplateArgumentLocInfo ArgInfo(Lit); | |||
1896 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | |||
1897 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | |||
1898 | &ExplicitArgs); | |||
1899 | } | |||
1900 | ||||
1901 | case LOLR_StringTemplatePack: { | |||
1902 | TemplateArgumentListInfo ExplicitArgs; | |||
1903 | ||||
1904 | unsigned CharBits = Context.getIntWidth(CharTy); | |||
1905 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); | |||
1906 | llvm::APSInt Value(CharBits, CharIsUnsigned); | |||
1907 | ||||
1908 | TemplateArgument TypeArg(CharTy); | |||
1909 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); | |||
1910 | ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); | |||
1911 | ||||
1912 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { | |||
1913 | Value = Lit->getCodeUnit(I); | |||
1914 | TemplateArgument Arg(Context, Value, CharTy); | |||
1915 | TemplateArgumentLocInfo ArgInfo; | |||
1916 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | |||
1917 | } | |||
1918 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | |||
1919 | &ExplicitArgs); | |||
1920 | } | |||
1921 | case LOLR_Raw: | |||
1922 | case LOLR_ErrorNoDiagnostic: | |||
1923 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "clang/lib/Sema/SemaExpr.cpp", 1923); | |||
1924 | case LOLR_Error: | |||
1925 | return ExprError(); | |||
1926 | } | |||
1927 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "clang/lib/Sema/SemaExpr.cpp", 1927); | |||
1928 | } | |||
1929 | ||||
1930 | DeclRefExpr * | |||
1931 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | |||
1932 | SourceLocation Loc, | |||
1933 | const CXXScopeSpec *SS) { | |||
1934 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); | |||
1935 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); | |||
1936 | } | |||
1937 | ||||
1938 | DeclRefExpr * | |||
1939 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | |||
1940 | const DeclarationNameInfo &NameInfo, | |||
1941 | const CXXScopeSpec *SS, NamedDecl *FoundD, | |||
1942 | SourceLocation TemplateKWLoc, | |||
1943 | const TemplateArgumentListInfo *TemplateArgs) { | |||
1944 | NestedNameSpecifierLoc NNS = | |||
1945 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); | |||
1946 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, | |||
1947 | TemplateArgs); | |||
1948 | } | |||
1949 | ||||
1950 | // CUDA/HIP: Check whether a captured reference variable is referencing a | |||
1951 | // host variable in a device or host device lambda. | |||
1952 | static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, | |||
1953 | VarDecl *VD) { | |||
1954 | if (!S.getLangOpts().CUDA || !VD->hasInit()) | |||
1955 | return false; | |||
1956 | assert(VD->getType()->isReferenceType())(static_cast <bool> (VD->getType()->isReferenceType ()) ? void (0) : __assert_fail ("VD->getType()->isReferenceType()" , "clang/lib/Sema/SemaExpr.cpp", 1956, __extension__ __PRETTY_FUNCTION__ )); | |||
1957 | ||||
1958 | // Check whether the reference variable is referencing a host variable. | |||
1959 | auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); | |||
1960 | if (!DRE) | |||
1961 | return false; | |||
1962 | auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); | |||
1963 | if (!Referee || !Referee->hasGlobalStorage() || | |||
1964 | Referee->hasAttr<CUDADeviceAttr>()) | |||
1965 | return false; | |||
1966 | ||||
1967 | // Check whether the current function is a device or host device lambda. | |||
1968 | // Check whether the reference variable is a capture by getDeclContext() | |||
1969 | // since refersToEnclosingVariableOrCapture() is not ready at this point. | |||
1970 | auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); | |||
1971 | if (MD && MD->getParent()->isLambda() && | |||
1972 | MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && | |||
1973 | VD->getDeclContext() != MD) | |||
1974 | return true; | |||
1975 | ||||
1976 | return false; | |||
1977 | } | |||
1978 | ||||
1979 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { | |||
1980 | // A declaration named in an unevaluated operand never constitutes an odr-use. | |||
1981 | if (isUnevaluatedContext()) | |||
1982 | return NOUR_Unevaluated; | |||
1983 | ||||
1984 | // C++2a [basic.def.odr]p4: | |||
1985 | // A variable x whose name appears as a potentially-evaluated expression e | |||
1986 | // is odr-used by e unless [...] x is a reference that is usable in | |||
1987 | // constant expressions. | |||
1988 | // CUDA/HIP: | |||
1989 | // If a reference variable referencing a host variable is captured in a | |||
1990 | // device or host device lambda, the value of the referee must be copied | |||
1991 | // to the capture and the reference variable must be treated as odr-use | |||
1992 | // since the value of the referee is not known at compile time and must | |||
1993 | // be loaded from the captured. | |||
1994 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
1995 | if (VD->getType()->isReferenceType() && | |||
1996 | !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && | |||
1997 | !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && | |||
1998 | VD->isUsableInConstantExpressions(Context)) | |||
1999 | return NOUR_Constant; | |||
2000 | } | |||
2001 | ||||
2002 | // All remaining non-variable cases constitute an odr-use. For variables, we | |||
2003 | // need to wait and see how the expression is used. | |||
2004 | return NOUR_None; | |||
2005 | } | |||
2006 | ||||
2007 | /// BuildDeclRefExpr - Build an expression that references a | |||
2008 | /// declaration that does not require a closure capture. | |||
2009 | DeclRefExpr * | |||
2010 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | |||
2011 | const DeclarationNameInfo &NameInfo, | |||
2012 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, | |||
2013 | SourceLocation TemplateKWLoc, | |||
2014 | const TemplateArgumentListInfo *TemplateArgs) { | |||
2015 | bool RefersToCapturedVariable = | |||
2016 | isa<VarDecl>(D) && | |||
2017 | NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); | |||
2018 | ||||
2019 | DeclRefExpr *E = DeclRefExpr::Create( | |||
2020 | Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, | |||
2021 | VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); | |||
2022 | MarkDeclRefReferenced(E); | |||
2023 | ||||
2024 | // C++ [except.spec]p17: | |||
2025 | // An exception-specification is considered to be needed when: | |||
2026 | // - in an expression, the function is the unique lookup result or | |||
2027 | // the selected member of a set of overloaded functions. | |||
2028 | // | |||
2029 | // We delay doing this until after we've built the function reference and | |||
2030 | // marked it as used so that: | |||
2031 | // a) if the function is defaulted, we get errors from defining it before / | |||
2032 | // instead of errors from computing its exception specification, and | |||
2033 | // b) if the function is a defaulted comparison, we can use the body we | |||
2034 | // build when defining it as input to the exception specification | |||
2035 | // computation rather than computing a new body. | |||
2036 | if (auto *FPT = Ty->getAs<FunctionProtoType>()) { | |||
2037 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { | |||
2038 | if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) | |||
2039 | E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); | |||
2040 | } | |||
2041 | } | |||
2042 | ||||
2043 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && | |||
2044 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && | |||
2045 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) | |||
2046 | getCurFunction()->recordUseOfWeak(E); | |||
2047 | ||||
2048 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | |||
2049 | if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) | |||
2050 | FD = IFD->getAnonField(); | |||
2051 | if (FD) { | |||
2052 | UnusedPrivateFields.remove(FD); | |||
2053 | // Just in case we're building an illegal pointer-to-member. | |||
2054 | if (FD->isBitField()) | |||
2055 | E->setObjectKind(OK_BitField); | |||
2056 | } | |||
2057 | ||||
2058 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier | |||
2059 | // designates a bit-field. | |||
2060 | if (auto *BD = dyn_cast<BindingDecl>(D)) | |||
2061 | if (auto *BE = BD->getBinding()) | |||
2062 | E->setObjectKind(BE->getObjectKind()); | |||
2063 | ||||
2064 | return E; | |||
2065 | } | |||
2066 | ||||
2067 | /// Decomposes the given name into a DeclarationNameInfo, its location, and | |||
2068 | /// possibly a list of template arguments. | |||
2069 | /// | |||
2070 | /// If this produces template arguments, it is permitted to call | |||
2071 | /// DecomposeTemplateName. | |||
2072 | /// | |||
2073 | /// This actually loses a lot of source location information for | |||
2074 | /// non-standard name kinds; we should consider preserving that in | |||
2075 | /// some way. | |||
2076 | void | |||
2077 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, | |||
2078 | TemplateArgumentListInfo &Buffer, | |||
2079 | DeclarationNameInfo &NameInfo, | |||
2080 | const TemplateArgumentListInfo *&TemplateArgs) { | |||
2081 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { | |||
2082 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); | |||
2083 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); | |||
2084 | ||||
2085 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), | |||
2086 | Id.TemplateId->NumArgs); | |||
2087 | translateTemplateArguments(TemplateArgsPtr, Buffer); | |||
2088 | ||||
2089 | TemplateName TName = Id.TemplateId->Template.get(); | |||
2090 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; | |||
2091 | NameInfo = Context.getNameForTemplate(TName, TNameLoc); | |||
2092 | TemplateArgs = &Buffer; | |||
2093 | } else { | |||
2094 | NameInfo = GetNameFromUnqualifiedId(Id); | |||
2095 | TemplateArgs = nullptr; | |||
2096 | } | |||
2097 | } | |||
2098 | ||||
2099 | static void emitEmptyLookupTypoDiagnostic( | |||
2100 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, | |||
2101 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, | |||
2102 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { | |||
2103 | DeclContext *Ctx = | |||
2104 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); | |||
2105 | if (!TC) { | |||
2106 | // Emit a special diagnostic for failed member lookups. | |||
2107 | // FIXME: computing the declaration context might fail here (?) | |||
2108 | if (Ctx) | |||
2109 | SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx | |||
2110 | << SS.getRange(); | |||
2111 | else | |||
2112 | SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; | |||
2113 | return; | |||
2114 | } | |||
2115 | ||||
2116 | std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); | |||
2117 | bool DroppedSpecifier = | |||
2118 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; | |||
2119 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() | |||
2120 | ? diag::note_implicit_param_decl | |||
2121 | : diag::note_previous_decl; | |||
2122 | if (!Ctx) | |||
2123 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, | |||
2124 | SemaRef.PDiag(NoteID)); | |||
2125 | else | |||
2126 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) | |||
2127 | << Typo << Ctx << DroppedSpecifier | |||
2128 | << SS.getRange(), | |||
2129 | SemaRef.PDiag(NoteID)); | |||
2130 | } | |||
2131 | ||||
2132 | /// Diagnose a lookup that found results in an enclosing class during error | |||
2133 | /// recovery. This usually indicates that the results were found in a dependent | |||
2134 | /// base class that could not be searched as part of a template definition. | |||
2135 | /// Always issues a diagnostic (though this may be only a warning in MS | |||
2136 | /// compatibility mode). | |||
2137 | /// | |||
2138 | /// Return \c true if the error is unrecoverable, or \c false if the caller | |||
2139 | /// should attempt to recover using these lookup results. | |||
2140 | bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { | |||
2141 | // During a default argument instantiation the CurContext points | |||
2142 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a | |||
2143 | // function parameter list, hence add an explicit check. | |||
2144 | bool isDefaultArgument = | |||
2145 | !CodeSynthesisContexts.empty() && | |||
2146 | CodeSynthesisContexts.back().Kind == | |||
2147 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; | |||
2148 | CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); | |||
2149 | bool isInstance = CurMethod && CurMethod->isInstance() && | |||
2150 | R.getNamingClass() == CurMethod->getParent() && | |||
2151 | !isDefaultArgument; | |||
2152 | ||||
2153 | // There are two ways we can find a class-scope declaration during template | |||
2154 | // instantiation that we did not find in the template definition: if it is a | |||
2155 | // member of a dependent base class, or if it is declared after the point of | |||
2156 | // use in the same class. Distinguish these by comparing the class in which | |||
2157 | // the member was found to the naming class of the lookup. | |||
2158 | unsigned DiagID = diag::err_found_in_dependent_base; | |||
2159 | unsigned NoteID = diag::note_member_declared_at; | |||
2160 | if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { | |||
2161 | DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class | |||
2162 | : diag::err_found_later_in_class; | |||
2163 | } else if (getLangOpts().MSVCCompat) { | |||
2164 | DiagID = diag::ext_found_in_dependent_base; | |||
2165 | NoteID = diag::note_dependent_member_use; | |||
2166 | } | |||
2167 | ||||
2168 | if (isInstance) { | |||
2169 | // Give a code modification hint to insert 'this->'. | |||
2170 | Diag(R.getNameLoc(), DiagID) | |||
2171 | << R.getLookupName() | |||
2172 | << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); | |||
2173 | CheckCXXThisCapture(R.getNameLoc()); | |||
2174 | } else { | |||
2175 | // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming | |||
2176 | // they're not shadowed). | |||
2177 | Diag(R.getNameLoc(), DiagID) << R.getLookupName(); | |||
2178 | } | |||
2179 | ||||
2180 | for (NamedDecl *D : R) | |||
2181 | Diag(D->getLocation(), NoteID); | |||
2182 | ||||
2183 | // Return true if we are inside a default argument instantiation | |||
2184 | // and the found name refers to an instance member function, otherwise | |||
2185 | // the caller will try to create an implicit member call and this is wrong | |||
2186 | // for default arguments. | |||
2187 | // | |||
2188 | // FIXME: Is this special case necessary? We could allow the caller to | |||
2189 | // diagnose this. | |||
2190 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { | |||
2191 | Diag(R.getNameLoc(), diag::err_member_call_without_object); | |||
2192 | return true; | |||
2193 | } | |||
2194 | ||||
2195 | // Tell the callee to try to recover. | |||
2196 | return false; | |||
2197 | } | |||
2198 | ||||
2199 | /// Diagnose an empty lookup. | |||
2200 | /// | |||
2201 | /// \return false if new lookup candidates were found | |||
2202 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, | |||
2203 | CorrectionCandidateCallback &CCC, | |||
2204 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
2205 | ArrayRef<Expr *> Args, TypoExpr **Out) { | |||
2206 | DeclarationName Name = R.getLookupName(); | |||
2207 | ||||
2208 | unsigned diagnostic = diag::err_undeclared_var_use; | |||
2209 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; | |||
2210 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || | |||
2211 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || | |||
2212 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | |||
2213 | diagnostic = diag::err_undeclared_use; | |||
2214 | diagnostic_suggest = diag::err_undeclared_use_suggest; | |||
2215 | } | |||
2216 | ||||
2217 | // If the original lookup was an unqualified lookup, fake an | |||
2218 | // unqualified lookup. This is useful when (for example) the | |||
2219 | // original lookup would not have found something because it was a | |||
2220 | // dependent name. | |||
2221 | DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; | |||
2222 | while (DC) { | |||
2223 | if (isa<CXXRecordDecl>(DC)) { | |||
2224 | LookupQualifiedName(R, DC); | |||
2225 | ||||
2226 | if (!R.empty()) { | |||
2227 | // Don't give errors about ambiguities in this lookup. | |||
2228 | R.suppressDiagnostics(); | |||
2229 | ||||
2230 | // If there's a best viable function among the results, only mention | |||
2231 | // that one in the notes. | |||
2232 | OverloadCandidateSet Candidates(R.getNameLoc(), | |||
2233 | OverloadCandidateSet::CSK_Normal); | |||
2234 | AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); | |||
2235 | OverloadCandidateSet::iterator Best; | |||
2236 | if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == | |||
2237 | OR_Success) { | |||
2238 | R.clear(); | |||
2239 | R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); | |||
2240 | R.resolveKind(); | |||
2241 | } | |||
2242 | ||||
2243 | return DiagnoseDependentMemberLookup(R); | |||
2244 | } | |||
2245 | ||||
2246 | R.clear(); | |||
2247 | } | |||
2248 | ||||
2249 | DC = DC->getLookupParent(); | |||
2250 | } | |||
2251 | ||||
2252 | // We didn't find anything, so try to correct for a typo. | |||
2253 | TypoCorrection Corrected; | |||
2254 | if (S && Out) { | |||
2255 | SourceLocation TypoLoc = R.getNameLoc(); | |||
2256 | 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", 2257, __extension__ __PRETTY_FUNCTION__ )) | |||
2257 | "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", 2257, __extension__ __PRETTY_FUNCTION__ )); | |||
2258 | *Out = CorrectTypoDelayed( | |||
2259 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | |||
2260 | [=](const TypoCorrection &TC) { | |||
2261 | emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, | |||
2262 | diagnostic, diagnostic_suggest); | |||
2263 | }, | |||
2264 | nullptr, CTK_ErrorRecovery); | |||
2265 | if (*Out) | |||
2266 | return true; | |||
2267 | } else if (S && | |||
2268 | (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), | |||
2269 | S, &SS, CCC, CTK_ErrorRecovery))) { | |||
2270 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | |||
2271 | bool DroppedSpecifier = | |||
2272 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; | |||
2273 | R.setLookupName(Corrected.getCorrection()); | |||
2274 | ||||
2275 | bool AcceptableWithRecovery = false; | |||
2276 | bool AcceptableWithoutRecovery = false; | |||
2277 | NamedDecl *ND = Corrected.getFoundDecl(); | |||
2278 | if (ND) { | |||
2279 | if (Corrected.isOverloaded()) { | |||
2280 | OverloadCandidateSet OCS(R.getNameLoc(), | |||
2281 | OverloadCandidateSet::CSK_Normal); | |||
2282 | OverloadCandidateSet::iterator Best; | |||
2283 | for (NamedDecl *CD : Corrected) { | |||
2284 | if (FunctionTemplateDecl *FTD = | |||
2285 | dyn_cast<FunctionTemplateDecl>(CD)) | |||
2286 | AddTemplateOverloadCandidate( | |||
2287 | FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, | |||
2288 | Args, OCS); | |||
2289 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | |||
2290 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) | |||
2291 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), | |||
2292 | Args, OCS); | |||
2293 | } | |||
2294 | switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { | |||
2295 | case OR_Success: | |||
2296 | ND = Best->FoundDecl; | |||
2297 | Corrected.setCorrectionDecl(ND); | |||
2298 | break; | |||
2299 | default: | |||
2300 | // FIXME: Arbitrarily pick the first declaration for the note. | |||
2301 | Corrected.setCorrectionDecl(ND); | |||
2302 | break; | |||
2303 | } | |||
2304 | } | |||
2305 | R.addDecl(ND); | |||
2306 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { | |||
2307 | CXXRecordDecl *Record = nullptr; | |||
2308 | if (Corrected.getCorrectionSpecifier()) { | |||
2309 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); | |||
2310 | Record = Ty->getAsCXXRecordDecl(); | |||
2311 | } | |||
2312 | if (!Record) | |||
2313 | Record = cast<CXXRecordDecl>( | |||
2314 | ND->getDeclContext()->getRedeclContext()); | |||
2315 | R.setNamingClass(Record); | |||
2316 | } | |||
2317 | ||||
2318 | auto *UnderlyingND = ND->getUnderlyingDecl(); | |||
2319 | AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || | |||
2320 | isa<FunctionTemplateDecl>(UnderlyingND); | |||
2321 | // FIXME: If we ended up with a typo for a type name or | |||
2322 | // Objective-C class name, we're in trouble because the parser | |||
2323 | // is in the wrong place to recover. Suggest the typo | |||
2324 | // correction, but don't make it a fix-it since we're not going | |||
2325 | // to recover well anyway. | |||
2326 | AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || | |||
2327 | getAsTypeTemplateDecl(UnderlyingND) || | |||
2328 | isa<ObjCInterfaceDecl>(UnderlyingND); | |||
2329 | } else { | |||
2330 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it | |||
2331 | // because we aren't able to recover. | |||
2332 | AcceptableWithoutRecovery = true; | |||
2333 | } | |||
2334 | ||||
2335 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { | |||
2336 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() | |||
2337 | ? diag::note_implicit_param_decl | |||
2338 | : diag::note_previous_decl; | |||
2339 | if (SS.isEmpty()) | |||
2340 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, | |||
2341 | PDiag(NoteID), AcceptableWithRecovery); | |||
2342 | else | |||
2343 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | |||
2344 | << Name << computeDeclContext(SS, false) | |||
2345 | << DroppedSpecifier << SS.getRange(), | |||
2346 | PDiag(NoteID), AcceptableWithRecovery); | |||
2347 | ||||
2348 | // Tell the callee whether to try to recover. | |||
2349 | return !AcceptableWithRecovery; | |||
2350 | } | |||
2351 | } | |||
2352 | R.clear(); | |||
2353 | ||||
2354 | // Emit a special diagnostic for failed member lookups. | |||
2355 | // FIXME: computing the declaration context might fail here (?) | |||
2356 | if (!SS.isEmpty()) { | |||
2357 | Diag(R.getNameLoc(), diag::err_no_member) | |||
2358 | << Name << computeDeclContext(SS, false) | |||
2359 | << SS.getRange(); | |||
2360 | return true; | |||
2361 | } | |||
2362 | ||||
2363 | // Give up, we can't recover. | |||
2364 | Diag(R.getNameLoc(), diagnostic) << Name; | |||
2365 | return true; | |||
2366 | } | |||
2367 | ||||
2368 | /// In Microsoft mode, if we are inside a template class whose parent class has | |||
2369 | /// dependent base classes, and we can't resolve an unqualified identifier, then | |||
2370 | /// assume the identifier is a member of a dependent base class. We can only | |||
2371 | /// recover successfully in static methods, instance methods, and other contexts | |||
2372 | /// where 'this' is available. This doesn't precisely match MSVC's | |||
2373 | /// instantiation model, but it's close enough. | |||
2374 | static Expr * | |||
2375 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, | |||
2376 | DeclarationNameInfo &NameInfo, | |||
2377 | SourceLocation TemplateKWLoc, | |||
2378 | const TemplateArgumentListInfo *TemplateArgs) { | |||
2379 | // Only try to recover from lookup into dependent bases in static methods or | |||
2380 | // contexts where 'this' is available. | |||
2381 | QualType ThisType = S.getCurrentThisType(); | |||
2382 | const CXXRecordDecl *RD = nullptr; | |||
2383 | if (!ThisType.isNull()) | |||
2384 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); | |||
2385 | else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) | |||
2386 | RD = MD->getParent(); | |||
2387 | if (!RD || !RD->hasAnyDependentBases()) | |||
2388 | return nullptr; | |||
2389 | ||||
2390 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' | |||
2391 | // is available, suggest inserting 'this->' as a fixit. | |||
2392 | SourceLocation Loc = NameInfo.getLoc(); | |||
2393 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); | |||
2394 | DB << NameInfo.getName() << RD; | |||
2395 | ||||
2396 | if (!ThisType.isNull()) { | |||
2397 | DB << FixItHint::CreateInsertion(Loc, "this->"); | |||
2398 | return CXXDependentScopeMemberExpr::Create( | |||
2399 | Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, | |||
2400 | /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, | |||
2401 | /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); | |||
2402 | } | |||
2403 | ||||
2404 | // Synthesize a fake NNS that points to the derived class. This will | |||
2405 | // perform name lookup during template instantiation. | |||
2406 | CXXScopeSpec SS; | |||
2407 | auto *NNS = | |||
2408 | NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); | |||
2409 | SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); | |||
2410 | return DependentScopeDeclRefExpr::Create( | |||
2411 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, | |||
2412 | TemplateArgs); | |||
2413 | } | |||
2414 | ||||
2415 | ExprResult | |||
2416 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, | |||
2417 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, | |||
2418 | bool HasTrailingLParen, bool IsAddressOfOperand, | |||
2419 | CorrectionCandidateCallback *CCC, | |||
2420 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { | |||
2421 | 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", 2422, __extension__ __PRETTY_FUNCTION__ )) | |||
2422 | "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", 2422, __extension__ __PRETTY_FUNCTION__ )); | |||
2423 | if (SS.isInvalid()) | |||
2424 | return ExprError(); | |||
2425 | ||||
2426 | TemplateArgumentListInfo TemplateArgsBuffer; | |||
2427 | ||||
2428 | // Decompose the UnqualifiedId into the following data. | |||
2429 | DeclarationNameInfo NameInfo; | |||
2430 | const TemplateArgumentListInfo *TemplateArgs; | |||
2431 | DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); | |||
2432 | ||||
2433 | DeclarationName Name = NameInfo.getName(); | |||
2434 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | |||
2435 | SourceLocation NameLoc = NameInfo.getLoc(); | |||
2436 | ||||
2437 | if (II && II->isEditorPlaceholder()) { | |||
2438 | // FIXME: When typed placeholders are supported we can create a typed | |||
2439 | // placeholder expression node. | |||
2440 | return ExprError(); | |||
2441 | } | |||
2442 | ||||
2443 | // C++ [temp.dep.expr]p3: | |||
2444 | // An id-expression is type-dependent if it contains: | |||
2445 | // -- an identifier that was declared with a dependent type, | |||
2446 | // (note: handled after lookup) | |||
2447 | // -- a template-id that is dependent, | |||
2448 | // (note: handled in BuildTemplateIdExpr) | |||
2449 | // -- a conversion-function-id that specifies a dependent type, | |||
2450 | // -- a nested-name-specifier that contains a class-name that | |||
2451 | // names a dependent type. | |||
2452 | // Determine whether this is a member of an unknown specialization; | |||
2453 | // we need to handle these differently. | |||
2454 | bool DependentID = false; | |||
2455 | if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && | |||
2456 | Name.getCXXNameType()->isDependentType()) { | |||
2457 | DependentID = true; | |||
2458 | } else if (SS.isSet()) { | |||
2459 | if (DeclContext *DC = computeDeclContext(SS, false)) { | |||
2460 | if (RequireCompleteDeclContext(SS, DC)) | |||
2461 | return ExprError(); | |||
2462 | } else { | |||
2463 | DependentID = true; | |||
2464 | } | |||
2465 | } | |||
2466 | ||||
2467 | if (DependentID) | |||
2468 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | |||
2469 | IsAddressOfOperand, TemplateArgs); | |||
2470 | ||||
2471 | // Perform the required lookup. | |||
2472 | LookupResult R(*this, NameInfo, | |||
2473 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) | |||
2474 | ? LookupObjCImplicitSelfParam | |||
2475 | : LookupOrdinaryName); | |||
2476 | if (TemplateKWLoc.isValid() || TemplateArgs) { | |||
2477 | // Lookup the template name again to correctly establish the context in | |||
2478 | // which it was found. This is really unfortunate as we already did the | |||
2479 | // lookup to determine that it was a template name in the first place. If | |||
2480 | // this becomes a performance hit, we can work harder to preserve those | |||
2481 | // results until we get here but it's likely not worth it. | |||
2482 | bool MemberOfUnknownSpecialization; | |||
2483 | AssumedTemplateKind AssumedTemplate; | |||
2484 | if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, | |||
2485 | MemberOfUnknownSpecialization, TemplateKWLoc, | |||
2486 | &AssumedTemplate)) | |||
2487 | return ExprError(); | |||
2488 | ||||
2489 | if (MemberOfUnknownSpecialization || | |||
2490 | (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) | |||
2491 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | |||
2492 | IsAddressOfOperand, TemplateArgs); | |||
2493 | } else { | |||
2494 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); | |||
2495 | LookupParsedName(R, S, &SS, !IvarLookupFollowUp); | |||
2496 | ||||
2497 | // If the result might be in a dependent base class, this is a dependent | |||
2498 | // id-expression. | |||
2499 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | |||
2500 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | |||
2501 | IsAddressOfOperand, TemplateArgs); | |||
2502 | ||||
2503 | // If this reference is in an Objective-C method, then we need to do | |||
2504 | // some special Objective-C lookup, too. | |||
2505 | if (IvarLookupFollowUp) { | |||
2506 | ExprResult E(LookupInObjCMethod(R, S, II, true)); | |||
2507 | if (E.isInvalid()) | |||
2508 | return ExprError(); | |||
2509 | ||||
2510 | if (Expr *Ex = E.getAs<Expr>()) | |||
2511 | return Ex; | |||
2512 | } | |||
2513 | } | |||
2514 | ||||
2515 | if (R.isAmbiguous()) | |||
2516 | return ExprError(); | |||
2517 | ||||
2518 | // This could be an implicitly declared function reference (legal in C90, | |||
2519 | // extension in C99, forbidden in C++). | |||
2520 | if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { | |||
2521 | NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); | |||
2522 | if (D) R.addDecl(D); | |||
2523 | } | |||
2524 | ||||
2525 | // Determine whether this name might be a candidate for | |||
2526 | // argument-dependent lookup. | |||
2527 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); | |||
2528 | ||||
2529 | if (R.empty() && !ADL) { | |||
2530 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { | |||
2531 | if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, | |||
2532 | TemplateKWLoc, TemplateArgs)) | |||
2533 | return E; | |||
2534 | } | |||
2535 | ||||
2536 | // Don't diagnose an empty lookup for inline assembly. | |||
2537 | if (IsInlineAsmIdentifier) | |||
2538 | return ExprError(); | |||
2539 | ||||
2540 | // If this name wasn't predeclared and if this is not a function | |||
2541 | // call, diagnose the problem. | |||
2542 | TypoExpr *TE = nullptr; | |||
2543 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() | |||
2544 | : nullptr); | |||
2545 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; | |||
2546 | 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", 2547, __extension__ __PRETTY_FUNCTION__ )) | |||
2547 | "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", 2547, __extension__ __PRETTY_FUNCTION__ )); | |||
2548 | if (CCC) { | |||
2549 | // Make sure the callback knows what the typo being diagnosed is. | |||
2550 | CCC->setTypoName(II); | |||
2551 | if (SS.isValid()) | |||
2552 | CCC->setTypoNNS(SS.getScopeRep()); | |||
2553 | } | |||
2554 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for | |||
2555 | // a template name, but we happen to have always already looked up the name | |||
2556 | // before we get here if it must be a template name. | |||
2557 | if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, | |||
2558 | None, &TE)) { | |||
2559 | if (TE && KeywordReplacement) { | |||
2560 | auto &State = getTypoExprState(TE); | |||
2561 | auto BestTC = State.Consumer->getNextCorrection(); | |||
2562 | if (BestTC.isKeyword()) { | |||
2563 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); | |||
2564 | if (State.DiagHandler) | |||
2565 | State.DiagHandler(BestTC); | |||
2566 | KeywordReplacement->startToken(); | |||
2567 | KeywordReplacement->setKind(II->getTokenID()); | |||
2568 | KeywordReplacement->setIdentifierInfo(II); | |||
2569 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); | |||
2570 | // Clean up the state associated with the TypoExpr, since it has | |||
2571 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). | |||
2572 | clearDelayedTypo(TE); | |||
2573 | // Signal that a correction to a keyword was performed by returning a | |||
2574 | // valid-but-null ExprResult. | |||
2575 | return (Expr*)nullptr; | |||
2576 | } | |||
2577 | State.Consumer->resetCorrectionStream(); | |||
2578 | } | |||
2579 | return TE ? TE : ExprError(); | |||
2580 | } | |||
2581 | ||||
2582 | 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", 2583, __extension__ __PRETTY_FUNCTION__ )) | |||
2583 | "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", 2583, __extension__ __PRETTY_FUNCTION__ )); | |||
2584 | ||||
2585 | // If we found an Objective-C instance variable, let | |||
2586 | // LookupInObjCMethod build the appropriate expression to | |||
2587 | // reference the ivar. | |||
2588 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { | |||
2589 | R.clear(); | |||
2590 | ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); | |||
2591 | // In a hopelessly buggy code, Objective-C instance variable | |||
2592 | // lookup fails and no expression will be built to reference it. | |||
2593 | if (!E.isInvalid() && !E.get()) | |||
2594 | return ExprError(); | |||
2595 | return E; | |||
2596 | } | |||
2597 | } | |||
2598 | ||||
2599 | // This is guaranteed from this point on. | |||
2600 | assert(!R.empty() || ADL)(static_cast <bool> (!R.empty() || ADL) ? void (0) : __assert_fail ("!R.empty() || ADL", "clang/lib/Sema/SemaExpr.cpp", 2600, __extension__ __PRETTY_FUNCTION__)); | |||
2601 | ||||
2602 | // Check whether this might be a C++ implicit instance member access. | |||
2603 | // C++ [class.mfct.non-static]p3: | |||
2604 | // When an id-expression that is not part of a class member access | |||
2605 | // syntax and not used to form a pointer to member is used in the | |||
2606 | // body of a non-static member function of class X, if name lookup | |||
2607 | // resolves the name in the id-expression to a non-static non-type | |||
2608 | // member of some class C, the id-expression is transformed into a | |||
2609 | // class member access expression using (*this) as the | |||
2610 | // postfix-expression to the left of the . operator. | |||
2611 | // | |||
2612 | // But we don't actually need to do this for '&' operands if R | |||
2613 | // resolved to a function or overloaded function set, because the | |||
2614 | // expression is ill-formed if it actually works out to be a | |||
2615 | // non-static member function: | |||
2616 | // | |||
2617 | // C++ [expr.ref]p4: | |||
2618 | // Otherwise, if E1.E2 refers to a non-static member function. . . | |||
2619 | // [t]he expression can be used only as the left-hand operand of a | |||
2620 | // member function call. | |||
2621 | // | |||
2622 | // There are other safeguards against such uses, but it's important | |||
2623 | // to get this right here so that we don't end up making a | |||
2624 | // spuriously dependent expression if we're inside a dependent | |||
2625 | // instance method. | |||
2626 | if (!R.empty() && (*R.begin())->isCXXClassMember()) { | |||
2627 | bool MightBeImplicitMember; | |||
2628 | if (!IsAddressOfOperand) | |||
2629 | MightBeImplicitMember = true; | |||
2630 | else if (!SS.isEmpty()) | |||
2631 | MightBeImplicitMember = false; | |||
2632 | else if (R.isOverloadedResult()) | |||
2633 | MightBeImplicitMember = false; | |||
2634 | else if (R.isUnresolvableResult()) | |||
2635 | MightBeImplicitMember = true; | |||
2636 | else | |||
2637 | MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || | |||
2638 | isa<IndirectFieldDecl>(R.getFoundDecl()) || | |||
2639 | isa<MSPropertyDecl>(R.getFoundDecl()); | |||
2640 | ||||
2641 | if (MightBeImplicitMember) | |||
2642 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, | |||
2643 | R, TemplateArgs, S); | |||
2644 | } | |||
2645 | ||||
2646 | if (TemplateArgs || TemplateKWLoc.isValid()) { | |||
2647 | ||||
2648 | // In C++1y, if this is a variable template id, then check it | |||
2649 | // in BuildTemplateIdExpr(). | |||
2650 | // The single lookup result must be a variable template declaration. | |||
2651 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && | |||
2652 | Id.TemplateId->Kind == TNK_Var_template) { | |||
2653 | 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", 2654, __extension__ __PRETTY_FUNCTION__ )) | |||
2654 | "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", 2654, __extension__ __PRETTY_FUNCTION__ )); | |||
2655 | } | |||
2656 | ||||
2657 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); | |||
2658 | } | |||
2659 | ||||
2660 | return BuildDeclarationNameExpr(SS, R, ADL); | |||
2661 | } | |||
2662 | ||||
2663 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified | |||
2664 | /// declaration name, generally during template instantiation. | |||
2665 | /// There's a large number of things which don't need to be done along | |||
2666 | /// this path. | |||
2667 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( | |||
2668 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, | |||
2669 | bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { | |||
2670 | DeclContext *DC = computeDeclContext(SS, false); | |||
2671 | if (!DC) | |||
2672 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | |||
2673 | NameInfo, /*TemplateArgs=*/nullptr); | |||
2674 | ||||
2675 | if (RequireCompleteDeclContext(SS, DC)) | |||
2676 | return ExprError(); | |||
2677 | ||||
2678 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | |||
2679 | LookupQualifiedName(R, DC); | |||
2680 | ||||
2681 | if (R.isAmbiguous()) | |||
2682 | return ExprError(); | |||
2683 | ||||
2684 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | |||
2685 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | |||
2686 | NameInfo, /*TemplateArgs=*/nullptr); | |||
2687 | ||||
2688 | if (R.empty()) { | |||
2689 | // Don't diagnose problems with invalid record decl, the secondary no_member | |||
2690 | // diagnostic during template instantiation is likely bogus, e.g. if a class | |||
2691 | // is invalid because it's derived from an invalid base class, then missing | |||
2692 | // members were likely supposed to be inherited. | |||
2693 | if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) | |||
2694 | if (CD->isInvalidDecl()) | |||
2695 | return ExprError(); | |||
2696 | Diag(NameInfo.getLoc(), diag::err_no_member) | |||
2697 | << NameInfo.getName() << DC << SS.getRange(); | |||
2698 | return ExprError(); | |||
2699 | } | |||
2700 | ||||
2701 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { | |||
2702 | // Diagnose a missing typename if this resolved unambiguously to a type in | |||
2703 | // a dependent context. If we can recover with a type, downgrade this to | |||
2704 | // a warning in Microsoft compatibility mode. | |||
2705 | unsigned DiagID = diag::err_typename_missing; | |||
2706 | if (RecoveryTSI && getLangOpts().MSVCCompat) | |||
2707 | DiagID = diag::ext_typename_missing; | |||
2708 | SourceLocation Loc = SS.getBeginLoc(); | |||
2709 | auto D = Diag(Loc, DiagID); | |||
2710 | D << SS.getScopeRep() << NameInfo.getName().getAsString() | |||
2711 | << SourceRange(Loc, NameInfo.getEndLoc()); | |||
2712 | ||||
2713 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE | |||
2714 | // context. | |||
2715 | if (!RecoveryTSI) | |||
2716 | return ExprError(); | |||
2717 | ||||
2718 | // Only issue the fixit if we're prepared to recover. | |||
2719 | D << FixItHint::CreateInsertion(Loc, "typename "); | |||
2720 | ||||
2721 | // Recover by pretending this was an elaborated type. | |||
2722 | QualType Ty = Context.getTypeDeclType(TD); | |||
2723 | TypeLocBuilder TLB; | |||
2724 | TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); | |||
2725 | ||||
2726 | QualType ET = getElaboratedType(ETK_None, SS, Ty); | |||
2727 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); | |||
2728 | QTL.setElaboratedKeywordLoc(SourceLocation()); | |||
2729 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
2730 | ||||
2731 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); | |||
2732 | ||||
2733 | return ExprEmpty(); | |||
2734 | } | |||
2735 | ||||
2736 | // Defend against this resolving to an implicit member access. We usually | |||
2737 | // won't get here if this might be a legitimate a class member (we end up in | |||
2738 | // BuildMemberReferenceExpr instead), but this can be valid if we're forming | |||
2739 | // a pointer-to-member or in an unevaluated context in C++11. | |||
2740 | if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) | |||
2741 | return BuildPossibleImplicitMemberExpr(SS, | |||
2742 | /*TemplateKWLoc=*/SourceLocation(), | |||
2743 | R, /*TemplateArgs=*/nullptr, S); | |||
2744 | ||||
2745 | return BuildDeclarationNameExpr(SS, R, /* ADL */ false); | |||
2746 | } | |||
2747 | ||||
2748 | /// The parser has read a name in, and Sema has detected that we're currently | |||
2749 | /// inside an ObjC method. Perform some additional checks and determine if we | |||
2750 | /// should form a reference to an ivar. | |||
2751 | /// | |||
2752 | /// Ideally, most of this would be done by lookup, but there's | |||
2753 | /// actually quite a lot of extra work involved. | |||
2754 | DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, | |||
2755 | IdentifierInfo *II) { | |||
2756 | SourceLocation Loc = Lookup.getNameLoc(); | |||
2757 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | |||
2758 | ||||
2759 | // Check for error condition which is already reported. | |||
2760 | if (!CurMethod) | |||
2761 | return DeclResult(true); | |||
2762 | ||||
2763 | // There are two cases to handle here. 1) scoped lookup could have failed, | |||
2764 | // in which case we should look for an ivar. 2) scoped lookup could have | |||
2765 | // found a decl, but that decl is outside the current instance method (i.e. | |||
2766 | // a global variable). In these two cases, we do a lookup for an ivar with | |||
2767 | // this name, if the lookup sucedes, we replace it our current decl. | |||
2768 | ||||
2769 | // If we're in a class method, we don't normally want to look for | |||
2770 | // ivars. But if we don't find anything else, and there's an | |||
2771 | // ivar, that's an error. | |||
2772 | bool IsClassMethod = CurMethod->isClassMethod(); | |||
2773 | ||||
2774 | bool LookForIvars; | |||
2775 | if (Lookup.empty()) | |||
2776 | LookForIvars = true; | |||
2777 | else if (IsClassMethod) | |||
2778 | LookForIvars = false; | |||
2779 | else | |||
2780 | LookForIvars = (Lookup.isSingleResult() && | |||
2781 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); | |||
2782 | ObjCInterfaceDecl *IFace = nullptr; | |||
2783 | if (LookForIvars) { | |||
2784 | IFace = CurMethod->getClassInterface(); | |||
2785 | ObjCInterfaceDecl *ClassDeclared; | |||
2786 | ObjCIvarDecl *IV = nullptr; | |||
2787 | if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { | |||
2788 | // Diagnose using an ivar in a class method. | |||
2789 | if (IsClassMethod) { | |||
2790 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | |||
2791 | return DeclResult(true); | |||
2792 | } | |||
2793 | ||||
2794 | // Diagnose the use of an ivar outside of the declaring class. | |||
2795 | if (IV->getAccessControl() == ObjCIvarDecl::Private && | |||
2796 | !declaresSameEntity(ClassDeclared, IFace) && | |||
2797 | !getLangOpts().DebuggerSupport) | |||
2798 | Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); | |||
2799 | ||||
2800 | // Success. | |||
2801 | return IV; | |||
2802 | } | |||
2803 | } else if (CurMethod->isInstanceMethod()) { | |||
2804 | // We should warn if a local variable hides an ivar. | |||
2805 | if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { | |||
2806 | ObjCInterfaceDecl *ClassDeclared; | |||
2807 | if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { | |||
2808 | if (IV->getAccessControl() != ObjCIvarDecl::Private || | |||
2809 | declaresSameEntity(IFace, ClassDeclared)) | |||
2810 | Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); | |||
2811 | } | |||
2812 | } | |||
2813 | } else if (Lookup.isSingleResult() && | |||
2814 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { | |||
2815 | // If accessing a stand-alone ivar in a class method, this is an error. | |||
2816 | if (const ObjCIvarDecl *IV = | |||
2817 | dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { | |||
2818 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | |||
2819 | return DeclResult(true); | |||
2820 | } | |||
2821 | } | |||
2822 | ||||
2823 | // Didn't encounter an error, didn't find an ivar. | |||
2824 | return DeclResult(false); | |||
2825 | } | |||
2826 | ||||
2827 | ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, | |||
2828 | ObjCIvarDecl *IV) { | |||
2829 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | |||
2830 | 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", 2831, __extension__ __PRETTY_FUNCTION__ )) | |||
2831 | "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", 2831, __extension__ __PRETTY_FUNCTION__ )); | |||
2832 | ||||
2833 | ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); | |||
2834 | 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", 2834, __extension__ __PRETTY_FUNCTION__ )); | |||
2835 | ||||
2836 | // If we're referencing an invalid decl, just return this as a silent | |||
2837 | // error node. The error diagnostic was already emitted on the decl. | |||
2838 | if (IV->isInvalidDecl()) | |||
2839 | return ExprError(); | |||
2840 | ||||
2841 | // Check if referencing a field with __attribute__((deprecated)). | |||
2842 | if (DiagnoseUseOfDecl(IV, Loc)) | |||
2843 | return ExprError(); | |||
2844 | ||||
2845 | // FIXME: This should use a new expr for a direct reference, don't | |||
2846 | // turn this into Self->ivar, just return a BareIVarExpr or something. | |||
2847 | IdentifierInfo &II = Context.Idents.get("self"); | |||
2848 | UnqualifiedId SelfName; | |||
2849 | SelfName.setImplicitSelfParam(&II); | |||
2850 | CXXScopeSpec SelfScopeSpec; | |||
2851 | SourceLocation TemplateKWLoc; | |||
2852 | ExprResult SelfExpr = | |||
2853 | ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, | |||
2854 | /*HasTrailingLParen=*/false, | |||
2855 | /*IsAddressOfOperand=*/false); | |||
2856 | if (SelfExpr.isInvalid()) | |||
2857 | return ExprError(); | |||
2858 | ||||
2859 | SelfExpr = DefaultLvalueConversion(SelfExpr.get()); | |||
2860 | if (SelfExpr.isInvalid()) | |||
2861 | return ExprError(); | |||
2862 | ||||
2863 | MarkAnyDeclReferenced(Loc, IV, true); | |||
2864 | ||||
2865 | ObjCMethodFamily MF = CurMethod->getMethodFamily(); | |||
2866 | if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && | |||
2867 | !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) | |||
2868 | Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); | |||
2869 | ||||
2870 | ObjCIvarRefExpr *Result = new (Context) | |||
2871 | ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, | |||
2872 | IV->getLocation(), SelfExpr.get(), true, true); | |||
2873 | ||||
2874 | if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { | |||
2875 | if (!isUnevaluatedContext() && | |||
2876 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | |||
2877 | getCurFunction()->recordUseOfWeak(Result); | |||
2878 | } | |||
2879 | if (getLangOpts().ObjCAutoRefCount) | |||
2880 | if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) | |||
2881 | ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); | |||
2882 | ||||
2883 | return Result; | |||
2884 | } | |||
2885 | ||||
2886 | /// The parser has read a name in, and Sema has detected that we're currently | |||
2887 | /// inside an ObjC method. Perform some additional checks and determine if we | |||
2888 | /// should form a reference to an ivar. If so, build an expression referencing | |||
2889 | /// that ivar. | |||
2890 | ExprResult | |||
2891 | Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, | |||
2892 | IdentifierInfo *II, bool AllowBuiltinCreation) { | |||
2893 | // FIXME: Integrate this lookup step into LookupParsedName. | |||
2894 | DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); | |||
2895 | if (Ivar.isInvalid()) | |||
2896 | return ExprError(); | |||
2897 | if (Ivar.isUsable()) | |||
2898 | return BuildIvarRefExpr(S, Lookup.getNameLoc(), | |||
2899 | cast<ObjCIvarDecl>(Ivar.get())); | |||
2900 | ||||
2901 | if (Lookup.empty() && II && AllowBuiltinCreation) | |||
2902 | LookupBuiltin(Lookup); | |||
2903 | ||||
2904 | // Sentinel value saying that we didn't do anything special. | |||
2905 | return ExprResult(false); | |||
2906 | } | |||
2907 | ||||
2908 | /// Cast a base object to a member's actual type. | |||
2909 | /// | |||
2910 | /// There are two relevant checks: | |||
2911 | /// | |||
2912 | /// C++ [class.access.base]p7: | |||
2913 | /// | |||
2914 | /// If a class member access operator [...] is used to access a non-static | |||
2915 | /// data member or non-static member function, the reference is ill-formed if | |||
2916 | /// the left operand [...] cannot be implicitly converted to a pointer to the | |||
2917 | /// naming class of the right operand. | |||
2918 | /// | |||
2919 | /// C++ [expr.ref]p7: | |||
2920 | /// | |||
2921 | /// If E2 is a non-static data member or a non-static member function, the | |||
2922 | /// program is ill-formed if the class of which E2 is directly a member is an | |||
2923 | /// ambiguous base (11.8) of the naming class (11.9.3) of E2. | |||
2924 | /// | |||
2925 | /// Note that the latter check does not consider access; the access of the | |||
2926 | /// "real" base class is checked as appropriate when checking the access of the | |||
2927 | /// member name. | |||
2928 | ExprResult | |||
2929 | Sema::PerformObjectMemberConversion(Expr *From, | |||
2930 | NestedNameSpecifier *Qualifier, | |||
2931 | NamedDecl *FoundDecl, | |||
2932 | NamedDecl *Member) { | |||
2933 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); | |||
2934 | if (!RD) | |||
2935 | return From; | |||
2936 | ||||
2937 | QualType DestRecordType; | |||
2938 | QualType DestType; | |||
2939 | QualType FromRecordType; | |||
2940 | QualType FromType = From->getType(); | |||
2941 | bool PointerConversions = false; | |||
2942 | if (isa<FieldDecl>(Member)) { | |||
2943 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); | |||
2944 | auto FromPtrType = FromType->getAs<PointerType>(); | |||
2945 | DestRecordType = Context.getAddrSpaceQualType( | |||
2946 | DestRecordType, FromPtrType | |||
2947 | ? FromType->getPointeeType().getAddressSpace() | |||
2948 | : FromType.getAddressSpace()); | |||
2949 | ||||
2950 | if (FromPtrType) { | |||
2951 | DestType = Context.getPointerType(DestRecordType); | |||
2952 | FromRecordType = FromPtrType->getPointeeType(); | |||
2953 | PointerConversions = true; | |||
2954 | } else { | |||
2955 | DestType = DestRecordType; | |||
2956 | FromRecordType = FromType; | |||
2957 | } | |||
2958 | } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { | |||
2959 | if (Method->isStatic()) | |||
2960 | return From; | |||
2961 | ||||
2962 | DestType = Method->getThisType(); | |||
2963 | DestRecordType = DestType->getPointeeType(); | |||
2964 | ||||
2965 | if (FromType->getAs<PointerType>()) { | |||
2966 | FromRecordType = FromType->getPointeeType(); | |||
2967 | PointerConversions = true; | |||
2968 | } else { | |||
2969 | FromRecordType = FromType; | |||
2970 | DestType = DestRecordType; | |||
2971 | } | |||
2972 | ||||
2973 | LangAS FromAS = FromRecordType.getAddressSpace(); | |||
2974 | LangAS DestAS = DestRecordType.getAddressSpace(); | |||
2975 | if (FromAS != DestAS) { | |||
2976 | QualType FromRecordTypeWithoutAS = | |||
2977 | Context.removeAddrSpaceQualType(FromRecordType); | |||
2978 | QualType FromTypeWithDestAS = | |||
2979 | Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); | |||
2980 | if (PointerConversions) | |||
2981 | FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); | |||
2982 | From = ImpCastExprToType(From, FromTypeWithDestAS, | |||
2983 | CK_AddressSpaceConversion, From->getValueKind()) | |||
2984 | .get(); | |||
2985 | } | |||
2986 | } else { | |||
2987 | // No conversion necessary. | |||
2988 | return From; | |||
2989 | } | |||
2990 | ||||
2991 | if (DestType->isDependentType() || FromType->isDependentType()) | |||
2992 | return From; | |||
2993 | ||||
2994 | // If the unqualified types are the same, no conversion is necessary. | |||
2995 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | |||
2996 | return From; | |||
2997 | ||||
2998 | SourceRange FromRange = From->getSourceRange(); | |||
2999 | SourceLocation FromLoc = FromRange.getBegin(); | |||
3000 | ||||
3001 | ExprValueKind VK = From->getValueKind(); | |||
3002 | ||||
3003 | // C++ [class.member.lookup]p8: | |||
3004 | // [...] Ambiguities can often be resolved by qualifying a name with its | |||
3005 | // class name. | |||
3006 | // | |||
3007 | // If the member was a qualified name and the qualified referred to a | |||
3008 | // specific base subobject type, we'll cast to that intermediate type | |||
3009 | // first and then to the object in which the member is declared. That allows | |||
3010 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: | |||
3011 | // | |||
3012 | // class Base { public: int x; }; | |||
3013 | // class Derived1 : public Base { }; | |||
3014 | // class Derived2 : public Base { }; | |||
3015 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; | |||
3016 | // | |||
3017 | // void VeryDerived::f() { | |||
3018 | // x = 17; // error: ambiguous base subobjects | |||
3019 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 | |||
3020 | // } | |||
3021 | if (Qualifier && Qualifier->getAsType()) { | |||
3022 | QualType QType = QualType(Qualifier->getAsType(), 0); | |||
3023 | 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", 3023, __extension__ __PRETTY_FUNCTION__ )); | |||
3024 | ||||
3025 | QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); | |||
3026 | ||||
3027 | // In C++98, the qualifier type doesn't actually have to be a base | |||
3028 | // type of the object type, in which case we just ignore it. | |||
3029 | // Otherwise build the appropriate casts. | |||
3030 | if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { | |||
3031 | CXXCastPath BasePath; | |||
3032 | if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, | |||
3033 | FromLoc, FromRange, &BasePath)) | |||
3034 | return ExprError(); | |||
3035 | ||||
3036 | if (PointerConversions) | |||
3037 | QType = Context.getPointerType(QType); | |||
3038 | From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, | |||
3039 | VK, &BasePath).get(); | |||
3040 | ||||
3041 | FromType = QType; | |||
3042 | FromRecordType = QRecordType; | |||
3043 | ||||
3044 | // If the qualifier type was the same as the destination type, | |||
3045 | // we're done. | |||
3046 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | |||
3047 | return From; | |||
3048 | } | |||
3049 | } | |||
3050 | ||||
3051 | CXXCastPath BasePath; | |||
3052 | if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, | |||
3053 | FromLoc, FromRange, &BasePath, | |||
3054 | /*IgnoreAccess=*/true)) | |||
3055 | return ExprError(); | |||
3056 | ||||
3057 | return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, | |||
3058 | VK, &BasePath); | |||
3059 | } | |||
3060 | ||||
3061 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, | |||
3062 | const LookupResult &R, | |||
3063 | bool HasTrailingLParen) { | |||
3064 | // Only when used directly as the postfix-expression of a call. | |||
3065 | if (!HasTrailingLParen) | |||
3066 | return false; | |||
3067 | ||||
3068 | // Never if a scope specifier was provided. | |||
3069 | if (SS.isSet()) | |||
3070 | return false; | |||
3071 | ||||
3072 | // Only in C++ or ObjC++. | |||
3073 | if (!getLangOpts().CPlusPlus) | |||
3074 | return false; | |||
3075 | ||||
3076 | // Turn off ADL when we find certain kinds of declarations during | |||
3077 | // normal lookup: | |||
3078 | for (NamedDecl *D : R) { | |||
3079 | // C++0x [basic.lookup.argdep]p3: | |||
3080 | // -- a declaration of a class member | |||
3081 | // Since using decls preserve this property, we check this on the | |||
3082 | // original decl. | |||
3083 | if (D->isCXXClassMember()) | |||
3084 | return false; | |||
3085 | ||||
3086 | // C++0x [basic.lookup.argdep]p3: | |||
3087 | // -- a block-scope function declaration that is not a | |||
3088 | // using-declaration | |||
3089 | // NOTE: we also trigger this for function templates (in fact, we | |||
3090 | // don't check the decl type at all, since all other decl types | |||
3091 | // turn off ADL anyway). | |||
3092 | if (isa<UsingShadowDecl>(D)) | |||
3093 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
3094 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) | |||
3095 | return false; | |||
3096 | ||||
3097 | // C++0x [basic.lookup.argdep]p3: | |||
3098 | // -- a declaration that is neither a function or a function | |||
3099 | // template | |||
3100 | // And also for builtin functions. | |||
3101 | if (isa<FunctionDecl>(D)) { | |||
3102 | FunctionDecl *FDecl = cast<FunctionDecl>(D); | |||
3103 | ||||
3104 | // But also builtin functions. | |||
3105 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) | |||
3106 | return false; | |||
3107 | } else if (!isa<FunctionTemplateDecl>(D)) | |||
3108 | return false; | |||
3109 | } | |||
3110 | ||||
3111 | return true; | |||
3112 | } | |||
3113 | ||||
3114 | ||||
3115 | /// Diagnoses obvious problems with the use of the given declaration | |||
3116 | /// as an expression. This is only actually called for lookups that | |||
3117 | /// were not overloaded, and it doesn't promise that the declaration | |||
3118 | /// will in fact be used. | |||
3119 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { | |||
3120 | if (D->isInvalidDecl()) | |||
3121 | return true; | |||
3122 | ||||
3123 | if (isa<TypedefNameDecl>(D)) { | |||
3124 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); | |||
3125 | return true; | |||
3126 | } | |||
3127 | ||||
3128 | if (isa<ObjCInterfaceDecl>(D)) { | |||
3129 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); | |||
3130 | return true; | |||
3131 | } | |||
3132 | ||||
3133 | if (isa<NamespaceDecl>(D)) { | |||
3134 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); | |||
3135 | return true; | |||
3136 | } | |||
3137 | ||||
3138 | return false; | |||
3139 | } | |||
3140 | ||||
3141 | // Certain multiversion types should be treated as overloaded even when there is | |||
3142 | // only one result. | |||
3143 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { | |||
3144 | 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", 3144, __extension__ __PRETTY_FUNCTION__ )); | |||
3145 | const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); | |||
3146 | return FD && | |||
3147 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); | |||
3148 | } | |||
3149 | ||||
3150 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, | |||
3151 | LookupResult &R, bool NeedsADL, | |||
3152 | bool AcceptInvalidDecl) { | |||
3153 | // If this is a single, fully-resolved result and we don't need ADL, | |||
3154 | // just build an ordinary singleton decl ref. | |||
3155 | if (!NeedsADL && R.isSingleResult() && | |||
3156 | !R.getAsSingle<FunctionTemplateDecl>() && | |||
3157 | !ShouldLookupResultBeMultiVersionOverload(R)) | |||
3158 | return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), | |||
3159 | R.getRepresentativeDecl(), nullptr, | |||
3160 | AcceptInvalidDecl); | |||
3161 | ||||
3162 | // We only need to check the declaration if there's exactly one | |||
3163 | // result, because in the overloaded case the results can only be | |||
3164 | // functions and function templates. | |||
3165 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && | |||
3166 | CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) | |||
3167 | return ExprError(); | |||
3168 | ||||
3169 | // Otherwise, just build an unresolved lookup expression. Suppress | |||
3170 | // any lookup-related diagnostics; we'll hash these out later, when | |||
3171 | // we've picked a target. | |||
3172 | R.suppressDiagnostics(); | |||
3173 | ||||
3174 | UnresolvedLookupExpr *ULE | |||
3175 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), | |||
3176 | SS.getWithLocInContext(Context), | |||
3177 | R.getLookupNameInfo(), | |||
3178 | NeedsADL, R.isOverloadedResult(), | |||
3179 | R.begin(), R.end()); | |||
3180 | ||||
3181 | return ULE; | |||
3182 | } | |||
3183 | ||||
3184 | static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | |||
3185 | ValueDecl *var); | |||
3186 | ||||
3187 | /// Complete semantic analysis for a reference to the given declaration. | |||
3188 | ExprResult Sema::BuildDeclarationNameExpr( | |||
3189 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, | |||
3190 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, | |||
3191 | bool AcceptInvalidDecl) { | |||
3192 | 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", 3192, __extension__ __PRETTY_FUNCTION__ )); | |||
3193 | 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", 3194, __extension__ __PRETTY_FUNCTION__ )) | |||
3194 | "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", 3194, __extension__ __PRETTY_FUNCTION__ )); | |||
3195 | ||||
3196 | SourceLocation Loc = NameInfo.getLoc(); | |||
3197 | if (CheckDeclInExpr(*this, Loc, D)) | |||
3198 | return ExprError(); | |||
3199 | ||||
3200 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { | |||
3201 | // Specifically diagnose references to class templates that are missing | |||
3202 | // a template argument list. | |||
3203 | diagnoseMissingTemplateArguments(TemplateName(Template), Loc); | |||
3204 | return ExprError(); | |||
3205 | } | |||
3206 | ||||
3207 | // Make sure that we're referring to a value. | |||
3208 | if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { | |||
3209 | Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); | |||
3210 | Diag(D->getLocation(), diag::note_declared_at); | |||
3211 | return ExprError(); | |||
3212 | } | |||
3213 | ||||
3214 | // Check whether this declaration can be used. Note that we suppress | |||
3215 | // this check when we're going to perform argument-dependent lookup | |||
3216 | // on this function name, because this might not be the function | |||
3217 | // that overload resolution actually selects. | |||
3218 | if (DiagnoseUseOfDecl(D, Loc)) | |||
3219 | return ExprError(); | |||
3220 | ||||
3221 | auto *VD = cast<ValueDecl>(D); | |||
3222 | ||||
3223 | // Only create DeclRefExpr's for valid Decl's. | |||
3224 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) | |||
3225 | return ExprError(); | |||
3226 | ||||
3227 | // Handle members of anonymous structs and unions. If we got here, | |||
3228 | // and the reference is to a class member indirect field, then this | |||
3229 | // must be the subject of a pointer-to-member expression. | |||
3230 | if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) | |||
3231 | if (!indirectField->isCXXClassMember()) | |||
3232 | return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), | |||
3233 | indirectField); | |||
3234 | ||||
3235 | QualType type = VD->getType(); | |||
3236 | if (type.isNull()) | |||
3237 | return ExprError(); | |||
3238 | ExprValueKind valueKind = VK_PRValue; | |||
3239 | ||||
3240 | // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of | |||
3241 | // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, | |||
3242 | // is expanded by some outer '...' in the context of the use. | |||
3243 | type = type.getNonPackExpansionType(); | |||
3244 | ||||
3245 | switch (D->getKind()) { | |||
3246 | // Ignore all the non-ValueDecl kinds. | |||
3247 | #define ABSTRACT_DECL(kind) | |||
3248 | #define VALUE(type, base) | |||
3249 | #define DECL(type, base) case Decl::type: | |||
3250 | #include "clang/AST/DeclNodes.inc" | |||
3251 | llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "clang/lib/Sema/SemaExpr.cpp" , 3251); | |||
3252 | ||||
3253 | // These shouldn't make it here. | |||
3254 | case Decl::ObjCAtDefsField: | |||
3255 | llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?" , "clang/lib/Sema/SemaExpr.cpp", 3255); | |||
3256 | ||||
3257 | // Enum constants are always r-values and never references. | |||
3258 | // Unresolved using declarations are dependent. | |||
3259 | case Decl::EnumConstant: | |||
3260 | case Decl::UnresolvedUsingValue: | |||
3261 | case Decl::OMPDeclareReduction: | |||
3262 | case Decl::OMPDeclareMapper: | |||
3263 | valueKind = VK_PRValue; | |||
3264 | break; | |||
3265 | ||||
3266 | // Fields and indirect fields that got here must be for | |||
3267 | // pointer-to-member expressions; we just call them l-values for | |||
3268 | // internal consistency, because this subexpression doesn't really | |||
3269 | // exist in the high-level semantics. | |||
3270 | case Decl::Field: | |||
3271 | case Decl::IndirectField: | |||
3272 | case Decl::ObjCIvar: | |||
3273 | 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", 3273, __extension__ __PRETTY_FUNCTION__ )); | |||
3274 | ||||
3275 | // These can't have reference type in well-formed programs, but | |||
3276 | // for internal consistency we do this anyway. | |||
3277 | type = type.getNonReferenceType(); | |||
3278 | valueKind = VK_LValue; | |||
3279 | break; | |||
3280 | ||||
3281 | // Non-type template parameters are either l-values or r-values | |||
3282 | // depending on the type. | |||
3283 | case Decl::NonTypeTemplateParm: { | |||
3284 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { | |||
3285 | type = reftype->getPointeeType(); | |||
3286 | valueKind = VK_LValue; // even if the parameter is an r-value reference | |||
3287 | break; | |||
3288 | } | |||
3289 | ||||
3290 | // [expr.prim.id.unqual]p2: | |||
3291 | // If the entity is a template parameter object for a template | |||
3292 | // parameter of type T, the type of the expression is const T. | |||
3293 | // [...] The expression is an lvalue if the entity is a [...] template | |||
3294 | // parameter object. | |||
3295 | if (type->isRecordType()) { | |||
3296 | type = type.getUnqualifiedType().withConst(); | |||
3297 | valueKind = VK_LValue; | |||
3298 | break; | |||
3299 | } | |||
3300 | ||||
3301 | // For non-references, we need to strip qualifiers just in case | |||
3302 | // the template parameter was declared as 'const int' or whatever. | |||
3303 | valueKind = VK_PRValue; | |||
3304 | type = type.getUnqualifiedType(); | |||
3305 | break; | |||
3306 | } | |||
3307 | ||||
3308 | case Decl::Var: | |||
3309 | case Decl::VarTemplateSpecialization: | |||
3310 | case Decl::VarTemplatePartialSpecialization: | |||
3311 | case Decl::Decomposition: | |||
3312 | case Decl::OMPCapturedExpr: | |||
3313 | // In C, "extern void blah;" is valid and is an r-value. | |||
3314 | if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && | |||
3315 | type->isVoidType()) { | |||
3316 | valueKind = VK_PRValue; | |||
3317 | break; | |||
3318 | } | |||
3319 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
3320 | ||||
3321 | case Decl::ImplicitParam: | |||
3322 | case Decl::ParmVar: { | |||
3323 | // These are always l-values. | |||
3324 | valueKind = VK_LValue; | |||
3325 | type = type.getNonReferenceType(); | |||
3326 | ||||
3327 | // FIXME: Does the addition of const really only apply in | |||
3328 | // potentially-evaluated contexts? Since the variable isn't actually | |||
3329 | // captured in an unevaluated context, it seems that the answer is no. | |||
3330 | if (!isUnevaluatedContext()) { | |||
3331 | QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); | |||
3332 | if (!CapturedType.isNull()) | |||
3333 | type = CapturedType; | |||
3334 | } | |||
3335 | ||||
3336 | break; | |||
3337 | } | |||
3338 | ||||
3339 | case Decl::Binding: { | |||
3340 | // These are always lvalues. | |||
3341 | valueKind = VK_LValue; | |||
3342 | type = type.getNonReferenceType(); | |||
3343 | // FIXME: Support lambda-capture of BindingDecls, once CWG actually | |||
3344 | // decides how that's supposed to work. | |||
3345 | auto *BD = cast<BindingDecl>(VD); | |||
3346 | if (BD->getDeclContext() != CurContext) { | |||
3347 | auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); | |||
3348 | if (DD && DD->hasLocalStorage()) | |||
3349 | diagnoseUncapturableValueReference(*this, Loc, BD); | |||
3350 | } | |||
3351 | break; | |||
3352 | } | |||
3353 | ||||
3354 | case Decl::Function: { | |||
3355 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { | |||
3356 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { | |||
3357 | type = Context.BuiltinFnTy; | |||
3358 | valueKind = VK_PRValue; | |||
3359 | break; | |||
3360 | } | |||
3361 | } | |||
3362 | ||||
3363 | const FunctionType *fty = type->castAs<FunctionType>(); | |||
3364 | ||||
3365 | // If we're referring to a function with an __unknown_anytype | |||
3366 | // result type, make the entire expression __unknown_anytype. | |||
3367 | if (fty->getReturnType() == Context.UnknownAnyTy) { | |||
3368 | type = Context.UnknownAnyTy; | |||
3369 | valueKind = VK_PRValue; | |||
3370 | break; | |||
3371 | } | |||
3372 | ||||
3373 | // Functions are l-values in C++. | |||
3374 | if (getLangOpts().CPlusPlus) { | |||
3375 | valueKind = VK_LValue; | |||
3376 | break; | |||
3377 | } | |||
3378 | ||||
3379 | // C99 DR 316 says that, if a function type comes from a | |||
3380 | // function definition (without a prototype), that type is only | |||
3381 | // used for checking compatibility. Therefore, when referencing | |||
3382 | // the function, we pretend that we don't have the full function | |||
3383 | // type. | |||
3384 | if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) | |||
3385 | type = Context.getFunctionNoProtoType(fty->getReturnType(), | |||
3386 | fty->getExtInfo()); | |||
3387 | ||||
3388 | // Functions are r-values in C. | |||
3389 | valueKind = VK_PRValue; | |||
3390 | break; | |||
3391 | } | |||
3392 | ||||
3393 | case Decl::CXXDeductionGuide: | |||
3394 | llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide" , "clang/lib/Sema/SemaExpr.cpp", 3394); | |||
3395 | ||||
3396 | case Decl::MSProperty: | |||
3397 | case Decl::MSGuid: | |||
3398 | case Decl::TemplateParamObject: | |||
3399 | // FIXME: Should MSGuidDecl and template parameter objects be subject to | |||
3400 | // capture in OpenMP, or duplicated between host and device? | |||
3401 | valueKind = VK_LValue; | |||
3402 | break; | |||
3403 | ||||
3404 | case Decl::CXXMethod: | |||
3405 | // If we're referring to a method with an __unknown_anytype | |||
3406 | // result type, make the entire expression __unknown_anytype. | |||
3407 | // This should only be possible with a type written directly. | |||
3408 | if (const FunctionProtoType *proto = | |||
3409 | dyn_cast<FunctionProtoType>(VD->getType())) | |||
3410 | if (proto->getReturnType() == Context.UnknownAnyTy) { | |||
3411 | type = Context.UnknownAnyTy; | |||
3412 | valueKind = VK_PRValue; | |||
3413 | break; | |||
3414 | } | |||
3415 | ||||
3416 | // C++ methods are l-values if static, r-values if non-static. | |||
3417 | if (cast<CXXMethodDecl>(VD)->isStatic()) { | |||
3418 | valueKind = VK_LValue; | |||
3419 | break; | |||
3420 | } | |||
3421 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
3422 | ||||
3423 | case Decl::CXXConversion: | |||
3424 | case Decl::CXXDestructor: | |||
3425 | case Decl::CXXConstructor: | |||
3426 | valueKind = VK_PRValue; | |||
3427 | break; | |||
3428 | } | |||
3429 | ||||
3430 | return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, | |||
3431 | /*FIXME: TemplateKWLoc*/ SourceLocation(), | |||
3432 | TemplateArgs); | |||
3433 | } | |||
3434 | ||||
3435 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, | |||
3436 | SmallString<32> &Target) { | |||
3437 | Target.resize(CharByteWidth * (Source.size() + 1)); | |||
3438 | char *ResultPtr = &Target[0]; | |||
3439 | const llvm::UTF8 *ErrorPtr; | |||
3440 | bool success = | |||
3441 | llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); | |||
3442 | (void)success; | |||
3443 | assert(success)(static_cast <bool> (success) ? void (0) : __assert_fail ("success", "clang/lib/Sema/SemaExpr.cpp", 3443, __extension__ __PRETTY_FUNCTION__)); | |||
3444 | Target.resize(ResultPtr - &Target[0]); | |||
3445 | } | |||
3446 | ||||
3447 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, | |||
3448 | PredefinedExpr::IdentKind IK) { | |||
3449 | // Pick the current block, lambda, captured statement or function. | |||
3450 | Decl *currentDecl = nullptr; | |||
3451 | if (const BlockScopeInfo *BSI = getCurBlock()) | |||
3452 | currentDecl = BSI->TheDecl; | |||
3453 | else if (const LambdaScopeInfo *LSI = getCurLambda()) | |||
3454 | currentDecl = LSI->CallOperator; | |||
3455 | else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) | |||
3456 | currentDecl = CSI->TheCapturedDecl; | |||
3457 | else | |||
3458 | currentDecl = getCurFunctionOrMethodDecl(); | |||
3459 | ||||
3460 | if (!currentDecl) { | |||
3461 | Diag(Loc, diag::ext_predef_outside_function); | |||
3462 | currentDecl = Context.getTranslationUnitDecl(); | |||
3463 | } | |||
3464 | ||||
3465 | QualType ResTy; | |||
3466 | StringLiteral *SL = nullptr; | |||
3467 | if (cast<DeclContext>(currentDecl)->isDependentContext()) | |||
3468 | ResTy = Context.DependentTy; | |||
3469 | else { | |||
3470 | // Pre-defined identifiers are of type char[x], where x is the length of | |||
3471 | // the string. | |||
3472 | auto Str = PredefinedExpr::ComputeName(IK, currentDecl); | |||
3473 | unsigned Length = Str.length(); | |||
3474 | ||||
3475 | llvm::APInt LengthI(32, Length + 1); | |||
3476 | if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { | |||
3477 | ResTy = | |||
3478 | Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); | |||
3479 | SmallString<32> RawChars; | |||
3480 | ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), | |||
3481 | Str, RawChars); | |||
3482 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | |||
3483 | ArrayType::Normal, | |||
3484 | /*IndexTypeQuals*/ 0); | |||
3485 | SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, | |||
3486 | /*Pascal*/ false, ResTy, Loc); | |||
3487 | } else { | |||
3488 | ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); | |||
3489 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | |||
3490 | ArrayType::Normal, | |||
3491 | /*IndexTypeQuals*/ 0); | |||
3492 | SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, | |||
3493 | /*Pascal*/ false, ResTy, Loc); | |||
3494 | } | |||
3495 | } | |||
3496 | ||||
3497 | return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); | |||
3498 | } | |||
3499 | ||||
3500 | ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, | |||
3501 | SourceLocation LParen, | |||
3502 | SourceLocation RParen, | |||
3503 | TypeSourceInfo *TSI) { | |||
3504 | return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); | |||
3505 | } | |||
3506 | ||||
3507 | ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, | |||
3508 | SourceLocation LParen, | |||
3509 | SourceLocation RParen, | |||
3510 | ParsedType ParsedTy) { | |||
3511 | TypeSourceInfo *TSI = nullptr; | |||
3512 | QualType Ty = GetTypeFromParser(ParsedTy, &TSI); | |||
3513 | ||||
3514 | if (Ty.isNull()) | |||
3515 | return ExprError(); | |||
3516 | if (!TSI) | |||
3517 | TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); | |||
3518 | ||||
3519 | return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); | |||
3520 | } | |||
3521 | ||||
3522 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { | |||
3523 | PredefinedExpr::IdentKind IK; | |||
3524 | ||||
3525 | switch (Kind) { | |||
3526 | default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!" , "clang/lib/Sema/SemaExpr.cpp", 3526); | |||
3527 | case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] | |||
3528 | case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; | |||
3529 | case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] | |||
3530 | case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] | |||
3531 | case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] | |||
3532 | case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] | |||
3533 | case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; | |||
3534 | } | |||
3535 | ||||
3536 | return BuildPredefinedExpr(Loc, IK); | |||
3537 | } | |||
3538 | ||||
3539 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { | |||
3540 | SmallString<16> CharBuffer; | |||
3541 | bool Invalid = false; | |||
3542 | StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); | |||
3543 | if (Invalid) | |||
3544 | return ExprError(); | |||
3545 | ||||
3546 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), | |||
3547 | PP, Tok.getKind()); | |||
3548 | if (Literal.hadError()) | |||
3549 | return ExprError(); | |||
3550 | ||||
3551 | QualType Ty; | |||
3552 | if (Literal.isWide()) | |||
3553 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. | |||
3554 | else if (Literal.isUTF8() && getLangOpts().Char8) | |||
3555 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. | |||
3556 | else if (Literal.isUTF16()) | |||
3557 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. | |||
3558 | else if (Literal.isUTF32()) | |||
3559 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. | |||
3560 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) | |||
3561 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. | |||
3562 | else | |||
3563 | Ty = Context.CharTy; // 'x' -> char in C++ | |||
3564 | ||||
3565 | CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; | |||
3566 | if (Literal.isWide()) | |||
3567 | Kind = CharacterLiteral::Wide; | |||
3568 | else if (Literal.isUTF16()) | |||
3569 | Kind = CharacterLiteral::UTF16; | |||
3570 | else if (Literal.isUTF32()) | |||
3571 | Kind = CharacterLiteral::UTF32; | |||
3572 | else if (Literal.isUTF8()) | |||
3573 | Kind = CharacterLiteral::UTF8; | |||
3574 | ||||
3575 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, | |||
3576 | Tok.getLocation()); | |||
3577 | ||||
3578 | if (Literal.getUDSuffix().empty()) | |||
3579 | return Lit; | |||
3580 | ||||
3581 | // We're building a user-defined literal. | |||
3582 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | |||
3583 | SourceLocation UDSuffixLoc = | |||
3584 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | |||
3585 | ||||
3586 | // Make sure we're allowed user-defined literals here. | |||
3587 | if (!UDLScope) | |||
3588 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); | |||
3589 | ||||
3590 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form | |||
3591 | // operator "" X (ch) | |||
3592 | return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, | |||
3593 | Lit, Tok.getLocation()); | |||
3594 | } | |||
3595 | ||||
3596 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { | |||
3597 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | |||
3598 | return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), | |||
3599 | Context.IntTy, Loc); | |||
3600 | } | |||
3601 | ||||
3602 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, | |||
3603 | QualType Ty, SourceLocation Loc) { | |||
3604 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); | |||
3605 | ||||
3606 | using llvm::APFloat; | |||
3607 | APFloat Val(Format); | |||
3608 | ||||
3609 | APFloat::opStatus result = Literal.GetFloatValue(Val); | |||
3610 | ||||
3611 | // Overflow is always an error, but underflow is only an error if | |||
3612 | // we underflowed to zero (APFloat reports denormals as underflow). | |||
3613 | if ((result & APFloat::opOverflow) || | |||
3614 | ((result & APFloat::opUnderflow) && Val.isZero())) { | |||
3615 | unsigned diagnostic; | |||
3616 | SmallString<20> buffer; | |||
3617 | if (result & APFloat::opOverflow) { | |||
3618 | diagnostic = diag::warn_float_overflow; | |||
3619 | APFloat::getLargest(Format).toString(buffer); | |||
3620 | } else { | |||
3621 | diagnostic = diag::warn_float_underflow; | |||
3622 | APFloat::getSmallest(Format).toString(buffer); | |||
3623 | } | |||
3624 | ||||
3625 | S.Diag(Loc, diagnostic) | |||
3626 | << Ty | |||
3627 | << StringRef(buffer.data(), buffer.size()); | |||
3628 | } | |||
3629 | ||||
3630 | bool isExact = (result == APFloat::opOK); | |||
3631 | return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); | |||
3632 | } | |||
3633 | ||||
3634 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { | |||
3635 | assert(E && "Invalid expression")(static_cast <bool> (E && "Invalid expression") ? void (0) : __assert_fail ("E && \"Invalid expression\"" , "clang/lib/Sema/SemaExpr.cpp", 3635, __extension__ __PRETTY_FUNCTION__ )); | |||
3636 | ||||
3637 | if (E->isValueDependent()) | |||
3638 | return false; | |||
3639 | ||||
3640 | QualType QT = E->getType(); | |||
3641 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { | |||
3642 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; | |||
3643 | return true; | |||
3644 | } | |||
3645 | ||||
3646 | llvm::APSInt ValueAPS; | |||
3647 | ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); | |||
3648 | ||||
3649 | if (R.isInvalid()) | |||
3650 | return true; | |||
3651 | ||||
3652 | bool ValueIsPositive = ValueAPS.isStrictlyPositive(); | |||
3653 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { | |||
3654 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) | |||
3655 | << toString(ValueAPS, 10) << ValueIsPositive; | |||
3656 | return true; | |||
3657 | } | |||
3658 | ||||
3659 | return false; | |||
3660 | } | |||
3661 | ||||
3662 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { | |||
3663 | // Fast path for a single digit (which is quite common). A single digit | |||
3664 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. | |||
3665 | if (Tok.getLength() == 1) { | |||
3666 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); | |||
3667 | return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); | |||
3668 | } | |||
3669 | ||||
3670 | SmallString<128> SpellingBuffer; | |||
3671 | // NumericLiteralParser wants to overread by one character. Add padding to | |||
3672 | // the buffer in case the token is copied to the buffer. If getSpelling() | |||
3673 | // returns a StringRef to the memory buffer, it should have a null char at | |||
3674 | // the EOF, so it is also safe. | |||
3675 | SpellingBuffer.resize(Tok.getLength() + 1); | |||
3676 | ||||
3677 | // Get the spelling of the token, which eliminates trigraphs, etc. | |||
3678 | bool Invalid = false; | |||
3679 | StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); | |||
3680 | if (Invalid) | |||
3681 | return ExprError(); | |||
3682 | ||||
3683 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), | |||
3684 | PP.getSourceManager(), PP.getLangOpts(), | |||
3685 | PP.getTargetInfo(), PP.getDiagnostics()); | |||
3686 | if (Literal.hadError) | |||
3687 | return ExprError(); | |||
3688 | ||||
3689 | if (Literal.hasUDSuffix()) { | |||
3690 | // We're building a user-defined literal. | |||
3691 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | |||
3692 | SourceLocation UDSuffixLoc = | |||
3693 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | |||
3694 | ||||
3695 | // Make sure we're allowed user-defined literals here. | |||
3696 | if (!UDLScope) | |||
3697 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); | |||
3698 | ||||
3699 | QualType CookedTy; | |||
3700 | if (Literal.isFloatingLiteral()) { | |||
3701 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type | |||
3702 | // long double, the literal is treated as a call of the form | |||
3703 | // operator "" X (f L) | |||
3704 | CookedTy = Context.LongDoubleTy; | |||
3705 | } else { | |||
3706 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type | |||
3707 | // unsigned long long, the literal is treated as a call of the form | |||
3708 | // operator "" X (n ULL) | |||
3709 | CookedTy = Context.UnsignedLongLongTy; | |||
3710 | } | |||
3711 | ||||
3712 | DeclarationName OpName = | |||
3713 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | |||
3714 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | |||
3715 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | |||
3716 | ||||
3717 | SourceLocation TokLoc = Tok.getLocation(); | |||
3718 | ||||
3719 | // Perform literal operator lookup to determine if we're building a raw | |||
3720 | // literal or a cooked one. | |||
3721 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | |||
3722 | switch (LookupLiteralOperator(UDLScope, R, CookedTy, | |||
3723 | /*AllowRaw*/ true, /*AllowTemplate*/ true, | |||
3724 | /*AllowStringTemplatePack*/ false, | |||
3725 | /*DiagnoseMissing*/ !Literal.isImaginary)) { | |||
3726 | case LOLR_ErrorNoDiagnostic: | |||
3727 | // Lookup failure for imaginary constants isn't fatal, there's still the | |||
3728 | // GNU extension producing _Complex types. | |||
3729 | break; | |||
3730 | case LOLR_Error: | |||
3731 | return ExprError(); | |||
3732 | case LOLR_Cooked: { | |||
3733 | Expr *Lit; | |||
3734 | if (Literal.isFloatingLiteral()) { | |||
3735 | Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); | |||
3736 | } else { | |||
3737 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); | |||
3738 | if (Literal.GetIntegerValue(ResultVal)) | |||
3739 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | |||
3740 | << /* Unsigned */ 1; | |||
3741 | Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, | |||
3742 | Tok.getLocation()); | |||
3743 | } | |||
3744 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | |||
3745 | } | |||
3746 | ||||
3747 | case LOLR_Raw: { | |||
3748 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the | |||
3749 | // literal is treated as a call of the form | |||
3750 | // operator "" X ("n") | |||
3751 | unsigned Length = Literal.getUDSuffixOffset(); | |||
3752 | QualType StrTy = Context.getConstantArrayType( | |||
3753 | Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), | |||
3754 | llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); | |||
3755 | Expr *Lit = StringLiteral::Create( | |||
3756 | Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, | |||
3757 | /*Pascal*/false, StrTy, &TokLoc, 1); | |||
3758 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | |||
3759 | } | |||
3760 | ||||
3761 | case LOLR_Template: { | |||
3762 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator | |||
3763 | // template), L is treated as a call fo the form | |||
3764 | // operator "" X <'c1', 'c2', ... 'ck'>() | |||
3765 | // where n is the source character sequence c1 c2 ... ck. | |||
3766 | TemplateArgumentListInfo ExplicitArgs; | |||
3767 | unsigned CharBits = Context.getIntWidth(Context.CharTy); | |||
3768 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); | |||
3769 | llvm::APSInt Value(CharBits, CharIsUnsigned); | |||
3770 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { | |||
3771 | Value = TokSpelling[I]; | |||
3772 | TemplateArgument Arg(Context, Value, Context.CharTy); | |||
3773 | TemplateArgumentLocInfo ArgInfo; | |||
3774 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | |||
3775 | } | |||
3776 | return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, | |||
3777 | &ExplicitArgs); | |||
3778 | } | |||
3779 | case LOLR_StringTemplatePack: | |||
3780 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "clang/lib/Sema/SemaExpr.cpp", 3780); | |||
3781 | } | |||
3782 | } | |||
3783 | ||||
3784 | Expr *Res; | |||
3785 | ||||
3786 | if (Literal.isFixedPointLiteral()) { | |||
3787 | QualType Ty; | |||
3788 | ||||
3789 | if (Literal.isAccum) { | |||
3790 | if (Literal.isHalf) { | |||
3791 | Ty = Context.ShortAccumTy; | |||
3792 | } else if (Literal.isLong) { | |||
3793 | Ty = Context.LongAccumTy; | |||
3794 | } else { | |||
3795 | Ty = Context.AccumTy; | |||
3796 | } | |||
3797 | } else if (Literal.isFract) { | |||
3798 | if (Literal.isHalf) { | |||
3799 | Ty = Context.ShortFractTy; | |||
3800 | } else if (Literal.isLong) { | |||
3801 | Ty = Context.LongFractTy; | |||
3802 | } else { | |||
3803 | Ty = Context.FractTy; | |||
3804 | } | |||
3805 | } | |||
3806 | ||||
3807 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); | |||
3808 | ||||
3809 | bool isSigned = !Literal.isUnsigned; | |||
3810 | unsigned scale = Context.getFixedPointScale(Ty); | |||
3811 | unsigned bit_width = Context.getTypeInfo(Ty).Width; | |||
3812 | ||||
3813 | llvm::APInt Val(bit_width, 0, isSigned); | |||
3814 | bool Overflowed = Literal.GetFixedPointValue(Val, scale); | |||
3815 | bool ValIsZero = Val.isZero() && !Overflowed; | |||
3816 | ||||
3817 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); | |||
3818 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) | |||
3819 | // Clause 6.4.4 - The value of a constant shall be in the range of | |||
3820 | // representable values for its type, with exception for constants of a | |||
3821 | // fract type with a value of exactly 1; such a constant shall denote | |||
3822 | // the maximal value for the type. | |||
3823 | --Val; | |||
3824 | else if (Val.ugt(MaxVal) || Overflowed) | |||
3825 | Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); | |||
3826 | ||||
3827 | Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, | |||
3828 | Tok.getLocation(), scale); | |||
3829 | } else if (Literal.isFloatingLiteral()) { | |||
3830 | QualType Ty; | |||
3831 | if (Literal.isHalf){ | |||
3832 | if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) | |||
3833 | Ty = Context.HalfTy; | |||
3834 | else { | |||
3835 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); | |||
3836 | return ExprError(); | |||
3837 | } | |||
3838 | } else if (Literal.isFloat) | |||
3839 | Ty = Context.FloatTy; | |||
3840 | else if (Literal.isLong) | |||
3841 | Ty = Context.LongDoubleTy; | |||
3842 | else if (Literal.isFloat16) | |||
3843 | Ty = Context.Float16Ty; | |||
3844 | else if (Literal.isFloat128) | |||
3845 | Ty = Context.Float128Ty; | |||
3846 | else | |||
3847 | Ty = Context.DoubleTy; | |||
3848 | ||||
3849 | Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); | |||
3850 | ||||
3851 | if (Ty == Context.DoubleTy) { | |||
3852 | if (getLangOpts().SinglePrecisionConstants) { | |||
3853 | if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { | |||
3854 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | |||
3855 | } | |||
3856 | } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( | |||
3857 | "cl_khr_fp64", getLangOpts())) { | |||
3858 | // Impose single-precision float type when cl_khr_fp64 is not enabled. | |||
3859 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) | |||
3860 | << (getLangOpts().getOpenCLCompatibleVersion() >= 300); | |||
3861 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | |||
3862 | } | |||
3863 | } | |||
3864 | } else if (!Literal.isIntegerLiteral()) { | |||
3865 | return ExprError(); | |||
3866 | } else { | |||
3867 | QualType Ty; | |||
3868 | ||||
3869 | // 'long long' is a C99 or C++11 feature. | |||
3870 | if (!getLangOpts().C99 && Literal.isLongLong) { | |||
3871 | if (getLangOpts().CPlusPlus) | |||
3872 | Diag(Tok.getLocation(), | |||
3873 | getLangOpts().CPlusPlus11 ? | |||
3874 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | |||
3875 | else | |||
3876 | Diag(Tok.getLocation(), diag::ext_c99_longlong); | |||
3877 | } | |||
3878 | ||||
3879 | // 'z/uz' literals are a C++2b feature. | |||
3880 | if (Literal.isSizeT) | |||
3881 | Diag(Tok.getLocation(), getLangOpts().CPlusPlus | |||
3882 | ? getLangOpts().CPlusPlus2b | |||
3883 | ? diag::warn_cxx20_compat_size_t_suffix | |||
3884 | : diag::ext_cxx2b_size_t_suffix | |||
3885 | : diag::err_cxx2b_size_t_suffix); | |||
3886 | ||||
3887 | // Get the value in the widest-possible width. | |||
3888 | unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); | |||
3889 | llvm::APInt ResultVal(MaxWidth, 0); | |||
3890 | ||||
3891 | if (Literal.GetIntegerValue(ResultVal)) { | |||
3892 | // If this value didn't fit into uintmax_t, error and force to ull. | |||
3893 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | |||
3894 | << /* Unsigned */ 1; | |||
3895 | Ty = Context.UnsignedLongLongTy; | |||
3896 | 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", 3897, __extension__ __PRETTY_FUNCTION__ )) | |||
3897 | "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", 3897, __extension__ __PRETTY_FUNCTION__ )); | |||
3898 | } else { | |||
3899 | // If this value fits into a ULL, try to figure out what else it fits into | |||
3900 | // according to the rules of C99 6.4.4.1p5. | |||
3901 | ||||
3902 | // Octal, Hexadecimal, and integers with a U suffix are allowed to | |||
3903 | // be an unsigned int. | |||
3904 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; | |||
3905 | ||||
3906 | // Check from smallest to largest, picking the smallest type we can. | |||
3907 | unsigned Width = 0; | |||
3908 | ||||
3909 | // Microsoft specific integer suffixes are explicitly sized. | |||
3910 | if (Literal.MicrosoftInteger) { | |||
3911 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { | |||
3912 | Width = 8; | |||
3913 | Ty = Context.CharTy; | |||
3914 | } else { | |||
3915 | Width = Literal.MicrosoftInteger; | |||
3916 | Ty = Context.getIntTypeForBitwidth(Width, | |||
3917 | /*Signed=*/!Literal.isUnsigned); | |||
3918 | } | |||
3919 | } | |||
3920 | ||||
3921 | // Check C++2b size_t literals. | |||
3922 | if (Literal.isSizeT) { | |||
3923 | 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", 3924, __extension__ __PRETTY_FUNCTION__ )) | |||
3924 | "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", 3924, __extension__ __PRETTY_FUNCTION__ )); | |||
3925 | unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( | |||
3926 | Context.getTargetInfo().getSizeType()); | |||
3927 | ||||
3928 | // Does it fit in size_t? | |||
3929 | if (ResultVal.isIntN(SizeTSize)) { | |||
3930 | // Does it fit in ssize_t? | |||
3931 | if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) | |||
3932 | Ty = Context.getSignedSizeType(); | |||
3933 | else if (AllowUnsigned) | |||
3934 | Ty = Context.getSizeType(); | |||
3935 | Width = SizeTSize; | |||
3936 | } | |||
3937 | } | |||
3938 | ||||
3939 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && | |||
3940 | !Literal.isSizeT) { | |||
3941 | // Are int/unsigned possibilities? | |||
3942 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | |||
3943 | ||||
3944 | // Does it fit in a unsigned int? | |||
3945 | if (ResultVal.isIntN(IntSize)) { | |||
3946 | // Does it fit in a signed int? | |||
3947 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) | |||
3948 | Ty = Context.IntTy; | |||
3949 | else if (AllowUnsigned) | |||
3950 | Ty = Context.UnsignedIntTy; | |||
3951 | Width = IntSize; | |||
3952 | } | |||
3953 | } | |||
3954 | ||||
3955 | // Are long/unsigned long possibilities? | |||
3956 | if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { | |||
3957 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); | |||
3958 | ||||
3959 | // Does it fit in a unsigned long? | |||
3960 | if (ResultVal.isIntN(LongSize)) { | |||
3961 | // Does it fit in a signed long? | |||
3962 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) | |||
3963 | Ty = Context.LongTy; | |||
3964 | else if (AllowUnsigned) | |||
3965 | Ty = Context.UnsignedLongTy; | |||
3966 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 | |||
3967 | // is compatible. | |||
3968 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { | |||
3969 | const unsigned LongLongSize = | |||
3970 | Context.getTargetInfo().getLongLongWidth(); | |||
3971 | Diag(Tok.getLocation(), | |||
3972 | getLangOpts().CPlusPlus | |||
3973 | ? Literal.isLong | |||
3974 | ? diag::warn_old_implicitly_unsigned_long_cxx | |||
3975 | : /*C++98 UB*/ diag:: | |||
3976 | ext_old_implicitly_unsigned_long_cxx | |||
3977 | : diag::warn_old_implicitly_unsigned_long) | |||
3978 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 | |||
3979 | : /*will be ill-formed*/ 1); | |||
3980 | Ty = Context.UnsignedLongTy; | |||
3981 | } | |||
3982 | Width = LongSize; | |||
3983 | } | |||
3984 | } | |||
3985 | ||||
3986 | // Check long long if needed. | |||
3987 | if (Ty.isNull() && !Literal.isSizeT) { | |||
3988 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); | |||
3989 | ||||
3990 | // Does it fit in a unsigned long long? | |||
3991 | if (ResultVal.isIntN(LongLongSize)) { | |||
3992 | // Does it fit in a signed long long? | |||
3993 | // To be compatible with MSVC, hex integer literals ending with the | |||
3994 | // LL or i64 suffix are always signed in Microsoft mode. | |||
3995 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || | |||
3996 | (getLangOpts().MSVCCompat && Literal.isLongLong))) | |||
3997 | Ty = Context.LongLongTy; | |||
3998 | else if (AllowUnsigned) | |||
3999 | Ty = Context.UnsignedLongLongTy; | |||
4000 | Width = LongLongSize; | |||
4001 | } | |||
4002 | } | |||
4003 | ||||
4004 | // If we still couldn't decide a type, we either have 'size_t' literal | |||
4005 | // that is out of range, or a decimal literal that does not fit in a | |||
4006 | // signed long long and has no U suffix. | |||
4007 | if (Ty.isNull()) { | |||
4008 | if (Literal.isSizeT) | |||
4009 | Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) | |||
4010 | << Literal.isUnsigned; | |||
4011 | else | |||
4012 | Diag(Tok.getLocation(), | |||
4013 | diag::ext_integer_literal_too_large_for_signed); | |||
4014 | Ty = Context.UnsignedLongLongTy; | |||
4015 | Width = Context.getTargetInfo().getLongLongWidth(); | |||
4016 | } | |||
4017 | ||||
4018 | if (ResultVal.getBitWidth() != Width) | |||
4019 | ResultVal = ResultVal.trunc(Width); | |||
4020 | } | |||
4021 | Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); | |||
4022 | } | |||
4023 | ||||
4024 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. | |||
4025 | if (Literal.isImaginary) { | |||
4026 | Res = new (Context) ImaginaryLiteral(Res, | |||
4027 | Context.getComplexType(Res->getType())); | |||
4028 | ||||
4029 | Diag(Tok.getLocation(), diag::ext_imaginary_constant); | |||
4030 | } | |||
4031 | return Res; | |||
4032 | } | |||
4033 | ||||
4034 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { | |||
4035 | 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", 4035, __extension__ __PRETTY_FUNCTION__ )); | |||
4036 | QualType ExprTy = E->getType(); | |||
4037 | if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && | |||
4038 | !E->isLValue() && ExprTy->hasFloatingRepresentation()) | |||
4039 | return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); | |||
4040 | return new (Context) ParenExpr(L, R, E); | |||
4041 | } | |||
4042 | ||||
4043 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, | |||
4044 | SourceLocation Loc, | |||
4045 | SourceRange ArgRange) { | |||
4046 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in | |||
4047 | // scalar or vector data type argument..." | |||
4048 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic | |||
4049 | // type (C99 6.2.5p18) or void. | |||
4050 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { | |||
4051 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) | |||
4052 | << T << ArgRange; | |||
4053 | return true; | |||
4054 | } | |||
4055 | ||||
4056 | 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", 4057, __extension__ __PRETTY_FUNCTION__ )) | |||
4057 | "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", 4057, __extension__ __PRETTY_FUNCTION__ )); | |||
4058 | return false; | |||
4059 | } | |||
4060 | ||||
4061 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, | |||
4062 | SourceLocation Loc, | |||
4063 | SourceRange ArgRange, | |||
4064 | UnaryExprOrTypeTrait TraitKind) { | |||
4065 | // Invalid types must be hard errors for SFINAE in C++. | |||
4066 | if (S.LangOpts.CPlusPlus) | |||
4067 | return true; | |||
4068 | ||||
4069 | // C99 6.5.3.4p1: | |||
4070 | if (T->isFunctionType() && | |||
4071 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || | |||
4072 | TraitKind == UETT_PreferredAlignOf)) { | |||
4073 | // sizeof(function)/alignof(function) is allowed as an extension. | |||
4074 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) | |||
4075 | << getTraitSpelling(TraitKind) << ArgRange; | |||
4076 | return false; | |||
4077 | } | |||
4078 | ||||
4079 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where | |||
4080 | // this is an error (OpenCL v1.1 s6.3.k) | |||
4081 | if (T->isVoidType()) { | |||
4082 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type | |||
4083 | : diag::ext_sizeof_alignof_void_type; | |||
4084 | S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; | |||
4085 | return false; | |||
4086 | } | |||
4087 | ||||
4088 | return true; | |||
4089 | } | |||
4090 | ||||
4091 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, | |||
4092 | SourceLocation Loc, | |||
4093 | SourceRange ArgRange, | |||
4094 | UnaryExprOrTypeTrait TraitKind) { | |||
4095 | // Reject sizeof(interface) and sizeof(interface<proto>) if the | |||
4096 | // runtime doesn't allow it. | |||
4097 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { | |||
4098 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) | |||
4099 | << T << (TraitKind == UETT_SizeOf) | |||
4100 | << ArgRange; | |||
4101 | return true; | |||
4102 | } | |||
4103 | ||||
4104 | return false; | |||
4105 | } | |||
4106 | ||||
4107 | /// Check whether E is a pointer from a decayed array type (the decayed | |||
4108 | /// pointer type is equal to T) and emit a warning if it is. | |||
4109 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, | |||
4110 | Expr *E) { | |||
4111 | // Don't warn if the operation changed the type. | |||
4112 | if (T != E->getType()) | |||
4113 | return; | |||
4114 | ||||
4115 | // Now look for array decays. | |||
4116 | ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); | |||
4117 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) | |||
4118 | return; | |||
4119 | ||||
4120 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() | |||
4121 | << ICE->getType() | |||
4122 | << ICE->getSubExpr()->getType(); | |||
4123 | } | |||
4124 | ||||
4125 | /// Check the constraints on expression operands to unary type expression | |||
4126 | /// and type traits. | |||
4127 | /// | |||
4128 | /// Completes any types necessary and validates the constraints on the operand | |||
4129 | /// expression. The logic mostly mirrors the type-based overload, but may modify | |||
4130 | /// the expression as it completes the type for that expression through template | |||
4131 | /// instantiation, etc. | |||
4132 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, | |||
4133 | UnaryExprOrTypeTrait ExprKind) { | |||
4134 | QualType ExprTy = E->getType(); | |||
4135 | assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void (0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp" , 4135, __extension__ __PRETTY_FUNCTION__)); | |||
4136 | ||||
4137 | bool IsUnevaluatedOperand = | |||
4138 | (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || | |||
4139 | ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); | |||
4140 | if (IsUnevaluatedOperand) { | |||
4141 | ExprResult Result = CheckUnevaluatedOperand(E); | |||
4142 | if (Result.isInvalid()) | |||
4143 | return true; | |||
4144 | E = Result.get(); | |||
4145 | } | |||
4146 | ||||
4147 | // The operand for sizeof and alignof is in an unevaluated expression context, | |||
4148 | // so side effects could result in unintended consequences. | |||
4149 | // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes | |||
4150 | // used to build SFINAE gadgets. | |||
4151 | // FIXME: Should we consider instantiation-dependent operands to 'alignof'? | |||
4152 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && | |||
4153 | !E->isInstantiationDependent() && | |||
4154 | E->HasSideEffects(Context, false)) | |||
4155 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | |||
4156 | ||||
4157 | if (ExprKind == UETT_VecStep) | |||
4158 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), | |||
4159 | E->getSourceRange()); | |||
4160 | ||||
4161 | // Explicitly list some types as extensions. | |||
4162 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), | |||
4163 | E->getSourceRange(), ExprKind)) | |||
4164 | return false; | |||
4165 | ||||
4166 | // 'alignof' applied to an expression only requires the base element type of | |||
4167 | // the expression to be complete. 'sizeof' requires the expression's type to | |||
4168 | // be complete (and will attempt to complete it if it's an array of unknown | |||
4169 | // bound). | |||
4170 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | |||
4171 | if (RequireCompleteSizedType( | |||
4172 | E->getExprLoc(), Context.getBaseElementType(E->getType()), | |||
4173 | diag::err_sizeof_alignof_incomplete_or_sizeless_type, | |||
4174 | getTraitSpelling(ExprKind), E->getSourceRange())) | |||
4175 | return true; | |||
4176 | } else { | |||
4177 | if (RequireCompleteSizedExprType( | |||
4178 | E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | |||
4179 | getTraitSpelling(ExprKind), E->getSourceRange())) | |||
4180 | return true; | |||
4181 | } | |||
4182 | ||||
4183 | // Completing the expression's type may have changed it. | |||
4184 | ExprTy = E->getType(); | |||
4185 | assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void (0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp" , 4185, __extension__ __PRETTY_FUNCTION__)); | |||
4186 | ||||
4187 | if (ExprTy->isFunctionType()) { | |||
4188 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) | |||
4189 | << getTraitSpelling(ExprKind) << E->getSourceRange(); | |||
4190 | return true; | |||
4191 | } | |||
4192 | ||||
4193 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), | |||
4194 | E->getSourceRange(), ExprKind)) | |||
4195 | return true; | |||
4196 | ||||
4197 | if (ExprKind == UETT_SizeOf) { | |||
4198 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | |||
4199 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { | |||
4200 | QualType OType = PVD->getOriginalType(); | |||
4201 | QualType Type = PVD->getType(); | |||
4202 | if (Type->isPointerType() && OType->isArrayType()) { | |||
4203 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) | |||
4204 | << Type << OType; | |||
4205 | Diag(PVD->getLocation(), diag::note_declared_at); | |||
4206 | } | |||
4207 | } | |||
4208 | } | |||
4209 | ||||
4210 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array | |||
4211 | // decays into a pointer and returns an unintended result. This is most | |||
4212 | // likely a typo for "sizeof(array) op x". | |||
4213 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { | |||
4214 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | |||
4215 | BO->getLHS()); | |||
4216 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | |||
4217 | BO->getRHS()); | |||
4218 | } | |||
4219 | } | |||
4220 | ||||
4221 | return false; | |||
4222 | } | |||
4223 | ||||
4224 | /// Check the constraints on operands to unary expression and type | |||
4225 | /// traits. | |||
4226 | /// | |||
4227 | /// This will complete any types necessary, and validate the various constraints | |||
4228 | /// on those operands. | |||
4229 | /// | |||
4230 | /// The UsualUnaryConversions() function is *not* called by this routine. | |||
4231 | /// C99 6.3.2.1p[2-4] all state: | |||
4232 | /// Except when it is the operand of the sizeof operator ... | |||
4233 | /// | |||
4234 | /// C++ [expr.sizeof]p4 | |||
4235 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer | |||
4236 | /// standard conversions are not applied to the operand of sizeof. | |||
4237 | /// | |||
4238 | /// This policy is followed for all of the unary trait expressions. | |||
4239 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, | |||
4240 | SourceLocation OpLoc, | |||
4241 | SourceRange ExprRange, | |||
4242 | UnaryExprOrTypeTrait ExprKind) { | |||
4243 | if (ExprType->isDependentType()) | |||
4244 | return false; | |||
4245 | ||||
4246 | // C++ [expr.sizeof]p2: | |||
4247 | // When applied to a reference or a reference type, the result | |||
4248 | // is the size of the referenced type. | |||
4249 | // C++11 [expr.alignof]p3: | |||
4250 | // When alignof is applied to a reference type, the result | |||
4251 | // shall be the alignment of the referenced type. | |||
4252 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) | |||
4253 | ExprType = Ref->getPointeeType(); | |||
4254 | ||||
4255 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: | |||
4256 | // When alignof or _Alignof is applied to an array type, the result | |||
4257 | // is the alignment of the element type. | |||
4258 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || | |||
4259 | ExprKind == UETT_OpenMPRequiredSimdAlign) | |||
4260 | ExprType = Context.getBaseElementType(ExprType); | |||
4261 | ||||
4262 | if (ExprKind == UETT_VecStep) | |||
4263 | return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); | |||
4264 | ||||
4265 | // Explicitly list some types as extensions. | |||
4266 | if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, | |||
4267 | ExprKind)) | |||
4268 | return false; | |||
4269 | ||||
4270 | if (RequireCompleteSizedType( | |||
4271 | OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | |||
4272 | getTraitSpelling(ExprKind), ExprRange)) | |||
4273 | return true; | |||
4274 | ||||
4275 | if (ExprType->isFunctionType()) { | |||
4276 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) | |||
4277 | << getTraitSpelling(ExprKind) << ExprRange; | |||
4278 | return true; | |||
4279 | } | |||
4280 | ||||
4281 | if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, | |||
4282 | ExprKind)) | |||
4283 | return true; | |||
4284 | ||||
4285 | return false; | |||
4286 | } | |||
4287 | ||||
4288 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { | |||
4289 | // Cannot know anything else if the expression is dependent. | |||
4290 | if (E->isTypeDependent()) | |||
4291 | return false; | |||
4292 | ||||
4293 | if (E->getObjectKind() == OK_BitField) { | |||
4294 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) | |||
4295 | << 1 << E->getSourceRange(); | |||
4296 | return true; | |||
4297 | } | |||
4298 | ||||
4299 | ValueDecl *D = nullptr; | |||
4300 | Expr *Inner = E->IgnoreParens(); | |||
4301 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { | |||
4302 | D = DRE->getDecl(); | |||
4303 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { | |||
4304 | D = ME->getMemberDecl(); | |||
4305 | } | |||
4306 | ||||
4307 | // If it's a field, require the containing struct to have a | |||
4308 | // complete definition so that we can compute the layout. | |||
4309 | // | |||
4310 | // This can happen in C++11 onwards, either by naming the member | |||
4311 | // in a way that is not transformed into a member access expression | |||
4312 | // (in an unevaluated operand, for instance), or by naming the member | |||
4313 | // in a trailing-return-type. | |||
4314 | // | |||
4315 | // For the record, since __alignof__ on expressions is a GCC | |||
4316 | // extension, GCC seems to permit this but always gives the | |||
4317 | // nonsensical answer 0. | |||
4318 | // | |||
4319 | // We don't really need the layout here --- we could instead just | |||
4320 | // directly check for all the appropriate alignment-lowing | |||
4321 | // attributes --- but that would require duplicating a lot of | |||
4322 | // logic that just isn't worth duplicating for such a marginal | |||
4323 | // use-case. | |||
4324 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { | |||
4325 | // Fast path this check, since we at least know the record has a | |||
4326 | // definition if we can find a member of it. | |||
4327 | if (!FD->getParent()->isCompleteDefinition()) { | |||
4328 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) | |||
4329 | << E->getSourceRange(); | |||
4330 | return true; | |||
4331 | } | |||
4332 | ||||
4333 | // Otherwise, if it's a field, and the field doesn't have | |||
4334 | // reference type, then it must have a complete type (or be a | |||
4335 | // flexible array member, which we explicitly want to | |||
4336 | // white-list anyway), which makes the following checks trivial. | |||
4337 | if (!FD->getType()->isReferenceType()) | |||
4338 | return false; | |||
4339 | } | |||
4340 | ||||
4341 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); | |||
4342 | } | |||
4343 | ||||
4344 | bool Sema::CheckVecStepExpr(Expr *E) { | |||
4345 | E = E->IgnoreParens(); | |||
4346 | ||||
4347 | // Cannot know anything else if the expression is dependent. | |||
4348 | if (E->isTypeDependent()) | |||
4349 | return false; | |||
4350 | ||||
4351 | return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); | |||
4352 | } | |||
4353 | ||||
4354 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, | |||
4355 | CapturingScopeInfo *CSI) { | |||
4356 | assert(T->isVariablyModifiedType())(static_cast <bool> (T->isVariablyModifiedType()) ? void (0) : __assert_fail ("T->isVariablyModifiedType()", "clang/lib/Sema/SemaExpr.cpp" , 4356, __extension__ __PRETTY_FUNCTION__)); | |||
4357 | assert(CSI != nullptr)(static_cast <bool> (CSI != nullptr) ? void (0) : __assert_fail ("CSI != nullptr", "clang/lib/Sema/SemaExpr.cpp", 4357, __extension__ __PRETTY_FUNCTION__)); | |||
4358 | ||||
4359 | // We're going to walk down into the type and look for VLA expressions. | |||
4360 | do { | |||
4361 | const Type *Ty = T.getTypePtr(); | |||
4362 | switch (Ty->getTypeClass()) { | |||
4363 | #define TYPE(Class, Base) | |||
4364 | #define ABSTRACT_TYPE(Class, Base) | |||
4365 | #define NON_CANONICAL_TYPE(Class, Base) | |||
4366 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: | |||
4367 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) | |||
4368 | #include "clang/AST/TypeNodes.inc" | |||
4369 | T = QualType(); | |||
4370 | break; | |||
4371 | // These types are never variably-modified. | |||
4372 | case Type::Builtin: | |||
4373 | case Type::Complex: | |||
4374 | case Type::Vector: | |||
4375 | case Type::ExtVector: | |||
4376 | case Type::ConstantMatrix: | |||
4377 | case Type::Record: | |||
4378 | case Type::Enum: | |||
4379 | case Type::Elaborated: | |||
4380 | case Type::TemplateSpecialization: | |||
4381 | case Type::ObjCObject: | |||
4382 | case Type::ObjCInterface: | |||
4383 | case Type::ObjCObjectPointer: | |||
4384 | case Type::ObjCTypeParam: | |||
4385 | case Type::Pipe: | |||
4386 | case Type::BitInt: | |||
4387 | llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!" , "clang/lib/Sema/SemaExpr.cpp", 4387); | |||
4388 | case Type::Adjusted: | |||
4389 | T = cast<AdjustedType>(Ty)->getOriginalType(); | |||
4390 | break; | |||
4391 | case Type::Decayed: | |||
4392 | T = cast<DecayedType>(Ty)->getPointeeType(); | |||
4393 | break; | |||
4394 | case Type::Pointer: | |||
4395 | T = cast<PointerType>(Ty)->getPointeeType(); | |||
4396 | break; | |||
4397 | case Type::BlockPointer: | |||
4398 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | |||
4399 | break; | |||
4400 | case Type::LValueReference: | |||
4401 | case Type::RValueReference: | |||
4402 | T = cast<ReferenceType>(Ty)->getPointeeType(); | |||
4403 | break; | |||
4404 | case Type::MemberPointer: | |||
4405 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | |||
4406 | break; | |||
4407 | case Type::ConstantArray: | |||
4408 | case Type::IncompleteArray: | |||
4409 | // Losing element qualification here is fine. | |||
4410 | T = cast<ArrayType>(Ty)->getElementType(); | |||
4411 | break; | |||
4412 | case Type::VariableArray: { | |||
4413 | // Losing element qualification here is fine. | |||
4414 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); | |||
4415 | ||||
4416 | // Unknown size indication requires no size computation. | |||
4417 | // Otherwise, evaluate and record it. | |||
4418 | auto Size = VAT->getSizeExpr(); | |||
4419 | if (Size && !CSI->isVLATypeCaptured(VAT) && | |||
4420 | (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) | |||
4421 | CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); | |||
4422 | ||||
4423 | T = VAT->getElementType(); | |||
4424 | break; | |||
4425 | } | |||
4426 | case Type::FunctionProto: | |||
4427 | case Type::FunctionNoProto: | |||
4428 | T = cast<FunctionType>(Ty)->getReturnType(); | |||
4429 | break; | |||
4430 | case Type::Paren: | |||
4431 | case Type::TypeOf: | |||
4432 | case Type::UnaryTransform: | |||
4433 | case Type::Attributed: | |||
4434 | case Type::SubstTemplateTypeParm: | |||
4435 | case Type::MacroQualified: | |||
4436 | // Keep walking after single level desugaring. | |||
4437 | T = T.getSingleStepDesugaredType(Context); | |||
4438 | break; | |||
4439 | case Type::Typedef: | |||
4440 | T = cast<TypedefType>(Ty)->desugar(); | |||
4441 | break; | |||
4442 | case Type::Decltype: | |||
4443 | T = cast<DecltypeType>(Ty)->desugar(); | |||
4444 | break; | |||
4445 | case Type::Using: | |||
4446 | T = cast<UsingType>(Ty)->desugar(); | |||
4447 | break; | |||
4448 | case Type::Auto: | |||
4449 | case Type::DeducedTemplateSpecialization: | |||
4450 | T = cast<DeducedType>(Ty)->getDeducedType(); | |||
4451 | break; | |||
4452 | case Type::TypeOfExpr: | |||
4453 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); | |||
4454 | break; | |||
4455 | case Type::Atomic: | |||
4456 | T = cast<AtomicType>(Ty)->getValueType(); | |||
4457 | break; | |||
4458 | } | |||
4459 | } while (!T.isNull() && T->isVariablyModifiedType()); | |||
4460 | } | |||
4461 | ||||
4462 | /// Build a sizeof or alignof expression given a type operand. | |||
4463 | ExprResult | |||
4464 | Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, | |||
4465 | SourceLocation OpLoc, | |||
4466 | UnaryExprOrTypeTrait ExprKind, | |||
4467 | SourceRange R) { | |||
4468 | if (!TInfo) | |||
4469 | return ExprError(); | |||
4470 | ||||
4471 | QualType T = TInfo->getType(); | |||
4472 | ||||
4473 | if (!T->isDependentType() && | |||
4474 | CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) | |||
4475 | return ExprError(); | |||
4476 | ||||
4477 | if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { | |||
4478 | if (auto *TT = T->getAs<TypedefType>()) { | |||
4479 | for (auto I = FunctionScopes.rbegin(), | |||
4480 | E = std::prev(FunctionScopes.rend()); | |||
4481 | I != E; ++I) { | |||
4482 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | |||
4483 | if (CSI == nullptr) | |||
4484 | break; | |||
4485 | DeclContext *DC = nullptr; | |||
4486 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | |||
4487 | DC = LSI->CallOperator; | |||
4488 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | |||
4489 | DC = CRSI->TheCapturedDecl; | |||
4490 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | |||
4491 | DC = BSI->TheDecl; | |||
4492 | if (DC) { | |||
4493 | if (DC->containsDecl(TT->getDecl())) | |||
4494 | break; | |||
4495 | captureVariablyModifiedType(Context, T, CSI); | |||
4496 | } | |||
4497 | } | |||
4498 | } | |||
4499 | } | |||
4500 | ||||
4501 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | |||
4502 | if (isUnevaluatedContext() && ExprKind == UETT_SizeOf && | |||
4503 | TInfo->getType()->isVariablyModifiedType()) | |||
4504 | TInfo = TransformToPotentiallyEvaluated(TInfo); | |||
4505 | ||||
4506 | return new (Context) UnaryExprOrTypeTraitExpr( | |||
4507 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); | |||
4508 | } | |||
4509 | ||||
4510 | /// Build a sizeof or alignof expression given an expression | |||
4511 | /// operand. | |||
4512 | ExprResult | |||
4513 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, | |||
4514 | UnaryExprOrTypeTrait ExprKind) { | |||
4515 | ExprResult PE = CheckPlaceholderExpr(E); | |||
4516 | if (PE.isInvalid()) | |||
4517 | return ExprError(); | |||
4518 | ||||
4519 | E = PE.get(); | |||
4520 | ||||
4521 | // Verify that the operand is valid. | |||
4522 | bool isInvalid = false; | |||
4523 | if (E->isTypeDependent()) { | |||
4524 | // Delay type-checking for type-dependent expressions. | |||
4525 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | |||
4526 | isInvalid = CheckAlignOfExpr(*this, E, ExprKind); | |||
4527 | } else if (ExprKind == UETT_VecStep) { | |||
4528 | isInvalid = CheckVecStepExpr(E); | |||
4529 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { | |||
4530 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); | |||
4531 | isInvalid = true; | |||
4532 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. | |||
4533 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; | |||
4534 | isInvalid = true; | |||
4535 | } else { | |||
4536 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); | |||
4537 | } | |||
4538 | ||||
4539 | if (isInvalid) | |||
4540 | return ExprError(); | |||
4541 | ||||
4542 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { | |||
4543 | PE = TransformToPotentiallyEvaluated(E); | |||
4544 | if (PE.isInvalid()) return ExprError(); | |||
4545 | E = PE.get(); | |||
4546 | } | |||
4547 | ||||
4548 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | |||
4549 | return new (Context) UnaryExprOrTypeTraitExpr( | |||
4550 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); | |||
4551 | } | |||
4552 | ||||
4553 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c | |||
4554 | /// expr and the same for @c alignof and @c __alignof | |||
4555 | /// Note that the ArgRange is invalid if isType is false. | |||
4556 | ExprResult | |||
4557 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, | |||
4558 | UnaryExprOrTypeTrait ExprKind, bool IsType, | |||
4559 | void *TyOrEx, SourceRange ArgRange) { | |||
4560 | // If error parsing type, ignore. | |||
4561 | if (!TyOrEx) return ExprError(); | |||
4562 | ||||
4563 | if (IsType) { | |||
4564 | TypeSourceInfo *TInfo; | |||
4565 | (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); | |||
4566 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); | |||
4567 | } | |||
4568 | ||||
4569 | Expr *ArgEx = (Expr *)TyOrEx; | |||
4570 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); | |||
4571 | return Result; | |||
4572 | } | |||
4573 | ||||
4574 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, | |||
4575 | bool IsReal) { | |||
4576 | if (V.get()->isTypeDependent()) | |||
4577 | return S.Context.DependentTy; | |||
4578 | ||||
4579 | // _Real and _Imag are only l-values for normal l-values. | |||
4580 | if (V.get()->getObjectKind() != OK_Ordinary) { | |||
4581 | V = S.DefaultLvalueConversion(V.get()); | |||
4582 | if (V.isInvalid()) | |||
4583 | return QualType(); | |||
4584 | } | |||
4585 | ||||
4586 | // These operators return the element type of a complex type. | |||
4587 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) | |||
4588 | return CT->getElementType(); | |||
4589 | ||||
4590 | // Otherwise they pass through real integer and floating point types here. | |||
4591 | if (V.get()->getType()->isArithmeticType()) | |||
4592 | return V.get()->getType(); | |||
4593 | ||||
4594 | // Test for placeholders. | |||
4595 | ExprResult PR = S.CheckPlaceholderExpr(V.get()); | |||
4596 | if (PR.isInvalid()) return QualType(); | |||
4597 | if (PR.get() != V.get()) { | |||
4598 | V = PR; | |||
4599 | return CheckRealImagOperand(S, V, Loc, IsReal); | |||
4600 | } | |||
4601 | ||||
4602 | // Reject anything else. | |||
4603 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() | |||
4604 | << (IsReal ? "__real" : "__imag"); | |||
4605 | return QualType(); | |||
4606 | } | |||
4607 | ||||
4608 | ||||
4609 | ||||
4610 | ExprResult | |||
4611 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, | |||
4612 | tok::TokenKind Kind, Expr *Input) { | |||
4613 | UnaryOperatorKind Opc; | |||
4614 | switch (Kind) { | |||
4615 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp" , 4615); | |||
4616 | case tok::plusplus: Opc = UO_PostInc; break; | |||
4617 | case tok::minusminus: Opc = UO_PostDec; break; | |||
4618 | } | |||
4619 | ||||
4620 | // Since this might is a postfix expression, get rid of ParenListExprs. | |||
4621 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); | |||
4622 | if (Result.isInvalid()) return ExprError(); | |||
4623 | Input = Result.get(); | |||
4624 | ||||
4625 | return BuildUnaryOp(S, OpLoc, Opc, Input); | |||
4626 | } | |||
4627 | ||||
4628 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. | |||
4629 | /// | |||
4630 | /// \return true on error | |||
4631 | static bool checkArithmeticOnObjCPointer(Sema &S, | |||
4632 | SourceLocation opLoc, | |||
4633 | Expr *op) { | |||
4634 | assert(op->getType()->isObjCObjectPointerType())(static_cast <bool> (op->getType()->isObjCObjectPointerType ()) ? void (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 4634, __extension__ __PRETTY_FUNCTION__ )); | |||
4635 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && | |||
4636 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) | |||
4637 | return false; | |||
4638 | ||||
4639 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) | |||
4640 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() | |||
4641 | << op->getSourceRange(); | |||
4642 | return true; | |||
4643 | } | |||
4644 | ||||
4645 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { | |||
4646 | auto *BaseNoParens = Base->IgnoreParens(); | |||
4647 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) | |||
4648 | return MSProp->getPropertyDecl()->getType()->isArrayType(); | |||
4649 | return isa<MSPropertySubscriptExpr>(BaseNoParens); | |||
4650 | } | |||
4651 | ||||
4652 | // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. | |||
4653 | // Typically this is DependentTy, but can sometimes be more precise. | |||
4654 | // | |||
4655 | // There are cases when we could determine a non-dependent type: | |||
4656 | // - LHS and RHS may have non-dependent types despite being type-dependent | |||
4657 | // (e.g. unbounded array static members of the current instantiation) | |||
4658 | // - one may be a dependent-sized array with known element type | |||
4659 | // - one may be a dependent-typed valid index (enum in current instantiation) | |||
4660 | // | |||
4661 | // We *always* return a dependent type, in such cases it is DependentTy. | |||
4662 | // This avoids creating type-dependent expressions with non-dependent types. | |||
4663 | // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 | |||
4664 | static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, | |||
4665 | const ASTContext &Ctx) { | |||
4666 | 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", 4666, __extension__ __PRETTY_FUNCTION__ )); | |||
4667 | QualType LTy = LHS->getType(), RTy = RHS->getType(); | |||
4668 | QualType Result = Ctx.DependentTy; | |||
4669 | if (RTy->isIntegralOrUnscopedEnumerationType()) { | |||
4670 | if (const PointerType *PT = LTy->getAs<PointerType>()) | |||
4671 | Result = PT->getPointeeType(); | |||
4672 | else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) | |||
4673 | Result = AT->getElementType(); | |||
4674 | } else if (LTy->isIntegralOrUnscopedEnumerationType()) { | |||
4675 | if (const PointerType *PT = RTy->getAs<PointerType>()) | |||
4676 | Result = PT->getPointeeType(); | |||
4677 | else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) | |||
4678 | Result = AT->getElementType(); | |||
4679 | } | |||
4680 | // Ensure we return a dependent type. | |||
4681 | return Result->isDependentType() ? Result : Ctx.DependentTy; | |||
4682 | } | |||
4683 | ||||
4684 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args); | |||
4685 | ||||
4686 | ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, | |||
4687 | SourceLocation lbLoc, | |||
4688 | MultiExprArg ArgExprs, | |||
4689 | SourceLocation rbLoc) { | |||
4690 | ||||
4691 | if (base && !base->getType().isNull() && | |||
4692 | base->hasPlaceholderType(BuiltinType::OMPArraySection)) | |||
4693 | return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(), | |||
4694 | SourceLocation(), /*Length*/ nullptr, | |||
4695 | /*Stride=*/nullptr, rbLoc); | |||
4696 | ||||
4697 | // Since this might be a postfix expression, get rid of ParenListExprs. | |||
4698 | if (isa<ParenListExpr>(base)) { | |||
4699 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); | |||
4700 | if (result.isInvalid()) | |||
4701 | return ExprError(); | |||
4702 | base = result.get(); | |||
4703 | } | |||
4704 | ||||
4705 | // Check if base and idx form a MatrixSubscriptExpr. | |||
4706 | // | |||
4707 | // Helper to check for comma expressions, which are not allowed as indices for | |||
4708 | // matrix subscript expressions. | |||
4709 | auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { | |||
4710 | if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { | |||
4711 | Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) | |||
4712 | << SourceRange(base->getBeginLoc(), rbLoc); | |||
4713 | return true; | |||
4714 | } | |||
4715 | return false; | |||
4716 | }; | |||
4717 | // The matrix subscript operator ([][])is considered a single operator. | |||
4718 | // Separating the index expressions by parenthesis is not allowed. | |||
4719 | if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) && | |||
4720 | !isa<MatrixSubscriptExpr>(base)) { | |||
4721 | Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) | |||
4722 | << SourceRange(base->getBeginLoc(), rbLoc); | |||
4723 | return ExprError(); | |||
4724 | } | |||
4725 | // If the base is a MatrixSubscriptExpr, try to create a new | |||
4726 | // MatrixSubscriptExpr. | |||
4727 | auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); | |||
4728 | if (matSubscriptE) { | |||
4729 | assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) : __assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp" , 4729, __extension__ __PRETTY_FUNCTION__)); | |||
4730 | if (CheckAndReportCommaError(ArgExprs.front())) | |||
4731 | return ExprError(); | |||
4732 | ||||
4733 | 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", 4734, __extension__ __PRETTY_FUNCTION__ )) | |||
4734 | "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", 4734, __extension__ __PRETTY_FUNCTION__ )); | |||
4735 | return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(), | |||
4736 | matSubscriptE->getRowIdx(), | |||
4737 | ArgExprs.front(), rbLoc); | |||
4738 | } | |||
4739 | ||||
4740 | // Handle any non-overload placeholder types in the base and index | |||
4741 | // expressions. We can't handle overloads here because the other | |||
4742 | // operand might be an overloadable type, in which case the overload | |||
4743 | // resolution for the operator overload should get the first crack | |||
4744 | // at the overload. | |||
4745 | bool IsMSPropertySubscript = false; | |||
4746 | if (base->getType()->isNonOverloadPlaceholderType()) { | |||
4747 | IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); | |||
4748 | if (!IsMSPropertySubscript) { | |||
4749 | ExprResult result = CheckPlaceholderExpr(base); | |||
4750 | if (result.isInvalid()) | |||
4751 | return ExprError(); | |||
4752 | base = result.get(); | |||
4753 | } | |||
4754 | } | |||
4755 | ||||
4756 | // If the base is a matrix type, try to create a new MatrixSubscriptExpr. | |||
4757 | if (base->getType()->isMatrixType()) { | |||
4758 | assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) : __assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp" , 4758, __extension__ __PRETTY_FUNCTION__)); | |||
4759 | if (CheckAndReportCommaError(ArgExprs.front())) | |||
4760 | return ExprError(); | |||
4761 | ||||
4762 | return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr, | |||
4763 | rbLoc); | |||
4764 | } | |||
4765 | ||||
4766 | if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { | |||
4767 | Expr *idx = ArgExprs[0]; | |||
4768 | if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || | |||
4769 | (isa<CXXOperatorCallExpr>(idx) && | |||
4770 | cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) { | |||
4771 | Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) | |||
4772 | << SourceRange(base->getBeginLoc(), rbLoc); | |||
4773 | } | |||
4774 | } | |||
4775 | ||||
4776 | if (ArgExprs.size() == 1 && | |||
4777 | ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { | |||
4778 | ExprResult result = CheckPlaceholderExpr(ArgExprs[0]); | |||
4779 | if (result.isInvalid()) | |||
4780 | return ExprError(); | |||
4781 | ArgExprs[0] = result.get(); | |||
4782 | } else { | |||
4783 | if (checkArgsForPlaceholders(*this, ArgExprs)) | |||
4784 | return ExprError(); | |||
4785 | } | |||
4786 | ||||
4787 | // Build an unanalyzed expression if either operand is type-dependent. | |||
4788 | if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && | |||
4789 | (base->isTypeDependent() || | |||
4790 | Expr::hasAnyTypeDependentArguments(ArgExprs))) { | |||
4791 | return new (Context) ArraySubscriptExpr( | |||
4792 | base, ArgExprs.front(), | |||
4793 | getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()), | |||
4794 | VK_LValue, OK_Ordinary, rbLoc); | |||
4795 | } | |||
4796 | ||||
4797 | // MSDN, property (C++) | |||
4798 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx | |||
4799 | // This attribute can also be used in the declaration of an empty array in a | |||
4800 | // class or structure definition. For example: | |||
4801 | // __declspec(property(get=GetX, put=PutX)) int x[]; | |||
4802 | // The above statement indicates that x[] can be used with one or more array | |||
4803 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), | |||
4804 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); | |||
4805 | if (IsMSPropertySubscript) { | |||
4806 | assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) : __assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp" , 4806, __extension__ __PRETTY_FUNCTION__)); | |||
4807 | // Build MS property subscript expression if base is MS property reference | |||
4808 | // or MS property subscript. | |||
4809 | return new (Context) | |||
4810 | MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, | |||
4811 | VK_LValue, OK_Ordinary, rbLoc); | |||
4812 | } | |||
4813 | ||||
4814 | // Use C++ overloaded-operator rules if either operand has record | |||
4815 | // type. The spec says to do this if either type is *overloadable*, | |||
4816 | // but enum types can't declare subscript operators or conversion | |||
4817 | // operators, so there's nothing interesting for overload resolution | |||
4818 | // to do if there aren't any record types involved. | |||
4819 | // | |||
4820 | // ObjC pointers have their own subscripting logic that is not tied | |||
4821 | // to overload resolution and so should not take this path. | |||
4822 | if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && | |||
4823 | ((base->getType()->isRecordType() || | |||
4824 | (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) { | |||
4825 | return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs); | |||
4826 | } | |||
4827 | ||||
4828 | ExprResult Res = | |||
4829 | CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc); | |||
4830 | ||||
4831 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) | |||
4832 | CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); | |||
4833 | ||||
4834 | return Res; | |||
4835 | } | |||
4836 | ||||
4837 | ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { | |||
4838 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); | |||
4839 | InitializationKind Kind = | |||
4840 | InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); | |||
4841 | InitializationSequence InitSeq(*this, Entity, Kind, E); | |||
4842 | return InitSeq.Perform(*this, Entity, Kind, E); | |||
4843 | } | |||
4844 | ||||
4845 | ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, | |||
4846 | Expr *ColumnIdx, | |||
4847 | SourceLocation RBLoc) { | |||
4848 | ExprResult BaseR = CheckPlaceholderExpr(Base); | |||
4849 | if (BaseR.isInvalid()) | |||
4850 | return BaseR; | |||
4851 | Base = BaseR.get(); | |||
4852 | ||||
4853 | ExprResult RowR = CheckPlaceholderExpr(RowIdx); | |||
4854 | if (RowR.isInvalid()) | |||
4855 | return RowR; | |||
4856 | RowIdx = RowR.get(); | |||
4857 | ||||
4858 | if (!ColumnIdx) | |||
4859 | return new (Context) MatrixSubscriptExpr( | |||
4860 | Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); | |||
4861 | ||||
4862 | // Build an unanalyzed expression if any of the operands is type-dependent. | |||
4863 | if (Base->isTypeDependent() || RowIdx->isTypeDependent() || | |||
4864 | ColumnIdx->isTypeDependent()) | |||
4865 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | |||
4866 | Context.DependentTy, RBLoc); | |||
4867 | ||||
4868 | ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); | |||
4869 | if (ColumnR.isInvalid()) | |||
4870 | return ColumnR; | |||
4871 | ColumnIdx = ColumnR.get(); | |||
4872 | ||||
4873 | // Check that IndexExpr is an integer expression. If it is a constant | |||
4874 | // expression, check that it is less than Dim (= the number of elements in the | |||
4875 | // corresponding dimension). | |||
4876 | auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, | |||
4877 | bool IsColumnIdx) -> Expr * { | |||
4878 | if (!IndexExpr->getType()->isIntegerType() && | |||
4879 | !IndexExpr->isTypeDependent()) { | |||
4880 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) | |||
4881 | << IsColumnIdx; | |||
4882 | return nullptr; | |||
4883 | } | |||
4884 | ||||
4885 | if (Optional<llvm::APSInt> Idx = | |||
4886 | IndexExpr->getIntegerConstantExpr(Context)) { | |||
4887 | if ((*Idx < 0 || *Idx >= Dim)) { | |||
4888 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) | |||
4889 | << IsColumnIdx << Dim; | |||
4890 | return nullptr; | |||
4891 | } | |||
4892 | } | |||
4893 | ||||
4894 | ExprResult ConvExpr = | |||
4895 | tryConvertExprToType(IndexExpr, Context.getSizeType()); | |||
4896 | 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", 4897, __extension__ __PRETTY_FUNCTION__ )) | |||
4897 | "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", 4897, __extension__ __PRETTY_FUNCTION__ )); | |||
4898 | return ConvExpr.get(); | |||
4899 | }; | |||
4900 | ||||
4901 | auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); | |||
4902 | RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); | |||
4903 | ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); | |||
4904 | if (!RowIdx || !ColumnIdx) | |||
4905 | return ExprError(); | |||
4906 | ||||
4907 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | |||
4908 | MTy->getElementType(), RBLoc); | |||
4909 | } | |||
4910 | ||||
4911 | void Sema::CheckAddressOfNoDeref(const Expr *E) { | |||
4912 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | |||
4913 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); | |||
4914 | ||||
4915 | // For expressions like `&(*s).b`, the base is recorded and what should be | |||
4916 | // checked. | |||
4917 | const MemberExpr *Member = nullptr; | |||
4918 | while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) | |||
4919 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); | |||
4920 | ||||
4921 | LastRecord.PossibleDerefs.erase(StrippedExpr); | |||
4922 | } | |||
4923 | ||||
4924 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { | |||
4925 | if (isUnevaluatedContext()) | |||
4926 | return; | |||
4927 | ||||
4928 | QualType ResultTy = E->getType(); | |||
4929 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | |||
4930 | ||||
4931 | // Bail if the element is an array since it is not memory access. | |||
4932 | if (isa<ArrayType>(ResultTy)) | |||
4933 | return; | |||
4934 | ||||
4935 | if (ResultTy->hasAttr(attr::NoDeref)) { | |||
4936 | LastRecord.PossibleDerefs.insert(E); | |||
4937 | return; | |||
4938 | } | |||
4939 | ||||
4940 | // Check if the base type is a pointer to a member access of a struct | |||
4941 | // marked with noderef. | |||
4942 | const Expr *Base = E->getBase(); | |||
4943 | QualType BaseTy = Base->getType(); | |||
4944 | if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) | |||
4945 | // Not a pointer access | |||
4946 | return; | |||
4947 | ||||
4948 | const MemberExpr *Member = nullptr; | |||
4949 | while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && | |||
4950 | Member->isArrow()) | |||
4951 | Base = Member->getBase(); | |||
4952 | ||||
4953 | if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { | |||
4954 | if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) | |||
4955 | LastRecord.PossibleDerefs.insert(E); | |||
4956 | } | |||
4957 | } | |||
4958 | ||||
4959 | ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, | |||
4960 | Expr *LowerBound, | |||
4961 | SourceLocation ColonLocFirst, | |||
4962 | SourceLocation ColonLocSecond, | |||
4963 | Expr *Length, Expr *Stride, | |||
4964 | SourceLocation RBLoc) { | |||
4965 | if (Base->hasPlaceholderType() && | |||
4966 | !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { | |||
4967 | ExprResult Result = CheckPlaceholderExpr(Base); | |||
4968 | if (Result.isInvalid()) | |||
4969 | return ExprError(); | |||
4970 | Base = Result.get(); | |||
4971 | } | |||
4972 | if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { | |||
4973 | ExprResult Result = CheckPlaceholderExpr(LowerBound); | |||
4974 | if (Result.isInvalid()) | |||
4975 | return ExprError(); | |||
4976 | Result = DefaultLvalueConversion(Result.get()); | |||
4977 | if (Result.isInvalid()) | |||
4978 | return ExprError(); | |||
4979 | LowerBound = Result.get(); | |||
4980 | } | |||
4981 | if (Length && Length->getType()->isNonOverloadPlaceholderType()) { | |||
4982 | ExprResult Result = CheckPlaceholderExpr(Length); | |||
4983 | if (Result.isInvalid()) | |||
4984 | return ExprError(); | |||
4985 | Result = DefaultLvalueConversion(Result.get()); | |||
4986 | if (Result.isInvalid()) | |||
4987 | return ExprError(); | |||
4988 | Length = Result.get(); | |||
4989 | } | |||
4990 | if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { | |||
4991 | ExprResult Result = CheckPlaceholderExpr(Stride); | |||
4992 | if (Result.isInvalid()) | |||
4993 | return ExprError(); | |||
4994 | Result = DefaultLvalueConversion(Result.get()); | |||
4995 | if (Result.isInvalid()) | |||
4996 | return ExprError(); | |||
4997 | Stride = Result.get(); | |||
4998 | } | |||
4999 | ||||
5000 | // Build an unanalyzed expression if either operand is type-dependent. | |||
5001 | if (Base->isTypeDependent() || | |||
5002 | (LowerBound && | |||
5003 | (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || | |||
5004 | (Length && (Length->isTypeDependent() || Length->isValueDependent())) || | |||
5005 | (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { | |||
5006 | return new (Context) OMPArraySectionExpr( | |||
5007 | Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, | |||
5008 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | |||
5009 | } | |||
5010 | ||||
5011 | // Perform default conversions. | |||
5012 | QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); | |||
5013 | QualType ResultTy; | |||
5014 | if (OriginalTy->isAnyPointerType()) { | |||
5015 | ResultTy = OriginalTy->getPointeeType(); | |||
5016 | } else if (OriginalTy->isArrayType()) { | |||
5017 | ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); | |||
5018 | } else { | |||
5019 | return ExprError( | |||
5020 | Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) | |||
5021 | << Base->getSourceRange()); | |||
5022 | } | |||
5023 | // C99 6.5.2.1p1 | |||
5024 | if (LowerBound) { | |||
5025 | auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), | |||
5026 | LowerBound); | |||
5027 | if (Res.isInvalid()) | |||
5028 | return ExprError(Diag(LowerBound->getExprLoc(), | |||
5029 | diag::err_omp_typecheck_section_not_integer) | |||
5030 | << 0 << LowerBound->getSourceRange()); | |||
5031 | LowerBound = Res.get(); | |||
5032 | ||||
5033 | if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
5034 | LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
5035 | Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) | |||
5036 | << 0 << LowerBound->getSourceRange(); | |||
5037 | } | |||
5038 | if (Length) { | |||
5039 | auto Res = | |||
5040 | PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); | |||
5041 | if (Res.isInvalid()) | |||
5042 | return ExprError(Diag(Length->getExprLoc(), | |||
5043 | diag::err_omp_typecheck_section_not_integer) | |||
5044 | << 1 << Length->getSourceRange()); | |||
5045 | Length = Res.get(); | |||
5046 | ||||
5047 | if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
5048 | Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
5049 | Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) | |||
5050 | << 1 << Length->getSourceRange(); | |||
5051 | } | |||
5052 | if (Stride) { | |||
5053 | ExprResult Res = | |||
5054 | PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); | |||
5055 | if (Res.isInvalid()) | |||
5056 | return ExprError(Diag(Stride->getExprLoc(), | |||
5057 | diag::err_omp_typecheck_section_not_integer) | |||
5058 | << 1 << Stride->getSourceRange()); | |||
5059 | Stride = Res.get(); | |||
5060 | ||||
5061 | if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
5062 | Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
5063 | Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) | |||
5064 | << 1 << Stride->getSourceRange(); | |||
5065 | } | |||
5066 | ||||
5067 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | |||
5068 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | |||
5069 | // type. Note that functions are not objects, and that (in C99 parlance) | |||
5070 | // incomplete types are not object types. | |||
5071 | if (ResultTy->isFunctionType()) { | |||
5072 | Diag(Base->getExprLoc(), diag::err_omp_section_function_type) | |||
5073 | << ResultTy << Base->getSourceRange(); | |||
5074 | return ExprError(); | |||
5075 | } | |||
5076 | ||||
5077 | if (RequireCompleteType(Base->getExprLoc(), ResultTy, | |||
5078 | diag::err_omp_section_incomplete_type, Base)) | |||
5079 | return ExprError(); | |||
5080 | ||||
5081 | if (LowerBound && !OriginalTy->isAnyPointerType()) { | |||
5082 | Expr::EvalResult Result; | |||
5083 | if (LowerBound->EvaluateAsInt(Result, Context)) { | |||
5084 | // OpenMP 5.0, [2.1.5 Array Sections] | |||
5085 | // The array section must be a subset of the original array. | |||
5086 | llvm::APSInt LowerBoundValue = Result.Val.getInt(); | |||
5087 | if (LowerBoundValue.isNegative()) { | |||
5088 | Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) | |||
5089 | << LowerBound->getSourceRange(); | |||
5090 | return ExprError(); | |||
5091 | } | |||
5092 | } | |||
5093 | } | |||
5094 | ||||
5095 | if (Length) { | |||
5096 | Expr::EvalResult Result; | |||
5097 | if (Length->EvaluateAsInt(Result, Context)) { | |||
5098 | // OpenMP 5.0, [2.1.5 Array Sections] | |||
5099 | // The length must evaluate to non-negative integers. | |||
5100 | llvm::APSInt LengthValue = Result.Val.getInt(); | |||
5101 | if (LengthValue.isNegative()) { | |||
5102 | Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) | |||
5103 | << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) | |||
5104 | << Length->getSourceRange(); | |||
5105 | return ExprError(); | |||
5106 | } | |||
5107 | } | |||
5108 | } else if (ColonLocFirst.isValid() && | |||
5109 | (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && | |||
5110 | !OriginalTy->isVariableArrayType()))) { | |||
5111 | // OpenMP 5.0, [2.1.5 Array Sections] | |||
5112 | // When the size of the array dimension is not known, the length must be | |||
5113 | // specified explicitly. | |||
5114 | Diag(ColonLocFirst, diag::err_omp_section_length_undefined) | |||
5115 | << (!OriginalTy.isNull() && OriginalTy->isArrayType()); | |||
5116 | return ExprError(); | |||
5117 | } | |||
5118 | ||||
5119 | if (Stride) { | |||
5120 | Expr::EvalResult Result; | |||
5121 | if (Stride->EvaluateAsInt(Result, Context)) { | |||
5122 | // OpenMP 5.0, [2.1.5 Array Sections] | |||
5123 | // The stride must evaluate to a positive integer. | |||
5124 | llvm::APSInt StrideValue = Result.Val.getInt(); | |||
5125 | if (!StrideValue.isStrictlyPositive()) { | |||
5126 | Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) | |||
5127 | << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) | |||
5128 | << Stride->getSourceRange(); | |||
5129 | return ExprError(); | |||
5130 | } | |||
5131 | } | |||
5132 | } | |||
5133 | ||||
5134 | if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { | |||
5135 | ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); | |||
5136 | if (Result.isInvalid()) | |||
5137 | return ExprError(); | |||
5138 | Base = Result.get(); | |||
5139 | } | |||
5140 | return new (Context) OMPArraySectionExpr( | |||
5141 | Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, | |||
5142 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | |||
5143 | } | |||
5144 | ||||
5145 | ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, | |||
5146 | SourceLocation RParenLoc, | |||
5147 | ArrayRef<Expr *> Dims, | |||
5148 | ArrayRef<SourceRange> Brackets) { | |||
5149 | if (Base->hasPlaceholderType()) { | |||
5150 | ExprResult Result = CheckPlaceholderExpr(Base); | |||
5151 | if (Result.isInvalid()) | |||
5152 | return ExprError(); | |||
5153 | Result = DefaultLvalueConversion(Result.get()); | |||
5154 | if (Result.isInvalid()) | |||
5155 | return ExprError(); | |||
5156 | Base = Result.get(); | |||
5157 | } | |||
5158 | QualType BaseTy = Base->getType(); | |||
5159 | // Delay analysis of the types/expressions if instantiation/specialization is | |||
5160 | // required. | |||
5161 | if (!BaseTy->isPointerType() && Base->isTypeDependent()) | |||
5162 | return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, | |||
5163 | LParenLoc, RParenLoc, Dims, Brackets); | |||
5164 | if (!BaseTy->isPointerType() || | |||
5165 | (!Base->isTypeDependent() && | |||
5166 | BaseTy->getPointeeType()->isIncompleteType())) | |||
5167 | return ExprError(Diag(Base->getExprLoc(), | |||
5168 | diag::err_omp_non_pointer_type_array_shaping_base) | |||
5169 | << Base->getSourceRange()); | |||
5170 | ||||
5171 | SmallVector<Expr *, 4> NewDims; | |||
5172 | bool ErrorFound = false; | |||
5173 | for (Expr *Dim : Dims) { | |||
5174 | if (Dim->hasPlaceholderType()) { | |||
5175 | ExprResult Result = CheckPlaceholderExpr(Dim); | |||
5176 | if (Result.isInvalid()) { | |||
5177 | ErrorFound = true; | |||
5178 | continue; | |||
5179 | } | |||
5180 | Result = DefaultLvalueConversion(Result.get()); | |||
5181 | if (Result.isInvalid()) { | |||
5182 | ErrorFound = true; | |||
5183 | continue; | |||
5184 | } | |||
5185 | Dim = Result.get(); | |||
5186 | } | |||
5187 | if (!Dim->isTypeDependent()) { | |||
5188 | ExprResult Result = | |||
5189 | PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); | |||
5190 | if (Result.isInvalid()) { | |||
5191 | ErrorFound = true; | |||
5192 | Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) | |||
5193 | << Dim->getSourceRange(); | |||
5194 | continue; | |||
5195 | } | |||
5196 | Dim = Result.get(); | |||
5197 | Expr::EvalResult EvResult; | |||
5198 | if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { | |||
5199 | // OpenMP 5.0, [2.1.4 Array Shaping] | |||
5200 | // Each si is an integral type expression that must evaluate to a | |||
5201 | // positive integer. | |||
5202 | llvm::APSInt Value = EvResult.Val.getInt(); | |||
5203 | if (!Value.isStrictlyPositive()) { | |||
5204 | Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) | |||
5205 | << toString(Value, /*Radix=*/10, /*Signed=*/true) | |||
5206 | << Dim->getSourceRange(); | |||
5207 | ErrorFound = true; | |||
5208 | continue; | |||
5209 | } | |||
5210 | } | |||
5211 | } | |||
5212 | NewDims.push_back(Dim); | |||
5213 | } | |||
5214 | if (ErrorFound) | |||
5215 | return ExprError(); | |||
5216 | return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, | |||
5217 | LParenLoc, RParenLoc, NewDims, Brackets); | |||
5218 | } | |||
5219 | ||||
5220 | ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, | |||
5221 | SourceLocation LLoc, SourceLocation RLoc, | |||
5222 | ArrayRef<OMPIteratorData> Data) { | |||
5223 | SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; | |||
5224 | bool IsCorrect = true; | |||
5225 | for (const OMPIteratorData &D : Data) { | |||
5226 | TypeSourceInfo *TInfo = nullptr; | |||
5227 | SourceLocation StartLoc; | |||
5228 | QualType DeclTy; | |||
5229 | if (!D.Type.getAsOpaquePtr()) { | |||
5230 | // OpenMP 5.0, 2.1.6 Iterators | |||
5231 | // In an iterator-specifier, if the iterator-type is not specified then | |||
5232 | // the type of that iterator is of int type. | |||
5233 | DeclTy = Context.IntTy; | |||
5234 | StartLoc = D.DeclIdentLoc; | |||
5235 | } else { | |||
5236 | DeclTy = GetTypeFromParser(D.Type, &TInfo); | |||
5237 | StartLoc = TInfo->getTypeLoc().getBeginLoc(); | |||
5238 | } | |||
5239 | ||||
5240 | bool IsDeclTyDependent = DeclTy->isDependentType() || | |||
5241 | DeclTy->containsUnexpandedParameterPack() || | |||
5242 | DeclTy->isInstantiationDependentType(); | |||
5243 | if (!IsDeclTyDependent) { | |||
5244 | if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { | |||
5245 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | |||
5246 | // The iterator-type must be an integral or pointer type. | |||
5247 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | |||
5248 | << DeclTy; | |||
5249 | IsCorrect = false; | |||
5250 | continue; | |||
5251 | } | |||
5252 | if (DeclTy.isConstant(Context)) { | |||
5253 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | |||
5254 | // The iterator-type must not be const qualified. | |||
5255 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | |||
5256 | << DeclTy; | |||
5257 | IsCorrect = false; | |||
5258 | continue; | |||
5259 | } | |||
5260 | } | |||
5261 | ||||
5262 | // Iterator declaration. | |||
5263 | 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", 5263, __extension__ __PRETTY_FUNCTION__ )); | |||
5264 | // Always try to create iterator declarator to avoid extra error messages | |||
5265 | // about unknown declarations use. | |||
5266 | auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, | |||
5267 | D.DeclIdent, DeclTy, TInfo, SC_None); | |||
5268 | VD->setImplicit(); | |||
5269 | if (S) { | |||
5270 | // Check for conflicting previous declaration. | |||
5271 | DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); | |||
5272 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
5273 | ForVisibleRedeclaration); | |||
5274 | Previous.suppressDiagnostics(); | |||
5275 | LookupName(Previous, S); | |||
5276 | ||||
5277 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, | |||
5278 | /*AllowInlineNamespace=*/false); | |||
5279 | if (!Previous.empty()) { | |||
5280 | NamedDecl *Old = Previous.getRepresentativeDecl(); | |||
5281 | Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); | |||
5282 | Diag(Old->getLocation(), diag::note_previous_definition); | |||
5283 | } else { | |||
5284 | PushOnScopeChains(VD, S); | |||
5285 | } | |||
5286 | } else { | |||
5287 | CurContext->addDecl(VD); | |||
5288 | } | |||
5289 | Expr *Begin = D.Range.Begin; | |||
5290 | if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { | |||
5291 | ExprResult BeginRes = | |||
5292 | PerformImplicitConversion(Begin, DeclTy, AA_Converting); | |||
5293 | Begin = BeginRes.get(); | |||
5294 | } | |||
5295 | Expr *End = D.Range.End; | |||
5296 | if (!IsDeclTyDependent && End && !End->isTypeDependent()) { | |||
5297 | ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); | |||
5298 | End = EndRes.get(); | |||
5299 | } | |||
5300 | Expr *Step = D.Range.Step; | |||
5301 | if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { | |||
5302 | if (!Step->getType()->isIntegralType(Context)) { | |||
5303 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) | |||
5304 | << Step << Step->getSourceRange(); | |||
5305 | IsCorrect = false; | |||
5306 | continue; | |||
5307 | } | |||
5308 | Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); | |||
5309 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions | |||
5310 | // If the step expression of a range-specification equals zero, the | |||
5311 | // behavior is unspecified. | |||
5312 | if (Result && Result->isZero()) { | |||
5313 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) | |||
5314 | << Step << Step->getSourceRange(); | |||
5315 | IsCorrect = false; | |||
5316 | continue; | |||
5317 | } | |||
5318 | } | |||
5319 | if (!Begin || !End || !IsCorrect) { | |||
5320 | IsCorrect = false; | |||
5321 | continue; | |||
5322 | } | |||
5323 | OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); | |||
5324 | IDElem.IteratorDecl = VD; | |||
5325 | IDElem.AssignmentLoc = D.AssignLoc; | |||
5326 | IDElem.Range.Begin = Begin; | |||
5327 | IDElem.Range.End = End; | |||
5328 | IDElem.Range.Step = Step; | |||
5329 | IDElem.ColonLoc = D.ColonLoc; | |||
5330 | IDElem.SecondColonLoc = D.SecColonLoc; | |||
5331 | } | |||
5332 | if (!IsCorrect) { | |||
5333 | // Invalidate all created iterator declarations if error is found. | |||
5334 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | |||
5335 | if (Decl *ID = D.IteratorDecl) | |||
5336 | ID->setInvalidDecl(); | |||
5337 | } | |||
5338 | return ExprError(); | |||
5339 | } | |||
5340 | SmallVector<OMPIteratorHelperData, 4> Helpers; | |||
5341 | if (!CurContext->isDependentContext()) { | |||
5342 | // Build number of ityeration for each iteration range. | |||
5343 | // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : | |||
5344 | // ((Begini-Stepi-1-Endi) / -Stepi); | |||
5345 | for (OMPIteratorExpr::IteratorDefinition &D : ID) { | |||
5346 | // (Endi - Begini) | |||
5347 | ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, | |||
5348 | D.Range.Begin); | |||
5349 | if(!Res.isUsable()) { | |||
5350 | IsCorrect = false; | |||
5351 | continue; | |||
5352 | } | |||
5353 | ExprResult St, St1; | |||
5354 | if (D.Range.Step) { | |||
5355 | St = D.Range.Step; | |||
5356 | // (Endi - Begini) + Stepi | |||
5357 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); | |||
5358 | if (!Res.isUsable()) { | |||
5359 | IsCorrect = false; | |||
5360 | continue; | |||
5361 | } | |||
5362 | // (Endi - Begini) + Stepi - 1 | |||
5363 | Res = | |||
5364 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), | |||
5365 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | |||
5366 | if (!Res.isUsable()) { | |||
5367 | IsCorrect = false; | |||
5368 | continue; | |||
5369 | } | |||
5370 | // ((Endi - Begini) + Stepi - 1) / Stepi | |||
5371 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); | |||
5372 | if (!Res.isUsable()) { | |||
5373 | IsCorrect = false; | |||
5374 | continue; | |||
5375 | } | |||
5376 | St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); | |||
5377 | // (Begini - Endi) | |||
5378 | ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, | |||
5379 | D.Range.Begin, D.Range.End); | |||
5380 | if (!Res1.isUsable()) { | |||
5381 | IsCorrect = false; | |||
5382 | continue; | |||
5383 | } | |||
5384 | // (Begini - Endi) - Stepi | |||
5385 | Res1 = | |||
5386 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); | |||
5387 | if (!Res1.isUsable()) { | |||
5388 | IsCorrect = false; | |||
5389 | continue; | |||
5390 | } | |||
5391 | // (Begini - Endi) - Stepi - 1 | |||
5392 | Res1 = | |||
5393 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), | |||
5394 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | |||
5395 | if (!Res1.isUsable()) { | |||
5396 | IsCorrect = false; | |||
5397 | continue; | |||
5398 | } | |||
5399 | // ((Begini - Endi) - Stepi - 1) / (-Stepi) | |||
5400 | Res1 = | |||
5401 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); | |||
5402 | if (!Res1.isUsable()) { | |||
5403 | IsCorrect = false; | |||
5404 | continue; | |||
5405 | } | |||
5406 | // Stepi > 0. | |||
5407 | ExprResult CmpRes = | |||
5408 | CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, | |||
5409 | ActOnIntegerConstant(D.AssignmentLoc, 0).get()); | |||
5410 | if (!CmpRes.isUsable()) { | |||
5411 | IsCorrect = false; | |||
5412 | continue; | |||
5413 | } | |||
5414 | Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), | |||
5415 | Res.get(), Res1.get()); | |||
5416 | if (!Res.isUsable()) { | |||
5417 | IsCorrect = false; | |||
5418 | continue; | |||
5419 | } | |||
5420 | } | |||
5421 | Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); | |||
5422 | if (!Res.isUsable()) { | |||
5423 | IsCorrect = false; | |||
5424 | continue; | |||
5425 | } | |||
5426 | ||||
5427 | // Build counter update. | |||
5428 | // Build counter. | |||
5429 | auto *CounterVD = | |||
5430 | VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), | |||
5431 | D.IteratorDecl->getBeginLoc(), nullptr, | |||
5432 | Res.get()->getType(), nullptr, SC_None); | |||
5433 | CounterVD->setImplicit(); | |||
5434 | ExprResult RefRes = | |||
5435 | BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, | |||
5436 | D.IteratorDecl->getBeginLoc()); | |||
5437 | // Build counter update. | |||
5438 | // I = Begini + counter * Stepi; | |||
5439 | ExprResult UpdateRes; | |||
5440 | if (D.Range.Step) { | |||
5441 | UpdateRes = CreateBuiltinBinOp( | |||
5442 | D.AssignmentLoc, BO_Mul, | |||
5443 | DefaultLvalueConversion(RefRes.get()).get(), St.get()); | |||
5444 | } else { | |||
5445 | UpdateRes = DefaultLvalueConversion(RefRes.get()); | |||
5446 | } | |||
5447 | if (!UpdateRes.isUsable()) { | |||
5448 | IsCorrect = false; | |||
5449 | continue; | |||
5450 | } | |||
5451 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, | |||
5452 | UpdateRes.get()); | |||
5453 | if (!UpdateRes.isUsable()) { | |||
5454 | IsCorrect = false; | |||
5455 | continue; | |||
5456 | } | |||
5457 | ExprResult VDRes = | |||
5458 | BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), | |||
5459 | cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, | |||
5460 | D.IteratorDecl->getBeginLoc()); | |||
5461 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), | |||
5462 | UpdateRes.get()); | |||
5463 | if (!UpdateRes.isUsable()) { | |||
5464 | IsCorrect = false; | |||
5465 | continue; | |||
5466 | } | |||
5467 | UpdateRes = | |||
5468 | ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); | |||
5469 | if (!UpdateRes.isUsable()) { | |||
5470 | IsCorrect = false; | |||
5471 | continue; | |||
5472 | } | |||
5473 | ExprResult CounterUpdateRes = | |||
5474 | CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); | |||
5475 | if (!CounterUpdateRes.isUsable()) { | |||
5476 | IsCorrect = false; | |||
5477 | continue; | |||
5478 | } | |||
5479 | CounterUpdateRes = | |||
5480 | ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); | |||
5481 | if (!CounterUpdateRes.isUsable()) { | |||
5482 | IsCorrect = false; | |||
5483 | continue; | |||
5484 | } | |||
5485 | OMPIteratorHelperData &HD = Helpers.emplace_back(); | |||
5486 | HD.CounterVD = CounterVD; | |||
5487 | HD.Upper = Res.get(); | |||
5488 | HD.Update = UpdateRes.get(); | |||
5489 | HD.CounterUpdate = CounterUpdateRes.get(); | |||
5490 | } | |||
5491 | } else { | |||
5492 | Helpers.assign(ID.size(), {}); | |||
5493 | } | |||
5494 | if (!IsCorrect) { | |||
5495 | // Invalidate all created iterator declarations if error is found. | |||
5496 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | |||
5497 | if (Decl *ID = D.IteratorDecl) | |||
5498 | ID->setInvalidDecl(); | |||
5499 | } | |||
5500 | return ExprError(); | |||
5501 | } | |||
5502 | return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, | |||
5503 | LLoc, RLoc, ID, Helpers); | |||
5504 | } | |||
5505 | ||||
5506 | ExprResult | |||
5507 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, | |||
5508 | Expr *Idx, SourceLocation RLoc) { | |||
5509 | Expr *LHSExp = Base; | |||
5510 | Expr *RHSExp = Idx; | |||
5511 | ||||
5512 | ExprValueKind VK = VK_LValue; | |||
5513 | ExprObjectKind OK = OK_Ordinary; | |||
5514 | ||||
5515 | // Per C++ core issue 1213, the result is an xvalue if either operand is | |||
5516 | // a non-lvalue array, and an lvalue otherwise. | |||
5517 | if (getLangOpts().CPlusPlus11) { | |||
5518 | for (auto *Op : {LHSExp, RHSExp}) { | |||
5519 | Op = Op->IgnoreImplicit(); | |||
5520 | if (Op->getType()->isArrayType() && !Op->isLValue()) | |||
5521 | VK = VK_XValue; | |||
5522 | } | |||
5523 | } | |||
5524 | ||||
5525 | // Perform default conversions. | |||
5526 | if (!LHSExp->getType()->getAs<VectorType>()) { | |||
5527 | ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); | |||
5528 | if (Result.isInvalid()) | |||
5529 | return ExprError(); | |||
5530 | LHSExp = Result.get(); | |||
5531 | } | |||
5532 | ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); | |||
5533 | if (Result.isInvalid()) | |||
5534 | return ExprError(); | |||
5535 | RHSExp = Result.get(); | |||
5536 | ||||
5537 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); | |||
5538 | ||||
5539 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent | |||
5540 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be | |||
5541 | // in the subscript position. As a result, we need to derive the array base | |||
5542 | // and index from the expression types. | |||
5543 | Expr *BaseExpr, *IndexExpr; | |||
5544 | QualType ResultType; | |||
5545 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { | |||
5546 | BaseExpr = LHSExp; | |||
5547 | IndexExpr = RHSExp; | |||
5548 | ResultType = | |||
5549 | getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext()); | |||
5550 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { | |||
5551 | BaseExpr = LHSExp; | |||
5552 | IndexExpr = RHSExp; | |||
5553 | ResultType = PTy->getPointeeType(); | |||
5554 | } else if (const ObjCObjectPointerType *PTy = | |||
5555 | LHSTy->getAs<ObjCObjectPointerType>()) { | |||
5556 | BaseExpr = LHSExp; | |||
5557 | IndexExpr = RHSExp; | |||
5558 | ||||
5559 | // Use custom logic if this should be the pseudo-object subscript | |||
5560 | // expression. | |||
5561 | if (!LangOpts.isSubscriptPointerArithmetic()) | |||
5562 | return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, | |||
5563 | nullptr); | |||
5564 | ||||
5565 | ResultType = PTy->getPointeeType(); | |||
5566 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { | |||
5567 | // Handle the uncommon case of "123[Ptr]". | |||
5568 | BaseExpr = RHSExp; | |||
5569 | IndexExpr = LHSExp; | |||
5570 | ResultType = PTy->getPointeeType(); | |||
5571 | } else if (const ObjCObjectPointerType *PTy = | |||
5572 | RHSTy->getAs<ObjCObjectPointerType>()) { | |||
5573 | // Handle the uncommon case of "123[Ptr]". | |||
5574 | BaseExpr = RHSExp; | |||
5575 | IndexExpr = LHSExp; | |||
5576 | ResultType = PTy->getPointeeType(); | |||
5577 | if (!LangOpts.isSubscriptPointerArithmetic()) { | |||
5578 | Diag(LLoc, diag::err_subscript_nonfragile_interface) | |||
5579 | << ResultType << BaseExpr->getSourceRange(); | |||
5580 | return ExprError(); | |||
5581 | } | |||
5582 | } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { | |||
5583 | BaseExpr = LHSExp; // vectors: V[123] | |||
5584 | IndexExpr = RHSExp; | |||
5585 | // We apply C++ DR1213 to vector subscripting too. | |||
5586 | if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { | |||
5587 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); | |||
5588 | if (Materialized.isInvalid()) | |||
5589 | return ExprError(); | |||
5590 | LHSExp = Materialized.get(); | |||
5591 | } | |||
5592 | VK = LHSExp->getValueKind(); | |||
5593 | if (VK != VK_PRValue) | |||
5594 | OK = OK_VectorComponent; | |||
5595 | ||||
5596 | ResultType = VTy->getElementType(); | |||
5597 | QualType BaseType = BaseExpr->getType(); | |||
5598 | Qualifiers BaseQuals = BaseType.getQualifiers(); | |||
5599 | Qualifiers MemberQuals = ResultType.getQualifiers(); | |||
5600 | Qualifiers Combined = BaseQuals + MemberQuals; | |||
5601 | if (Combined != MemberQuals) | |||
5602 | ResultType = Context.getQualifiedType(ResultType, Combined); | |||
5603 | } else if (LHSTy->isArrayType()) { | |||
5604 | // If we see an array that wasn't promoted by | |||
5605 | // DefaultFunctionArrayLvalueConversion, it must be an array that | |||
5606 | // wasn't promoted because of the C90 rule that doesn't | |||
5607 | // allow promoting non-lvalue arrays. Warn, then | |||
5608 | // force the promotion here. | |||
5609 | Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | |||
5610 | << LHSExp->getSourceRange(); | |||
5611 | LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), | |||
5612 | CK_ArrayToPointerDecay).get(); | |||
5613 | LHSTy = LHSExp->getType(); | |||
5614 | ||||
5615 | BaseExpr = LHSExp; | |||
5616 | IndexExpr = RHSExp; | |||
5617 | ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); | |||
5618 | } else if (RHSTy->isArrayType()) { | |||
5619 | // Same as previous, except for 123[f().a] case | |||
5620 | Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | |||
5621 | << RHSExp->getSourceRange(); | |||
5622 | RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), | |||
5623 | CK_ArrayToPointerDecay).get(); | |||
5624 | RHSTy = RHSExp->getType(); | |||
5625 | ||||
5626 | BaseExpr = RHSExp; | |||
5627 | IndexExpr = LHSExp; | |||
5628 | ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); | |||
5629 | } else { | |||
5630 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) | |||
5631 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | |||
5632 | } | |||
5633 | // C99 6.5.2.1p1 | |||
5634 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) | |||
5635 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) | |||
5636 | << IndexExpr->getSourceRange()); | |||
5637 | ||||
5638 | if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
5639 | IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
5640 | && !IndexExpr->isTypeDependent()) | |||
5641 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); | |||
5642 | ||||
5643 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | |||
5644 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | |||
5645 | // type. Note that Functions are not objects, and that (in C99 parlance) | |||
5646 | // incomplete types are not object types. | |||
5647 | if (ResultType->isFunctionType()) { | |||
5648 | Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) | |||
5649 | << ResultType << BaseExpr->getSourceRange(); | |||
5650 | return ExprError(); | |||
5651 | } | |||
5652 | ||||
5653 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { | |||
5654 | // GNU extension: subscripting on pointer to void | |||
5655 | Diag(LLoc, diag::ext_gnu_subscript_void_type) | |||
5656 | << BaseExpr->getSourceRange(); | |||
5657 | ||||
5658 | // C forbids expressions of unqualified void type from being l-values. | |||
5659 | // See IsCForbiddenLValueType. | |||
5660 | if (!ResultType.hasQualifiers()) | |||
5661 | VK = VK_PRValue; | |||
5662 | } else if (!ResultType->isDependentType() && | |||
5663 | RequireCompleteSizedType( | |||
5664 | LLoc, ResultType, | |||
5665 | diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) | |||
5666 | return ExprError(); | |||
5667 | ||||
5668 | 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", 5669, __extension__ __PRETTY_FUNCTION__ )) | |||
5669 | !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", 5669, __extension__ __PRETTY_FUNCTION__ )); | |||
5670 | ||||
5671 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && | |||
5672 | FunctionScopes.size() > 1) { | |||
5673 | if (auto *TT = | |||
5674 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { | |||
5675 | for (auto I = FunctionScopes.rbegin(), | |||
5676 | E = std::prev(FunctionScopes.rend()); | |||
5677 | I != E; ++I) { | |||
5678 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | |||
5679 | if (CSI == nullptr) | |||
5680 | break; | |||
5681 | DeclContext *DC = nullptr; | |||
5682 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | |||
5683 | DC = LSI->CallOperator; | |||
5684 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | |||
5685 | DC = CRSI->TheCapturedDecl; | |||
5686 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | |||
5687 | DC = BSI->TheDecl; | |||
5688 | if (DC) { | |||
5689 | if (DC->containsDecl(TT->getDecl())) | |||
5690 | break; | |||
5691 | captureVariablyModifiedType( | |||
5692 | Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); | |||
5693 | } | |||
5694 | } | |||
5695 | } | |||
5696 | } | |||
5697 | ||||
5698 | return new (Context) | |||
5699 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); | |||
5700 | } | |||
5701 | ||||
5702 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, | |||
5703 | ParmVarDecl *Param) { | |||
5704 | if (Param->hasUnparsedDefaultArg()) { | |||
5705 | // If we've already cleared out the location for the default argument, | |||
5706 | // that means we're parsing it right now. | |||
5707 | if (!UnparsedDefaultArgLocs.count(Param)) { | |||
5708 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; | |||
5709 | Diag(CallLoc, diag::note_recursive_default_argument_used_here); | |||
5710 | Param->setInvalidDecl(); | |||
5711 | return true; | |||
5712 | } | |||
5713 | ||||
5714 | Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) | |||
5715 | << FD << cast<CXXRecordDecl>(FD->getDeclContext()); | |||
5716 | Diag(UnparsedDefaultArgLocs[Param], | |||
5717 | diag::note_default_argument_declared_here); | |||
5718 | return true; | |||
5719 | } | |||
5720 | ||||
5721 | if (Param->hasUninstantiatedDefaultArg() && | |||
5722 | InstantiateDefaultArgument(CallLoc, FD, Param)) | |||
5723 | return true; | |||
5724 | ||||
5725 | assert(Param->hasInit() && "default argument but no initializer?")(static_cast <bool> (Param->hasInit() && "default argument but no initializer?" ) ? void (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\"" , "clang/lib/Sema/SemaExpr.cpp", 5725, __extension__ __PRETTY_FUNCTION__ )); | |||
5726 | ||||
5727 | // If the default expression creates temporaries, we need to | |||
5728 | // push them to the current stack of expression temporaries so they'll | |||
5729 | // be properly destroyed. | |||
5730 | // FIXME: We should really be rebuilding the default argument with new | |||
5731 | // bound temporaries; see the comment in PR5810. | |||
5732 | // We don't need to do that with block decls, though, because | |||
5733 | // blocks in default argument expression can never capture anything. | |||
5734 | if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { | |||
5735 | // Set the "needs cleanups" bit regardless of whether there are | |||
5736 | // any explicit objects. | |||
5737 | Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); | |||
5738 | ||||
5739 | // Append all the objects to the cleanup list. Right now, this | |||
5740 | // should always be a no-op, because blocks in default argument | |||
5741 | // expressions should never be able to capture anything. | |||
5742 | assert(!Init->getNumObjects() &&(static_cast <bool> (!Init->getNumObjects() && "default argument expression has capturing blocks?") ? void ( 0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "clang/lib/Sema/SemaExpr.cpp", 5743, __extension__ __PRETTY_FUNCTION__ )) | |||
5743 | "default argument expression has capturing blocks?")(static_cast <bool> (!Init->getNumObjects() && "default argument expression has capturing blocks?") ? void ( 0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "clang/lib/Sema/SemaExpr.cpp", 5743, __extension__ __PRETTY_FUNCTION__ )); | |||
5744 | } | |||
5745 | ||||
5746 | // We already type-checked the argument, so we know it works. | |||
5747 | // Just mark all of the declarations in this potentially-evaluated expression | |||
5748 | // as being "referenced". | |||
5749 | EnterExpressionEvaluationContext EvalContext( | |||
5750 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | |||
5751 | MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), | |||
5752 | /*SkipLocalVariables=*/true); | |||
5753 | return false; | |||
5754 | } | |||
5755 | ||||
5756 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, | |||
5757 | FunctionDecl *FD, ParmVarDecl *Param) { | |||
5758 | assert(Param->hasDefaultArg() && "can't build nonexistent default arg")(static_cast <bool> (Param->hasDefaultArg() && "can't build nonexistent default arg") ? void (0) : __assert_fail ("Param->hasDefaultArg() && \"can't build nonexistent default arg\"" , "clang/lib/Sema/SemaExpr.cpp", 5758, __extension__ __PRETTY_FUNCTION__ )); | |||
5759 | if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) | |||
5760 | return ExprError(); | |||
5761 | return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); | |||
5762 | } | |||
5763 | ||||
5764 | Sema::VariadicCallType | |||
5765 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, | |||
5766 | Expr *Fn) { | |||
5767 | if (Proto && Proto->isVariadic()) { | |||
5768 | if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) | |||
5769 | return VariadicConstructor; | |||
5770 | else if (Fn && Fn->getType()->isBlockPointerType()) | |||
5771 | return VariadicBlock; | |||
5772 | else if (FDecl) { | |||
5773 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | |||
5774 | if (Method->isInstance()) | |||
5775 | return VariadicMethod; | |||
5776 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) | |||
5777 | return VariadicMethod; | |||
5778 | return VariadicFunction; | |||
5779 | } | |||
5780 | return VariadicDoesNotApply; | |||
5781 | } | |||
5782 | ||||
5783 | namespace { | |||
5784 | class FunctionCallCCC final : public FunctionCallFilterCCC { | |||
5785 | public: | |||
5786 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, | |||
5787 | unsigned NumArgs, MemberExpr *ME) | |||
5788 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), | |||
5789 | FunctionName(FuncName) {} | |||
5790 | ||||
5791 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
5792 | if (!candidate.getCorrectionSpecifier() || | |||
5793 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { | |||
5794 | return false; | |||
5795 | } | |||
5796 | ||||
5797 | return FunctionCallFilterCCC::ValidateCandidate(candidate); | |||
5798 | } | |||
5799 | ||||
5800 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
5801 | return std::make_unique<FunctionCallCCC>(*this); | |||
5802 | } | |||
5803 | ||||
5804 | private: | |||
5805 | const IdentifierInfo *const FunctionName; | |||
5806 | }; | |||
5807 | } | |||
5808 | ||||
5809 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, | |||
5810 | FunctionDecl *FDecl, | |||
5811 | ArrayRef<Expr *> Args) { | |||
5812 | MemberExpr *ME = dyn_cast<MemberExpr>(Fn); | |||
5813 | DeclarationName FuncName = FDecl->getDeclName(); | |||
5814 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); | |||
5815 | ||||
5816 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); | |||
5817 | if (TypoCorrection Corrected = S.CorrectTypo( | |||
5818 | DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, | |||
5819 | S.getScopeForContext(S.CurContext), nullptr, CCC, | |||
5820 | Sema::CTK_ErrorRecovery)) { | |||
5821 | if (NamedDecl *ND = Corrected.getFoundDecl()) { | |||
5822 | if (Corrected.isOverloaded()) { | |||
5823 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); | |||
5824 | OverloadCandidateSet::iterator Best; | |||
5825 | for (NamedDecl *CD : Corrected) { | |||
5826 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | |||
5827 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, | |||
5828 | OCS); | |||
5829 | } | |||
5830 | switch (OCS.BestViableFunction(S, NameLoc, Best)) { | |||
5831 | case OR_Success: | |||
5832 | ND = Best->FoundDecl; | |||
5833 | Corrected.setCorrectionDecl(ND); | |||
5834 | break; | |||
5835 | default: | |||
5836 | break; | |||
5837 | } | |||
5838 | } | |||
5839 | ND = ND->getUnderlyingDecl(); | |||
5840 | if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) | |||
5841 | return Corrected; | |||
5842 | } | |||
5843 | } | |||
5844 | return TypoCorrection(); | |||
5845 | } | |||
5846 | ||||
5847 | /// ConvertArgumentsForCall - Converts the arguments specified in | |||
5848 | /// Args/NumArgs to the parameter types of the function FDecl with | |||
5849 | /// function prototype Proto. Call is the call expression itself, and | |||
5850 | /// Fn is the function expression. For a C++ member function, this | |||
5851 | /// routine does not attempt to convert the object argument. Returns | |||
5852 | /// true if the call is ill-formed. | |||
5853 | bool | |||
5854 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, | |||
5855 | FunctionDecl *FDecl, | |||
5856 | const FunctionProtoType *Proto, | |||
5857 | ArrayRef<Expr *> Args, | |||
5858 | SourceLocation RParenLoc, | |||
5859 | bool IsExecConfig) { | |||
5860 | // Bail out early if calling a builtin with custom typechecking. | |||
5861 | if (FDecl) | |||
5862 | if (unsigned ID = FDecl->getBuiltinID()) | |||
5863 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) | |||
5864 | return false; | |||
5865 | ||||
5866 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by | |||
5867 | // assignment, to the types of the corresponding parameter, ... | |||
5868 | unsigned NumParams = Proto->getNumParams(); | |||
5869 | bool Invalid = false; | |||
5870 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; | |||
5871 | unsigned FnKind = Fn->getType()->isBlockPointerType() | |||
5872 | ? 1 /* block */ | |||
5873 | : (IsExecConfig ? 3 /* kernel function (exec config) */ | |||
5874 | : 0 /* function */); | |||
5875 | ||||
5876 | // If too few arguments are available (and we don't have default | |||
5877 | // arguments for the remaining parameters), don't make the call. | |||
5878 | if (Args.size() < NumParams) { | |||
5879 | if (Args.size() < MinArgs) { | |||
5880 | TypoCorrection TC; | |||
5881 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | |||
5882 | unsigned diag_id = | |||
5883 | MinArgs == NumParams && !Proto->isVariadic() | |||
5884 | ? diag::err_typecheck_call_too_few_args_suggest | |||
5885 | : diag::err_typecheck_call_too_few_args_at_least_suggest; | |||
5886 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs | |||
5887 | << static_cast<unsigned>(Args.size()) | |||
5888 | << TC.getCorrectionRange()); | |||
5889 | } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) | |||
5890 | Diag(RParenLoc, | |||
5891 | MinArgs == NumParams && !Proto->isVariadic() | |||
5892 | ? diag::err_typecheck_call_too_few_args_one | |||
5893 | : diag::err_typecheck_call_too_few_args_at_least_one) | |||
5894 | << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); | |||
5895 | else | |||
5896 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() | |||
5897 | ? diag::err_typecheck_call_too_few_args | |||
5898 | : diag::err_typecheck_call_too_few_args_at_least) | |||
5899 | << FnKind << MinArgs << static_cast<unsigned>(Args.size()) | |||
5900 | << Fn->getSourceRange(); | |||
5901 | ||||
5902 | // Emit the location of the prototype. | |||
5903 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | |||
5904 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | |||
5905 | ||||
5906 | return true; | |||
5907 | } | |||
5908 | // We reserve space for the default arguments when we create | |||
5909 | // the call expression, before calling ConvertArgumentsForCall. | |||
5910 | assert((Call->getNumArgs() == NumParams) &&(static_cast <bool> ((Call->getNumArgs() == NumParams ) && "We should have reserved space for the default arguments before!" ) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "clang/lib/Sema/SemaExpr.cpp", 5911, __extension__ __PRETTY_FUNCTION__ )) | |||
5911 | "We should have reserved space for the default arguments before!")(static_cast <bool> ((Call->getNumArgs() == NumParams ) && "We should have reserved space for the default arguments before!" ) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "clang/lib/Sema/SemaExpr.cpp", 5911, __extension__ __PRETTY_FUNCTION__ )); | |||
5912 | } | |||
5913 | ||||
5914 | // If too many are passed and not variadic, error on the extras and drop | |||
5915 | // them. | |||
5916 | if (Args.size() > NumParams) { | |||
5917 | if (!Proto->isVariadic()) { | |||
5918 | TypoCorrection TC; | |||
5919 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | |||
5920 | unsigned diag_id = | |||
5921 | MinArgs == NumParams && !Proto->isVariadic() | |||
5922 | ? diag::err_typecheck_call_too_many_args_suggest | |||
5923 | : diag::err_typecheck_call_too_many_args_at_most_suggest; | |||
5924 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams | |||
5925 | << static_cast<unsigned>(Args.size()) | |||
5926 | << TC.getCorrectionRange()); | |||
5927 | } else if (NumParams == 1 && FDecl && | |||
5928 | FDecl->getParamDecl(0)->getDeclName()) | |||
5929 | Diag(Args[NumParams]->getBeginLoc(), | |||
5930 | MinArgs == NumParams | |||
5931 | ? diag::err_typecheck_call_too_many_args_one | |||
5932 | : diag::err_typecheck_call_too_many_args_at_most_one) | |||
5933 | << FnKind << FDecl->getParamDecl(0) | |||
5934 | << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() | |||
5935 | << SourceRange(Args[NumParams]->getBeginLoc(), | |||
5936 | Args.back()->getEndLoc()); | |||
5937 | else | |||
5938 | Diag(Args[NumParams]->getBeginLoc(), | |||
5939 | MinArgs == NumParams | |||
5940 | ? diag::err_typecheck_call_too_many_args | |||
5941 | : diag::err_typecheck_call_too_many_args_at_most) | |||
5942 | << FnKind << NumParams << static_cast<unsigned>(Args.size()) | |||
5943 | << Fn->getSourceRange() | |||
5944 | << SourceRange(Args[NumParams]->getBeginLoc(), | |||
5945 | Args.back()->getEndLoc()); | |||
5946 | ||||
5947 | // Emit the location of the prototype. | |||
5948 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | |||
5949 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | |||
5950 | ||||
5951 | // This deletes the extra arguments. | |||
5952 | Call->shrinkNumArgs(NumParams); | |||
5953 | return true; | |||
5954 | } | |||
5955 | } | |||
5956 | SmallVector<Expr *, 8> AllArgs; | |||
5957 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); | |||
5958 | ||||
5959 | Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, | |||
5960 | AllArgs, CallType); | |||
5961 | if (Invalid) | |||
5962 | return true; | |||
5963 | unsigned TotalNumArgs = AllArgs.size(); | |||
5964 | for (unsigned i = 0; i < TotalNumArgs; ++i) | |||
5965 | Call->setArg(i, AllArgs[i]); | |||
5966 | ||||
5967 | Call->computeDependence(); | |||
5968 | return false; | |||
5969 | } | |||
5970 | ||||
5971 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, | |||
5972 | const FunctionProtoType *Proto, | |||
5973 | unsigned FirstParam, ArrayRef<Expr *> Args, | |||
5974 | SmallVectorImpl<Expr *> &AllArgs, | |||
5975 | VariadicCallType CallType, bool AllowExplicit, | |||
5976 | bool IsListInitialization) { | |||
5977 | unsigned NumParams = Proto->getNumParams(); | |||
5978 | bool Invalid = false; | |||
5979 | size_t ArgIx = 0; | |||
5980 | // Continue to check argument types (even if we have too few/many args). | |||
5981 | for (unsigned i = FirstParam; i < NumParams; i++) { | |||
5982 | QualType ProtoArgType = Proto->getParamType(i); | |||
5983 | ||||
5984 | Expr *Arg; | |||
5985 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; | |||
5986 | if (ArgIx < Args.size()) { | |||
5987 | Arg = Args[ArgIx++]; | |||
5988 | ||||
5989 | if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, | |||
5990 | diag::err_call_incomplete_argument, Arg)) | |||
5991 | return true; | |||
5992 | ||||
5993 | // Strip the unbridged-cast placeholder expression off, if applicable. | |||
5994 | bool CFAudited = false; | |||
5995 | if (Arg->getType() == Context.ARCUnbridgedCastTy && | |||
5996 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | |||
5997 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | |||
5998 | Arg = stripARCUnbridgedCast(Arg); | |||
5999 | else if (getLangOpts().ObjCAutoRefCount && | |||
6000 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | |||
6001 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | |||
6002 | CFAudited = true; | |||
6003 | ||||
6004 | if (Proto->getExtParameterInfo(i).isNoEscape() && | |||
6005 | ProtoArgType->isBlockPointerType()) | |||
6006 | if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) | |||
6007 | BE->getBlockDecl()->setDoesNotEscape(); | |||
6008 | ||||
6009 | InitializedEntity Entity = | |||
6010 | Param ? InitializedEntity::InitializeParameter(Context, Param, | |||
6011 | ProtoArgType) | |||
6012 | : InitializedEntity::InitializeParameter( | |||
6013 | Context, ProtoArgType, Proto->isParamConsumed(i)); | |||
6014 | ||||
6015 | // Remember that parameter belongs to a CF audited API. | |||
6016 | if (CFAudited) | |||
6017 | Entity.setParameterCFAudited(); | |||
6018 | ||||
6019 | ExprResult ArgE = PerformCopyInitialization( | |||
6020 | Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); | |||
6021 | if (ArgE.isInvalid()) | |||
6022 | return true; | |||
6023 | ||||
6024 | Arg = ArgE.getAs<Expr>(); | |||
6025 | } else { | |||
6026 | assert(Param && "can't use default arguments without a known callee")(static_cast <bool> (Param && "can't use default arguments without a known callee" ) ? void (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\"" , "clang/lib/Sema/SemaExpr.cpp", 6026, __extension__ __PRETTY_FUNCTION__ )); | |||
6027 | ||||
6028 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); | |||
6029 | if (ArgExpr.isInvalid()) | |||
6030 | return true; | |||
6031 | ||||
6032 | Arg = ArgExpr.getAs<Expr>(); | |||
6033 | } | |||
6034 | ||||
6035 | // Check for array bounds violations for each argument to the call. This | |||
6036 | // check only triggers warnings when the argument isn't a more complex Expr | |||
6037 | // with its own checking, such as a BinaryOperator. | |||
6038 | CheckArrayAccess(Arg); | |||
6039 | ||||
6040 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). | |||
6041 | CheckStaticArrayArgument(CallLoc, Param, Arg); | |||
6042 | ||||
6043 | AllArgs.push_back(Arg); | |||
6044 | } | |||
6045 | ||||
6046 | // If this is a variadic call, handle args passed through "...". | |||
6047 | if (CallType != VariadicDoesNotApply) { | |||
6048 | // Assume that extern "C" functions with variadic arguments that | |||
6049 | // return __unknown_anytype aren't *really* variadic. | |||
6050 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && | |||
6051 | FDecl->isExternC()) { | |||
6052 | for (Expr *A : Args.slice(ArgIx)) { | |||
6053 | QualType paramType; // ignored | |||
6054 | ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); | |||
6055 | Invalid |= arg.isInvalid(); | |||
6056 | AllArgs.push_back(arg.get()); | |||
6057 | } | |||
6058 | ||||
6059 | // Otherwise do argument promotion, (C99 6.5.2.2p7). | |||
6060 | } else { | |||
6061 | for (Expr *A : Args.slice(ArgIx)) { | |||
6062 | ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); | |||
6063 | Invalid |= Arg.isInvalid(); | |||
6064 | AllArgs.push_back(Arg.get()); | |||
6065 | } | |||
6066 | } | |||
6067 | ||||
6068 | // Check for array bounds violations. | |||
6069 | for (Expr *A : Args.slice(ArgIx)) | |||
6070 | CheckArrayAccess(A); | |||
6071 | } | |||
6072 | return Invalid; | |||
6073 | } | |||
6074 | ||||
6075 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { | |||
6076 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); | |||
6077 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) | |||
6078 | TL = DTL.getOriginalLoc(); | |||
6079 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) | |||
6080 | S.Diag(PVD->getLocation(), diag::note_callee_static_array) | |||
6081 | << ATL.getLocalSourceRange(); | |||
6082 | } | |||
6083 | ||||
6084 | /// CheckStaticArrayArgument - If the given argument corresponds to a static | |||
6085 | /// array parameter, check that it is non-null, and that if it is formed by | |||
6086 | /// array-to-pointer decay, the underlying array is sufficiently large. | |||
6087 | /// | |||
6088 | /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the | |||
6089 | /// array type derivation, then for each call to the function, the value of the | |||
6090 | /// corresponding actual argument shall provide access to the first element of | |||
6091 | /// an array with at least as many elements as specified by the size expression. | |||
6092 | void | |||
6093 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, | |||
6094 | ParmVarDecl *Param, | |||
6095 | const Expr *ArgExpr) { | |||
6096 | // Static array parameters are not supported in C++. | |||
6097 | if (!Param || getLangOpts().CPlusPlus) | |||
6098 | return; | |||
6099 | ||||
6100 | QualType OrigTy = Param->getOriginalType(); | |||
6101 | ||||
6102 | const ArrayType *AT = Context.getAsArrayType(OrigTy); | |||
6103 | if (!AT || AT->getSizeModifier() != ArrayType::Static) | |||
6104 | return; | |||
6105 | ||||
6106 | if (ArgExpr->isNullPointerConstant(Context, | |||
6107 | Expr::NPC_NeverValueDependent)) { | |||
6108 | Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); | |||
6109 | DiagnoseCalleeStaticArrayParam(*this, Param); | |||
6110 | return; | |||
6111 | } | |||
6112 | ||||
6113 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); | |||
6114 | if (!CAT) | |||
6115 | return; | |||
6116 | ||||
6117 | const ConstantArrayType *ArgCAT = | |||
6118 | Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); | |||
6119 | if (!ArgCAT) | |||
6120 | return; | |||
6121 | ||||
6122 | if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), | |||
6123 | ArgCAT->getElementType())) { | |||
6124 | if (ArgCAT->getSize().ult(CAT->getSize())) { | |||
6125 | Diag(CallLoc, diag::warn_static_array_too_small) | |||
6126 | << ArgExpr->getSourceRange() | |||
6127 | << (unsigned)ArgCAT->getSize().getZExtValue() | |||
6128 | << (unsigned)CAT->getSize().getZExtValue() << 0; | |||
6129 | DiagnoseCalleeStaticArrayParam(*this, Param); | |||
6130 | } | |||
6131 | return; | |||
6132 | } | |||
6133 | ||||
6134 | Optional<CharUnits> ArgSize = | |||
6135 | getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); | |||
6136 | Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); | |||
6137 | if (ArgSize && ParmSize && *ArgSize < *ParmSize) { | |||
6138 | Diag(CallLoc, diag::warn_static_array_too_small) | |||
6139 | << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() | |||
6140 | << (unsigned)ParmSize->getQuantity() << 1; | |||
6141 | DiagnoseCalleeStaticArrayParam(*this, Param); | |||
6142 | } | |||
6143 | } | |||
6144 | ||||
6145 | /// Given a function expression of unknown-any type, try to rebuild it | |||
6146 | /// to have a function type. | |||
6147 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); | |||
6148 | ||||
6149 | /// Is the given type a placeholder that we need to lower out | |||
6150 | /// immediately during argument processing? | |||
6151 | static bool isPlaceholderToRemoveAsArg(QualType type) { | |||
6152 | // Placeholders are never sugared. | |||
6153 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); | |||
6154 | if (!placeholder) return false; | |||
6155 | ||||
6156 | switch (placeholder->getKind()) { | |||
6157 | // Ignore all the non-placeholder types. | |||
6158 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | |||
6159 | case BuiltinType::Id: | |||
6160 | #include "clang/Basic/OpenCLImageTypes.def" | |||
6161 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | |||
6162 | case BuiltinType::Id: | |||
6163 | #include "clang/Basic/OpenCLExtensionTypes.def" | |||
6164 | // In practice we'll never use this, since all SVE types are sugared | |||
6165 | // via TypedefTypes rather than exposed directly as BuiltinTypes. | |||
6166 | #define SVE_TYPE(Name, Id, SingletonId) \ | |||
6167 | case BuiltinType::Id: | |||
6168 | #include "clang/Basic/AArch64SVEACLETypes.def" | |||
6169 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | |||
6170 | case BuiltinType::Id: | |||
6171 | #include "clang/Basic/PPCTypes.def" | |||
6172 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | |||
6173 | #include "clang/Basic/RISCVVTypes.def" | |||
6174 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) | |||
6175 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: | |||
6176 | #include "clang/AST/BuiltinTypes.def" | |||
6177 | return false; | |||
6178 | ||||
6179 | // We cannot lower out overload sets; they might validly be resolved | |||
6180 | // by the call machinery. | |||
6181 | case BuiltinType::Overload: | |||
6182 | return false; | |||
6183 | ||||
6184 | // Unbridged casts in ARC can be handled in some call positions and | |||
6185 | // should be left in place. | |||
6186 | case BuiltinType::ARCUnbridgedCast: | |||
6187 | return false; | |||
6188 | ||||
6189 | // Pseudo-objects should be converted as soon as possible. | |||
6190 | case BuiltinType::PseudoObject: | |||
6191 | return true; | |||
6192 | ||||
6193 | // The debugger mode could theoretically but currently does not try | |||
6194 | // to resolve unknown-typed arguments based on known parameter types. | |||
6195 | case BuiltinType::UnknownAny: | |||
6196 | return true; | |||
6197 | ||||
6198 | // These are always invalid as call arguments and should be reported. | |||
6199 | case BuiltinType::BoundMember: | |||
6200 | case BuiltinType::BuiltinFn: | |||
6201 | case BuiltinType::IncompleteMatrixIdx: | |||
6202 | case BuiltinType::OMPArraySection: | |||
6203 | case BuiltinType::OMPArrayShaping: | |||
6204 | case BuiltinType::OMPIterator: | |||
6205 | return true; | |||
6206 | ||||
6207 | } | |||
6208 | llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "clang/lib/Sema/SemaExpr.cpp" , 6208); | |||
6209 | } | |||
6210 | ||||
6211 | /// Check an argument list for placeholders that we won't try to | |||
6212 | /// handle later. | |||
6213 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { | |||
6214 | // Apply this processing to all the arguments at once instead of | |||
6215 | // dying at the first failure. | |||
6216 | bool hasInvalid = false; | |||
6217 | for (size_t i = 0, e = args.size(); i != e; i++) { | |||
6218 | if (isPlaceholderToRemoveAsArg(args[i]->getType())) { | |||
6219 | ExprResult result = S.CheckPlaceholderExpr(args[i]); | |||
6220 | if (result.isInvalid()) hasInvalid = true; | |||
6221 | else args[i] = result.get(); | |||
6222 | } | |||
6223 | } | |||
6224 | return hasInvalid; | |||
6225 | } | |||
6226 | ||||
6227 | /// If a builtin function has a pointer argument with no explicit address | |||
6228 | /// space, then it should be able to accept a pointer to any address | |||
6229 | /// space as input. In order to do this, we need to replace the | |||
6230 | /// standard builtin declaration with one that uses the same address space | |||
6231 | /// as the call. | |||
6232 | /// | |||
6233 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. | |||
6234 | /// it does not contain any pointer arguments without | |||
6235 | /// an address space qualifer. Otherwise the rewritten | |||
6236 | /// FunctionDecl is returned. | |||
6237 | /// TODO: Handle pointer return types. | |||
6238 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, | |||
6239 | FunctionDecl *FDecl, | |||
6240 | MultiExprArg ArgExprs) { | |||
6241 | ||||
6242 | QualType DeclType = FDecl->getType(); | |||
6243 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); | |||
6244 | ||||
6245 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || | |||
6246 | ArgExprs.size() < FT->getNumParams()) | |||
6247 | return nullptr; | |||
6248 | ||||
6249 | bool NeedsNewDecl = false; | |||
6250 | unsigned i = 0; | |||
6251 | SmallVector<QualType, 8> OverloadParams; | |||
6252 | ||||
6253 | for (QualType ParamType : FT->param_types()) { | |||
6254 | ||||
6255 | // Convert array arguments to pointer to simplify type lookup. | |||
6256 | ExprResult ArgRes = | |||
6257 | Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); | |||
6258 | if (ArgRes.isInvalid()) | |||
6259 | return nullptr; | |||
6260 | Expr *Arg = ArgRes.get(); | |||
6261 | QualType ArgType = Arg->getType(); | |||
6262 | if (!ParamType->isPointerType() || | |||
6263 | ParamType.hasAddressSpace() || | |||
6264 | !ArgType->isPointerType() || | |||
6265 | !ArgType->getPointeeType().hasAddressSpace()) { | |||
6266 | OverloadParams.push_back(ParamType); | |||
6267 | continue; | |||
6268 | } | |||
6269 | ||||
6270 | QualType PointeeType = ParamType->getPointeeType(); | |||
6271 | if (PointeeType.hasAddressSpace()) | |||
6272 | continue; | |||
6273 | ||||
6274 | NeedsNewDecl = true; | |||
6275 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); | |||
6276 | ||||
6277 | PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); | |||
6278 | OverloadParams.push_back(Context.getPointerType(PointeeType)); | |||
6279 | } | |||
6280 | ||||
6281 | if (!NeedsNewDecl) | |||
6282 | return nullptr; | |||
6283 | ||||
6284 | FunctionProtoType::ExtProtoInfo EPI; | |||
6285 | EPI.Variadic = FT->isVariadic(); | |||
6286 | QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), | |||
6287 | OverloadParams, EPI); | |||
6288 | DeclContext *Parent = FDecl->getParent(); | |||
6289 | FunctionDecl *OverloadDecl = FunctionDecl::Create( | |||
6290 | Context, Parent, FDecl->getLocation(), FDecl->getLocation(), | |||
6291 | FDecl->getIdentifier(), OverloadTy, | |||
6292 | /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), | |||
6293 | false, | |||
6294 | /*hasPrototype=*/true); | |||
6295 | SmallVector<ParmVarDecl*, 16> Params; | |||
6296 | FT = cast<FunctionProtoType>(OverloadTy); | |||
6297 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | |||
6298 | QualType ParamType = FT->getParamType(i); | |||
6299 | ParmVarDecl *Parm = | |||
6300 | ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), | |||
6301 | SourceLocation(), nullptr, ParamType, | |||
6302 | /*TInfo=*/nullptr, SC_None, nullptr); | |||
6303 | Parm->setScopeInfo(0, i); | |||
6304 | Params.push_back(Parm); | |||
6305 | } | |||
6306 | OverloadDecl->setParams(Params); | |||
6307 | Sema->mergeDeclAttributes(OverloadDecl, FDecl); | |||
6308 | return OverloadDecl; | |||
6309 | } | |||
6310 | ||||
6311 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, | |||
6312 | FunctionDecl *Callee, | |||
6313 | MultiExprArg ArgExprs) { | |||
6314 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and | |||
6315 | // similar attributes) really don't like it when functions are called with an | |||
6316 | // invalid number of args. | |||
6317 | if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), | |||
6318 | /*PartialOverloading=*/false) && | |||
6319 | !Callee->isVariadic()) | |||
6320 | return; | |||
6321 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) | |||
6322 | return; | |||
6323 | ||||
6324 | if (const EnableIfAttr *Attr = | |||
6325 | S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { | |||
6326 | S.Diag(Fn->getBeginLoc(), | |||
6327 | isa<CXXMethodDecl>(Callee) | |||
6328 | ? diag::err_ovl_no_viable_member_function_in_call | |||
6329 | : diag::err_ovl_no_viable_function_in_call) | |||
6330 | << Callee << Callee->getSourceRange(); | |||
6331 | S.Diag(Callee->getLocation(), | |||
6332 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | |||
6333 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | |||
6334 | return; | |||
6335 | } | |||
6336 | } | |||
6337 | ||||
6338 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( | |||
6339 | const UnresolvedMemberExpr *const UME, Sema &S) { | |||
6340 | ||||
6341 | const auto GetFunctionLevelDCIfCXXClass = | |||
6342 | [](Sema &S) -> const CXXRecordDecl * { | |||
6343 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); | |||
6344 | if (!DC || !DC->getParent()) | |||
6345 | return nullptr; | |||
6346 | ||||
6347 | // If the call to some member function was made from within a member | |||
6348 | // function body 'M' return return 'M's parent. | |||
6349 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | |||
6350 | return MD->getParent()->getCanonicalDecl(); | |||
6351 | // else the call was made from within a default member initializer of a | |||
6352 | // class, so return the class. | |||
6353 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) | |||
6354 | return RD->getCanonicalDecl(); | |||
6355 | return nullptr; | |||
6356 | }; | |||
6357 | // If our DeclContext is neither a member function nor a class (in the | |||
6358 | // case of a lambda in a default member initializer), we can't have an | |||
6359 | // enclosing 'this'. | |||
6360 | ||||
6361 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); | |||
6362 | if (!CurParentClass) | |||
6363 | return false; | |||
6364 | ||||
6365 | // The naming class for implicit member functions call is the class in which | |||
6366 | // name lookup starts. | |||
6367 | const CXXRecordDecl *const NamingClass = | |||
6368 | UME->getNamingClass()->getCanonicalDecl(); | |||
6369 | assert(NamingClass && "Must have naming class even for implicit access")(static_cast <bool> (NamingClass && "Must have naming class even for implicit access" ) ? void (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\"" , "clang/lib/Sema/SemaExpr.cpp", 6369, __extension__ __PRETTY_FUNCTION__ )); | |||
6370 | ||||
6371 | // If the unresolved member functions were found in a 'naming class' that is | |||
6372 | // related (either the same or derived from) to the class that contains the | |||
6373 | // member function that itself contained the implicit member access. | |||
6374 | ||||
6375 | return CurParentClass == NamingClass || | |||
6376 | CurParentClass->isDerivedFrom(NamingClass); | |||
6377 | } | |||
6378 | ||||
6379 | static void | |||
6380 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | |||
6381 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { | |||
6382 | ||||
6383 | if (!UME) | |||
6384 | return; | |||
6385 | ||||
6386 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); | |||
6387 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't | |||
6388 | // already been captured, or if this is an implicit member function call (if | |||
6389 | // it isn't, an attempt to capture 'this' should already have been made). | |||
6390 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || | |||
6391 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) | |||
6392 | return; | |||
6393 | ||||
6394 | // Check if the naming class in which the unresolved members were found is | |||
6395 | // related (same as or is a base of) to the enclosing class. | |||
6396 | ||||
6397 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) | |||
6398 | return; | |||
6399 | ||||
6400 | ||||
6401 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); | |||
6402 | // If the enclosing function is not dependent, then this lambda is | |||
6403 | // capture ready, so if we can capture this, do so. | |||
6404 | if (!EnclosingFunctionCtx->isDependentContext()) { | |||
6405 | // If the current lambda and all enclosing lambdas can capture 'this' - | |||
6406 | // then go ahead and capture 'this' (since our unresolved overload set | |||
6407 | // contains at least one non-static member function). | |||
6408 | if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) | |||
6409 | S.CheckCXXThisCapture(CallLoc); | |||
6410 | } else if (S.CurContext->isDependentContext()) { | |||
6411 | // ... since this is an implicit member reference, that might potentially | |||
6412 | // involve a 'this' capture, mark 'this' for potential capture in | |||
6413 | // enclosing lambdas. | |||
6414 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) | |||
6415 | CurLSI->addPotentialThisCapture(CallLoc); | |||
6416 | } | |||
6417 | } | |||
6418 | ||||
6419 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | |||
6420 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | |||
6421 | Expr *ExecConfig) { | |||
6422 | ExprResult Call = | |||
6423 | BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | |||
6424 | /*IsExecConfig=*/false, /*AllowRecovery=*/true); | |||
6425 | if (Call.isInvalid()) | |||
6426 | return Call; | |||
6427 | ||||
6428 | // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier | |||
6429 | // language modes. | |||
6430 | if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { | |||
6431 | if (ULE->hasExplicitTemplateArgs() && | |||
6432 | ULE->decls_begin() == ULE->decls_end()) { | |||
6433 | Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 | |||
6434 | ? diag::warn_cxx17_compat_adl_only_template_id | |||
6435 | : diag::ext_adl_only_template_id) | |||
6436 | << ULE->getName(); | |||
6437 | } | |||
6438 | } | |||
6439 | ||||
6440 | if (LangOpts.OpenMP) | |||
6441 | Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, | |||
6442 | ExecConfig); | |||
6443 | ||||
6444 | return Call; | |||
6445 | } | |||
6446 | ||||
6447 | /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. | |||
6448 | /// This provides the location of the left/right parens and a list of comma | |||
6449 | /// locations. | |||
6450 | ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | |||
6451 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | |||
6452 | Expr *ExecConfig, bool IsExecConfig, | |||
6453 | bool AllowRecovery) { | |||
6454 | // Since this might be a postfix expression, get rid of ParenListExprs. | |||
6455 | ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); | |||
6456 | if (Result.isInvalid()) return ExprError(); | |||
6457 | Fn = Result.get(); | |||
6458 | ||||
6459 | if (checkArgsForPlaceholders(*this, ArgExprs)) | |||
6460 | return ExprError(); | |||
6461 | ||||
6462 | if (getLangOpts().CPlusPlus) { | |||
6463 | // If this is a pseudo-destructor expression, build the call immediately. | |||
6464 | if (isa<CXXPseudoDestructorExpr>(Fn)) { | |||
6465 | if (!ArgExprs.empty()) { | |||
6466 | // Pseudo-destructor calls should not have any arguments. | |||
6467 | Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) | |||
6468 | << FixItHint::CreateRemoval( | |||
6469 | SourceRange(ArgExprs.front()->getBeginLoc(), | |||
6470 | ArgExprs.back()->getEndLoc())); | |||
6471 | } | |||
6472 | ||||
6473 | return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, | |||
6474 | VK_PRValue, RParenLoc, CurFPFeatureOverrides()); | |||
6475 | } | |||
6476 | if (Fn->getType() == Context.PseudoObjectTy) { | |||
6477 | ExprResult result = CheckPlaceholderExpr(Fn); | |||
6478 | if (result.isInvalid()) return ExprError(); | |||
6479 | Fn = result.get(); | |||
6480 | } | |||
6481 | ||||
6482 | // Determine whether this is a dependent call inside a C++ template, | |||
6483 | // in which case we won't do any semantic analysis now. | |||
6484 | if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { | |||
6485 | if (ExecConfig) { | |||
6486 | return CUDAKernelCallExpr::Create(Context, Fn, | |||
6487 | cast<CallExpr>(ExecConfig), ArgExprs, | |||
6488 | Context.DependentTy, VK_PRValue, | |||
6489 | RParenLoc, CurFPFeatureOverrides()); | |||
6490 | } else { | |||
6491 | ||||
6492 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | |||
6493 | *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), | |||
6494 | Fn->getBeginLoc()); | |||
6495 | ||||
6496 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | |||
6497 | VK_PRValue, RParenLoc, CurFPFeatureOverrides()); | |||
6498 | } | |||
6499 | } | |||
6500 | ||||
6501 | // Determine whether this is a call to an object (C++ [over.call.object]). | |||
6502 | if (Fn->getType()->isRecordType()) | |||
6503 | return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, | |||
6504 | RParenLoc); | |||
6505 | ||||
6506 | if (Fn->getType() == Context.UnknownAnyTy) { | |||
6507 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | |||
6508 | if (result.isInvalid()) return ExprError(); | |||
6509 | Fn = result.get(); | |||
6510 | } | |||
6511 | ||||
6512 | if (Fn->getType() == Context.BoundMemberTy) { | |||
6513 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | |||
6514 | RParenLoc, ExecConfig, IsExecConfig, | |||
6515 | AllowRecovery); | |||
6516 | } | |||
6517 | } | |||
6518 | ||||
6519 | // Check for overloaded calls. This can happen even in C due to extensions. | |||
6520 | if (Fn->getType() == Context.OverloadTy) { | |||
6521 | OverloadExpr::FindResult find = OverloadExpr::find(Fn); | |||
6522 | ||||
6523 | // We aren't supposed to apply this logic if there's an '&' involved. | |||
6524 | if (!find.HasFormOfMemberPointer) { | |||
6525 | if (Expr::hasAnyTypeDependentArguments(ArgExprs)) | |||
6526 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | |||
6527 | VK_PRValue, RParenLoc, CurFPFeatureOverrides()); | |||
6528 | OverloadExpr *ovl = find.Expression; | |||
6529 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) | |||
6530 | return BuildOverloadedCallExpr( | |||
6531 | Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | |||
6532 | /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); | |||
6533 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | |||
6534 | RParenLoc, ExecConfig, IsExecConfig, | |||
6535 | AllowRecovery); | |||
6536 | } | |||
6537 | } | |||
6538 | ||||
6539 | // If we're directly calling a function, get the appropriate declaration. | |||
6540 | if (Fn->getType() == Context.UnknownAnyTy) { | |||
6541 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | |||
6542 | if (result.isInvalid()) return ExprError(); | |||
6543 | Fn = result.get(); | |||
6544 | } | |||
6545 | ||||
6546 | Expr *NakedFn = Fn->IgnoreParens(); | |||
6547 | ||||
6548 | bool CallingNDeclIndirectly = false; | |||
6549 | NamedDecl *NDecl = nullptr; | |||
6550 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { | |||
6551 | if (UnOp->getOpcode() == UO_AddrOf) { | |||
6552 | CallingNDeclIndirectly = true; | |||
6553 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); | |||
6554 | } | |||
6555 | } | |||
6556 | ||||
6557 | if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { | |||
6558 | NDecl = DRE->getDecl(); | |||
6559 | ||||
6560 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); | |||
6561 | if (FDecl && FDecl->getBuiltinID()) { | |||
6562 | // Rewrite the function decl for this builtin by replacing parameters | |||
6563 | // with no explicit address space with the address space of the arguments | |||
6564 | // in ArgExprs. | |||
6565 | if ((FDecl = | |||
6566 | rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { | |||
6567 | NDecl = FDecl; | |||
6568 | Fn = DeclRefExpr::Create( | |||
6569 | Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, | |||
6570 | SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, | |||
6571 | nullptr, DRE->isNonOdrUse()); | |||
6572 | } | |||
6573 | } | |||
6574 | } else if (isa<MemberExpr>(NakedFn)) | |||
6575 | NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); | |||
6576 | ||||
6577 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { | |||
6578 | if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( | |||
6579 | FD, /*Complain=*/true, Fn->getBeginLoc())) | |||
6580 | return ExprError(); | |||
6581 | ||||
6582 | checkDirectCallValidity(*this, Fn, FD, ArgExprs); | |||
6583 | ||||
6584 | // If this expression is a call to a builtin function in HIP device | |||
6585 | // compilation, allow a pointer-type argument to default address space to be | |||
6586 | // passed as a pointer-type parameter to a non-default address space. | |||
6587 | // If Arg is declared in the default address space and Param is declared | |||
6588 | // in a non-default address space, perform an implicit address space cast to | |||
6589 | // the parameter type. | |||
6590 | if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && | |||
6591 | FD->getBuiltinID()) { | |||
6592 | for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { | |||
6593 | ParmVarDecl *Param = FD->getParamDecl(Idx); | |||
6594 | if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || | |||
6595 | !ArgExprs[Idx]->getType()->isPointerType()) | |||
6596 | continue; | |||
6597 | ||||
6598 | auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); | |||
6599 | auto ArgTy = ArgExprs[Idx]->getType(); | |||
6600 | auto ArgPtTy = ArgTy->getPointeeType(); | |||
6601 | auto ArgAS = ArgPtTy.getAddressSpace(); | |||
6602 | ||||
6603 | // Add address space cast if target address spaces are different | |||
6604 | bool NeedImplicitASC = | |||
6605 | ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. | |||
6606 | ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS | |||
6607 | // or from specific AS which has target AS matching that of Param. | |||
6608 | getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); | |||
6609 | if (!NeedImplicitASC) | |||
6610 | continue; | |||
6611 | ||||
6612 | // First, ensure that the Arg is an RValue. | |||
6613 | if (ArgExprs[Idx]->isGLValue()) { | |||
6614 | ArgExprs[Idx] = ImplicitCastExpr::Create( | |||
6615 | Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], | |||
6616 | nullptr, VK_PRValue, FPOptionsOverride()); | |||
6617 | } | |||
6618 | ||||
6619 | // Construct a new arg type with address space of Param | |||
6620 | Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); | |||
6621 | ArgPtQuals.setAddressSpace(ParamAS); | |||
6622 | auto NewArgPtTy = | |||
6623 | Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); | |||
6624 | auto NewArgTy = | |||
6625 | Context.getQualifiedType(Context.getPointerType(NewArgPtTy), | |||
6626 | ArgTy.getQualifiers()); | |||
6627 | ||||
6628 | // Finally perform an implicit address space cast | |||
6629 | ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, | |||
6630 | CK_AddressSpaceConversion) | |||
6631 | .get(); | |||
6632 | } | |||
6633 | } | |||
6634 | } | |||
6635 | ||||
6636 | if (Context.isDependenceAllowed() && | |||
6637 | (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { | |||
6638 | assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp" , 6638, __extension__ __PRETTY_FUNCTION__)); | |||
6639 | assert((Fn->containsErrors() ||(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 6642, __extension__ __PRETTY_FUNCTION__ )) | |||
6640 | llvm::any_of(ArgExprs,(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 6642, __extension__ __PRETTY_FUNCTION__ )) | |||
6641 | [](clang::Expr *E) { return E->containsErrors(); })) &&(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 6642, __extension__ __PRETTY_FUNCTION__ )) | |||
6642 | "should only occur in error-recovery path.")(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 6642, __extension__ __PRETTY_FUNCTION__ )); | |||
6643 | QualType ReturnType = | |||
6644 | llvm::isa_and_nonnull<FunctionDecl>(NDecl) | |||
6645 | ? cast<FunctionDecl>(NDecl)->getCallResultType() | |||
6646 | : Context.DependentTy; | |||
6647 | return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, | |||
6648 | Expr::getValueKindForType(ReturnType), RParenLoc, | |||
6649 | CurFPFeatureOverrides()); | |||
6650 | } | |||
6651 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, | |||
6652 | ExecConfig, IsExecConfig); | |||
6653 | } | |||
6654 | ||||
6655 | /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id | |||
6656 | // with the specified CallArgs | |||
6657 | Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, | |||
6658 | MultiExprArg CallArgs) { | |||
6659 | StringRef Name = Context.BuiltinInfo.getName(Id); | |||
6660 | LookupResult R(*this, &Context.Idents.get(Name), Loc, | |||
6661 | Sema::LookupOrdinaryName); | |||
6662 | LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); | |||
6663 | ||||
6664 | auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); | |||
6665 | assert(BuiltInDecl && "failed to find builtin declaration")(static_cast <bool> (BuiltInDecl && "failed to find builtin declaration" ) ? void (0) : __assert_fail ("BuiltInDecl && \"failed to find builtin declaration\"" , "clang/lib/Sema/SemaExpr.cpp", 6665, __extension__ __PRETTY_FUNCTION__ )); | |||
6666 | ||||
6667 | ExprResult DeclRef = | |||
6668 | BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); | |||
6669 | assert(DeclRef.isUsable() && "Builtin reference cannot fail")(static_cast <bool> (DeclRef.isUsable() && "Builtin reference cannot fail" ) ? void (0) : __assert_fail ("DeclRef.isUsable() && \"Builtin reference cannot fail\"" , "clang/lib/Sema/SemaExpr.cpp", 6669, __extension__ __PRETTY_FUNCTION__ )); | |||
6670 | ||||
6671 | ExprResult Call = | |||
6672 | BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); | |||
6673 | ||||
6674 | assert(!Call.isInvalid() && "Call to builtin cannot fail!")(static_cast <bool> (!Call.isInvalid() && "Call to builtin cannot fail!" ) ? void (0) : __assert_fail ("!Call.isInvalid() && \"Call to builtin cannot fail!\"" , "clang/lib/Sema/SemaExpr.cpp", 6674, __extension__ __PRETTY_FUNCTION__ )); | |||
6675 | return Call.get(); | |||
6676 | } | |||
6677 | ||||
6678 | /// Parse a __builtin_astype expression. | |||
6679 | /// | |||
6680 | /// __builtin_astype( value, dst type ) | |||
6681 | /// | |||
6682 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, | |||
6683 | SourceLocation BuiltinLoc, | |||
6684 | SourceLocation RParenLoc) { | |||
6685 | QualType DstTy = GetTypeFromParser(ParsedDestTy); | |||
6686 | return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); | |||
6687 | } | |||
6688 | ||||
6689 | /// Create a new AsTypeExpr node (bitcast) from the arguments. | |||
6690 | ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, | |||
6691 | SourceLocation BuiltinLoc, | |||
6692 | SourceLocation RParenLoc) { | |||
6693 | ExprValueKind VK = VK_PRValue; | |||
6694 | ExprObjectKind OK = OK_Ordinary; | |||
6695 | QualType SrcTy = E->getType(); | |||
6696 | if (!SrcTy->isDependentType() && | |||
6697 | Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) | |||
6698 | return ExprError( | |||
6699 | Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) | |||
6700 | << DestTy << SrcTy << E->getSourceRange()); | |||
6701 | return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); | |||
6702 | } | |||
6703 | ||||
6704 | /// ActOnConvertVectorExpr - create a new convert-vector expression from the | |||
6705 | /// provided arguments. | |||
6706 | /// | |||
6707 | /// __builtin_convertvector( value, dst type ) | |||
6708 | /// | |||
6709 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, | |||
6710 | SourceLocation BuiltinLoc, | |||
6711 | SourceLocation RParenLoc) { | |||
6712 | TypeSourceInfo *TInfo; | |||
6713 | GetTypeFromParser(ParsedDestTy, &TInfo); | |||
6714 | return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); | |||
6715 | } | |||
6716 | ||||
6717 | /// BuildResolvedCallExpr - Build a call to a resolved expression, | |||
6718 | /// i.e. an expression not of \p OverloadTy. The expression should | |||
6719 | /// unary-convert to an expression of function-pointer or | |||
6720 | /// block-pointer type. | |||
6721 | /// | |||
6722 | /// \param NDecl the declaration being called, if available | |||
6723 | ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, | |||
6724 | SourceLocation LParenLoc, | |||
6725 | ArrayRef<Expr *> Args, | |||
6726 | SourceLocation RParenLoc, Expr *Config, | |||
6727 | bool IsExecConfig, ADLCallKind UsesADL) { | |||
6728 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); | |||
6729 | unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); | |||
6730 | ||||
6731 | // Functions with 'interrupt' attribute cannot be called directly. | |||
6732 | if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { | |||
6733 | Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); | |||
6734 | return ExprError(); | |||
6735 | } | |||
6736 | ||||
6737 | // Interrupt handlers don't save off the VFP regs automatically on ARM, | |||
6738 | // so there's some risk when calling out to non-interrupt handler functions | |||
6739 | // that the callee might not preserve them. This is easy to diagnose here, | |||
6740 | // but can be very challenging to debug. | |||
6741 | // Likewise, X86 interrupt handlers may only call routines with attribute | |||
6742 | // no_caller_saved_registers since there is no efficient way to | |||
6743 | // save and restore the non-GPR state. | |||
6744 | if (auto *Caller = getCurFunctionDecl()) { | |||
6745 | if (Caller->hasAttr<ARMInterruptAttr>()) { | |||
6746 | bool VFP = Context.getTargetInfo().hasFeature("vfp"); | |||
6747 | if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { | |||
6748 | Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); | |||
6749 | if (FDecl) | |||
6750 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | |||
6751 | } | |||
6752 | } | |||
6753 | if (Caller->hasAttr<AnyX86InterruptAttr>() && | |||
6754 | ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { | |||
6755 | Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); | |||
6756 | if (FDecl) | |||
6757 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | |||
6758 | } | |||
6759 | } | |||
6760 | ||||
6761 | // Promote the function operand. | |||
6762 | // We special-case function promotion here because we only allow promoting | |||
6763 | // builtin functions to function pointers in the callee of a call. | |||
6764 | ExprResult Result; | |||
6765 | QualType ResultTy; | |||
6766 | if (BuiltinID && | |||
6767 | Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { | |||
6768 | // Extract the return type from the (builtin) function pointer type. | |||
6769 | // FIXME Several builtins still have setType in | |||
6770 | // Sema::CheckBuiltinFunctionCall. One should review their definitions in | |||
6771 | // Builtins.def to ensure they are correct before removing setType calls. | |||
6772 | QualType FnPtrTy = Context.getPointerType(FDecl->getType()); | |||
6773 | Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); | |||
6774 | ResultTy = FDecl->getCallResultType(); | |||
6775 | } else { | |||
6776 | Result = CallExprUnaryConversions(Fn); | |||
6777 | ResultTy = Context.BoolTy; | |||
6778 | } | |||
6779 | if (Result.isInvalid()) | |||
6780 | return ExprError(); | |||
6781 | Fn = Result.get(); | |||
6782 | ||||
6783 | // Check for a valid function type, but only if it is not a builtin which | |||
6784 | // requires custom type checking. These will be handled by | |||
6785 | // CheckBuiltinFunctionCall below just after creation of the call expression. | |||
6786 | const FunctionType *FuncT = nullptr; | |||
6787 | if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { | |||
6788 | retry: | |||
6789 | if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { | |||
6790 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall | |||
6791 | // have type pointer to function". | |||
6792 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); | |||
6793 | if (!FuncT) | |||
6794 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | |||
6795 | << Fn->getType() << Fn->getSourceRange()); | |||
6796 | } else if (const BlockPointerType *BPT = | |||
6797 | Fn->getType()->getAs<BlockPointerType>()) { | |||
6798 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); | |||
6799 | } else { | |||
6800 | // Handle calls to expressions of unknown-any type. | |||
6801 | if (Fn->getType() == Context.UnknownAnyTy) { | |||
6802 | ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); | |||
6803 | if (rewrite.isInvalid()) | |||
6804 | return ExprError(); | |||
6805 | Fn = rewrite.get(); | |||
6806 | goto retry; | |||
6807 | } | |||
6808 | ||||
6809 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | |||
6810 | << Fn->getType() << Fn->getSourceRange()); | |||
6811 | } | |||
6812 | } | |||
6813 | ||||
6814 | // Get the number of parameters in the function prototype, if any. | |||
6815 | // We will allocate space for max(Args.size(), NumParams) arguments | |||
6816 | // in the call expression. | |||
6817 | const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); | |||
6818 | unsigned NumParams = Proto ? Proto->getNumParams() : 0; | |||
6819 | ||||
6820 | CallExpr *TheCall; | |||
6821 | if (Config) { | |||
6822 | assert(UsesADL == ADLCallKind::NotADL &&(static_cast <bool> (UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL") ? void (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "clang/lib/Sema/SemaExpr.cpp", 6823, __extension__ __PRETTY_FUNCTION__ )) | |||
6823 | "CUDAKernelCallExpr should not use ADL")(static_cast <bool> (UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL") ? void (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "clang/lib/Sema/SemaExpr.cpp", 6823, __extension__ __PRETTY_FUNCTION__ )); | |||
6824 | TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), | |||
6825 | Args, ResultTy, VK_PRValue, RParenLoc, | |||
6826 | CurFPFeatureOverrides(), NumParams); | |||
6827 | } else { | |||
6828 | TheCall = | |||
6829 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, | |||
6830 | CurFPFeatureOverrides(), NumParams, UsesADL); | |||
6831 | } | |||
6832 | ||||
6833 | if (!Context.isDependenceAllowed()) { | |||
6834 | // Forget about the nulled arguments since typo correction | |||
6835 | // do not handle them well. | |||
6836 | TheCall->shrinkNumArgs(Args.size()); | |||
6837 | // C cannot always handle TypoExpr nodes in builtin calls and direct | |||
6838 | // function calls as their argument checking don't necessarily handle | |||
6839 | // dependent types properly, so make sure any TypoExprs have been | |||
6840 | // dealt with. | |||
6841 | ExprResult Result = CorrectDelayedTyposInExpr(TheCall); | |||
6842 | if (!Result.isUsable()) return ExprError(); | |||
6843 | CallExpr *TheOldCall = TheCall; | |||
6844 | TheCall = dyn_cast<CallExpr>(Result.get()); | |||
6845 | bool CorrectedTypos = TheCall != TheOldCall; | |||
6846 | if (!TheCall) return Result; | |||
6847 | Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); | |||
6848 | ||||
6849 | // A new call expression node was created if some typos were corrected. | |||
6850 | // However it may not have been constructed with enough storage. In this | |||
6851 | // case, rebuild the node with enough storage. The waste of space is | |||
6852 | // immaterial since this only happens when some typos were corrected. | |||
6853 | if (CorrectedTypos && Args.size() < NumParams) { | |||
6854 | if (Config) | |||
6855 | TheCall = CUDAKernelCallExpr::Create( | |||
6856 | Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, | |||
6857 | RParenLoc, CurFPFeatureOverrides(), NumParams); | |||
6858 | else | |||
6859 | TheCall = | |||
6860 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, | |||
6861 | CurFPFeatureOverrides(), NumParams, UsesADL); | |||
6862 | } | |||
6863 | // We can now handle the nulled arguments for the default arguments. | |||
6864 | TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); | |||
6865 | } | |||
6866 | ||||
6867 | // Bail out early if calling a builtin with custom type checking. | |||
6868 | if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) | |||
6869 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | |||
6870 | ||||
6871 | if (getLangOpts().CUDA) { | |||
6872 | if (Config) { | |||
6873 | // CUDA: Kernel calls must be to global functions | |||
6874 | if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) | |||
6875 | return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) | |||
6876 | << FDecl << Fn->getSourceRange()); | |||
6877 | ||||
6878 | // CUDA: Kernel function must have 'void' return type | |||
6879 | if (!FuncT->getReturnType()->isVoidType() && | |||
6880 | !FuncT->getReturnType()->getAs<AutoType>() && | |||
6881 | !FuncT->getReturnType()->isInstantiationDependentType()) | |||
6882 | return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) | |||
6883 | << Fn->getType() << Fn->getSourceRange()); | |||
6884 | } else { | |||
6885 | // CUDA: Calls to global functions must be configured | |||
6886 | if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) | |||
6887 | return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) | |||
6888 | << FDecl << Fn->getSourceRange()); | |||
6889 | } | |||
6890 | } | |||
6891 | ||||
6892 | // Check for a valid return type | |||
6893 | if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, | |||
6894 | FDecl)) | |||
6895 | return ExprError(); | |||
6896 | ||||
6897 | // We know the result type of the call, set it. | |||
6898 | TheCall->setType(FuncT->getCallResultType(Context)); | |||
6899 | TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); | |||
6900 | ||||
6901 | if (Proto) { | |||
6902 | if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, | |||
6903 | IsExecConfig)) | |||
6904 | return ExprError(); | |||
6905 | } else { | |||
6906 | assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")(static_cast <bool> (isa<FunctionNoProtoType>(FuncT ) && "Unknown FunctionType!") ? void (0) : __assert_fail ("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\"" , "clang/lib/Sema/SemaExpr.cpp", 6906, __extension__ __PRETTY_FUNCTION__ )); | |||
6907 | ||||
6908 | if (FDecl) { | |||
6909 | // Check if we have too few/too many template arguments, based | |||
6910 | // on our knowledge of the function definition. | |||
6911 | const FunctionDecl *Def = nullptr; | |||
6912 | if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { | |||
6913 | Proto = Def->getType()->getAs<FunctionProtoType>(); | |||
6914 | if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) | |||
6915 | Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) | |||
6916 | << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); | |||
6917 | } | |||
6918 | ||||
6919 | // If the function we're calling isn't a function prototype, but we have | |||
6920 | // a function prototype from a prior declaratiom, use that prototype. | |||
6921 | if (!FDecl->hasPrototype()) | |||
6922 | Proto = FDecl->getType()->getAs<FunctionProtoType>(); | |||
6923 | } | |||
6924 | ||||
6925 | // Promote the arguments (C99 6.5.2.2p6). | |||
6926 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | |||
6927 | Expr *Arg = Args[i]; | |||
6928 | ||||
6929 | if (Proto && i < Proto->getNumParams()) { | |||
6930 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | |||
6931 | Context, Proto->getParamType(i), Proto->isParamConsumed(i)); | |||
6932 | ExprResult ArgE = | |||
6933 | PerformCopyInitialization(Entity, SourceLocation(), Arg); | |||
6934 | if (ArgE.isInvalid()) | |||
6935 | return true; | |||
6936 | ||||
6937 | Arg = ArgE.getAs<Expr>(); | |||
6938 | ||||
6939 | } else { | |||
6940 | ExprResult ArgE = DefaultArgumentPromotion(Arg); | |||
6941 | ||||
6942 | if (ArgE.isInvalid()) | |||
6943 | return true; | |||
6944 | ||||
6945 | Arg = ArgE.getAs<Expr>(); | |||
6946 | } | |||
6947 | ||||
6948 | if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), | |||
6949 | diag::err_call_incomplete_argument, Arg)) | |||
6950 | return ExprError(); | |||
6951 | ||||
6952 | TheCall->setArg(i, Arg); | |||
6953 | } | |||
6954 | TheCall->computeDependence(); | |||
6955 | } | |||
6956 | ||||
6957 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | |||
6958 | if (!Method->isStatic()) | |||
6959 | return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) | |||
6960 | << Fn->getSourceRange()); | |||
6961 | ||||
6962 | // Check for sentinels | |||
6963 | if (NDecl) | |||
6964 | DiagnoseSentinelCalls(NDecl, LParenLoc, Args); | |||
6965 | ||||
6966 | // Warn for unions passing across security boundary (CMSE). | |||
6967 | if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { | |||
6968 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | |||
6969 | if (const auto *RT = | |||
6970 | dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { | |||
6971 | if (RT->getDecl()->isOrContainsUnion()) | |||
6972 | Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) | |||
6973 | << 0 << i; | |||
6974 | } | |||
6975 | } | |||
6976 | } | |||
6977 | ||||
6978 | // Do special checking on direct calls to functions. | |||
6979 | if (FDecl) { | |||
6980 | if (CheckFunctionCall(FDecl, TheCall, Proto)) | |||
6981 | return ExprError(); | |||
6982 | ||||
6983 | checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); | |||
6984 | ||||
6985 | if (BuiltinID) | |||
6986 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | |||
6987 | } else if (NDecl) { | |||
6988 | if (CheckPointerCall(NDecl, TheCall, Proto)) | |||
6989 | return ExprError(); | |||
6990 | } else { | |||
6991 | if (CheckOtherCall(TheCall, Proto)) | |||
6992 | return ExprError(); | |||
6993 | } | |||
6994 | ||||
6995 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); | |||
6996 | } | |||
6997 | ||||
6998 | ExprResult | |||
6999 | Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, | |||
7000 | SourceLocation RParenLoc, Expr *InitExpr) { | |||
7001 | assert(Ty && "ActOnCompoundLiteral(): missing type")(static_cast <bool> (Ty && "ActOnCompoundLiteral(): missing type" ) ? void (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\"" , "clang/lib/Sema/SemaExpr.cpp", 7001, __extension__ __PRETTY_FUNCTION__ )); | |||
7002 | assert(InitExpr && "ActOnCompoundLiteral(): missing expression")(static_cast <bool> (InitExpr && "ActOnCompoundLiteral(): missing expression" ) ? void (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\"" , "clang/lib/Sema/SemaExpr.cpp", 7002, __extension__ __PRETTY_FUNCTION__ )); | |||
7003 | ||||
7004 | TypeSourceInfo *TInfo; | |||
7005 | QualType literalType = GetTypeFromParser(Ty, &TInfo); | |||
7006 | if (!TInfo) | |||
7007 | TInfo = Context.getTrivialTypeSourceInfo(literalType); | |||
7008 | ||||
7009 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); | |||
7010 | } | |||
7011 | ||||
7012 | ExprResult | |||
7013 | Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, | |||
7014 | SourceLocation RParenLoc, Expr *LiteralExpr) { | |||
7015 | QualType literalType = TInfo->getType(); | |||
7016 | ||||
7017 | if (literalType->isArrayType()) { | |||
7018 | if (RequireCompleteSizedType( | |||
7019 | LParenLoc, Context.getBaseElementType(literalType), | |||
7020 | diag::err_array_incomplete_or_sizeless_type, | |||
7021 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | |||
7022 | return ExprError(); | |||
7023 | if (literalType->isVariableArrayType()) { | |||
7024 | if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, | |||
7025 | diag::err_variable_object_no_init)) { | |||
7026 | return ExprError(); | |||
7027 | } | |||
7028 | } | |||
7029 | } else if (!literalType->isDependentType() && | |||
7030 | RequireCompleteType(LParenLoc, literalType, | |||
7031 | diag::err_typecheck_decl_incomplete_type, | |||
7032 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | |||
7033 | return ExprError(); | |||
7034 | ||||
7035 | InitializedEntity Entity | |||
7036 | = InitializedEntity::InitializeCompoundLiteralInit(TInfo); | |||
7037 | InitializationKind Kind | |||
7038 | = InitializationKind::CreateCStyleCast(LParenLoc, | |||
7039 | SourceRange(LParenLoc, RParenLoc), | |||
7040 | /*InitList=*/true); | |||
7041 | InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); | |||
7042 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, | |||
7043 | &literalType); | |||
7044 | if (Result.isInvalid()) | |||
7045 | return ExprError(); | |||
7046 | LiteralExpr = Result.get(); | |||
7047 | ||||
7048 | bool isFileScope = !CurContext->isFunctionOrMethod(); | |||
7049 | ||||
7050 | // In C, compound literals are l-values for some reason. | |||
7051 | // For GCC compatibility, in C++, file-scope array compound literals with | |||
7052 | // constant initializers are also l-values, and compound literals are | |||
7053 | // otherwise prvalues. | |||
7054 | // | |||
7055 | // (GCC also treats C++ list-initialized file-scope array prvalues with | |||
7056 | // constant initializers as l-values, but that's non-conforming, so we don't | |||
7057 | // follow it there.) | |||
7058 | // | |||
7059 | // FIXME: It would be better to handle the lvalue cases as materializing and | |||
7060 | // lifetime-extending a temporary object, but our materialized temporaries | |||
7061 | // representation only supports lifetime extension from a variable, not "out | |||
7062 | // of thin air". | |||
7063 | // FIXME: For C++, we might want to instead lifetime-extend only if a pointer | |||
7064 | // is bound to the result of applying array-to-pointer decay to the compound | |||
7065 | // literal. | |||
7066 | // FIXME: GCC supports compound literals of reference type, which should | |||
7067 | // obviously have a value kind derived from the kind of reference involved. | |||
7068 | ExprValueKind VK = | |||
7069 | (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) | |||
7070 | ? VK_PRValue | |||
7071 | : VK_LValue; | |||
7072 | ||||
7073 | if (isFileScope) | |||
7074 | if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) | |||
7075 | for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { | |||
7076 | Expr *Init = ILE->getInit(i); | |||
7077 | ILE->setInit(i, ConstantExpr::Create(Context, Init)); | |||
7078 | } | |||
7079 | ||||
7080 | auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, | |||
7081 | VK, LiteralExpr, isFileScope); | |||
7082 | if (isFileScope) { | |||
7083 | if (!LiteralExpr->isTypeDependent() && | |||
7084 | !LiteralExpr->isValueDependent() && | |||
7085 | !literalType->isDependentType()) // C99 6.5.2.5p3 | |||
7086 | if (CheckForConstantInitializer(LiteralExpr, literalType)) | |||
7087 | return ExprError(); | |||
7088 | } else if (literalType.getAddressSpace() != LangAS::opencl_private && | |||
7089 | literalType.getAddressSpace() != LangAS::Default) { | |||
7090 | // Embedded-C extensions to C99 6.5.2.5: | |||
7091 | // "If the compound literal occurs inside the body of a function, the | |||
7092 | // type name shall not be qualified by an address-space qualifier." | |||
7093 | Diag(LParenLoc, diag::err_compound_literal_with_address_space) | |||
7094 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); | |||
7095 | return ExprError(); | |||
7096 | } | |||
7097 | ||||
7098 | if (!isFileScope && !getLangOpts().CPlusPlus) { | |||
7099 | // Compound literals that have automatic storage duration are destroyed at | |||
7100 | // the end of the scope in C; in C++, they're just temporaries. | |||
7101 | ||||
7102 | // Emit diagnostics if it is or contains a C union type that is non-trivial | |||
7103 | // to destruct. | |||
7104 | if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) | |||
7105 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | |||
7106 | NTCUC_CompoundLiteral, NTCUK_Destruct); | |||
7107 | ||||
7108 | // Diagnose jumps that enter or exit the lifetime of the compound literal. | |||
7109 | if (literalType.isDestructedType()) { | |||
7110 | Cleanup.setExprNeedsCleanups(true); | |||
7111 | ExprCleanupObjects.push_back(E); | |||
7112 | getCurFunction()->setHasBranchProtectedScope(); | |||
7113 | } | |||
7114 | } | |||
7115 | ||||
7116 | if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | |||
7117 | E->getType().hasNonTrivialToPrimitiveCopyCUnion()) | |||
7118 | checkNonTrivialCUnionInInitializer(E->getInitializer(), | |||
7119 | E->getInitializer()->getExprLoc()); | |||
7120 | ||||
7121 | return MaybeBindToTemporary(E); | |||
7122 | } | |||
7123 | ||||
7124 | ExprResult | |||
7125 | Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | |||
7126 | SourceLocation RBraceLoc) { | |||
7127 | // Only produce each kind of designated initialization diagnostic once. | |||
7128 | SourceLocation FirstDesignator; | |||
7129 | bool DiagnosedArrayDesignator = false; | |||
7130 | bool DiagnosedNestedDesignator = false; | |||
7131 | bool DiagnosedMixedDesignator = false; | |||
7132 | ||||
7133 | // Check that any designated initializers are syntactically valid in the | |||
7134 | // current language mode. | |||
7135 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | |||
7136 | if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { | |||
7137 | if (FirstDesignator.isInvalid()) | |||
7138 | FirstDesignator = DIE->getBeginLoc(); | |||
7139 | ||||
7140 | if (!getLangOpts().CPlusPlus) | |||
7141 | break; | |||
7142 | ||||
7143 | if (!DiagnosedNestedDesignator && DIE->size() > 1) { | |||
7144 | DiagnosedNestedDesignator = true; | |||
7145 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) | |||
7146 | << DIE->getDesignatorsSourceRange(); | |||
7147 | } | |||
7148 | ||||
7149 | for (auto &Desig : DIE->designators()) { | |||
7150 | if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { | |||
7151 | DiagnosedArrayDesignator = true; | |||
7152 | Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) | |||
7153 | << Desig.getSourceRange(); | |||
7154 | } | |||
7155 | } | |||
7156 | ||||
7157 | if (!DiagnosedMixedDesignator && | |||
7158 | !isa<DesignatedInitExpr>(InitArgList[0])) { | |||
7159 | DiagnosedMixedDesignator = true; | |||
7160 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | |||
7161 | << DIE->getSourceRange(); | |||
7162 | Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) | |||
7163 | << InitArgList[0]->getSourceRange(); | |||
7164 | } | |||
7165 | } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && | |||
7166 | isa<DesignatedInitExpr>(InitArgList[0])) { | |||
7167 | DiagnosedMixedDesignator = true; | |||
7168 | auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); | |||
7169 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | |||
7170 | << DIE->getSourceRange(); | |||
7171 | Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) | |||
7172 | << InitArgList[I]->getSourceRange(); | |||
7173 | } | |||
7174 | } | |||
7175 | ||||
7176 | if (FirstDesignator.isValid()) { | |||
7177 | // Only diagnose designated initiaization as a C++20 extension if we didn't | |||
7178 | // already diagnose use of (non-C++20) C99 designator syntax. | |||
7179 | if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && | |||
7180 | !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { | |||
7181 | Diag(FirstDesignator, getLangOpts().CPlusPlus20 | |||
7182 | ? diag::warn_cxx17_compat_designated_init | |||
7183 | : diag::ext_cxx_designated_init); | |||
7184 | } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { | |||
7185 | Diag(FirstDesignator, diag::ext_designated_init); | |||
7186 | } | |||
7187 | } | |||
7188 | ||||
7189 | return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); | |||
7190 | } | |||
7191 | ||||
7192 | ExprResult | |||
7193 | Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | |||
7194 | SourceLocation RBraceLoc) { | |||
7195 | // Semantic analysis for initializers is done by ActOnDeclarator() and | |||
7196 | // CheckInitializer() - it requires knowledge of the object being initialized. | |||
7197 | ||||
7198 | // Immediately handle non-overload placeholders. Overloads can be | |||
7199 | // resolved contextually, but everything else here can't. | |||
7200 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | |||
7201 | if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { | |||
7202 | ExprResult result = CheckPlaceholderExpr(InitArgList[I]); | |||
7203 | ||||
7204 | // Ignore failures; dropping the entire initializer list because | |||
7205 | // of one failure would be terrible for indexing/etc. | |||
7206 | if (result.isInvalid()) continue; | |||
7207 | ||||
7208 | InitArgList[I] = result.get(); | |||
7209 | } | |||
7210 | } | |||
7211 | ||||
7212 | InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, | |||
7213 | RBraceLoc); | |||
7214 | E->setType(Context.VoidTy); // FIXME: just a place holder for now. | |||
7215 | return E; | |||
7216 | } | |||
7217 | ||||
7218 | /// Do an explicit extend of the given block pointer if we're in ARC. | |||
7219 | void Sema::maybeExtendBlockObject(ExprResult &E) { | |||
7220 | assert(E.get()->getType()->isBlockPointerType())(static_cast <bool> (E.get()->getType()->isBlockPointerType ()) ? void (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 7220, __extension__ __PRETTY_FUNCTION__ )); | |||
7221 | assert(E.get()->isPRValue())(static_cast <bool> (E.get()->isPRValue()) ? void (0 ) : __assert_fail ("E.get()->isPRValue()", "clang/lib/Sema/SemaExpr.cpp" , 7221, __extension__ __PRETTY_FUNCTION__)); | |||
7222 | ||||
7223 | // Only do this in an r-value context. | |||
7224 | if (!getLangOpts().ObjCAutoRefCount) return; | |||
7225 | ||||
7226 | E = ImplicitCastExpr::Create( | |||
7227 | Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), | |||
7228 | /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); | |||
7229 | Cleanup.setExprNeedsCleanups(true); | |||
7230 | } | |||
7231 | ||||
7232 | /// Prepare a conversion of the given expression to an ObjC object | |||
7233 | /// pointer type. | |||
7234 | CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { | |||
7235 | QualType type = E.get()->getType(); | |||
7236 | if (type->isObjCObjectPointerType()) { | |||
7237 | return CK_BitCast; | |||
7238 | } else if (type->isBlockPointerType()) { | |||
7239 | maybeExtendBlockObject(E); | |||
7240 | return CK_BlockPointerToObjCPointerCast; | |||
7241 | } else { | |||
7242 | assert(type->isPointerType())(static_cast <bool> (type->isPointerType()) ? void ( 0) : __assert_fail ("type->isPointerType()", "clang/lib/Sema/SemaExpr.cpp" , 7242, __extension__ __PRETTY_FUNCTION__)); | |||
7243 | return CK_CPointerToObjCPointerCast; | |||
7244 | } | |||
7245 | } | |||
7246 | ||||
7247 | /// Prepares for a scalar cast, performing all the necessary stages | |||
7248 | /// except the final cast and returning the kind required. | |||
7249 | CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { | |||
7250 | // Both Src and Dest are scalar types, i.e. arithmetic or pointer. | |||
7251 | // Also, callers should have filtered out the invalid cases with | |||
7252 | // pointers. Everything else should be possible. | |||
7253 | ||||
7254 | QualType SrcTy = Src.get()->getType(); | |||
7255 | if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) | |||
7256 | return CK_NoOp; | |||
7257 | ||||
7258 | switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { | |||
7259 | case Type::STK_MemberPointer: | |||
7260 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7260); | |||
7261 | ||||
7262 | case Type::STK_CPointer: | |||
7263 | case Type::STK_BlockPointer: | |||
7264 | case Type::STK_ObjCObjectPointer: | |||
7265 | switch (DestTy->getScalarTypeKind()) { | |||
7266 | case Type::STK_CPointer: { | |||
7267 | LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); | |||
7268 | LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); | |||
7269 | if (SrcAS != DestAS) | |||
7270 | return CK_AddressSpaceConversion; | |||
7271 | if (Context.hasCvrSimilarType(SrcTy, DestTy)) | |||
7272 | return CK_NoOp; | |||
7273 | return CK_BitCast; | |||
7274 | } | |||
7275 | case Type::STK_BlockPointer: | |||
7276 | return (SrcKind == Type::STK_BlockPointer | |||
7277 | ? CK_BitCast : CK_AnyPointerToBlockPointerCast); | |||
7278 | case Type::STK_ObjCObjectPointer: | |||
7279 | if (SrcKind == Type::STK_ObjCObjectPointer) | |||
7280 | return CK_BitCast; | |||
7281 | if (SrcKind == Type::STK_CPointer) | |||
7282 | return CK_CPointerToObjCPointerCast; | |||
7283 | maybeExtendBlockObject(Src); | |||
7284 | return CK_BlockPointerToObjCPointerCast; | |||
7285 | case Type::STK_Bool: | |||
7286 | return CK_PointerToBoolean; | |||
7287 | case Type::STK_Integral: | |||
7288 | return CK_PointerToIntegral; | |||
7289 | case Type::STK_Floating: | |||
7290 | case Type::STK_FloatingComplex: | |||
7291 | case Type::STK_IntegralComplex: | |||
7292 | case Type::STK_MemberPointer: | |||
7293 | case Type::STK_FixedPoint: | |||
7294 | llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer" , "clang/lib/Sema/SemaExpr.cpp", 7294); | |||
7295 | } | |||
7296 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7296); | |||
7297 | ||||
7298 | case Type::STK_FixedPoint: | |||
7299 | switch (DestTy->getScalarTypeKind()) { | |||
7300 | case Type::STK_FixedPoint: | |||
7301 | return CK_FixedPointCast; | |||
7302 | case Type::STK_Bool: | |||
7303 | return CK_FixedPointToBoolean; | |||
7304 | case Type::STK_Integral: | |||
7305 | return CK_FixedPointToIntegral; | |||
7306 | case Type::STK_Floating: | |||
7307 | return CK_FixedPointToFloating; | |||
7308 | case Type::STK_IntegralComplex: | |||
7309 | case Type::STK_FloatingComplex: | |||
7310 | Diag(Src.get()->getExprLoc(), | |||
7311 | diag::err_unimplemented_conversion_with_fixed_point_type) | |||
7312 | << DestTy; | |||
7313 | return CK_IntegralCast; | |||
7314 | case Type::STK_CPointer: | |||
7315 | case Type::STK_ObjCObjectPointer: | |||
7316 | case Type::STK_BlockPointer: | |||
7317 | case Type::STK_MemberPointer: | |||
7318 | llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type" , "clang/lib/Sema/SemaExpr.cpp", 7318); | |||
7319 | } | |||
7320 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7320); | |||
7321 | ||||
7322 | case Type::STK_Bool: // casting from bool is like casting from an integer | |||
7323 | case Type::STK_Integral: | |||
7324 | switch (DestTy->getScalarTypeKind()) { | |||
7325 | case Type::STK_CPointer: | |||
7326 | case Type::STK_ObjCObjectPointer: | |||
7327 | case Type::STK_BlockPointer: | |||
7328 | if (Src.get()->isNullPointerConstant(Context, | |||
7329 | Expr::NPC_ValueDependentIsNull)) | |||
7330 | return CK_NullToPointer; | |||
7331 | return CK_IntegralToPointer; | |||
7332 | case Type::STK_Bool: | |||
7333 | return CK_IntegralToBoolean; | |||
7334 | case Type::STK_Integral: | |||
7335 | return CK_IntegralCast; | |||
7336 | case Type::STK_Floating: | |||
7337 | return CK_IntegralToFloating; | |||
7338 | case Type::STK_IntegralComplex: | |||
7339 | Src = ImpCastExprToType(Src.get(), | |||
7340 | DestTy->castAs<ComplexType>()->getElementType(), | |||
7341 | CK_IntegralCast); | |||
7342 | return CK_IntegralRealToComplex; | |||
7343 | case Type::STK_FloatingComplex: | |||
7344 | Src = ImpCastExprToType(Src.get(), | |||
7345 | DestTy->castAs<ComplexType>()->getElementType(), | |||
7346 | CK_IntegralToFloating); | |||
7347 | return CK_FloatingRealToComplex; | |||
7348 | case Type::STK_MemberPointer: | |||
7349 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7349); | |||
7350 | case Type::STK_FixedPoint: | |||
7351 | return CK_IntegralToFixedPoint; | |||
7352 | } | |||
7353 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7353); | |||
7354 | ||||
7355 | case Type::STK_Floating: | |||
7356 | switch (DestTy->getScalarTypeKind()) { | |||
7357 | case Type::STK_Floating: | |||
7358 | return CK_FloatingCast; | |||
7359 | case Type::STK_Bool: | |||
7360 | return CK_FloatingToBoolean; | |||
7361 | case Type::STK_Integral: | |||
7362 | return CK_FloatingToIntegral; | |||
7363 | case Type::STK_FloatingComplex: | |||
7364 | Src = ImpCastExprToType(Src.get(), | |||
7365 | DestTy->castAs<ComplexType>()->getElementType(), | |||
7366 | CK_FloatingCast); | |||
7367 | return CK_FloatingRealToComplex; | |||
7368 | case Type::STK_IntegralComplex: | |||
7369 | Src = ImpCastExprToType(Src.get(), | |||
7370 | DestTy->castAs<ComplexType>()->getElementType(), | |||
7371 | CK_FloatingToIntegral); | |||
7372 | return CK_IntegralRealToComplex; | |||
7373 | case Type::STK_CPointer: | |||
7374 | case Type::STK_ObjCObjectPointer: | |||
7375 | case Type::STK_BlockPointer: | |||
7376 | llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?" , "clang/lib/Sema/SemaExpr.cpp", 7376); | |||
7377 | case Type::STK_MemberPointer: | |||
7378 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7378); | |||
7379 | case Type::STK_FixedPoint: | |||
7380 | return CK_FloatingToFixedPoint; | |||
7381 | } | |||
7382 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7382); | |||
7383 | ||||
7384 | case Type::STK_FloatingComplex: | |||
7385 | switch (DestTy->getScalarTypeKind()) { | |||
7386 | case Type::STK_FloatingComplex: | |||
7387 | return CK_FloatingComplexCast; | |||
7388 | case Type::STK_IntegralComplex: | |||
7389 | return CK_FloatingComplexToIntegralComplex; | |||
7390 | case Type::STK_Floating: { | |||
7391 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | |||
7392 | if (Context.hasSameType(ET, DestTy)) | |||
7393 | return CK_FloatingComplexToReal; | |||
7394 | Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); | |||
7395 | return CK_FloatingCast; | |||
7396 | } | |||
7397 | case Type::STK_Bool: | |||
7398 | return CK_FloatingComplexToBoolean; | |||
7399 | case Type::STK_Integral: | |||
7400 | Src = ImpCastExprToType(Src.get(), | |||
7401 | SrcTy->castAs<ComplexType>()->getElementType(), | |||
7402 | CK_FloatingComplexToReal); | |||
7403 | return CK_FloatingToIntegral; | |||
7404 | case Type::STK_CPointer: | |||
7405 | case Type::STK_ObjCObjectPointer: | |||
7406 | case Type::STK_BlockPointer: | |||
7407 | llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?" , "clang/lib/Sema/SemaExpr.cpp", 7407); | |||
7408 | case Type::STK_MemberPointer: | |||
7409 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7409); | |||
7410 | case Type::STK_FixedPoint: | |||
7411 | Diag(Src.get()->getExprLoc(), | |||
7412 | diag::err_unimplemented_conversion_with_fixed_point_type) | |||
7413 | << SrcTy; | |||
7414 | return CK_IntegralCast; | |||
7415 | } | |||
7416 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7416); | |||
7417 | ||||
7418 | case Type::STK_IntegralComplex: | |||
7419 | switch (DestTy->getScalarTypeKind()) { | |||
7420 | case Type::STK_FloatingComplex: | |||
7421 | return CK_IntegralComplexToFloatingComplex; | |||
7422 | case Type::STK_IntegralComplex: | |||
7423 | return CK_IntegralComplexCast; | |||
7424 | case Type::STK_Integral: { | |||
7425 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | |||
7426 | if (Context.hasSameType(ET, DestTy)) | |||
7427 | return CK_IntegralComplexToReal; | |||
7428 | Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); | |||
7429 | return CK_IntegralCast; | |||
7430 | } | |||
7431 | case Type::STK_Bool: | |||
7432 | return CK_IntegralComplexToBoolean; | |||
7433 | case Type::STK_Floating: | |||
7434 | Src = ImpCastExprToType(Src.get(), | |||
7435 | SrcTy->castAs<ComplexType>()->getElementType(), | |||
7436 | CK_IntegralComplexToReal); | |||
7437 | return CK_IntegralToFloating; | |||
7438 | case Type::STK_CPointer: | |||
7439 | case Type::STK_ObjCObjectPointer: | |||
7440 | case Type::STK_BlockPointer: | |||
7441 | llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?" , "clang/lib/Sema/SemaExpr.cpp", 7441); | |||
7442 | case Type::STK_MemberPointer: | |||
7443 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7443); | |||
7444 | case Type::STK_FixedPoint: | |||
7445 | Diag(Src.get()->getExprLoc(), | |||
7446 | diag::err_unimplemented_conversion_with_fixed_point_type) | |||
7447 | << SrcTy; | |||
7448 | return CK_IntegralCast; | |||
7449 | } | |||
7450 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7450); | |||
7451 | } | |||
7452 | ||||
7453 | llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "clang/lib/Sema/SemaExpr.cpp" , 7453); | |||
7454 | } | |||
7455 | ||||
7456 | static bool breakDownVectorType(QualType type, uint64_t &len, | |||
7457 | QualType &eltType) { | |||
7458 | // Vectors are simple. | |||
7459 | if (const VectorType *vecType = type->getAs<VectorType>()) { | |||
7460 | len = vecType->getNumElements(); | |||
7461 | eltType = vecType->getElementType(); | |||
7462 | assert(eltType->isScalarType())(static_cast <bool> (eltType->isScalarType()) ? void (0) : __assert_fail ("eltType->isScalarType()", "clang/lib/Sema/SemaExpr.cpp" , 7462, __extension__ __PRETTY_FUNCTION__)); | |||
7463 | return true; | |||
7464 | } | |||
7465 | ||||
7466 | // We allow lax conversion to and from non-vector types, but only if | |||
7467 | // they're real types (i.e. non-complex, non-pointer scalar types). | |||
7468 | if (!type->isRealType()) return false; | |||
7469 | ||||
7470 | len = 1; | |||
7471 | eltType = type; | |||
7472 | return true; | |||
7473 | } | |||
7474 | ||||
7475 | /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the | |||
7476 | /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) | |||
7477 | /// allowed? | |||
7478 | /// | |||
7479 | /// This will also return false if the two given types do not make sense from | |||
7480 | /// the perspective of SVE bitcasts. | |||
7481 | bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { | |||
7482 | assert(srcTy->isVectorType() || destTy->isVectorType())(static_cast <bool> (srcTy->isVectorType() || destTy ->isVectorType()) ? void (0) : __assert_fail ("srcTy->isVectorType() || destTy->isVectorType()" , "clang/lib/Sema/SemaExpr.cpp", 7482, __extension__ __PRETTY_FUNCTION__ )); | |||
7483 | ||||
7484 | auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { | |||
7485 | if (!FirstType->isSizelessBuiltinType()) | |||
7486 | return false; | |||
7487 | ||||
7488 | const auto *VecTy = SecondType->getAs<VectorType>(); | |||
7489 | return VecTy && | |||
7490 | VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; | |||
7491 | }; | |||
7492 | ||||
7493 | return ValidScalableConversion(srcTy, destTy) || | |||
7494 | ValidScalableConversion(destTy, srcTy); | |||
7495 | } | |||
7496 | ||||
7497 | /// Are the two types matrix types and do they have the same dimensions i.e. | |||
7498 | /// do they have the same number of rows and the same number of columns? | |||
7499 | bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { | |||
7500 | if (!destTy->isMatrixType() || !srcTy->isMatrixType()) | |||
7501 | return false; | |||
7502 | ||||
7503 | const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); | |||
7504 | const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); | |||
7505 | ||||
7506 | return matSrcType->getNumRows() == matDestType->getNumRows() && | |||
7507 | matSrcType->getNumColumns() == matDestType->getNumColumns(); | |||
7508 | } | |||
7509 | ||||
7510 | bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { | |||
7511 | assert(DestTy->isVectorType() || SrcTy->isVectorType())(static_cast <bool> (DestTy->isVectorType() || SrcTy ->isVectorType()) ? void (0) : __assert_fail ("DestTy->isVectorType() || SrcTy->isVectorType()" , "clang/lib/Sema/SemaExpr.cpp", 7511, __extension__ __PRETTY_FUNCTION__ )); | |||
7512 | ||||
7513 | uint64_t SrcLen, DestLen; | |||
7514 | QualType SrcEltTy, DestEltTy; | |||
7515 | if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) | |||
7516 | return false; | |||
7517 | if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) | |||
7518 | return false; | |||
7519 | ||||
7520 | // ASTContext::getTypeSize will return the size rounded up to a | |||
7521 | // power of 2, so instead of using that, we need to use the raw | |||
7522 | // element size multiplied by the element count. | |||
7523 | uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); | |||
7524 | uint64_t DestEltSize = Context.getTypeSize(DestEltTy); | |||
7525 | ||||
7526 | return (SrcLen * SrcEltSize == DestLen * DestEltSize); | |||
7527 | } | |||
7528 | ||||
7529 | /// Are the two types lax-compatible vector types? That is, given | |||
7530 | /// that one of them is a vector, do they have equal storage sizes, | |||
7531 | /// where the storage size is the number of elements times the element | |||
7532 | /// size? | |||
7533 | /// | |||
7534 | /// This will also return false if either of the types is neither a | |||
7535 | /// vector nor a real type. | |||
7536 | bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { | |||
7537 | assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy ->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "clang/lib/Sema/SemaExpr.cpp", 7537, __extension__ __PRETTY_FUNCTION__ )); | |||
7538 | ||||
7539 | // Disallow lax conversions between scalars and ExtVectors (these | |||
7540 | // conversions are allowed for other vector types because common headers | |||
7541 | // depend on them). Most scalar OP ExtVector cases are handled by the | |||
7542 | // splat path anyway, which does what we want (convert, not bitcast). | |||
7543 | // What this rules out for ExtVectors is crazy things like char4*float. | |||
7544 | if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; | |||
7545 | if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; | |||
7546 | ||||
7547 | return areVectorTypesSameSize(srcTy, destTy); | |||
7548 | } | |||
7549 | ||||
7550 | /// Is this a legal conversion between two types, one of which is | |||
7551 | /// known to be a vector type? | |||
7552 | bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { | |||
7553 | assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy ->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "clang/lib/Sema/SemaExpr.cpp", 7553, __extension__ __PRETTY_FUNCTION__ )); | |||
7554 | ||||
7555 | switch (Context.getLangOpts().getLaxVectorConversions()) { | |||
7556 | case LangOptions::LaxVectorConversionKind::None: | |||
7557 | return false; | |||
7558 | ||||
7559 | case LangOptions::LaxVectorConversionKind::Integer: | |||
7560 | if (!srcTy->isIntegralOrEnumerationType()) { | |||
7561 | auto *Vec = srcTy->getAs<VectorType>(); | |||
7562 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | |||
7563 | return false; | |||
7564 | } | |||
7565 | if (!destTy->isIntegralOrEnumerationType()) { | |||
7566 | auto *Vec = destTy->getAs<VectorType>(); | |||
7567 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | |||
7568 | return false; | |||
7569 | } | |||
7570 | // OK, integer (vector) -> integer (vector) bitcast. | |||
7571 | break; | |||
7572 | ||||
7573 | case LangOptions::LaxVectorConversionKind::All: | |||
7574 | break; | |||
7575 | } | |||
7576 | ||||
7577 | return areLaxCompatibleVectorTypes(srcTy, destTy); | |||
7578 | } | |||
7579 | ||||
7580 | bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, | |||
7581 | CastKind &Kind) { | |||
7582 | if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { | |||
7583 | if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { | |||
7584 | return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) | |||
7585 | << DestTy << SrcTy << R; | |||
7586 | } | |||
7587 | } else if (SrcTy->isMatrixType()) { | |||
7588 | return Diag(R.getBegin(), | |||
7589 | diag::err_invalid_conversion_between_matrix_and_type) | |||
7590 | << SrcTy << DestTy << R; | |||
7591 | } else if (DestTy->isMatrixType()) { | |||
7592 | return Diag(R.getBegin(), | |||
7593 | diag::err_invalid_conversion_between_matrix_and_type) | |||
7594 | << DestTy << SrcTy << R; | |||
7595 | } | |||
7596 | ||||
7597 | Kind = CK_MatrixCast; | |||
7598 | return false; | |||
7599 | } | |||
7600 | ||||
7601 | bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, | |||
7602 | CastKind &Kind) { | |||
7603 | assert(VectorTy->isVectorType() && "Not a vector type!")(static_cast <bool> (VectorTy->isVectorType() && "Not a vector type!") ? void (0) : __assert_fail ("VectorTy->isVectorType() && \"Not a vector type!\"" , "clang/lib/Sema/SemaExpr.cpp", 7603, __extension__ __PRETTY_FUNCTION__ )); | |||
7604 | ||||
7605 | if (Ty->isVectorType() || Ty->isIntegralType(Context)) { | |||
7606 | if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) | |||
7607 | return Diag(R.getBegin(), | |||
7608 | Ty->isVectorType() ? | |||
7609 | diag::err_invalid_conversion_between_vectors : | |||
7610 | diag::err_invalid_conversion_between_vector_and_integer) | |||
7611 | << VectorTy << Ty << R; | |||
7612 | } else | |||
7613 | return Diag(R.getBegin(), | |||
7614 | diag::err_invalid_conversion_between_vector_and_scalar) | |||
7615 | << VectorTy << Ty << R; | |||
7616 | ||||
7617 | Kind = CK_BitCast; | |||
7618 | return false; | |||
7619 | } | |||
7620 | ||||
7621 | ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { | |||
7622 | QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); | |||
7623 | ||||
7624 | if (DestElemTy == SplattedExpr->getType()) | |||
7625 | return SplattedExpr; | |||
7626 | ||||
7627 | assert(DestElemTy->isFloatingType() ||(static_cast <bool> (DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "clang/lib/Sema/SemaExpr.cpp", 7628, __extension__ __PRETTY_FUNCTION__ )) | |||
7628 | DestElemTy->isIntegralOrEnumerationType())(static_cast <bool> (DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "clang/lib/Sema/SemaExpr.cpp", 7628, __extension__ __PRETTY_FUNCTION__ )); | |||
7629 | ||||
7630 | CastKind CK; | |||
7631 | if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { | |||
7632 | // OpenCL requires that we convert `true` boolean expressions to -1, but | |||
7633 | // only when splatting vectors. | |||
7634 | if (DestElemTy->isFloatingType()) { | |||
7635 | // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast | |||
7636 | // in two steps: boolean to signed integral, then to floating. | |||
7637 | ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, | |||
7638 | CK_BooleanToSignedIntegral); | |||
7639 | SplattedExpr = CastExprRes.get(); | |||
7640 | CK = CK_IntegralToFloating; | |||
7641 | } else { | |||
7642 | CK = CK_BooleanToSignedIntegral; | |||
7643 | } | |||
7644 | } else { | |||
7645 | ExprResult CastExprRes = SplattedExpr; | |||
7646 | CK = PrepareScalarCast(CastExprRes, DestElemTy); | |||
7647 | if (CastExprRes.isInvalid()) | |||
7648 | return ExprError(); | |||
7649 | SplattedExpr = CastExprRes.get(); | |||
7650 | } | |||
7651 | return ImpCastExprToType(SplattedExpr, DestElemTy, CK); | |||
7652 | } | |||
7653 | ||||
7654 | ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, | |||
7655 | Expr *CastExpr, CastKind &Kind) { | |||
7656 | assert(DestTy->isExtVectorType() && "Not an extended vector type!")(static_cast <bool> (DestTy->isExtVectorType() && "Not an extended vector type!") ? void (0) : __assert_fail ( "DestTy->isExtVectorType() && \"Not an extended vector type!\"" , "clang/lib/Sema/SemaExpr.cpp", 7656, __extension__ __PRETTY_FUNCTION__ )); | |||
7657 | ||||
7658 | QualType SrcTy = CastExpr->getType(); | |||
7659 | ||||
7660 | // If SrcTy is a VectorType, the total size must match to explicitly cast to | |||
7661 | // an ExtVectorType. | |||
7662 | // In OpenCL, casts between vectors of different types are not allowed. | |||
7663 | // (See OpenCL 6.2). | |||
7664 | if (SrcTy->isVectorType()) { | |||
7665 | if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || | |||
7666 | (getLangOpts().OpenCL && | |||
7667 | !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { | |||
7668 | Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) | |||
7669 | << DestTy << SrcTy << R; | |||
7670 | return ExprError(); | |||
7671 | } | |||
7672 | Kind = CK_BitCast; | |||
7673 | return CastExpr; | |||
7674 | } | |||
7675 | ||||
7676 | // All non-pointer scalars can be cast to ExtVector type. The appropriate | |||
7677 | // conversion will take place first from scalar to elt type, and then | |||
7678 | // splat from elt type to vector. | |||
7679 | if (SrcTy->isPointerType()) | |||
7680 | return Diag(R.getBegin(), | |||
7681 | diag::err_invalid_conversion_between_vector_and_scalar) | |||
7682 | << DestTy << SrcTy << R; | |||
7683 | ||||
7684 | Kind = CK_VectorSplat; | |||
7685 | return prepareVectorSplat(DestTy, CastExpr); | |||
7686 | } | |||
7687 | ||||
7688 | ExprResult | |||
7689 | Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, | |||
7690 | Declarator &D, ParsedType &Ty, | |||
7691 | SourceLocation RParenLoc, Expr *CastExpr) { | |||
7692 | assert(!D.isInvalidType() && (CastExpr != nullptr) &&(static_cast <bool> (!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr" ) ? void (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "clang/lib/Sema/SemaExpr.cpp", 7693, __extension__ __PRETTY_FUNCTION__ )) | |||
7693 | "ActOnCastExpr(): missing type or expr")(static_cast <bool> (!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr" ) ? void (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "clang/lib/Sema/SemaExpr.cpp", 7693, __extension__ __PRETTY_FUNCTION__ )); | |||
7694 | ||||
7695 | TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); | |||
7696 | if (D.isInvalidType()) | |||
7697 | return ExprError(); | |||
7698 | ||||
7699 | if (getLangOpts().CPlusPlus) { | |||
7700 | // Check that there are no default arguments (C++ only). | |||
7701 | CheckExtraCXXDefaultArguments(D); | |||
7702 | } else { | |||
7703 | // Make sure any TypoExprs have been dealt with. | |||
7704 | ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); | |||
7705 | if (!Res.isUsable()) | |||
7706 | return ExprError(); | |||
7707 | CastExpr = Res.get(); | |||
7708 | } | |||
7709 | ||||
7710 | checkUnusedDeclAttributes(D); | |||
7711 | ||||
7712 | QualType castType = castTInfo->getType(); | |||
7713 | Ty = CreateParsedType(castType, castTInfo); | |||
7714 | ||||
7715 | bool isVectorLiteral = false; | |||
7716 | ||||
7717 | // Check for an altivec or OpenCL literal, | |||
7718 | // i.e. all the elements are integer constants. | |||
7719 | ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); | |||
7720 | ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); | |||
7721 | if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) | |||
7722 | && castType->isVectorType() && (PE || PLE)) { | |||
7723 | if (PLE && PLE->getNumExprs() == 0) { | |||
7724 | Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); | |||
7725 | return ExprError(); | |||
7726 | } | |||
7727 | if (PE || PLE->getNumExprs() == 1) { | |||
7728 | Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); | |||
7729 | if (!E->isTypeDependent() && !E->getType()->isVectorType()) | |||
7730 | isVectorLiteral = true; | |||
7731 | } | |||
7732 | else | |||
7733 | isVectorLiteral = true; | |||
7734 | } | |||
7735 | ||||
7736 | // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' | |||
7737 | // then handle it as such. | |||
7738 | if (isVectorLiteral) | |||
7739 | return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); | |||
7740 | ||||
7741 | // If the Expr being casted is a ParenListExpr, handle it specially. | |||
7742 | // This is not an AltiVec-style cast, so turn the ParenListExpr into a | |||
7743 | // sequence of BinOp comma operators. | |||
7744 | if (isa<ParenListExpr>(CastExpr)) { | |||
7745 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); | |||
7746 | if (Result.isInvalid()) return ExprError(); | |||
7747 | CastExpr = Result.get(); | |||
7748 | } | |||
7749 | ||||
7750 | if (getLangOpts().CPlusPlus && !castType->isVoidType()) | |||
7751 | Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); | |||
7752 | ||||
7753 | CheckTollFreeBridgeCast(castType, CastExpr); | |||
7754 | ||||
7755 | CheckObjCBridgeRelatedCast(castType, CastExpr); | |||
7756 | ||||
7757 | DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); | |||
7758 | ||||
7759 | return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); | |||
7760 | } | |||
7761 | ||||
7762 | ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, | |||
7763 | SourceLocation RParenLoc, Expr *E, | |||
7764 | TypeSourceInfo *TInfo) { | |||
7765 | assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(static_cast <bool> ((isa<ParenListExpr>(E) || isa <ParenExpr>(E)) && "Expected paren or paren list expression" ) ? void (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "clang/lib/Sema/SemaExpr.cpp", 7766, __extension__ __PRETTY_FUNCTION__ )) | |||
7766 | "Expected paren or paren list expression")(static_cast <bool> ((isa<ParenListExpr>(E) || isa <ParenExpr>(E)) && "Expected paren or paren list expression" ) ? void (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "clang/lib/Sema/SemaExpr.cpp", 7766, __extension__ __PRETTY_FUNCTION__ )); | |||
7767 | ||||
7768 | Expr **exprs; | |||
7769 | unsigned numExprs; | |||
7770 | Expr *subExpr; | |||
7771 | SourceLocation LiteralLParenLoc, LiteralRParenLoc; | |||
7772 | if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { | |||
7773 | LiteralLParenLoc = PE->getLParenLoc(); | |||
7774 | LiteralRParenLoc = PE->getRParenLoc(); | |||
7775 | exprs = PE->getExprs(); | |||
7776 | numExprs = PE->getNumExprs(); | |||
7777 | } else { // isa<ParenExpr> by assertion at function entrance | |||
7778 | LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); | |||
7779 | LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); | |||
7780 | subExpr = cast<ParenExpr>(E)->getSubExpr(); | |||
7781 | exprs = &subExpr; | |||
7782 | numExprs = 1; | |||
7783 | } | |||
7784 | ||||
7785 | QualType Ty = TInfo->getType(); | |||
7786 | assert(Ty->isVectorType() && "Expected vector type")(static_cast <bool> (Ty->isVectorType() && "Expected vector type" ) ? void (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\"" , "clang/lib/Sema/SemaExpr.cpp", 7786, __extension__ __PRETTY_FUNCTION__ )); | |||
7787 | ||||
7788 | SmallVector<Expr *, 8> initExprs; | |||
7789 | const VectorType *VTy = Ty->castAs<VectorType>(); | |||
7790 | unsigned numElems = VTy->getNumElements(); | |||
7791 | ||||
7792 | // '(...)' form of vector initialization in AltiVec: the number of | |||
7793 | // initializers must be one or must match the size of the vector. | |||
7794 | // If a single value is specified in the initializer then it will be | |||
7795 | // replicated to all the components of the vector | |||
7796 | if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, | |||
7797 | VTy->getElementType())) | |||
7798 | return ExprError(); | |||
7799 | if (ShouldSplatAltivecScalarInCast(VTy)) { | |||
7800 | // The number of initializers must be one or must match the size of the | |||
7801 | // vector. If a single value is specified in the initializer then it will | |||
7802 | // be replicated to all the components of the vector | |||
7803 | if (numExprs == 1) { | |||
7804 | QualType ElemTy = VTy->getElementType(); | |||
7805 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | |||
7806 | if (Literal.isInvalid()) | |||
7807 | return ExprError(); | |||
7808 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | |||
7809 | PrepareScalarCast(Literal, ElemTy)); | |||
7810 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | |||
7811 | } | |||
7812 | else if (numExprs < numElems) { | |||
7813 | Diag(E->getExprLoc(), | |||
7814 | diag::err_incorrect_number_of_vector_initializers); | |||
7815 | return ExprError(); | |||
7816 | } | |||
7817 | else | |||
7818 | initExprs.append(exprs, exprs + numExprs); | |||
7819 | } | |||
7820 | else { | |||
7821 | // For OpenCL, when the number of initializers is a single value, | |||
7822 | // it will be replicated to all components of the vector. | |||
7823 | if (getLangOpts().OpenCL && | |||
7824 | VTy->getVectorKind() == VectorType::GenericVector && | |||
7825 | numExprs == 1) { | |||
7826 | QualType ElemTy = VTy->getElementType(); | |||
7827 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | |||
7828 | if (Literal.isInvalid()) | |||
7829 | return ExprError(); | |||
7830 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | |||
7831 | PrepareScalarCast(Literal, ElemTy)); | |||
7832 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | |||
7833 | } | |||
7834 | ||||
7835 | initExprs.append(exprs, exprs + numExprs); | |||
7836 | } | |||
7837 | // FIXME: This means that pretty-printing the final AST will produce curly | |||
7838 | // braces instead of the original commas. | |||
7839 | InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, | |||
7840 | initExprs, LiteralRParenLoc); | |||
7841 | initE->setType(Ty); | |||
7842 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); | |||
7843 | } | |||
7844 | ||||
7845 | /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn | |||
7846 | /// the ParenListExpr into a sequence of comma binary operators. | |||
7847 | ExprResult | |||
7848 | Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { | |||
7849 | ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); | |||
7850 | if (!E) | |||
7851 | return OrigExpr; | |||
7852 | ||||
7853 | ExprResult Result(E->getExpr(0)); | |||
7854 | ||||
7855 | for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) | |||
7856 | Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), | |||
7857 | E->getExpr(i)); | |||
7858 | ||||
7859 | if (Result.isInvalid()) return ExprError(); | |||
7860 | ||||
7861 | return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); | |||
7862 | } | |||
7863 | ||||
7864 | ExprResult Sema::ActOnParenListExpr(SourceLocation L, | |||
7865 | SourceLocation R, | |||
7866 | MultiExprArg Val) { | |||
7867 | return ParenListExpr::Create(Context, L, Val, R); | |||
7868 | } | |||
7869 | ||||
7870 | /// Emit a specialized diagnostic when one expression is a null pointer | |||
7871 | /// constant and the other is not a pointer. Returns true if a diagnostic is | |||
7872 | /// emitted. | |||
7873 | bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, | |||
7874 | SourceLocation QuestionLoc) { | |||
7875 | Expr *NullExpr = LHSExpr; | |||
7876 | Expr *NonPointerExpr = RHSExpr; | |||
7877 | Expr::NullPointerConstantKind NullKind = | |||
7878 | NullExpr->isNullPointerConstant(Context, | |||
7879 | Expr::NPC_ValueDependentIsNotNull); | |||
7880 | ||||
7881 | if (NullKind == Expr::NPCK_NotNull) { | |||
7882 | NullExpr = RHSExpr; | |||
7883 | NonPointerExpr = LHSExpr; | |||
7884 | NullKind = | |||
7885 | NullExpr->isNullPointerConstant(Context, | |||
7886 | Expr::NPC_ValueDependentIsNotNull); | |||
7887 | } | |||
7888 | ||||
7889 | if (NullKind == Expr::NPCK_NotNull) | |||
7890 | return false; | |||
7891 | ||||
7892 | if (NullKind == Expr::NPCK_ZeroExpression) | |||
7893 | return false; | |||
7894 | ||||
7895 | if (NullKind == Expr::NPCK_ZeroLiteral) { | |||
7896 | // In this case, check to make sure that we got here from a "NULL" | |||
7897 | // string in the source code. | |||
7898 | NullExpr = NullExpr->IgnoreParenImpCasts(); | |||
7899 | SourceLocation loc = NullExpr->getExprLoc(); | |||
7900 | if (!findMacroSpelling(loc, "NULL")) | |||
7901 | return false; | |||
7902 | } | |||
7903 | ||||
7904 | int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); | |||
7905 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) | |||
7906 | << NonPointerExpr->getType() << DiagType | |||
7907 | << NonPointerExpr->getSourceRange(); | |||
7908 | return true; | |||
7909 | } | |||
7910 | ||||
7911 | /// Return false if the condition expression is valid, true otherwise. | |||
7912 | static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { | |||
7913 | QualType CondTy = Cond->getType(); | |||
7914 | ||||
7915 | // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. | |||
7916 | if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { | |||
7917 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | |||
7918 | << CondTy << Cond->getSourceRange(); | |||
7919 | return true; | |||
7920 | } | |||
7921 | ||||
7922 | // C99 6.5.15p2 | |||
7923 | if (CondTy->isScalarType()) return false; | |||
7924 | ||||
7925 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) | |||
7926 | << CondTy << Cond->getSourceRange(); | |||
7927 | return true; | |||
7928 | } | |||
7929 | ||||
7930 | /// Handle when one or both operands are void type. | |||
7931 | static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, | |||
7932 | ExprResult &RHS) { | |||
7933 | Expr *LHSExpr = LHS.get(); | |||
7934 | Expr *RHSExpr = RHS.get(); | |||
7935 | ||||
7936 | if (!LHSExpr->getType()->isVoidType()) | |||
7937 | S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) | |||
7938 | << RHSExpr->getSourceRange(); | |||
7939 | if (!RHSExpr->getType()->isVoidType()) | |||
7940 | S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) | |||
7941 | << LHSExpr->getSourceRange(); | |||
7942 | LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); | |||
7943 | RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); | |||
7944 | return S.Context.VoidTy; | |||
7945 | } | |||
7946 | ||||
7947 | /// Return false if the NullExpr can be promoted to PointerTy, | |||
7948 | /// true otherwise. | |||
7949 | static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, | |||
7950 | QualType PointerTy) { | |||
7951 | if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || | |||
7952 | !NullExpr.get()->isNullPointerConstant(S.Context, | |||
7953 | Expr::NPC_ValueDependentIsNull)) | |||
7954 | return true; | |||
7955 | ||||
7956 | NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); | |||
7957 | return false; | |||
7958 | } | |||
7959 | ||||
7960 | /// Checks compatibility between two pointers and return the resulting | |||
7961 | /// type. | |||
7962 | static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, | |||
7963 | ExprResult &RHS, | |||
7964 | SourceLocation Loc) { | |||
7965 | QualType LHSTy = LHS.get()->getType(); | |||
7966 | QualType RHSTy = RHS.get()->getType(); | |||
7967 | ||||
7968 | if (S.Context.hasSameType(LHSTy, RHSTy)) { | |||
7969 | // Two identical pointers types are always compatible. | |||
7970 | return LHSTy; | |||
7971 | } | |||
7972 | ||||
7973 | QualType lhptee, rhptee; | |||
7974 | ||||
7975 | // Get the pointee types. | |||
7976 | bool IsBlockPointer = false; | |||
7977 | if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { | |||
7978 | lhptee = LHSBTy->getPointeeType(); | |||
7979 | rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); | |||
7980 | IsBlockPointer = true; | |||
7981 | } else { | |||
7982 | lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | |||
7983 | rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | |||
7984 | } | |||
7985 | ||||
7986 | // C99 6.5.15p6: If both operands are pointers to compatible types or to | |||
7987 | // differently qualified versions of compatible types, the result type is | |||
7988 | // a pointer to an appropriately qualified version of the composite | |||
7989 | // type. | |||
7990 | ||||
7991 | // Only CVR-qualifiers exist in the standard, and the differently-qualified | |||
7992 | // clause doesn't make sense for our extensions. E.g. address space 2 should | |||
7993 | // be incompatible with address space 3: they may live on different devices or | |||
7994 | // anything. | |||
7995 | Qualifiers lhQual = lhptee.getQualifiers(); | |||
7996 | Qualifiers rhQual = rhptee.getQualifiers(); | |||
7997 | ||||
7998 | LangAS ResultAddrSpace = LangAS::Default; | |||
7999 | LangAS LAddrSpace = lhQual.getAddressSpace(); | |||
8000 | LangAS RAddrSpace = rhQual.getAddressSpace(); | |||
8001 | ||||
8002 | // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address | |||
8003 | // spaces is disallowed. | |||
8004 | if (lhQual.isAddressSpaceSupersetOf(rhQual)) | |||
8005 | ResultAddrSpace = LAddrSpace; | |||
8006 | else if (rhQual.isAddressSpaceSupersetOf(lhQual)) | |||
8007 | ResultAddrSpace = RAddrSpace; | |||
8008 | else { | |||
8009 | S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | |||
8010 | << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() | |||
8011 | << RHS.get()->getSourceRange(); | |||
8012 | return QualType(); | |||
8013 | } | |||
8014 | ||||
8015 | unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); | |||
8016 | auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; | |||
8017 | lhQual.removeCVRQualifiers(); | |||
8018 | rhQual.removeCVRQualifiers(); | |||
8019 | ||||
8020 | // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers | |||
8021 | // (C99 6.7.3) for address spaces. We assume that the check should behave in | |||
8022 | // the same manner as it's defined for CVR qualifiers, so for OpenCL two | |||
8023 | // qual types are compatible iff | |||
8024 | // * corresponded types are compatible | |||
8025 | // * CVR qualifiers are equal | |||
8026 | // * address spaces are equal | |||
8027 | // Thus for conditional operator we merge CVR and address space unqualified | |||
8028 | // pointees and if there is a composite type we return a pointer to it with | |||
8029 | // merged qualifiers. | |||
8030 | LHSCastKind = | |||
8031 | LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | |||
8032 | RHSCastKind = | |||
8033 | RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | |||
8034 | lhQual.removeAddressSpace(); | |||
8035 | rhQual.removeAddressSpace(); | |||
8036 | ||||
8037 | lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); | |||
8038 | rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); | |||
8039 | ||||
8040 | QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); | |||
8041 | ||||
8042 | if (CompositeTy.isNull()) { | |||
8043 | // In this situation, we assume void* type. No especially good | |||
8044 | // reason, but this is what gcc does, and we do have to pick | |||
8045 | // to get a consistent AST. | |||
8046 | QualType incompatTy; | |||
8047 | incompatTy = S.Context.getPointerType( | |||
8048 | S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); | |||
8049 | LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); | |||
8050 | RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); | |||
8051 | ||||
8052 | // FIXME: For OpenCL the warning emission and cast to void* leaves a room | |||
8053 | // for casts between types with incompatible address space qualifiers. | |||
8054 | // For the following code the compiler produces casts between global and | |||
8055 | // local address spaces of the corresponded innermost pointees: | |||
8056 | // local int *global *a; | |||
8057 | // global int *global *b; | |||
8058 | // a = (0 ? a : b); // see C99 6.5.16.1.p1. | |||
8059 | S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) | |||
8060 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | |||
8061 | << RHS.get()->getSourceRange(); | |||
8062 | ||||
8063 | return incompatTy; | |||
8064 | } | |||
8065 | ||||
8066 | // The pointer types are compatible. | |||
8067 | // In case of OpenCL ResultTy should have the address space qualifier | |||
8068 | // which is a superset of address spaces of both the 2nd and the 3rd | |||
8069 | // operands of the conditional operator. | |||
8070 | QualType ResultTy = [&, ResultAddrSpace]() { | |||
8071 | if (S.getLangOpts().OpenCL) { | |||
8072 | Qualifiers CompositeQuals = CompositeTy.getQualifiers(); | |||
8073 | CompositeQuals.setAddressSpace(ResultAddrSpace); | |||
8074 | return S.Context | |||
8075 | .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) | |||
8076 | .withCVRQualifiers(MergedCVRQual); | |||
8077 | } | |||
8078 | return CompositeTy.withCVRQualifiers(MergedCVRQual); | |||
8079 | }(); | |||
8080 | if (IsBlockPointer) | |||
8081 | ResultTy = S.Context.getBlockPointerType(ResultTy); | |||
8082 | else | |||
8083 | ResultTy = S.Context.getPointerType(ResultTy); | |||
8084 | ||||
8085 | LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); | |||
8086 | RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); | |||
8087 | return ResultTy; | |||
8088 | } | |||
8089 | ||||
8090 | /// Return the resulting type when the operands are both block pointers. | |||
8091 | static QualType checkConditionalBlockPointerCompatibility(Sema &S, | |||
8092 | ExprResult &LHS, | |||
8093 | ExprResult &RHS, | |||
8094 | SourceLocation Loc) { | |||
8095 | QualType LHSTy = LHS.get()->getType(); | |||
8096 | QualType RHSTy = RHS.get()->getType(); | |||
8097 | ||||
8098 | if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { | |||
8099 | if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { | |||
8100 | QualType destType = S.Context.getPointerType(S.Context.VoidTy); | |||
8101 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | |||
8102 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | |||
8103 | return destType; | |||
8104 | } | |||
8105 | S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) | |||
8106 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | |||
8107 | << RHS.get()->getSourceRange(); | |||
8108 | return QualType(); | |||
8109 | } | |||
8110 | ||||
8111 | // We have 2 block pointer types. | |||
8112 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | |||
8113 | } | |||
8114 | ||||
8115 | /// Return the resulting type when the operands are both pointers. | |||
8116 | static QualType | |||
8117 | checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, | |||
8118 | ExprResult &RHS, | |||
8119 | SourceLocation Loc) { | |||
8120 | // get the pointer types | |||
8121 | QualType LHSTy = LHS.get()->getType(); | |||
8122 | QualType RHSTy = RHS.get()->getType(); | |||
8123 | ||||
8124 | // get the "pointed to" types | |||
8125 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | |||
8126 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | |||
8127 | ||||
8128 | // ignore qualifiers on void (C99 6.5.15p3, clause 6) | |||
8129 | if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { | |||
8130 | // Figure out necessary qualifiers (C99 6.5.15p6) | |||
8131 | QualType destPointee | |||
8132 | = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | |||
8133 | QualType destType = S.Context.getPointerType(destPointee); | |||
8134 | // Add qualifiers if necessary. | |||
8135 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); | |||
8136 | // Promote to void*. | |||
8137 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | |||
8138 | return destType; | |||
8139 | } | |||
8140 | if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { | |||
8141 | QualType destPointee | |||
8142 | = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | |||
8143 | QualType destType = S.Context.getPointerType(destPointee); | |||
8144 | // Add qualifiers if necessary. | |||
8145 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); | |||
8146 | // Promote to void*. | |||
8147 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | |||
8148 | return destType; | |||
8149 | } | |||
8150 | ||||
8151 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | |||
8152 | } | |||
8153 | ||||
8154 | /// Return false if the first expression is not an integer and the second | |||
8155 | /// expression is not a pointer, true otherwise. | |||
8156 | static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, | |||
8157 | Expr* PointerExpr, SourceLocation Loc, | |||
8158 | bool IsIntFirstExpr) { | |||
8159 | if (!PointerExpr->getType()->isPointerType() || | |||
8160 | !Int.get()->getType()->isIntegerType()) | |||
8161 | return false; | |||
8162 | ||||
8163 | Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; | |||
8164 | Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); | |||
8165 | ||||
8166 | S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) | |||
8167 | << Expr1->getType() << Expr2->getType() | |||
8168 | << Expr1->getSourceRange() << Expr2->getSourceRange(); | |||
8169 | Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), | |||
8170 | CK_IntegralToPointer); | |||
8171 | return true; | |||
8172 | } | |||
8173 | ||||
8174 | /// Simple conversion between integer and floating point types. | |||
8175 | /// | |||
8176 | /// Used when handling the OpenCL conditional operator where the | |||
8177 | /// condition is a vector while the other operands are scalar. | |||
8178 | /// | |||
8179 | /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar | |||
8180 | /// types are either integer or floating type. Between the two | |||
8181 | /// operands, the type with the higher rank is defined as the "result | |||
8182 | /// type". The other operand needs to be promoted to the same type. No | |||
8183 | /// other type promotion is allowed. We cannot use | |||
8184 | /// UsualArithmeticConversions() for this purpose, since it always | |||
8185 | /// promotes promotable types. | |||
8186 | static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, | |||
8187 | ExprResult &RHS, | |||
8188 | SourceLocation QuestionLoc) { | |||
8189 | LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
8190 | if (LHS.isInvalid()) | |||
8191 | return QualType(); | |||
8192 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
8193 | if (RHS.isInvalid()) | |||
8194 | return QualType(); | |||
8195 | ||||
8196 | // For conversion purposes, we ignore any qualifiers. | |||
8197 | // For example, "const float" and "float" are equivalent. | |||
8198 | QualType LHSType = | |||
8199 | S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | |||
8200 | QualType RHSType = | |||
8201 | S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | |||
8202 | ||||
8203 | if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { | |||
8204 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | |||
8205 | << LHSType << LHS.get()->getSourceRange(); | |||
8206 | return QualType(); | |||
8207 | } | |||
8208 | ||||
8209 | if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { | |||
8210 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | |||
8211 | << RHSType << RHS.get()->getSourceRange(); | |||
8212 | return QualType(); | |||
8213 | } | |||
8214 | ||||
8215 | // If both types are identical, no conversion is needed. | |||
8216 | if (LHSType == RHSType) | |||
8217 | return LHSType; | |||
8218 | ||||
8219 | // Now handle "real" floating types (i.e. float, double, long double). | |||
8220 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | |||
8221 | return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, | |||
8222 | /*IsCompAssign = */ false); | |||
8223 | ||||
8224 | // Finally, we have two differing integer types. | |||
8225 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | |||
8226 | (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); | |||
8227 | } | |||
8228 | ||||
8229 | /// Convert scalar operands to a vector that matches the | |||
8230 | /// condition in length. | |||
8231 | /// | |||
8232 | /// Used when handling the OpenCL conditional operator where the | |||
8233 | /// condition is a vector while the other operands are scalar. | |||
8234 | /// | |||
8235 | /// We first compute the "result type" for the scalar operands | |||
8236 | /// according to OpenCL v1.1 s6.3.i. Both operands are then converted | |||
8237 | /// into a vector of that type where the length matches the condition | |||
8238 | /// vector type. s6.11.6 requires that the element types of the result | |||
8239 | /// and the condition must have the same number of bits. | |||
8240 | static QualType | |||
8241 | OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, | |||
8242 | QualType CondTy, SourceLocation QuestionLoc) { | |||
8243 | QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); | |||
8244 | if (ResTy.isNull()) return QualType(); | |||
8245 | ||||
8246 | const VectorType *CV = CondTy->getAs<VectorType>(); | |||
8247 | assert(CV)(static_cast <bool> (CV) ? void (0) : __assert_fail ("CV" , "clang/lib/Sema/SemaExpr.cpp", 8247, __extension__ __PRETTY_FUNCTION__ )); | |||
8248 | ||||
8249 | // Determine the vector result type | |||
8250 | unsigned NumElements = CV->getNumElements(); | |||
8251 | QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); | |||
8252 | ||||
8253 | // Ensure that all types have the same number of bits | |||
8254 | if (S.Context.getTypeSize(CV->getElementType()) | |||
8255 | != S.Context.getTypeSize(ResTy)) { | |||
8256 | // Since VectorTy is created internally, it does not pretty print | |||
8257 | // with an OpenCL name. Instead, we just print a description. | |||
8258 | std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); | |||
8259 | SmallString<64> Str; | |||
8260 | llvm::raw_svector_ostream OS(Str); | |||
8261 | OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; | |||
8262 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | |||
8263 | << CondTy << OS.str(); | |||
8264 | return QualType(); | |||
8265 | } | |||
8266 | ||||
8267 | // Convert operands to the vector result type | |||
8268 | LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); | |||
8269 | RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); | |||
8270 | ||||
8271 | return VectorTy; | |||
8272 | } | |||
8273 | ||||
8274 | /// Return false if this is a valid OpenCL condition vector | |||
8275 | static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, | |||
8276 | SourceLocation QuestionLoc) { | |||
8277 | // OpenCL v1.1 s6.11.6 says the elements of the vector must be of | |||
8278 | // integral type. | |||
8279 | const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); | |||
8280 | assert(CondTy)(static_cast <bool> (CondTy) ? void (0) : __assert_fail ("CondTy", "clang/lib/Sema/SemaExpr.cpp", 8280, __extension__ __PRETTY_FUNCTION__)); | |||
8281 | QualType EleTy = CondTy->getElementType(); | |||
8282 | if (EleTy->isIntegerType()) return false; | |||
8283 | ||||
8284 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | |||
8285 | << Cond->getType() << Cond->getSourceRange(); | |||
8286 | return true; | |||
8287 | } | |||
8288 | ||||
8289 | /// Return false if the vector condition type and the vector | |||
8290 | /// result type are compatible. | |||
8291 | /// | |||
8292 | /// OpenCL v1.1 s6.11.6 requires that both vector types have the same | |||
8293 | /// number of elements, and their element types have the same number | |||
8294 | /// of bits. | |||
8295 | static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, | |||
8296 | SourceLocation QuestionLoc) { | |||
8297 | const VectorType *CV = CondTy->getAs<VectorType>(); | |||
8298 | const VectorType *RV = VecResTy->getAs<VectorType>(); | |||
8299 | assert(CV && RV)(static_cast <bool> (CV && RV) ? void (0) : __assert_fail ("CV && RV", "clang/lib/Sema/SemaExpr.cpp", 8299, __extension__ __PRETTY_FUNCTION__)); | |||
8300 | ||||
8301 | if (CV->getNumElements() != RV->getNumElements()) { | |||
8302 | S.Diag(QuestionLoc, diag::err_conditional_vector_size) | |||
8303 | << CondTy << VecResTy; | |||
8304 | return true; | |||
8305 | } | |||
8306 | ||||
8307 | QualType CVE = CV->getElementType(); | |||
8308 | QualType RVE = RV->getElementType(); | |||
8309 | ||||
8310 | if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { | |||
8311 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | |||
8312 | << CondTy << VecResTy; | |||
8313 | return true; | |||
8314 | } | |||
8315 | ||||
8316 | return false; | |||
8317 | } | |||
8318 | ||||
8319 | /// Return the resulting type for the conditional operator in | |||
8320 | /// OpenCL (aka "ternary selection operator", OpenCL v1.1 | |||
8321 | /// s6.3.i) when the condition is a vector type. | |||
8322 | static QualType | |||
8323 | OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, | |||
8324 | ExprResult &LHS, ExprResult &RHS, | |||
8325 | SourceLocation QuestionLoc) { | |||
8326 | Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); | |||
8327 | if (Cond.isInvalid()) | |||
8328 | return QualType(); | |||
8329 | QualType CondTy = Cond.get()->getType(); | |||
8330 | ||||
8331 | if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) | |||
8332 | return QualType(); | |||
8333 | ||||
8334 | // If either operand is a vector then find the vector type of the | |||
8335 | // result as specified in OpenCL v1.1 s6.3.i. | |||
8336 | if (LHS.get()->getType()->isVectorType() || | |||
8337 | RHS.get()->getType()->isVectorType()) { | |||
8338 | QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, | |||
8339 | /*isCompAssign*/false, | |||
8340 | /*AllowBothBool*/true, | |||
8341 | /*AllowBoolConversions*/false); | |||
8342 | if (VecResTy.isNull()) return QualType(); | |||
8343 | // The result type must match the condition type as specified in | |||
8344 | // OpenCL v1.1 s6.11.6. | |||
8345 | if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) | |||
8346 | return QualType(); | |||
8347 | return VecResTy; | |||
8348 | } | |||
8349 | ||||
8350 | // Both operands are scalar. | |||
8351 | return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); | |||
8352 | } | |||
8353 | ||||
8354 | /// Return true if the Expr is block type | |||
8355 | static bool checkBlockType(Sema &S, const Expr *E) { | |||
8356 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | |||
8357 | QualType Ty = CE->getCallee()->getType(); | |||
8358 | if (Ty->isBlockPointerType()) { | |||
8359 | S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); | |||
8360 | return true; | |||
8361 | } | |||
8362 | } | |||
8363 | return false; | |||
8364 | } | |||
8365 | ||||
8366 | /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. | |||
8367 | /// In that case, LHS = cond. | |||
8368 | /// C99 6.5.15 | |||
8369 | QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, | |||
8370 | ExprResult &RHS, ExprValueKind &VK, | |||
8371 | ExprObjectKind &OK, | |||
8372 | SourceLocation QuestionLoc) { | |||
8373 | ||||
8374 | ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); | |||
8375 | if (!LHSResult.isUsable()) return QualType(); | |||
8376 | LHS = LHSResult; | |||
8377 | ||||
8378 | ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); | |||
8379 | if (!RHSResult.isUsable()) return QualType(); | |||
8380 | RHS = RHSResult; | |||
8381 | ||||
8382 | // C++ is sufficiently different to merit its own checker. | |||
8383 | if (getLangOpts().CPlusPlus) | |||
8384 | return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); | |||
8385 | ||||
8386 | VK = VK_PRValue; | |||
8387 | OK = OK_Ordinary; | |||
8388 | ||||
8389 | if (Context.isDependenceAllowed() && | |||
8390 | (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || | |||
8391 | RHS.get()->isTypeDependent())) { | |||
8392 | assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp" , 8392, __extension__ __PRETTY_FUNCTION__)); | |||
8393 | assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||(static_cast <bool> ((Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors ()) && "should only occur in error-recovery path.") ? void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 8395, __extension__ __PRETTY_FUNCTION__ )) | |||
8394 | RHS.get()->containsErrors()) &&(static_cast <bool> ((Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors ()) && "should only occur in error-recovery path.") ? void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 8395, __extension__ __PRETTY_FUNCTION__ )) | |||
8395 | "should only occur in error-recovery path.")(static_cast <bool> ((Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors ()) && "should only occur in error-recovery path.") ? void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 8395, __extension__ __PRETTY_FUNCTION__ )); | |||
8396 | return Context.DependentTy; | |||
8397 | } | |||
8398 | ||||
8399 | // The OpenCL operator with a vector condition is sufficiently | |||
8400 | // different to merit its own checker. | |||
8401 | if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || | |||
8402 | Cond.get()->getType()->isExtVectorType()) | |||
8403 | return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); | |||
8404 | ||||
8405 | // First, check the condition. | |||
8406 | Cond = UsualUnaryConversions(Cond.get()); | |||
8407 | if (Cond.isInvalid()) | |||
8408 | return QualType(); | |||
8409 | if (checkCondition(*this, Cond.get(), QuestionLoc)) | |||
8410 | return QualType(); | |||
8411 | ||||
8412 | // Now check the two expressions. | |||
8413 | if (LHS.get()->getType()->isVectorType() || | |||
8414 | RHS.get()->getType()->isVectorType()) | |||
8415 | return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, | |||
8416 | /*AllowBothBool*/true, | |||
8417 | /*AllowBoolConversions*/false); | |||
8418 | ||||
8419 | QualType ResTy = | |||
8420 | UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); | |||
8421 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
8422 | return QualType(); | |||
8423 | ||||
8424 | QualType LHSTy = LHS.get()->getType(); | |||
8425 | QualType RHSTy = RHS.get()->getType(); | |||
8426 | ||||
8427 | // Diagnose attempts to convert between __ibm128, __float128 and long double | |||
8428 | // where such conversions currently can't be handled. | |||
8429 | if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { | |||
8430 | Diag(QuestionLoc, | |||
8431 | diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy | |||
8432 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
8433 | return QualType(); | |||
8434 | } | |||
8435 | ||||
8436 | // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary | |||
8437 | // selection operator (?:). | |||
8438 | if (getLangOpts().OpenCL && | |||
8439 | ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { | |||
8440 | return QualType(); | |||
8441 | } | |||
8442 | ||||
8443 | // If both operands have arithmetic type, do the usual arithmetic conversions | |||
8444 | // to find a common type: C99 6.5.15p3,5. | |||
8445 | if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { | |||
8446 | // Disallow invalid arithmetic conversions, such as those between bit- | |||
8447 | // precise integers types of different sizes, or between a bit-precise | |||
8448 | // integer and another type. | |||
8449 | if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { | |||
8450 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | |||
8451 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | |||
8452 | << RHS.get()->getSourceRange(); | |||
8453 | return QualType(); | |||
8454 | } | |||
8455 | ||||
8456 | LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); | |||
8457 | RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); | |||
8458 | ||||
8459 | return ResTy; | |||
8460 | } | |||
8461 | ||||
8462 | // And if they're both bfloat (which isn't arithmetic), that's fine too. | |||
8463 | if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { | |||
8464 | return LHSTy; | |||
8465 | } | |||
8466 | ||||
8467 | // If both operands are the same structure or union type, the result is that | |||
8468 | // type. | |||
8469 | if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 | |||
8470 | if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) | |||
8471 | if (LHSRT->getDecl() == RHSRT->getDecl()) | |||
8472 | // "If both the operands have structure or union type, the result has | |||
8473 | // that type." This implies that CV qualifiers are dropped. | |||
8474 | return LHSTy.getUnqualifiedType(); | |||
8475 | // FIXME: Type of conditional expression must be complete in C mode. | |||
8476 | } | |||
8477 | ||||
8478 | // C99 6.5.15p5: "If both operands have void type, the result has void type." | |||
8479 | // The following || allows only one side to be void (a GCC-ism). | |||
8480 | if (LHSTy->isVoidType() || RHSTy->isVoidType()) { | |||
8481 | return checkConditionalVoidType(*this, LHS, RHS); | |||
8482 | } | |||
8483 | ||||
8484 | // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has | |||
8485 | // the type of the other operand." | |||
8486 | if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; | |||
8487 | if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; | |||
8488 | ||||
8489 | // All objective-c pointer type analysis is done here. | |||
8490 | QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, | |||
8491 | QuestionLoc); | |||
8492 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
8493 | return QualType(); | |||
8494 | if (!compositeType.isNull()) | |||
8495 | return compositeType; | |||
8496 | ||||
8497 | ||||
8498 | // Handle block pointer types. | |||
8499 | if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) | |||
8500 | return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, | |||
8501 | QuestionLoc); | |||
8502 | ||||
8503 | // Check constraints for C object pointers types (C99 6.5.15p3,6). | |||
8504 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) | |||
8505 | return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, | |||
8506 | QuestionLoc); | |||
8507 | ||||
8508 | // GCC compatibility: soften pointer/integer mismatch. Note that | |||
8509 | // null pointers have been filtered out by this point. | |||
8510 | if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, | |||
8511 | /*IsIntFirstExpr=*/true)) | |||
8512 | return RHSTy; | |||
8513 | if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, | |||
8514 | /*IsIntFirstExpr=*/false)) | |||
8515 | return LHSTy; | |||
8516 | ||||
8517 | // Allow ?: operations in which both operands have the same | |||
8518 | // built-in sizeless type. | |||
8519 | if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) | |||
8520 | return LHSTy; | |||
8521 | ||||
8522 | // Emit a better diagnostic if one of the expressions is a null pointer | |||
8523 | // constant and the other is not a pointer type. In this case, the user most | |||
8524 | // likely forgot to take the address of the other expression. | |||
8525 | if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | |||
8526 | return QualType(); | |||
8527 | ||||
8528 | // Otherwise, the operands are not compatible. | |||
8529 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | |||
8530 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | |||
8531 | << RHS.get()->getSourceRange(); | |||
8532 | return QualType(); | |||
8533 | } | |||
8534 | ||||
8535 | /// FindCompositeObjCPointerType - Helper method to find composite type of | |||
8536 | /// two objective-c pointer types of the two input expressions. | |||
8537 | QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, | |||
8538 | SourceLocation QuestionLoc) { | |||
8539 | QualType LHSTy = LHS.get()->getType(); | |||
8540 | QualType RHSTy = RHS.get()->getType(); | |||
8541 | ||||
8542 | // Handle things like Class and struct objc_class*. Here we case the result | |||
8543 | // to the pseudo-builtin, because that will be implicitly cast back to the | |||
8544 | // redefinition type if an attempt is made to access its fields. | |||
8545 | if (LHSTy->isObjCClassType() && | |||
8546 | (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { | |||
8547 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | |||
8548 | return LHSTy; | |||
8549 | } | |||
8550 | if (RHSTy->isObjCClassType() && | |||
8551 | (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { | |||
8552 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | |||
8553 | return RHSTy; | |||
8554 | } | |||
8555 | // And the same for struct objc_object* / id | |||
8556 | if (LHSTy->isObjCIdType() && | |||
8557 | (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { | |||
8558 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | |||
8559 | return LHSTy; | |||
8560 | } | |||
8561 | if (RHSTy->isObjCIdType() && | |||
8562 | (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { | |||
8563 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | |||
8564 | return RHSTy; | |||
8565 | } | |||
8566 | // And the same for struct objc_selector* / SEL | |||
8567 | if (Context.isObjCSelType(LHSTy) && | |||
8568 | (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { | |||
8569 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); | |||
8570 | return LHSTy; | |||
8571 | } | |||
8572 | if (Context.isObjCSelType(RHSTy) && | |||
8573 | (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { | |||
8574 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); | |||
8575 | return RHSTy; | |||
8576 | } | |||
8577 | // Check constraints for Objective-C object pointers types. | |||
8578 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { | |||
8579 | ||||
8580 | if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { | |||
8581 | // Two identical object pointer types are always compatible. | |||
8582 | return LHSTy; | |||
8583 | } | |||
8584 | const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); | |||
8585 | const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); | |||
8586 | QualType compositeType = LHSTy; | |||
8587 | ||||
8588 | // If both operands are interfaces and either operand can be | |||
8589 | // assigned to the other, use that type as the composite | |||
8590 | // type. This allows | |||
8591 | // xxx ? (A*) a : (B*) b | |||
8592 | // where B is a subclass of A. | |||
8593 | // | |||
8594 | // Additionally, as for assignment, if either type is 'id' | |||
8595 | // allow silent coercion. Finally, if the types are | |||
8596 | // incompatible then make sure to use 'id' as the composite | |||
8597 | // type so the result is acceptable for sending messages to. | |||
8598 | ||||
8599 | // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. | |||
8600 | // It could return the composite type. | |||
8601 | if (!(compositeType = | |||
8602 | Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { | |||
8603 | // Nothing more to do. | |||
8604 | } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { | |||
8605 | compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; | |||
8606 | } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { | |||
8607 | compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; | |||
8608 | } else if ((LHSOPT->isObjCQualifiedIdType() || | |||
8609 | RHSOPT->isObjCQualifiedIdType()) && | |||
8610 | Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, | |||
8611 | true)) { | |||
8612 | // Need to handle "id<xx>" explicitly. | |||
8613 | // GCC allows qualified id and any Objective-C type to devolve to | |||
8614 | // id. Currently localizing to here until clear this should be | |||
8615 | // part of ObjCQualifiedIdTypesAreCompatible. | |||
8616 | compositeType = Context.getObjCIdType(); | |||
8617 | } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { | |||
8618 | compositeType = Context.getObjCIdType(); | |||
8619 | } else { | |||
8620 | Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) | |||
8621 | << LHSTy << RHSTy | |||
8622 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
8623 | QualType incompatTy = Context.getObjCIdType(); | |||
8624 | LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); | |||
8625 | RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); | |||
8626 | return incompatTy; | |||
8627 | } | |||
8628 | // The object pointer types are compatible. | |||
8629 | LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); | |||
8630 | RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); | |||
8631 | return compositeType; | |||
8632 | } | |||
8633 | // Check Objective-C object pointer types and 'void *' | |||
8634 | if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { | |||
8635 | if (getLangOpts().ObjCAutoRefCount) { | |||
8636 | // ARC forbids the implicit conversion of object pointers to 'void *', | |||
8637 | // so these types are not compatible. | |||
8638 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | |||
8639 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
8640 | LHS = RHS = true; | |||
8641 | return QualType(); | |||
8642 | } | |||
8643 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | |||
8644 | QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | |||
8645 | QualType destPointee | |||
8646 | = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | |||
8647 | QualType destType = Context.getPointerType(destPointee); | |||
8648 | // Add qualifiers if necessary. | |||
8649 | LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); | |||
8650 | // Promote to void*. | |||
8651 | RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); | |||
8652 | return destType; | |||
8653 | } | |||
8654 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { | |||
8655 | if (getLangOpts().ObjCAutoRefCount) { | |||
8656 | // ARC forbids the implicit conversion of object pointers to 'void *', | |||
8657 | // so these types are not compatible. | |||
8658 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | |||
8659 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
8660 | LHS = RHS = true; | |||
8661 | return QualType(); | |||
8662 | } | |||
8663 | QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | |||
8664 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | |||
8665 | QualType destPointee | |||
8666 | = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | |||
8667 | QualType destType = Context.getPointerType(destPointee); | |||
8668 | // Add qualifiers if necessary. | |||
8669 | RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); | |||
8670 | // Promote to void*. | |||
8671 | LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); | |||
8672 | return destType; | |||
8673 | } | |||
8674 | return QualType(); | |||
8675 | } | |||
8676 | ||||
8677 | /// SuggestParentheses - Emit a note with a fixit hint that wraps | |||
8678 | /// ParenRange in parentheses. | |||
8679 | static void SuggestParentheses(Sema &Self, SourceLocation Loc, | |||
8680 | const PartialDiagnostic &Note, | |||
8681 | SourceRange ParenRange) { | |||
8682 | SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); | |||
8683 | if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && | |||
8684 | EndLoc.isValid()) { | |||
8685 | Self.Diag(Loc, Note) | |||
8686 | << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") | |||
8687 | << FixItHint::CreateInsertion(EndLoc, ")"); | |||
8688 | } else { | |||
8689 | // We can't display the parentheses, so just show the bare note. | |||
8690 | Self.Diag(Loc, Note) << ParenRange; | |||
8691 | } | |||
8692 | } | |||
8693 | ||||
8694 | static bool IsArithmeticOp(BinaryOperatorKind Opc) { | |||
8695 | return BinaryOperator::isAdditiveOp(Opc) || | |||
8696 | BinaryOperator::isMultiplicativeOp(Opc) || | |||
8697 | BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; | |||
8698 | // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and | |||
8699 | // not any of the logical operators. Bitwise-xor is commonly used as a | |||
8700 | // logical-xor because there is no logical-xor operator. The logical | |||
8701 | // operators, including uses of xor, have a high false positive rate for | |||
8702 | // precedence warnings. | |||
8703 | } | |||
8704 | ||||
8705 | /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary | |||
8706 | /// expression, either using a built-in or overloaded operator, | |||
8707 | /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side | |||
8708 | /// expression. | |||
8709 | static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, | |||
8710 | Expr **RHSExprs) { | |||
8711 | // Don't strip parenthesis: we should not warn if E is in parenthesis. | |||
8712 | E = E->IgnoreImpCasts(); | |||
8713 | E = E->IgnoreConversionOperatorSingleStep(); | |||
8714 | E = E->IgnoreImpCasts(); | |||
8715 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { | |||
8716 | E = MTE->getSubExpr(); | |||
8717 | E = E->IgnoreImpCasts(); | |||
8718 | } | |||
8719 | ||||
8720 | // Built-in binary operator. | |||
8721 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { | |||
8722 | if (IsArithmeticOp(OP->getOpcode())) { | |||
8723 | *Opcode = OP->getOpcode(); | |||
8724 | *RHSExprs = OP->getRHS(); | |||
8725 | return true; | |||
8726 | } | |||
8727 | } | |||
8728 | ||||
8729 | // Overloaded operator. | |||
8730 | if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { | |||
8731 | if (Call->getNumArgs() != 2) | |||
8732 | return false; | |||
8733 | ||||
8734 | // Make sure this is really a binary operator that is safe to pass into | |||
8735 | // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. | |||
8736 | OverloadedOperatorKind OO = Call->getOperator(); | |||
8737 | if (OO < OO_Plus || OO > OO_Arrow || | |||
8738 | OO == OO_PlusPlus || OO == OO_MinusMinus) | |||
8739 | return false; | |||
8740 | ||||
8741 | BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); | |||
8742 | if (IsArithmeticOp(OpKind)) { | |||
8743 | *Opcode = OpKind; | |||
8744 | *RHSExprs = Call->getArg(1); | |||
8745 | return true; | |||
8746 | } | |||
8747 | } | |||
8748 | ||||
8749 | return false; | |||
8750 | } | |||
8751 | ||||
8752 | /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type | |||
8753 | /// or is a logical expression such as (x==y) which has int type, but is | |||
8754 | /// commonly interpreted as boolean. | |||
8755 | static bool ExprLooksBoolean(Expr *E) { | |||
8756 | E = E->IgnoreParenImpCasts(); | |||
8757 | ||||
8758 | if (E->getType()->isBooleanType()) | |||
8759 | return true; | |||
8760 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) | |||
8761 | return OP->isComparisonOp() || OP->isLogicalOp(); | |||
8762 | if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) | |||
8763 | return OP->getOpcode() == UO_LNot; | |||
8764 | if (E->getType()->isPointerType()) | |||
8765 | return true; | |||
8766 | // FIXME: What about overloaded operator calls returning "unspecified boolean | |||
8767 | // type"s (commonly pointer-to-members)? | |||
8768 | ||||
8769 | return false; | |||
8770 | } | |||
8771 | ||||
8772 | /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator | |||
8773 | /// and binary operator are mixed in a way that suggests the programmer assumed | |||
8774 | /// the conditional operator has higher precedence, for example: | |||
8775 | /// "int x = a + someBinaryCondition ? 1 : 2". | |||
8776 | static void DiagnoseConditionalPrecedence(Sema &Self, | |||
8777 | SourceLocation OpLoc, | |||
8778 | Expr *Condition, | |||
8779 | Expr *LHSExpr, | |||
8780 | Expr *RHSExpr) { | |||
8781 | BinaryOperatorKind CondOpcode; | |||
8782 | Expr *CondRHS; | |||
8783 | ||||
8784 | if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) | |||
8785 | return; | |||
8786 | if (!ExprLooksBoolean(CondRHS)) | |||
8787 | return; | |||
8788 | ||||
8789 | // The condition is an arithmetic binary expression, with a right- | |||
8790 | // hand side that looks boolean, so warn. | |||
8791 | ||||
8792 | unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) | |||
8793 | ? diag::warn_precedence_bitwise_conditional | |||
8794 | : diag::warn_precedence_conditional; | |||
8795 | ||||
8796 | Self.Diag(OpLoc, DiagID) | |||
8797 | << Condition->getSourceRange() | |||
8798 | << BinaryOperator::getOpcodeStr(CondOpcode); | |||
8799 | ||||
8800 | SuggestParentheses( | |||
8801 | Self, OpLoc, | |||
8802 | Self.PDiag(diag::note_precedence_silence) | |||
8803 | << BinaryOperator::getOpcodeStr(CondOpcode), | |||
8804 | SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); | |||
8805 | ||||
8806 | SuggestParentheses(Self, OpLoc, | |||
8807 | Self.PDiag(diag::note_precedence_conditional_first), | |||
8808 | SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); | |||
8809 | } | |||
8810 | ||||
8811 | /// Compute the nullability of a conditional expression. | |||
8812 | static QualType computeConditionalNullability(QualType ResTy, bool IsBin, | |||
8813 | QualType LHSTy, QualType RHSTy, | |||
8814 | ASTContext &Ctx) { | |||
8815 | if (!ResTy->isAnyPointerType()) | |||
8816 | return ResTy; | |||
8817 | ||||
8818 | auto GetNullability = [&Ctx](QualType Ty) { | |||
8819 | Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); | |||
8820 | if (Kind) { | |||
8821 | // For our purposes, treat _Nullable_result as _Nullable. | |||
8822 | if (*Kind == NullabilityKind::NullableResult) | |||
8823 | return NullabilityKind::Nullable; | |||
8824 | return *Kind; | |||
8825 | } | |||
8826 | return NullabilityKind::Unspecified; | |||
8827 | }; | |||
8828 | ||||
8829 | auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); | |||
8830 | NullabilityKind MergedKind; | |||
8831 | ||||
8832 | // Compute nullability of a binary conditional expression. | |||
8833 | if (IsBin) { | |||
8834 | if (LHSKind == NullabilityKind::NonNull) | |||
8835 | MergedKind = NullabilityKind::NonNull; | |||
8836 | else | |||
8837 | MergedKind = RHSKind; | |||
8838 | // Compute nullability of a normal conditional expression. | |||
8839 | } else { | |||
8840 | if (LHSKind == NullabilityKind::Nullable || | |||
8841 | RHSKind == NullabilityKind::Nullable) | |||
8842 | MergedKind = NullabilityKind::Nullable; | |||
8843 | else if (LHSKind == NullabilityKind::NonNull) | |||
8844 | MergedKind = RHSKind; | |||
8845 | else if (RHSKind == NullabilityKind::NonNull) | |||
8846 | MergedKind = LHSKind; | |||
8847 | else | |||
8848 | MergedKind = NullabilityKind::Unspecified; | |||
8849 | } | |||
8850 | ||||
8851 | // Return if ResTy already has the correct nullability. | |||
8852 | if (GetNullability(ResTy) == MergedKind) | |||
8853 | return ResTy; | |||
8854 | ||||
8855 | // Strip all nullability from ResTy. | |||
8856 | while (ResTy->getNullability(Ctx)) | |||
8857 | ResTy = ResTy.getSingleStepDesugaredType(Ctx); | |||
8858 | ||||
8859 | // Create a new AttributedType with the new nullability kind. | |||
8860 | auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); | |||
8861 | return Ctx.getAttributedType(NewAttr, ResTy, ResTy); | |||
8862 | } | |||
8863 | ||||
8864 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null | |||
8865 | /// in the case of a the GNU conditional expr extension. | |||
8866 | ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, | |||
8867 | SourceLocation ColonLoc, | |||
8868 | Expr *CondExpr, Expr *LHSExpr, | |||
8869 | Expr *RHSExpr) { | |||
8870 | if (!Context.isDependenceAllowed()) { | |||
8871 | // C cannot handle TypoExpr nodes in the condition because it | |||
8872 | // doesn't handle dependent types properly, so make sure any TypoExprs have | |||
8873 | // been dealt with before checking the operands. | |||
8874 | ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); | |||
8875 | ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); | |||
8876 | ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); | |||
8877 | ||||
8878 | if (!CondResult.isUsable()) | |||
8879 | return ExprError(); | |||
8880 | ||||
8881 | if (LHSExpr) { | |||
8882 | if (!LHSResult.isUsable()) | |||
8883 | return ExprError(); | |||
8884 | } | |||
8885 | ||||
8886 | if (!RHSResult.isUsable()) | |||
8887 | return ExprError(); | |||
8888 | ||||
8889 | CondExpr = CondResult.get(); | |||
8890 | LHSExpr = LHSResult.get(); | |||
8891 | RHSExpr = RHSResult.get(); | |||
8892 | } | |||
8893 | ||||
8894 | // If this is the gnu "x ?: y" extension, analyze the types as though the LHS | |||
8895 | // was the condition. | |||
8896 | OpaqueValueExpr *opaqueValue = nullptr; | |||
8897 | Expr *commonExpr = nullptr; | |||
8898 | if (!LHSExpr) { | |||
8899 | commonExpr = CondExpr; | |||
8900 | // Lower out placeholder types first. This is important so that we don't | |||
8901 | // try to capture a placeholder. This happens in few cases in C++; such | |||
8902 | // as Objective-C++'s dictionary subscripting syntax. | |||
8903 | if (commonExpr->hasPlaceholderType()) { | |||
8904 | ExprResult result = CheckPlaceholderExpr(commonExpr); | |||
8905 | if (!result.isUsable()) return ExprError(); | |||
8906 | commonExpr = result.get(); | |||
8907 | } | |||
8908 | // We usually want to apply unary conversions *before* saving, except | |||
8909 | // in the special case of a C++ l-value conditional. | |||
8910 | if (!(getLangOpts().CPlusPlus | |||
8911 | && !commonExpr->isTypeDependent() | |||
8912 | && commonExpr->getValueKind() == RHSExpr->getValueKind() | |||
8913 | && commonExpr->isGLValue() | |||
8914 | && commonExpr->isOrdinaryOrBitFieldObject() | |||
8915 | && RHSExpr->isOrdinaryOrBitFieldObject() | |||
8916 | && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { | |||
8917 | ExprResult commonRes = UsualUnaryConversions(commonExpr); | |||
8918 | if (commonRes.isInvalid()) | |||
8919 | return ExprError(); | |||
8920 | commonExpr = commonRes.get(); | |||
8921 | } | |||
8922 | ||||
8923 | // If the common expression is a class or array prvalue, materialize it | |||
8924 | // so that we can safely refer to it multiple times. | |||
8925 | if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || | |||
8926 | commonExpr->getType()->isArrayType())) { | |||
8927 | ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); | |||
8928 | if (MatExpr.isInvalid()) | |||
8929 | return ExprError(); | |||
8930 | commonExpr = MatExpr.get(); | |||
8931 | } | |||
8932 | ||||
8933 | opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), | |||
8934 | commonExpr->getType(), | |||
8935 | commonExpr->getValueKind(), | |||
8936 | commonExpr->getObjectKind(), | |||
8937 | commonExpr); | |||
8938 | LHSExpr = CondExpr = opaqueValue; | |||
8939 | } | |||
8940 | ||||
8941 | QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); | |||
8942 | ExprValueKind VK = VK_PRValue; | |||
8943 | ExprObjectKind OK = OK_Ordinary; | |||
8944 | ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; | |||
8945 | QualType result = CheckConditionalOperands(Cond, LHS, RHS, | |||
8946 | VK, OK, QuestionLoc); | |||
8947 | if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || | |||
8948 | RHS.isInvalid()) | |||
8949 | return ExprError(); | |||
8950 | ||||
8951 | DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), | |||
8952 | RHS.get()); | |||
8953 | ||||
8954 | CheckBoolLikeConversion(Cond.get(), QuestionLoc); | |||
8955 | ||||
8956 | result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, | |||
8957 | Context); | |||
8958 | ||||
8959 | if (!commonExpr) | |||
8960 | return new (Context) | |||
8961 | ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, | |||
8962 | RHS.get(), result, VK, OK); | |||
8963 | ||||
8964 | return new (Context) BinaryConditionalOperator( | |||
8965 | commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, | |||
8966 | ColonLoc, result, VK, OK); | |||
8967 | } | |||
8968 | ||||
8969 | // Check if we have a conversion between incompatible cmse function pointer | |||
8970 | // types, that is, a conversion between a function pointer with the | |||
8971 | // cmse_nonsecure_call attribute and one without. | |||
8972 | static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, | |||
8973 | QualType ToType) { | |||
8974 | if (const auto *ToFn = | |||
8975 | dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { | |||
8976 | if (const auto *FromFn = | |||
8977 | dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { | |||
8978 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); | |||
8979 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); | |||
8980 | ||||
8981 | return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); | |||
8982 | } | |||
8983 | } | |||
8984 | return false; | |||
8985 | } | |||
8986 | ||||
8987 | // checkPointerTypesForAssignment - This is a very tricky routine (despite | |||
8988 | // being closely modeled after the C99 spec:-). The odd characteristic of this | |||
8989 | // routine is it effectively iqnores the qualifiers on the top level pointee. | |||
8990 | // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. | |||
8991 | // FIXME: add a couple examples in this comment. | |||
8992 | static Sema::AssignConvertType | |||
8993 | checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { | |||
8994 | assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 8994, __extension__ __PRETTY_FUNCTION__ )); | |||
8995 | assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 8995, __extension__ __PRETTY_FUNCTION__ )); | |||
8996 | ||||
8997 | // get the "pointed to" type (ignoring qualifiers at the top level) | |||
8998 | const Type *lhptee, *rhptee; | |||
8999 | Qualifiers lhq, rhq; | |||
9000 | std::tie(lhptee, lhq) = | |||
9001 | cast<PointerType>(LHSType)->getPointeeType().split().asPair(); | |||
9002 | std::tie(rhptee, rhq) = | |||
9003 | cast<PointerType>(RHSType)->getPointeeType().split().asPair(); | |||
9004 | ||||
9005 | Sema::AssignConvertType ConvTy = Sema::Compatible; | |||
9006 | ||||
9007 | // C99 6.5.16.1p1: This following citation is common to constraints | |||
9008 | // 3 & 4 (below). ...and the type *pointed to* by the left has all the | |||
9009 | // qualifiers of the type *pointed to* by the right; | |||
9010 | ||||
9011 | // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. | |||
9012 | if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && | |||
9013 | lhq.compatiblyIncludesObjCLifetime(rhq)) { | |||
9014 | // Ignore lifetime for further calculation. | |||
9015 | lhq.removeObjCLifetime(); | |||
9016 | rhq.removeObjCLifetime(); | |||
9017 | } | |||
9018 | ||||
9019 | if (!lhq.compatiblyIncludes(rhq)) { | |||
9020 | // Treat address-space mismatches as fatal. | |||
9021 | if (!lhq.isAddressSpaceSupersetOf(rhq)) | |||
9022 | return Sema::IncompatiblePointerDiscardsQualifiers; | |||
9023 | ||||
9024 | // It's okay to add or remove GC or lifetime qualifiers when converting to | |||
9025 | // and from void*. | |||
9026 | else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() | |||
9027 | .compatiblyIncludes( | |||
9028 | rhq.withoutObjCGCAttr().withoutObjCLifetime()) | |||
9029 | && (lhptee->isVoidType() || rhptee->isVoidType())) | |||
9030 | ; // keep old | |||
9031 | ||||
9032 | // Treat lifetime mismatches as fatal. | |||
9033 | else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) | |||
9034 | ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; | |||
9035 | ||||
9036 | // For GCC/MS compatibility, other qualifier mismatches are treated | |||
9037 | // as still compatible in C. | |||
9038 | else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | |||
9039 | } | |||
9040 | ||||
9041 | // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or | |||
9042 | // incomplete type and the other is a pointer to a qualified or unqualified | |||
9043 | // version of void... | |||
9044 | if (lhptee->isVoidType()) { | |||
9045 | if (rhptee->isIncompleteOrObjectType()) | |||
9046 | return ConvTy; | |||
9047 | ||||
9048 | // As an extension, we allow cast to/from void* to function pointer. | |||
9049 | assert(rhptee->isFunctionType())(static_cast <bool> (rhptee->isFunctionType()) ? void (0) : __assert_fail ("rhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp" , 9049, __extension__ __PRETTY_FUNCTION__)); | |||
9050 | return Sema::FunctionVoidPointer; | |||
9051 | } | |||
9052 | ||||
9053 | if (rhptee->isVoidType()) { | |||
9054 | if (lhptee->isIncompleteOrObjectType()) | |||
9055 | return ConvTy; | |||
9056 | ||||
9057 | // As an extension, we allow cast to/from void* to function pointer. | |||
9058 | assert(lhptee->isFunctionType())(static_cast <bool> (lhptee->isFunctionType()) ? void (0) : __assert_fail ("lhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp" , 9058, __extension__ __PRETTY_FUNCTION__)); | |||
9059 | return Sema::FunctionVoidPointer; | |||
9060 | } | |||
9061 | ||||
9062 | // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or | |||
9063 | // unqualified versions of compatible types, ... | |||
9064 | QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); | |||
9065 | if (!S.Context.typesAreCompatible(ltrans, rtrans)) { | |||
9066 | // Check if the pointee types are compatible ignoring the sign. | |||
9067 | // We explicitly check for char so that we catch "char" vs | |||
9068 | // "unsigned char" on systems where "char" is unsigned. | |||
9069 | if (lhptee->isCharType()) | |||
9070 | ltrans = S.Context.UnsignedCharTy; | |||
9071 | else if (lhptee->hasSignedIntegerRepresentation()) | |||
9072 | ltrans = S.Context.getCorrespondingUnsignedType(ltrans); | |||
9073 | ||||
9074 | if (rhptee->isCharType()) | |||
9075 | rtrans = S.Context.UnsignedCharTy; | |||
9076 | else if (rhptee->hasSignedIntegerRepresentation()) | |||
9077 | rtrans = S.Context.getCorrespondingUnsignedType(rtrans); | |||
9078 | ||||
9079 | if (ltrans == rtrans) { | |||
9080 | // Types are compatible ignoring the sign. Qualifier incompatibility | |||
9081 | // takes priority over sign incompatibility because the sign | |||
9082 | // warning can be disabled. | |||
9083 | if (ConvTy != Sema::Compatible) | |||
9084 | return ConvTy; | |||
9085 | ||||
9086 | return Sema::IncompatiblePointerSign; | |||
9087 | } | |||
9088 | ||||
9089 | // If we are a multi-level pointer, it's possible that our issue is simply | |||
9090 | // one of qualification - e.g. char ** -> const char ** is not allowed. If | |||
9091 | // the eventual target type is the same and the pointers have the same | |||
9092 | // level of indirection, this must be the issue. | |||
9093 | if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { | |||
9094 | do { | |||
9095 | std::tie(lhptee, lhq) = | |||
9096 | cast<PointerType>(lhptee)->getPointeeType().split().asPair(); | |||
9097 | std::tie(rhptee, rhq) = | |||
9098 | cast<PointerType>(rhptee)->getPointeeType().split().asPair(); | |||
9099 | ||||
9100 | // Inconsistent address spaces at this point is invalid, even if the | |||
9101 | // address spaces would be compatible. | |||
9102 | // FIXME: This doesn't catch address space mismatches for pointers of | |||
9103 | // different nesting levels, like: | |||
9104 | // __local int *** a; | |||
9105 | // int ** b = a; | |||
9106 | // It's not clear how to actually determine when such pointers are | |||
9107 | // invalidly incompatible. | |||
9108 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) | |||
9109 | return Sema::IncompatibleNestedPointerAddressSpaceMismatch; | |||
9110 | ||||
9111 | } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); | |||
9112 | ||||
9113 | if (lhptee == rhptee) | |||
9114 | return Sema::IncompatibleNestedPointerQualifiers; | |||
9115 | } | |||
9116 | ||||
9117 | // General pointer incompatibility takes priority over qualifiers. | |||
9118 | if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) | |||
9119 | return Sema::IncompatibleFunctionPointer; | |||
9120 | return Sema::IncompatiblePointer; | |||
9121 | } | |||
9122 | if (!S.getLangOpts().CPlusPlus && | |||
9123 | S.IsFunctionConversion(ltrans, rtrans, ltrans)) | |||
9124 | return Sema::IncompatibleFunctionPointer; | |||
9125 | if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) | |||
9126 | return Sema::IncompatibleFunctionPointer; | |||
9127 | return ConvTy; | |||
9128 | } | |||
9129 | ||||
9130 | /// checkBlockPointerTypesForAssignment - This routine determines whether two | |||
9131 | /// block pointer types are compatible or whether a block and normal pointer | |||
9132 | /// are compatible. It is more restrict than comparing two function pointer | |||
9133 | // types. | |||
9134 | static Sema::AssignConvertType | |||
9135 | checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, | |||
9136 | QualType RHSType) { | |||
9137 | assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9137, __extension__ __PRETTY_FUNCTION__ )); | |||
9138 | assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9138, __extension__ __PRETTY_FUNCTION__ )); | |||
9139 | ||||
9140 | QualType lhptee, rhptee; | |||
9141 | ||||
9142 | // get the "pointed to" type (ignoring qualifiers at the top level) | |||
9143 | lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); | |||
9144 | rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); | |||
9145 | ||||
9146 | // In C++, the types have to match exactly. | |||
9147 | if (S.getLangOpts().CPlusPlus) | |||
9148 | return Sema::IncompatibleBlockPointer; | |||
9149 | ||||
9150 | Sema::AssignConvertType ConvTy = Sema::Compatible; | |||
9151 | ||||
9152 | // For blocks we enforce that qualifiers are identical. | |||
9153 | Qualifiers LQuals = lhptee.getLocalQualifiers(); | |||
9154 | Qualifiers RQuals = rhptee.getLocalQualifiers(); | |||
9155 | if (S.getLangOpts().OpenCL) { | |||
9156 | LQuals.removeAddressSpace(); | |||
9157 | RQuals.removeAddressSpace(); | |||
9158 | } | |||
9159 | if (LQuals != RQuals) | |||
9160 | ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | |||
9161 | ||||
9162 | // FIXME: OpenCL doesn't define the exact compile time semantics for a block | |||
9163 | // assignment. | |||
9164 | // The current behavior is similar to C++ lambdas. A block might be | |||
9165 | // assigned to a variable iff its return type and parameters are compatible | |||
9166 | // (C99 6.2.7) with the corresponding return type and parameters of the LHS of | |||
9167 | // an assignment. Presumably it should behave in way that a function pointer | |||
9168 | // assignment does in C, so for each parameter and return type: | |||
9169 | // * CVR and address space of LHS should be a superset of CVR and address | |||
9170 | // space of RHS. | |||
9171 | // * unqualified types should be compatible. | |||
9172 | if (S.getLangOpts().OpenCL) { | |||
9173 | if (!S.Context.typesAreBlockPointerCompatible( | |||
9174 | S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), | |||
9175 | S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) | |||
9176 | return Sema::IncompatibleBlockPointer; | |||
9177 | } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) | |||
9178 | return Sema::IncompatibleBlockPointer; | |||
9179 | ||||
9180 | return ConvTy; | |||
9181 | } | |||
9182 | ||||
9183 | /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types | |||
9184 | /// for assignment compatibility. | |||
9185 | static Sema::AssignConvertType | |||
9186 | checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, | |||
9187 | QualType RHSType) { | |||
9188 | assert(LHSType.isCanonical() && "LHS was not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS was not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS was not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9188, __extension__ __PRETTY_FUNCTION__ )); | |||
9189 | assert(RHSType.isCanonical() && "RHS was not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS was not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS was not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9189, __extension__ __PRETTY_FUNCTION__ )); | |||
9190 | ||||
9191 | if (LHSType->isObjCBuiltinType()) { | |||
9192 | // Class is not compatible with ObjC object pointers. | |||
9193 | if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && | |||
9194 | !RHSType->isObjCQualifiedClassType()) | |||
9195 | return Sema::IncompatiblePointer; | |||
9196 | return Sema::Compatible; | |||
9197 | } | |||
9198 | if (RHSType->isObjCBuiltinType()) { | |||
9199 | if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && | |||
9200 | !LHSType->isObjCQualifiedClassType()) | |||
9201 | return Sema::IncompatiblePointer; | |||
9202 | return Sema::Compatible; | |||
9203 | } | |||
9204 | QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | |||
9205 | QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | |||
9206 | ||||
9207 | if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && | |||
9208 | // make an exception for id<P> | |||
9209 | !LHSType->isObjCQualifiedIdType()) | |||
9210 | return Sema::CompatiblePointerDiscardsQualifiers; | |||
9211 | ||||
9212 | if (S.Context.typesAreCompatible(LHSType, RHSType)) | |||
9213 | return Sema::Compatible; | |||
9214 | if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) | |||
9215 | return Sema::IncompatibleObjCQualifiedId; | |||
9216 | return Sema::IncompatiblePointer; | |||
9217 | } | |||
9218 | ||||
9219 | Sema::AssignConvertType | |||
9220 | Sema::CheckAssignmentConstraints(SourceLocation Loc, | |||
9221 | QualType LHSType, QualType RHSType) { | |||
9222 | // Fake up an opaque expression. We don't actually care about what | |||
9223 | // cast operations are required, so if CheckAssignmentConstraints | |||
9224 | // adds casts to this they'll be wasted, but fortunately that doesn't | |||
9225 | // usually happen on valid code. | |||
9226 | OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); | |||
9227 | ExprResult RHSPtr = &RHSExpr; | |||
9228 | CastKind K; | |||
9229 | ||||
9230 | return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); | |||
9231 | } | |||
9232 | ||||
9233 | /// This helper function returns true if QT is a vector type that has element | |||
9234 | /// type ElementType. | |||
9235 | static bool isVector(QualType QT, QualType ElementType) { | |||
9236 | if (const VectorType *VT = QT->getAs<VectorType>()) | |||
9237 | return VT->getElementType().getCanonicalType() == ElementType; | |||
9238 | return false; | |||
9239 | } | |||
9240 | ||||
9241 | /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently | |||
9242 | /// has code to accommodate several GCC extensions when type checking | |||
9243 | /// pointers. Here are some objectionable examples that GCC considers warnings: | |||
9244 | /// | |||
9245 | /// int a, *pint; | |||
9246 | /// short *pshort; | |||
9247 | /// struct foo *pfoo; | |||
9248 | /// | |||
9249 | /// pint = pshort; // warning: assignment from incompatible pointer type | |||
9250 | /// a = pint; // warning: assignment makes integer from pointer without a cast | |||
9251 | /// pint = a; // warning: assignment makes pointer from integer without a cast | |||
9252 | /// pint = pfoo; // warning: assignment from incompatible pointer type | |||
9253 | /// | |||
9254 | /// As a result, the code for dealing with pointers is more complex than the | |||
9255 | /// C99 spec dictates. | |||
9256 | /// | |||
9257 | /// Sets 'Kind' for any result kind except Incompatible. | |||
9258 | Sema::AssignConvertType | |||
9259 | Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, | |||
9260 | CastKind &Kind, bool ConvertRHS) { | |||
9261 | QualType RHSType = RHS.get()->getType(); | |||
9262 | QualType OrigLHSType = LHSType; | |||
9263 | ||||
9264 | // Get canonical types. We're not formatting these types, just comparing | |||
9265 | // them. | |||
9266 | LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); | |||
9267 | RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); | |||
9268 | ||||
9269 | // Common case: no conversion required. | |||
9270 | if (LHSType == RHSType) { | |||
9271 | Kind = CK_NoOp; | |||
9272 | return Compatible; | |||
9273 | } | |||
9274 | ||||
9275 | // If we have an atomic type, try a non-atomic assignment, then just add an | |||
9276 | // atomic qualification step. | |||
9277 | if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { | |||
9278 | Sema::AssignConvertType result = | |||
9279 | CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); | |||
9280 | if (result != Compatible) | |||
9281 | return result; | |||
9282 | if (Kind != CK_NoOp && ConvertRHS) | |||
9283 | RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); | |||
9284 | Kind = CK_NonAtomicToAtomic; | |||
9285 | return Compatible; | |||
9286 | } | |||
9287 | ||||
9288 | // If the left-hand side is a reference type, then we are in a | |||
9289 | // (rare!) case where we've allowed the use of references in C, | |||
9290 | // e.g., as a parameter type in a built-in function. In this case, | |||
9291 | // just make sure that the type referenced is compatible with the | |||
9292 | // right-hand side type. The caller is responsible for adjusting | |||
9293 | // LHSType so that the resulting expression does not have reference | |||
9294 | // type. | |||
9295 | if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { | |||
9296 | if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { | |||
9297 | Kind = CK_LValueBitCast; | |||
9298 | return Compatible; | |||
9299 | } | |||
9300 | return Incompatible; | |||
9301 | } | |||
9302 | ||||
9303 | // Allow scalar to ExtVector assignments, and assignments of an ExtVector type | |||
9304 | // to the same ExtVector type. | |||
9305 | if (LHSType->isExtVectorType()) { | |||
9306 | if (RHSType->isExtVectorType()) | |||
9307 | return Incompatible; | |||
9308 | if (RHSType->isArithmeticType()) { | |||
9309 | // CK_VectorSplat does T -> vector T, so first cast to the element type. | |||
9310 | if (ConvertRHS) | |||
9311 | RHS = prepareVectorSplat(LHSType, RHS.get()); | |||
9312 | Kind = CK_VectorSplat; | |||
9313 | return Compatible; | |||
9314 | } | |||
9315 | } | |||
9316 | ||||
9317 | // Conversions to or from vector type. | |||
9318 | if (LHSType->isVectorType() || RHSType->isVectorType()) { | |||
9319 | if (LHSType->isVectorType() && RHSType->isVectorType()) { | |||
9320 | // Allow assignments of an AltiVec vector type to an equivalent GCC | |||
9321 | // vector type and vice versa | |||
9322 | if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { | |||
9323 | Kind = CK_BitCast; | |||
9324 | return Compatible; | |||
9325 | } | |||
9326 | ||||
9327 | // If we are allowing lax vector conversions, and LHS and RHS are both | |||
9328 | // vectors, the total size only needs to be the same. This is a bitcast; | |||
9329 | // no bits are changed but the result type is different. | |||
9330 | if (isLaxVectorConversion(RHSType, LHSType)) { | |||
9331 | Kind = CK_BitCast; | |||
9332 | return IncompatibleVectors; | |||
9333 | } | |||
9334 | } | |||
9335 | ||||
9336 | // When the RHS comes from another lax conversion (e.g. binops between | |||
9337 | // scalars and vectors) the result is canonicalized as a vector. When the | |||
9338 | // LHS is also a vector, the lax is allowed by the condition above. Handle | |||
9339 | // the case where LHS is a scalar. | |||
9340 | if (LHSType->isScalarType()) { | |||
9341 | const VectorType *VecType = RHSType->getAs<VectorType>(); | |||
9342 | if (VecType && VecType->getNumElements() == 1 && | |||
9343 | isLaxVectorConversion(RHSType, LHSType)) { | |||
9344 | ExprResult *VecExpr = &RHS; | |||
9345 | *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); | |||
9346 | Kind = CK_BitCast; | |||
9347 | return Compatible; | |||
9348 | } | |||
9349 | } | |||
9350 | ||||
9351 | // Allow assignments between fixed-length and sizeless SVE vectors. | |||
9352 | if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || | |||
9353 | (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) | |||
9354 | if (Context.areCompatibleSveTypes(LHSType, RHSType) || | |||
9355 | Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { | |||
9356 | Kind = CK_BitCast; | |||
9357 | return Compatible; | |||
9358 | } | |||
9359 | ||||
9360 | return Incompatible; | |||
9361 | } | |||
9362 | ||||
9363 | // Diagnose attempts to convert between __ibm128, __float128 and long double | |||
9364 | // where such conversions currently can't be handled. | |||
9365 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | |||
9366 | return Incompatible; | |||
9367 | ||||
9368 | // Disallow assigning a _Complex to a real type in C++ mode since it simply | |||
9369 | // discards the imaginary part. | |||
9370 | if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && | |||
9371 | !LHSType->getAs<ComplexType>()) | |||
9372 | return Incompatible; | |||
9373 | ||||
9374 | // Arithmetic conversions. | |||
9375 | if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && | |||
9376 | !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { | |||
9377 | if (ConvertRHS) | |||
9378 | Kind = PrepareScalarCast(RHS, LHSType); | |||
9379 | return Compatible; | |||
9380 | } | |||
9381 | ||||
9382 | // Conversions to normal pointers. | |||
9383 | if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { | |||
9384 | // U* -> T* | |||
9385 | if (isa<PointerType>(RHSType)) { | |||
9386 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | |||
9387 | LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); | |||
9388 | if (AddrSpaceL != AddrSpaceR) | |||
9389 | Kind = CK_AddressSpaceConversion; | |||
9390 | else if (Context.hasCvrSimilarType(RHSType, LHSType)) | |||
9391 | Kind = CK_NoOp; | |||
9392 | else | |||
9393 | Kind = CK_BitCast; | |||
9394 | return checkPointerTypesForAssignment(*this, LHSType, RHSType); | |||
9395 | } | |||
9396 | ||||
9397 | // int -> T* | |||
9398 | if (RHSType->isIntegerType()) { | |||
9399 | Kind = CK_IntegralToPointer; // FIXME: null? | |||
9400 | return IntToPointer; | |||
9401 | } | |||
9402 | ||||
9403 | // C pointers are not compatible with ObjC object pointers, | |||
9404 | // with two exceptions: | |||
9405 | if (isa<ObjCObjectPointerType>(RHSType)) { | |||
9406 | // - conversions to void* | |||
9407 | if (LHSPointer->getPointeeType()->isVoidType()) { | |||
9408 | Kind = CK_BitCast; | |||
9409 | return Compatible; | |||
9410 | } | |||
9411 | ||||
9412 | // - conversions from 'Class' to the redefinition type | |||
9413 | if (RHSType->isObjCClassType() && | |||
9414 | Context.hasSameType(LHSType, | |||
9415 | Context.getObjCClassRedefinitionType())) { | |||
9416 | Kind = CK_BitCast; | |||
9417 | return Compatible; | |||
9418 | } | |||
9419 | ||||
9420 | Kind = CK_BitCast; | |||
9421 | return IncompatiblePointer; | |||
9422 | } | |||
9423 | ||||
9424 | // U^ -> void* | |||
9425 | if (RHSType->getAs<BlockPointerType>()) { | |||
9426 | if (LHSPointer->getPointeeType()->isVoidType()) { | |||
9427 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | |||
9428 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | |||
9429 | ->getPointeeType() | |||
9430 | .getAddressSpace(); | |||
9431 | Kind = | |||
9432 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | |||
9433 | return Compatible; | |||
9434 | } | |||
9435 | } | |||
9436 | ||||
9437 | return Incompatible; | |||
9438 | } | |||
9439 | ||||
9440 | // Conversions to block pointers. | |||
9441 | if (isa<BlockPointerType>(LHSType)) { | |||
9442 | // U^ -> T^ | |||
9443 | if (RHSType->isBlockPointerType()) { | |||
9444 | LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() | |||
9445 | ->getPointeeType() | |||
9446 | .getAddressSpace(); | |||
9447 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | |||
9448 | ->getPointeeType() | |||
9449 | .getAddressSpace(); | |||
9450 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | |||
9451 | return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); | |||
9452 | } | |||
9453 | ||||
9454 | // int or null -> T^ | |||
9455 | if (RHSType->isIntegerType()) { | |||
9456 | Kind = CK_IntegralToPointer; // FIXME: null | |||
9457 | return IntToBlockPointer; | |||
9458 | } | |||
9459 | ||||
9460 | // id -> T^ | |||
9461 | if (getLangOpts().ObjC && RHSType->isObjCIdType()) { | |||
9462 | Kind = CK_AnyPointerToBlockPointerCast; | |||
9463 | return Compatible; | |||
9464 | } | |||
9465 | ||||
9466 | // void* -> T^ | |||
9467 | if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) | |||
9468 | if (RHSPT->getPointeeType()->isVoidType()) { | |||
9469 | Kind = CK_AnyPointerToBlockPointerCast; | |||
9470 | return Compatible; | |||
9471 | } | |||
9472 | ||||
9473 | return Incompatible; | |||
9474 | } | |||
9475 | ||||
9476 | // Conversions to Objective-C pointers. | |||
9477 | if (isa<ObjCObjectPointerType>(LHSType)) { | |||
9478 | // A* -> B* | |||
9479 | if (RHSType->isObjCObjectPointerType()) { | |||
9480 | Kind = CK_BitCast; | |||
9481 | Sema::AssignConvertType result = | |||
9482 | checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); | |||
9483 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
9484 | result == Compatible && | |||
9485 | !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) | |||
9486 | result = IncompatibleObjCWeakRef; | |||
9487 | return result; | |||
9488 | } | |||
9489 | ||||
9490 | // int or null -> A* | |||
9491 | if (RHSType->isIntegerType()) { | |||
9492 | Kind = CK_IntegralToPointer; // FIXME: null | |||
9493 | return IntToPointer; | |||
9494 | } | |||
9495 | ||||
9496 | // In general, C pointers are not compatible with ObjC object pointers, | |||
9497 | // with two exceptions: | |||
9498 | if (isa<PointerType>(RHSType)) { | |||
9499 | Kind = CK_CPointerToObjCPointerCast; | |||
9500 | ||||
9501 | // - conversions from 'void*' | |||
9502 | if (RHSType->isVoidPointerType()) { | |||
9503 | return Compatible; | |||
9504 | } | |||
9505 | ||||
9506 | // - conversions to 'Class' from its redefinition type | |||
9507 | if (LHSType->isObjCClassType() && | |||
9508 | Context.hasSameType(RHSType, | |||
9509 | Context.getObjCClassRedefinitionType())) { | |||
9510 | return Compatible; | |||
9511 | } | |||
9512 | ||||
9513 | return IncompatiblePointer; | |||
9514 | } | |||
9515 | ||||
9516 | // Only under strict condition T^ is compatible with an Objective-C pointer. | |||
9517 | if (RHSType->isBlockPointerType() && | |||
9518 | LHSType->isBlockCompatibleObjCPointerType(Context)) { | |||
9519 | if (ConvertRHS) | |||
9520 | maybeExtendBlockObject(RHS); | |||
9521 | Kind = CK_BlockPointerToObjCPointerCast; | |||
9522 | return Compatible; | |||
9523 | } | |||
9524 | ||||
9525 | return Incompatible; | |||
9526 | } | |||
9527 | ||||
9528 | // Conversions from pointers that are not covered by the above. | |||
9529 | if (isa<PointerType>(RHSType)) { | |||
9530 | // T* -> _Bool | |||
9531 | if (LHSType == Context.BoolTy) { | |||
9532 | Kind = CK_PointerToBoolean; | |||
9533 | return Compatible; | |||
9534 | } | |||
9535 | ||||
9536 | // T* -> int | |||
9537 | if (LHSType->isIntegerType()) { | |||
9538 | Kind = CK_PointerToIntegral; | |||
9539 | return PointerToInt; | |||
9540 | } | |||
9541 | ||||
9542 | return Incompatible; | |||
9543 | } | |||
9544 | ||||
9545 | // Conversions from Objective-C pointers that are not covered by the above. | |||
9546 | if (isa<ObjCObjectPointerType>(RHSType)) { | |||
9547 | // T* -> _Bool | |||
9548 | if (LHSType == Context.BoolTy) { | |||
9549 | Kind = CK_PointerToBoolean; | |||
9550 | return Compatible; | |||
9551 | } | |||
9552 | ||||
9553 | // T* -> int | |||
9554 | if (LHSType->isIntegerType()) { | |||
9555 | Kind = CK_PointerToIntegral; | |||
9556 | return PointerToInt; | |||
9557 | } | |||
9558 | ||||
9559 | return Incompatible; | |||
9560 | } | |||
9561 | ||||
9562 | // struct A -> struct B | |||
9563 | if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { | |||
9564 | if (Context.typesAreCompatible(LHSType, RHSType)) { | |||
9565 | Kind = CK_NoOp; | |||
9566 | return Compatible; | |||
9567 | } | |||
9568 | } | |||
9569 | ||||
9570 | if (LHSType->isSamplerT() && RHSType->isIntegerType()) { | |||
9571 | Kind = CK_IntToOCLSampler; | |||
9572 | return Compatible; | |||
9573 | } | |||
9574 | ||||
9575 | return Incompatible; | |||
9576 | } | |||
9577 | ||||
9578 | /// Constructs a transparent union from an expression that is | |||
9579 | /// used to initialize the transparent union. | |||
9580 | static void ConstructTransparentUnion(Sema &S, ASTContext &C, | |||
9581 | ExprResult &EResult, QualType UnionType, | |||
9582 | FieldDecl *Field) { | |||
9583 | // Build an initializer list that designates the appropriate member | |||
9584 | // of the transparent union. | |||
9585 | Expr *E = EResult.get(); | |||
9586 | InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), | |||
9587 | E, SourceLocation()); | |||
9588 | Initializer->setType(UnionType); | |||
9589 | Initializer->setInitializedFieldInUnion(Field); | |||
9590 | ||||
9591 | // Build a compound literal constructing a value of the transparent | |||
9592 | // union type from this initializer list. | |||
9593 | TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); | |||
9594 | EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, | |||
9595 | VK_PRValue, Initializer, false); | |||
9596 | } | |||
9597 | ||||
9598 | Sema::AssignConvertType | |||
9599 | Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, | |||
9600 | ExprResult &RHS) { | |||
9601 | QualType RHSType = RHS.get()->getType(); | |||
9602 | ||||
9603 | // If the ArgType is a Union type, we want to handle a potential | |||
9604 | // transparent_union GCC extension. | |||
9605 | const RecordType *UT = ArgType->getAsUnionType(); | |||
9606 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) | |||
9607 | return Incompatible; | |||
9608 | ||||
9609 | // The field to initialize within the transparent union. | |||
9610 | RecordDecl *UD = UT->getDecl(); | |||
9611 | FieldDecl *InitField = nullptr; | |||
9612 | // It's compatible if the expression matches any of the fields. | |||
9613 | for (auto *it : UD->fields()) { | |||
9614 | if (it->getType()->isPointerType()) { | |||
9615 | // If the transparent union contains a pointer type, we allow: | |||
9616 | // 1) void pointer | |||
9617 | // 2) null pointer constant | |||
9618 | if (RHSType->isPointerType()) | |||
9619 | if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { | |||
9620 | RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); | |||
9621 | InitField = it; | |||
9622 | break; | |||
9623 | } | |||
9624 | ||||
9625 | if (RHS.get()->isNullPointerConstant(Context, | |||
9626 | Expr::NPC_ValueDependentIsNull)) { | |||
9627 | RHS = ImpCastExprToType(RHS.get(), it->getType(), | |||
9628 | CK_NullToPointer); | |||
9629 | InitField = it; | |||
9630 | break; | |||
9631 | } | |||
9632 | } | |||
9633 | ||||
9634 | CastKind Kind; | |||
9635 | if (CheckAssignmentConstraints(it->getType(), RHS, Kind) | |||
9636 | == Compatible) { | |||
9637 | RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); | |||
9638 | InitField = it; | |||
9639 | break; | |||
9640 | } | |||
9641 | } | |||
9642 | ||||
9643 | if (!InitField) | |||
9644 | return Incompatible; | |||
9645 | ||||
9646 | ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); | |||
9647 | return Compatible; | |||
9648 | } | |||
9649 | ||||
9650 | Sema::AssignConvertType | |||
9651 | Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, | |||
9652 | bool Diagnose, | |||
9653 | bool DiagnoseCFAudited, | |||
9654 | bool ConvertRHS) { | |||
9655 | // We need to be able to tell the caller whether we diagnosed a problem, if | |||
9656 | // they ask us to issue diagnostics. | |||
9657 | assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(static_cast <bool> ((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed") ? void (0) : __assert_fail ("(ConvertRHS || !Diagnose) && \"can't indicate whether we diagnosed\"" , "clang/lib/Sema/SemaExpr.cpp", 9657, __extension__ __PRETTY_FUNCTION__ )); | |||
9658 | ||||
9659 | // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, | |||
9660 | // we can't avoid *all* modifications at the moment, so we need some somewhere | |||
9661 | // to put the updated value. | |||
9662 | ExprResult LocalRHS = CallerRHS; | |||
9663 | ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; | |||
9664 | ||||
9665 | if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { | |||
9666 | if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { | |||
9667 | if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && | |||
9668 | !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { | |||
9669 | Diag(RHS.get()->getExprLoc(), | |||
9670 | diag::warn_noderef_to_dereferenceable_pointer) | |||
9671 | << RHS.get()->getSourceRange(); | |||
9672 | } | |||
9673 | } | |||
9674 | } | |||
9675 | ||||
9676 | if (getLangOpts().CPlusPlus) { | |||
9677 | if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { | |||
9678 | // C++ 5.17p3: If the left operand is not of class type, the | |||
9679 | // expression is implicitly converted (C++ 4) to the | |||
9680 | // cv-unqualified type of the left operand. | |||
9681 | QualType RHSType = RHS.get()->getType(); | |||
9682 | if (Diagnose) { | |||
9683 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | |||
9684 | AA_Assigning); | |||
9685 | } else { | |||
9686 | ImplicitConversionSequence ICS = | |||
9687 | TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | |||
9688 | /*SuppressUserConversions=*/false, | |||
9689 | AllowedExplicit::None, | |||
9690 | /*InOverloadResolution=*/false, | |||
9691 | /*CStyle=*/false, | |||
9692 | /*AllowObjCWritebackConversion=*/false); | |||
9693 | if (ICS.isFailure()) | |||
9694 | return Incompatible; | |||
9695 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | |||
9696 | ICS, AA_Assigning); | |||
9697 | } | |||
9698 | if (RHS.isInvalid()) | |||
9699 | return Incompatible; | |||
9700 | Sema::AssignConvertType result = Compatible; | |||
9701 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
9702 | !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) | |||
9703 | result = IncompatibleObjCWeakRef; | |||
9704 | return result; | |||
9705 | } | |||
9706 | ||||
9707 | // FIXME: Currently, we fall through and treat C++ classes like C | |||
9708 | // structures. | |||
9709 | // FIXME: We also fall through for atomics; not sure what should | |||
9710 | // happen there, though. | |||
9711 | } else if (RHS.get()->getType() == Context.OverloadTy) { | |||
9712 | // As a set of extensions to C, we support overloading on functions. These | |||
9713 | // functions need to be resolved here. | |||
9714 | DeclAccessPair DAP; | |||
9715 | if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( | |||
9716 | RHS.get(), LHSType, /*Complain=*/false, DAP)) | |||
9717 | RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); | |||
9718 | else | |||
9719 | return Incompatible; | |||
9720 | } | |||
9721 | ||||
9722 | // C99 6.5.16.1p1: the left operand is a pointer and the right is | |||
9723 | // a null pointer constant. | |||
9724 | if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || | |||
9725 | LHSType->isBlockPointerType()) && | |||
9726 | RHS.get()->isNullPointerConstant(Context, | |||
9727 | Expr::NPC_ValueDependentIsNull)) { | |||
9728 | if (Diagnose || ConvertRHS) { | |||
9729 | CastKind Kind; | |||
9730 | CXXCastPath Path; | |||
9731 | CheckPointerConversion(RHS.get(), LHSType, Kind, Path, | |||
9732 | /*IgnoreBaseAccess=*/false, Diagnose); | |||
9733 | if (ConvertRHS) | |||
9734 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); | |||
9735 | } | |||
9736 | return Compatible; | |||
9737 | } | |||
9738 | ||||
9739 | // OpenCL queue_t type assignment. | |||
9740 | if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( | |||
9741 | Context, Expr::NPC_ValueDependentIsNull)) { | |||
9742 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
9743 | return Compatible; | |||
9744 | } | |||
9745 | ||||
9746 | // This check seems unnatural, however it is necessary to ensure the proper | |||
9747 | // conversion of functions/arrays. If the conversion were done for all | |||
9748 | // DeclExpr's (created by ActOnIdExpression), it would mess up the unary | |||
9749 | // expressions that suppress this implicit conversion (&, sizeof). | |||
9750 | // | |||
9751 | // Suppress this for references: C++ 8.5.3p5. | |||
9752 | if (!LHSType->isReferenceType()) { | |||
9753 | // FIXME: We potentially allocate here even if ConvertRHS is false. | |||
9754 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); | |||
9755 | if (RHS.isInvalid()) | |||
9756 | return Incompatible; | |||
9757 | } | |||
9758 | CastKind Kind; | |||
9759 | Sema::AssignConvertType result = | |||
9760 | CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); | |||
9761 | ||||
9762 | // C99 6.5.16.1p2: The value of the right operand is converted to the | |||
9763 | // type of the assignment expression. | |||
9764 | // CheckAssignmentConstraints allows the left-hand side to be a reference, | |||
9765 | // so that we can use references in built-in functions even in C. | |||
9766 | // The getNonReferenceType() call makes sure that the resulting expression | |||
9767 | // does not have reference type. | |||
9768 | if (result != Incompatible && RHS.get()->getType() != LHSType) { | |||
9769 | QualType Ty = LHSType.getNonLValueExprType(Context); | |||
9770 | Expr *E = RHS.get(); | |||
9771 | ||||
9772 | // Check for various Objective-C errors. If we are not reporting | |||
9773 | // diagnostics and just checking for errors, e.g., during overload | |||
9774 | // resolution, return Incompatible to indicate the failure. | |||
9775 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
9776 | CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, | |||
9777 | Diagnose, DiagnoseCFAudited) != ACR_okay) { | |||
9778 | if (!Diagnose) | |||
9779 | return Incompatible; | |||
9780 | } | |||
9781 | if (getLangOpts().ObjC && | |||
9782 | (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, | |||
9783 | E->getType(), E, Diagnose) || | |||
9784 | CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { | |||
9785 | if (!Diagnose) | |||
9786 | return Incompatible; | |||
9787 | // Replace the expression with a corrected version and continue so we | |||
9788 | // can find further errors. | |||
9789 | RHS = E; | |||
9790 | return Compatible; | |||
9791 | } | |||
9792 | ||||
9793 | if (ConvertRHS) | |||
9794 | RHS = ImpCastExprToType(E, Ty, Kind); | |||
9795 | } | |||
9796 | ||||
9797 | return result; | |||
9798 | } | |||
9799 | ||||
9800 | namespace { | |||
9801 | /// The original operand to an operator, prior to the application of the usual | |||
9802 | /// arithmetic conversions and converting the arguments of a builtin operator | |||
9803 | /// candidate. | |||
9804 | struct OriginalOperand { | |||
9805 | explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { | |||
9806 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) | |||
9807 | Op = MTE->getSubExpr(); | |||
9808 | if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) | |||
9809 | Op = BTE->getSubExpr(); | |||
9810 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { | |||
9811 | Orig = ICE->getSubExprAsWritten(); | |||
9812 | Conversion = ICE->getConversionFunction(); | |||
9813 | } | |||
9814 | } | |||
9815 | ||||
9816 | QualType getType() const { return Orig->getType(); } | |||
9817 | ||||
9818 | Expr *Orig; | |||
9819 | NamedDecl *Conversion; | |||
9820 | }; | |||
9821 | } | |||
9822 | ||||
9823 | QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, | |||
9824 | ExprResult &RHS) { | |||
9825 | OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); | |||
9826 | ||||
9827 | Diag(Loc, diag::err_typecheck_invalid_operands) | |||
9828 | << OrigLHS.getType() << OrigRHS.getType() | |||
9829 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
9830 | ||||
9831 | // If a user-defined conversion was applied to either of the operands prior | |||
9832 | // to applying the built-in operator rules, tell the user about it. | |||
9833 | if (OrigLHS.Conversion) { | |||
9834 | Diag(OrigLHS.Conversion->getLocation(), | |||
9835 | diag::note_typecheck_invalid_operands_converted) | |||
9836 | << 0 << LHS.get()->getType(); | |||
9837 | } | |||
9838 | if (OrigRHS.Conversion) { | |||
9839 | Diag(OrigRHS.Conversion->getLocation(), | |||
9840 | diag::note_typecheck_invalid_operands_converted) | |||
9841 | << 1 << RHS.get()->getType(); | |||
9842 | } | |||
9843 | ||||
9844 | return QualType(); | |||
9845 | } | |||
9846 | ||||
9847 | // Diagnose cases where a scalar was implicitly converted to a vector and | |||
9848 | // diagnose the underlying types. Otherwise, diagnose the error | |||
9849 | // as invalid vector logical operands for non-C++ cases. | |||
9850 | QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, | |||
9851 | ExprResult &RHS) { | |||
9852 | QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); | |||
9853 | QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); | |||
9854 | ||||
9855 | bool LHSNatVec = LHSType->isVectorType(); | |||
9856 | bool RHSNatVec = RHSType->isVectorType(); | |||
9857 | ||||
9858 | if (!(LHSNatVec && RHSNatVec)) { | |||
9859 | Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); | |||
9860 | Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); | |||
9861 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | |||
9862 | << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() | |||
9863 | << Vector->getSourceRange(); | |||
9864 | return QualType(); | |||
9865 | } | |||
9866 | ||||
9867 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | |||
9868 | << 1 << LHSType << RHSType << LHS.get()->getSourceRange() | |||
9869 | << RHS.get()->getSourceRange(); | |||
9870 | ||||
9871 | return QualType(); | |||
9872 | } | |||
9873 | ||||
9874 | /// Try to convert a value of non-vector type to a vector type by converting | |||
9875 | /// the type to the element type of the vector and then performing a splat. | |||
9876 | /// If the language is OpenCL, we only use conversions that promote scalar | |||
9877 | /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except | |||
9878 | /// for float->int. | |||
9879 | /// | |||
9880 | /// OpenCL V2.0 6.2.6.p2: | |||
9881 | /// An error shall occur if any scalar operand type has greater rank | |||
9882 | /// than the type of the vector element. | |||
9883 | /// | |||
9884 | /// \param scalar - if non-null, actually perform the conversions | |||
9885 | /// \return true if the operation fails (but without diagnosing the failure) | |||
9886 | static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, | |||
9887 | QualType scalarTy, | |||
9888 | QualType vectorEltTy, | |||
9889 | QualType vectorTy, | |||
9890 | unsigned &DiagID) { | |||
9891 | // The conversion to apply to the scalar before splatting it, | |||
9892 | // if necessary. | |||
9893 | CastKind scalarCast = CK_NoOp; | |||
9894 | ||||
9895 | if (vectorEltTy->isIntegralType(S.Context)) { | |||
9896 | if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || | |||
9897 | (scalarTy->isIntegerType() && | |||
9898 | S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { | |||
9899 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | |||
9900 | return true; | |||
9901 | } | |||
9902 | if (!scalarTy->isIntegralType(S.Context)) | |||
9903 | return true; | |||
9904 | scalarCast = CK_IntegralCast; | |||
9905 | } else if (vectorEltTy->isRealFloatingType()) { | |||
9906 | if (scalarTy->isRealFloatingType()) { | |||
9907 | if (S.getLangOpts().OpenCL && | |||
9908 | S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { | |||
9909 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | |||
9910 | return true; | |||
9911 | } | |||
9912 | scalarCast = CK_FloatingCast; | |||
9913 | } | |||
9914 | else if (scalarTy->isIntegralType(S.Context)) | |||
9915 | scalarCast = CK_IntegralToFloating; | |||
9916 | else | |||
9917 | return true; | |||
9918 | } else { | |||
9919 | return true; | |||
9920 | } | |||
9921 | ||||
9922 | // Adjust scalar if desired. | |||
9923 | if (scalar) { | |||
9924 | if (scalarCast != CK_NoOp) | |||
9925 | *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); | |||
9926 | *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); | |||
9927 | } | |||
9928 | return false; | |||
9929 | } | |||
9930 | ||||
9931 | /// Convert vector E to a vector with the same number of elements but different | |||
9932 | /// element type. | |||
9933 | static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { | |||
9934 | const auto *VecTy = E->getType()->getAs<VectorType>(); | |||
9935 | assert(VecTy && "Expression E must be a vector")(static_cast <bool> (VecTy && "Expression E must be a vector" ) ? void (0) : __assert_fail ("VecTy && \"Expression E must be a vector\"" , "clang/lib/Sema/SemaExpr.cpp", 9935, __extension__ __PRETTY_FUNCTION__ )); | |||
9936 | QualType NewVecTy = S.Context.getVectorType(ElementType, | |||
9937 | VecTy->getNumElements(), | |||
9938 | VecTy->getVectorKind()); | |||
9939 | ||||
9940 | // Look through the implicit cast. Return the subexpression if its type is | |||
9941 | // NewVecTy. | |||
9942 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | |||
9943 | if (ICE->getSubExpr()->getType() == NewVecTy) | |||
9944 | return ICE->getSubExpr(); | |||
9945 | ||||
9946 | auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; | |||
9947 | return S.ImpCastExprToType(E, NewVecTy, Cast); | |||
9948 | } | |||
9949 | ||||
9950 | /// Test if a (constant) integer Int can be casted to another integer type | |||
9951 | /// IntTy without losing precision. | |||
9952 | static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, | |||
9953 | QualType OtherIntTy) { | |||
9954 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | |||
9955 | ||||
9956 | // Reject cases where the value of the Int is unknown as that would | |||
9957 | // possibly cause truncation, but accept cases where the scalar can be | |||
9958 | // demoted without loss of precision. | |||
9959 | Expr::EvalResult EVResult; | |||
9960 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | |||
9961 | int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); | |||
9962 | bool IntSigned = IntTy->hasSignedIntegerRepresentation(); | |||
9963 | bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); | |||
9964 | ||||
9965 | if (CstInt) { | |||
9966 | // If the scalar is constant and is of a higher order and has more active | |||
9967 | // bits that the vector element type, reject it. | |||
9968 | llvm::APSInt Result = EVResult.Val.getInt(); | |||
9969 | unsigned NumBits = IntSigned | |||
9970 | ? (Result.isNegative() ? Result.getMinSignedBits() | |||
9971 | : Result.getActiveBits()) | |||
9972 | : Result.getActiveBits(); | |||
9973 | if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) | |||
9974 | return true; | |||
9975 | ||||
9976 | // If the signedness of the scalar type and the vector element type | |||
9977 | // differs and the number of bits is greater than that of the vector | |||
9978 | // element reject it. | |||
9979 | return (IntSigned != OtherIntSigned && | |||
9980 | NumBits > S.Context.getIntWidth(OtherIntTy)); | |||
9981 | } | |||
9982 | ||||
9983 | // Reject cases where the value of the scalar is not constant and it's | |||
9984 | // order is greater than that of the vector element type. | |||
9985 | return (Order < 0); | |||
9986 | } | |||
9987 | ||||
9988 | /// Test if a (constant) integer Int can be casted to floating point type | |||
9989 | /// FloatTy without losing precision. | |||
9990 | static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, | |||
9991 | QualType FloatTy) { | |||
9992 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | |||
9993 | ||||
9994 | // Determine if the integer constant can be expressed as a floating point | |||
9995 | // number of the appropriate type. | |||
9996 | Expr::EvalResult EVResult; | |||
9997 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | |||
9998 | ||||
9999 | uint64_t Bits = 0; | |||
10000 | if (CstInt) { | |||
10001 | // Reject constants that would be truncated if they were converted to | |||
10002 | // the floating point type. Test by simple to/from conversion. | |||
10003 | // FIXME: Ideally the conversion to an APFloat and from an APFloat | |||
10004 | // could be avoided if there was a convertFromAPInt method | |||
10005 | // which could signal back if implicit truncation occurred. | |||
10006 | llvm::APSInt Result = EVResult.Val.getInt(); | |||
10007 | llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); | |||
10008 | Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), | |||
10009 | llvm::APFloat::rmTowardZero); | |||
10010 | llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), | |||
10011 | !IntTy->hasSignedIntegerRepresentation()); | |||
10012 | bool Ignored = false; | |||
10013 | Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, | |||
10014 | &Ignored); | |||
10015 | if (Result != ConvertBack) | |||
10016 | return true; | |||
10017 | } else { | |||
10018 | // Reject types that cannot be fully encoded into the mantissa of | |||
10019 | // the float. | |||
10020 | Bits = S.Context.getTypeSize(IntTy); | |||
10021 | unsigned FloatPrec = llvm::APFloat::semanticsPrecision( | |||
10022 | S.Context.getFloatTypeSemantics(FloatTy)); | |||
10023 | if (Bits > FloatPrec) | |||
10024 | return true; | |||
10025 | } | |||
10026 | ||||
10027 | return false; | |||
10028 | } | |||
10029 | ||||
10030 | /// Attempt to convert and splat Scalar into a vector whose types matches | |||
10031 | /// Vector following GCC conversion rules. The rule is that implicit | |||
10032 | /// conversion can occur when Scalar can be casted to match Vector's element | |||
10033 | /// type without causing truncation of Scalar. | |||
10034 | static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, | |||
10035 | ExprResult *Vector) { | |||
10036 | QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); | |||
10037 | QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); | |||
10038 | const VectorType *VT = VectorTy->getAs<VectorType>(); | |||
10039 | ||||
10040 | assert(!isa<ExtVectorType>(VT) &&(static_cast <bool> (!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!") ? void (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "clang/lib/Sema/SemaExpr.cpp", 10041, __extension__ __PRETTY_FUNCTION__ )) | |||
10041 | "ExtVectorTypes should not be handled here!")(static_cast <bool> (!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!") ? void (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "clang/lib/Sema/SemaExpr.cpp", 10041, __extension__ __PRETTY_FUNCTION__ )); | |||
10042 | ||||
10043 | QualType VectorEltTy = VT->getElementType(); | |||
| ||||
10044 | ||||
10045 | // Reject cases where the vector element type or the scalar element type are | |||
10046 | // not integral or floating point types. | |||
10047 | if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) | |||
10048 | return true; | |||
10049 | ||||
10050 | // The conversion to apply to the scalar before splatting it, | |||
10051 | // if necessary. | |||
10052 | CastKind ScalarCast = CK_NoOp; | |||
10053 | ||||
10054 | // Accept cases where the vector elements are integers and the scalar is | |||
10055 | // an integer. | |||
10056 | // FIXME: Notionally if the scalar was a floating point value with a precise | |||
10057 | // integral representation, we could cast it to an appropriate integer | |||
10058 | // type and then perform the rest of the checks here. GCC will perform | |||
10059 | // this conversion in some cases as determined by the input language. | |||
10060 | // We should accept it on a language independent basis. | |||
10061 | if (VectorEltTy->isIntegralType(S.Context) && | |||
10062 | ScalarTy->isIntegralType(S.Context) && | |||
10063 | S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { | |||
10064 | ||||
10065 | if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) | |||
10066 | return true; | |||
10067 | ||||
10068 | ScalarCast = CK_IntegralCast; | |||
10069 | } else if (VectorEltTy->isIntegralType(S.Context) && | |||
10070 | ScalarTy->isRealFloatingType()) { | |||
10071 | if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) | |||
10072 | ScalarCast = CK_FloatingToIntegral; | |||
10073 | else | |||
10074 | return true; | |||
10075 | } else if (VectorEltTy->isRealFloatingType()) { | |||
10076 | if (ScalarTy->isRealFloatingType()) { | |||
10077 | ||||
10078 | // Reject cases where the scalar type is not a constant and has a higher | |||
10079 | // Order than the vector element type. | |||
10080 | llvm::APFloat Result(0.0); | |||
10081 | ||||
10082 | // Determine whether this is a constant scalar. In the event that the | |||
10083 | // value is dependent (and thus cannot be evaluated by the constant | |||
10084 | // evaluator), skip the evaluation. This will then diagnose once the | |||
10085 | // expression is instantiated. | |||
10086 | bool CstScalar = Scalar->get()->isValueDependent() || | |||
10087 | Scalar->get()->EvaluateAsFloat(Result, S.Context); | |||
10088 | int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); | |||
10089 | if (!CstScalar && Order < 0) | |||
10090 | return true; | |||
10091 | ||||
10092 | // If the scalar cannot be safely casted to the vector element type, | |||
10093 | // reject it. | |||
10094 | if (CstScalar) { | |||
10095 | bool Truncated = false; | |||
10096 | Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), | |||
10097 | llvm::APFloat::rmNearestTiesToEven, &Truncated); | |||
10098 | if (Truncated) | |||
10099 | return true; | |||
10100 | } | |||
10101 | ||||
10102 | ScalarCast = CK_FloatingCast; | |||
10103 | } else if (ScalarTy->isIntegralType(S.Context)) { | |||
10104 | if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) | |||
10105 | return true; | |||
10106 | ||||
10107 | ScalarCast = CK_IntegralToFloating; | |||
10108 | } else | |||
10109 | return true; | |||
10110 | } else if (ScalarTy->isEnumeralType()) | |||
10111 | return true; | |||
10112 | ||||
10113 | // Adjust scalar if desired. | |||
10114 | if (Scalar) { | |||
10115 | if (ScalarCast != CK_NoOp) | |||
10116 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); | |||
10117 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); | |||
10118 | } | |||
10119 | return false; | |||
10120 | } | |||
10121 | ||||
10122 | QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, | |||
10123 | SourceLocation Loc, bool IsCompAssign, | |||
10124 | bool AllowBothBool, | |||
10125 | bool AllowBoolConversions) { | |||
10126 | if (!IsCompAssign) { | |||
| ||||
10127 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
10128 | if (LHS.isInvalid()) | |||
10129 | return QualType(); | |||
10130 | } | |||
10131 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
10132 | if (RHS.isInvalid()) | |||
10133 | return QualType(); | |||
10134 | ||||
10135 | // For conversion purposes, we ignore any qualifiers. | |||
10136 | // For example, "const float" and "float" are equivalent. | |||
10137 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | |||
10138 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | |||
10139 | ||||
10140 | const VectorType *LHSVecType = LHSType->getAs<VectorType>(); | |||
10141 | const VectorType *RHSVecType = RHSType->getAs<VectorType>(); | |||
10142 | assert(LHSVecType || RHSVecType)(static_cast <bool> (LHSVecType || RHSVecType) ? void ( 0) : __assert_fail ("LHSVecType || RHSVecType", "clang/lib/Sema/SemaExpr.cpp" , 10142, __extension__ __PRETTY_FUNCTION__)); | |||
10143 | ||||
10144 | if ((LHSVecType
| |||
10145 | (RHSVecType
| |||
10146 | return InvalidOperands(Loc, LHS, RHS); | |||
10147 | ||||
10148 | // AltiVec-style "vector bool op vector bool" combinations are allowed | |||
10149 | // for some operators but not others. | |||
10150 | if (!AllowBothBool && | |||
10151 | LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && | |||
10152 | RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) | |||
10153 | return InvalidOperands(Loc, LHS, RHS); | |||
10154 | ||||
10155 | // If the vector types are identical, return. | |||
10156 | if (Context.hasSameType(LHSType, RHSType)) | |||
10157 | return LHSType; | |||
10158 | ||||
10159 | // If we have compatible AltiVec and GCC vector types, use the AltiVec type. | |||
10160 | if (LHSVecType
| |||
10161 | Context.areCompatibleVectorTypes(LHSType, RHSType)) { | |||
10162 | if (isa<ExtVectorType>(LHSVecType)) { | |||
10163 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
10164 | return LHSType; | |||
10165 | } | |||
10166 | ||||
10167 | if (!IsCompAssign) | |||
10168 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | |||
10169 | return RHSType; | |||
10170 | } | |||
10171 | ||||
10172 | // AllowBoolConversions says that bool and non-bool AltiVec vectors | |||
10173 | // can be mixed, with the result being the non-bool type. The non-bool | |||
10174 | // operand must have integer element type. | |||
10175 | if (AllowBoolConversions && LHSVecType && RHSVecType && | |||
10176 | LHSVecType->getNumElements() == RHSVecType->getNumElements() && | |||
10177 | (Context.getTypeSize(LHSVecType->getElementType()) == | |||
10178 | Context.getTypeSize(RHSVecType->getElementType()))) { | |||
10179 | if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && | |||
10180 | LHSVecType->getElementType()->isIntegerType() && | |||
10181 | RHSVecType->getVectorKind() == VectorType::AltiVecBool) { | |||
10182 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
10183 | return LHSType; | |||
10184 | } | |||
10185 | if (!IsCompAssign && | |||
10186 | LHSVecType->getVectorKind() == VectorType::AltiVecBool && | |||
10187 | RHSVecType->getVectorKind() == VectorType::AltiVecVector && | |||
10188 | RHSVecType->getElementType()->isIntegerType()) { | |||
10189 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | |||
10190 | return RHSType; | |||
10191 | } | |||
10192 | } | |||
10193 | ||||
10194 | // Expressions containing fixed-length and sizeless SVE vectors are invalid | |||
10195 | // since the ambiguity can affect the ABI. | |||
10196 | auto IsSveConversion = [](QualType FirstType, QualType SecondType) { | |||
10197 | const VectorType *VecType = SecondType->getAs<VectorType>(); | |||
10198 | return FirstType->isSizelessBuiltinType() && VecType && | |||
10199 | (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || | |||
10200 | VecType->getVectorKind() == | |||
10201 | VectorType::SveFixedLengthPredicateVector); | |||
10202 | }; | |||
10203 | ||||
10204 | if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { | |||
10205 | Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; | |||
10206 | return QualType(); | |||
10207 | } | |||
10208 | ||||
10209 | // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid | |||
10210 | // since the ambiguity can affect the ABI. | |||
10211 | auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { | |||
10212 | const VectorType *FirstVecType = FirstType->getAs<VectorType>(); | |||
10213 | const VectorType *SecondVecType = SecondType->getAs<VectorType>(); | |||
10214 | ||||
10215 | if (FirstVecType && SecondVecType) | |||
10216 | return FirstVecType->getVectorKind() == VectorType::GenericVector && | |||
10217 | (SecondVecType->getVectorKind() == | |||
10218 | VectorType::SveFixedLengthDataVector || | |||
10219 | SecondVecType->getVectorKind() == | |||
10220 | VectorType::SveFixedLengthPredicateVector); | |||
10221 | ||||
10222 | return FirstType->isSizelessBuiltinType() && SecondVecType && | |||
10223 | SecondVecType->getVectorKind() == VectorType::GenericVector; | |||
10224 | }; | |||
10225 | ||||
10226 | if (IsSveGnuConversion(LHSType, RHSType) || | |||
10227 | IsSveGnuConversion(RHSType, LHSType)) { | |||
10228 | Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; | |||
10229 | return QualType(); | |||
10230 | } | |||
10231 | ||||
10232 | // If there's a vector type and a scalar, try to convert the scalar to | |||
10233 | // the vector element type and splat. | |||
10234 | unsigned DiagID = diag::err_typecheck_vector_not_convertable; | |||
10235 | if (!RHSVecType
| |||
10236 | if (isa<ExtVectorType>(LHSVecType)) { | |||
10237 | if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, | |||
10238 | LHSVecType->getElementType(), LHSType, | |||
10239 | DiagID)) | |||
10240 | return LHSType; | |||
10241 | } else { | |||
10242 | if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) | |||
10243 | return LHSType; | |||
10244 | } | |||
10245 | } | |||
10246 | if (!LHSVecType
| |||
10247 | if (isa<ExtVectorType>(RHSVecType)) { | |||
10248 | if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), | |||
10249 | LHSType, RHSVecType->getElementType(), | |||
10250 | RHSType, DiagID)) | |||
10251 | return RHSType; | |||
10252 | } else { | |||
10253 | if (LHS.get()->isLValue() || | |||
10254 | !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) | |||
10255 | return RHSType; | |||
10256 | } | |||
10257 | } | |||
10258 | ||||
10259 | // FIXME: The code below also handles conversion between vectors and | |||
10260 | // non-scalars, we should break this down into fine grained specific checks | |||
10261 | // and emit proper diagnostics. | |||
10262 | QualType VecType = LHSVecType ? LHSType : RHSType; | |||
10263 | const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; | |||
10264 | QualType OtherType = LHSVecType ? RHSType : LHSType; | |||
10265 | ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; | |||
10266 | if (isLaxVectorConversion(OtherType, VecType)) { | |||
10267 | // If we're allowing lax vector conversions, only the total (data) size | |||
10268 | // needs to be the same. For non compound assignment, if one of the types is | |||
10269 | // scalar, the result is always the vector type. | |||
10270 | if (!IsCompAssign) { | |||
10271 | *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); | |||
10272 | return VecType; | |||
10273 | // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding | |||
10274 | // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' | |||
10275 | // type. Note that this is already done by non-compound assignments in | |||
10276 | // CheckAssignmentConstraints. If it's a scalar type, only bitcast for | |||
10277 | // <1 x T> -> T. The result is also a vector type. | |||
10278 | } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || | |||
10279 | (OtherType->isScalarType() && VT->getNumElements() == 1)) { | |||
10280 | ExprResult *RHSExpr = &RHS; | |||
10281 | *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); | |||
10282 | return VecType; | |||
10283 | } | |||
10284 | } | |||
10285 | ||||
10286 | // Okay, the expression is invalid. | |||
10287 | ||||
10288 | // If there's a non-vector, non-real operand, diagnose that. | |||
10289 | if ((!RHSVecType && !RHSType->isRealType()) || | |||
10290 | (!LHSVecType && !LHSType->isRealType())) { | |||
10291 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) | |||
10292 | << LHSType << RHSType | |||
10293 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
10294 | return QualType(); | |||
10295 | } | |||
10296 | ||||
10297 | // OpenCL V1.1 6.2.6.p1: | |||
10298 | // If the operands are of more than one vector type, then an error shall | |||
10299 | // occur. Implicit conversions between vector types are not permitted, per | |||
10300 | // section 6.2.1. | |||
10301 | if (getLangOpts().OpenCL && | |||
10302 | RHSVecType && isa<ExtVectorType>(RHSVecType) && | |||
10303 | LHSVecType && isa<ExtVectorType>(LHSVecType)) { | |||
10304 | Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType | |||
10305 | << RHSType; | |||
10306 | return QualType(); | |||
10307 | } | |||
10308 | ||||
10309 | ||||
10310 | // If there is a vector type that is not a ExtVector and a scalar, we reach | |||
10311 | // this point if scalar could not be converted to the vector's element type | |||
10312 | // without truncation. | |||
10313 | if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || | |||
10314 | (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { | |||
10315 | QualType Scalar = LHSVecType ? RHSType : LHSType; | |||
10316 | QualType Vector = LHSVecType ? LHSType : RHSType; | |||
10317 | unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; | |||
10318 | Diag(Loc, | |||
10319 | diag::err_typecheck_vector_not_convertable_implict_truncation) | |||
10320 | << ScalarOrVector << Scalar << Vector; | |||
10321 | ||||
10322 | return QualType(); | |||
10323 | } | |||
10324 | ||||
10325 | // Otherwise, use the generic diagnostic. | |||
10326 | Diag(Loc, DiagID) | |||
10327 | << LHSType << RHSType | |||
10328 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
10329 | return QualType(); | |||
10330 | } | |||
10331 | ||||
10332 | // checkArithmeticNull - Detect when a NULL constant is used improperly in an | |||
10333 | // expression. These are mainly cases where the null pointer is used as an | |||
10334 | // integer instead of a pointer. | |||
10335 | static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, | |||
10336 | SourceLocation Loc, bool IsCompare) { | |||
10337 | // The canonical way to check for a GNU null is with isNullPointerConstant, | |||
10338 | // but we use a bit of a hack here for speed; this is a relatively | |||
10339 | // hot path, and isNullPointerConstant is slow. | |||
10340 | bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); | |||
10341 | bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); | |||
10342 | ||||
10343 | QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); | |||
10344 | ||||
10345 | // Avoid analyzing cases where the result will either be invalid (and | |||
10346 | // diagnosed as such) or entirely valid and not something to warn about. | |||
10347 | if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || | |||
10348 | NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) | |||
10349 | return; | |||
10350 | ||||
10351 | // Comparison operations would not make sense with a null pointer no matter | |||
10352 | // what the other expression is. | |||
10353 | if (!IsCompare) { | |||
10354 | S.Diag(Loc, diag::warn_null_in_arithmetic_operation) | |||
10355 | << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) | |||
10356 | << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); | |||
10357 | return; | |||
10358 | } | |||
10359 | ||||
10360 | // The rest of the operations only make sense with a null pointer | |||
10361 | // if the other expression is a pointer. | |||
10362 | if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || | |||
10363 | NonNullType->canDecayToPointerType()) | |||
10364 | return; | |||
10365 | ||||
10366 | S.Diag(Loc, diag::warn_null_in_comparison_operation) | |||
10367 | << LHSNull /* LHS is NULL */ << NonNullType | |||
10368 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
10369 | } | |||
10370 | ||||
10371 | static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, | |||
10372 | SourceLocation Loc) { | |||
10373 | const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); | |||
10374 | const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); | |||
10375 | if (!LUE || !RUE) | |||
10376 | return; | |||
10377 | if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || | |||
10378 | RUE->getKind() != UETT_SizeOf) | |||
10379 | return; | |||
10380 | ||||
10381 | const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); | |||
10382 | QualType LHSTy = LHSArg->getType(); | |||
10383 | QualType RHSTy; | |||
10384 | ||||
10385 | if (RUE->isArgumentType()) | |||
10386 | RHSTy = RUE->getArgumentType().getNonReferenceType(); | |||
10387 | else | |||
10388 | RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); | |||
10389 | ||||
10390 | if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { | |||
10391 | if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) | |||
10392 | return; | |||
10393 | ||||
10394 | S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); | |||
10395 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | |||
10396 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | |||
10397 | S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) | |||
10398 | << LHSArgDecl; | |||
10399 | } | |||
10400 | } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { | |||
10401 | QualType ArrayElemTy = ArrayTy->getElementType(); | |||
10402 | if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || | |||
10403 | ArrayElemTy->isDependentType() || RHSTy->isDependentType() || | |||
10404 | RHSTy->isReferenceType() || ArrayElemTy->isCharType() || | |||
10405 | S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) | |||
10406 | return; | |||
10407 | S.Diag(Loc, diag::warn_division_sizeof_array) | |||
10408 | << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; | |||
10409 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | |||
10410 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | |||
10411 | S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) | |||
10412 | << LHSArgDecl; | |||
10413 | } | |||
10414 | ||||
10415 | S.Diag(Loc, diag::note_precedence_silence) << RHS; | |||
10416 | } | |||
10417 | } | |||
10418 | ||||
10419 | static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, | |||
10420 | ExprResult &RHS, | |||
10421 | SourceLocation Loc, bool IsDiv) { | |||
10422 | // Check for division/remainder by zero. | |||
10423 | Expr::EvalResult RHSValue; | |||
10424 | if (!RHS.get()->isValueDependent() && | |||
10425 | RHS.get()->EvaluateAsInt(RHSValue, S.Context) && | |||
10426 | RHSValue.Val.getInt() == 0) | |||
10427 | S.DiagRuntimeBehavior(Loc, RHS.get(), | |||
10428 | S.PDiag(diag::warn_remainder_division_by_zero) | |||
10429 | << IsDiv << RHS.get()->getSourceRange()); | |||
10430 | } | |||
10431 | ||||
10432 | QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, | |||
10433 | SourceLocation Loc, | |||
10434 | bool IsCompAssign, bool IsDiv) { | |||
10435 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | |||
10436 | ||||
10437 | QualType LHSTy = LHS.get()->getType(); | |||
10438 | QualType RHSTy = RHS.get()->getType(); | |||
10439 | if (LHSTy->isVectorType() || RHSTy->isVectorType()) | |||
10440 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | |||
10441 | /*AllowBothBool*/getLangOpts().AltiVec, | |||
10442 | /*AllowBoolConversions*/false); | |||
10443 | if (!IsDiv && | |||
10444 | (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) | |||
10445 | return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); | |||
10446 | // For division, only matrix-by-scalar is supported. Other combinations with | |||
10447 | // matrix types are invalid. | |||
10448 | if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) | |||
10449 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); | |||
10450 | ||||
10451 | QualType compType = UsualArithmeticConversions( | |||
10452 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | |||
10453 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
10454 | return QualType(); | |||
10455 | ||||
10456 | ||||
10457 | if (compType.isNull() || !compType->isArithmeticType()) | |||
10458 | return InvalidOperands(Loc, LHS, RHS); | |||
10459 | if (IsDiv) { | |||
10460 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); | |||
10461 | DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); | |||
10462 | } | |||
10463 | return compType; | |||
10464 | } | |||
10465 | ||||
10466 | QualType Sema::CheckRemainderOperands( | |||
10467 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { | |||
10468 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | |||
10469 | ||||
10470 | if (LHS.get()->getType()->isVectorType() || | |||
10471 | RHS.get()->getType()->isVectorType()) { | |||
10472 | if (LHS.get()->getType()->hasIntegerRepresentation() && | |||
10473 | RHS.get()->getType()->hasIntegerRepresentation()) | |||
10474 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | |||
10475 | /*AllowBothBool*/getLangOpts().AltiVec, | |||
10476 | /*AllowBoolConversions*/false); | |||
10477 | return InvalidOperands(Loc, LHS, RHS); | |||
10478 | } | |||
10479 | ||||
10480 | QualType compType = UsualArithmeticConversions( | |||
10481 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | |||
10482 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
10483 | return QualType(); | |||
10484 | ||||
10485 | if (compType.isNull() || !compType->isIntegerType()) | |||
10486 | return InvalidOperands(Loc, LHS, RHS); | |||
10487 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); | |||
10488 | return compType; | |||
10489 | } | |||
10490 | ||||
10491 | /// Diagnose invalid arithmetic on two void pointers. | |||
10492 | static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, | |||
10493 | Expr *LHSExpr, Expr *RHSExpr) { | |||
10494 | S.Diag(Loc, S.getLangOpts().CPlusPlus | |||
10495 | ? diag::err_typecheck_pointer_arith_void_type | |||
10496 | : diag::ext_gnu_void_ptr) | |||
10497 | << 1 /* two pointers */ << LHSExpr->getSourceRange() | |||
10498 | << RHSExpr->getSourceRange(); | |||
10499 | } | |||
10500 | ||||
10501 | /// Diagnose invalid arithmetic on a void pointer. | |||
10502 | static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, | |||
10503 | Expr *Pointer) { | |||
10504 | S.Diag(Loc, S.getLangOpts().CPlusPlus | |||
10505 | ? diag::err_typecheck_pointer_arith_void_type | |||
10506 | : diag::ext_gnu_void_ptr) | |||
10507 | << 0 /* one pointer */ << Pointer->getSourceRange(); | |||
10508 | } | |||
10509 | ||||
10510 | /// Diagnose invalid arithmetic on a null pointer. | |||
10511 | /// | |||
10512 | /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' | |||
10513 | /// idiom, which we recognize as a GNU extension. | |||
10514 | /// | |||
10515 | static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, | |||
10516 | Expr *Pointer, bool IsGNUIdiom) { | |||
10517 | if (IsGNUIdiom) | |||
10518 | S.Diag(Loc, diag::warn_gnu_null_ptr_arith) | |||
10519 | << Pointer->getSourceRange(); | |||
10520 | else | |||
10521 | S.Diag(Loc, diag::warn_pointer_arith_null_ptr) | |||
10522 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); | |||
10523 | } | |||
10524 | ||||
10525 | /// Diagnose invalid subraction on a null pointer. | |||
10526 | /// | |||
10527 | static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, | |||
10528 | Expr *Pointer, bool BothNull) { | |||
10529 | // Null - null is valid in C++ [expr.add]p7 | |||
10530 | if (BothNull && S.getLangOpts().CPlusPlus) | |||
10531 | return; | |||
10532 | ||||
10533 | // Is this s a macro from a system header? | |||
10534 | if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) | |||
10535 | return; | |||
10536 | ||||
10537 | S.Diag(Loc, diag::warn_pointer_sub_null_ptr) | |||
10538 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); | |||
10539 | } | |||
10540 | ||||
10541 | /// Diagnose invalid arithmetic on two function pointers. | |||
10542 | static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, | |||
10543 | Expr *LHS, Expr *RHS) { | |||
10544 | assert(LHS->getType()->isAnyPointerType())(static_cast <bool> (LHS->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("LHS->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 10544, __extension__ __PRETTY_FUNCTION__ )); | |||
10545 | assert(RHS->getType()->isAnyPointerType())(static_cast <bool> (RHS->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("RHS->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 10545, __extension__ __PRETTY_FUNCTION__ )); | |||
10546 | S.Diag(Loc, S.getLangOpts().CPlusPlus | |||
10547 | ? diag::err_typecheck_pointer_arith_function_type | |||
10548 | : diag::ext_gnu_ptr_func_arith) | |||
10549 | << 1 /* two pointers */ << LHS->getType()->getPointeeType() | |||
10550 | // We only show the second type if it differs from the first. | |||
10551 | << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), | |||
10552 | RHS->getType()) | |||
10553 | << RHS->getType()->getPointeeType() | |||
10554 | << LHS->getSourceRange() << RHS->getSourceRange(); | |||
10555 | } | |||
10556 | ||||
10557 | /// Diagnose invalid arithmetic on a function pointer. | |||
10558 | static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, | |||
10559 | Expr *Pointer) { | |||
10560 | assert(Pointer->getType()->isAnyPointerType())(static_cast <bool> (Pointer->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 10560, __extension__ __PRETTY_FUNCTION__ )); | |||
10561 | S.Diag(Loc, S.getLangOpts().CPlusPlus | |||
10562 | ? diag::err_typecheck_pointer_arith_function_type | |||
10563 | : diag::ext_gnu_ptr_func_arith) | |||
10564 | << 0 /* one pointer */ << Pointer->getType()->getPointeeType() | |||
10565 | << 0 /* one pointer, so only one type */ | |||
10566 | << Pointer->getSourceRange(); | |||
10567 | } | |||
10568 | ||||
10569 | /// Emit error if Operand is incomplete pointer type | |||
10570 | /// | |||
10571 | /// \returns True if pointer has incomplete type | |||
10572 | static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, | |||
10573 | Expr *Operand) { | |||
10574 | QualType ResType = Operand->getType(); | |||
10575 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | |||
10576 | ResType = ResAtomicType->getValueType(); | |||
10577 | ||||
10578 | assert(ResType->isAnyPointerType() && !ResType->isDependentType())(static_cast <bool> (ResType->isAnyPointerType() && !ResType->isDependentType()) ? void (0) : __assert_fail ( "ResType->isAnyPointerType() && !ResType->isDependentType()" , "clang/lib/Sema/SemaExpr.cpp", 10578, __extension__ __PRETTY_FUNCTION__ )); | |||
10579 | QualType PointeeTy = ResType->getPointeeType(); | |||
10580 | return S.RequireCompleteSizedType( | |||
10581 | Loc, PointeeTy, | |||
10582 | diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, | |||
10583 | Operand->getSourceRange()); | |||
10584 | } | |||
10585 | ||||
10586 | /// Check the validity of an arithmetic pointer operand. | |||
10587 | /// | |||
10588 | /// If the operand has pointer type, this code will check for pointer types | |||
10589 | /// which are invalid in arithmetic operations. These will be diagnosed | |||
10590 | /// appropriately, including whether or not the use is supported as an | |||
10591 | /// extension. | |||
10592 | /// | |||
10593 | /// \returns True when the operand is valid to use (even if as an extension). | |||
10594 | static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, | |||
10595 | Expr *Operand) { | |||
10596 | QualType ResType = Operand->getType(); | |||
10597 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | |||
10598 | ResType = ResAtomicType->getValueType(); | |||
10599 | ||||
10600 | if (!ResType->isAnyPointerType()) return true; | |||
10601 | ||||
10602 | QualType PointeeTy = ResType->getPointeeType(); | |||
10603 | if (PointeeTy->isVoidType()) { | |||
10604 | diagnoseArithmeticOnVoidPointer(S, Loc, Operand); | |||
10605 | return !S.getLangOpts().CPlusPlus; | |||
10606 | } | |||
10607 | if (PointeeTy->isFunctionType()) { | |||
10608 | diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); | |||
10609 | return !S.getLangOpts().CPlusPlus; | |||
10610 | } | |||
10611 | ||||
10612 | if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; | |||
10613 | ||||
10614 | return true; | |||
10615 | } | |||
10616 | ||||
10617 | /// Check the validity of a binary arithmetic operation w.r.t. pointer | |||
10618 | /// operands. | |||
10619 | /// | |||
10620 | /// This routine will diagnose any invalid arithmetic on pointer operands much | |||
10621 | /// like \see checkArithmeticOpPointerOperand. However, it has special logic | |||
10622 | /// for emitting a single diagnostic even for operations where both LHS and RHS | |||
10623 | /// are (potentially problematic) pointers. | |||
10624 | /// | |||
10625 | /// \returns True when the operand is valid to use (even if as an extension). | |||
10626 | static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, | |||
10627 | Expr *LHSExpr, Expr *RHSExpr) { | |||
10628 | bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); | |||
10629 | bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); | |||
10630 | if (!isLHSPointer && !isRHSPointer) return true; | |||
10631 | ||||
10632 | QualType LHSPointeeTy, RHSPointeeTy; | |||
10633 | if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); | |||
10634 | if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); | |||
10635 | ||||
10636 | // if both are pointers check if operation is valid wrt address spaces | |||
10637 | if (isLHSPointer && isRHSPointer) { | |||
10638 | if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { | |||
10639 | S.Diag(Loc, | |||
10640 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | |||
10641 | << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ | |||
10642 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); | |||
10643 | return false; | |||
10644 | } | |||
10645 | } | |||
10646 | ||||
10647 | // Check for arithmetic on pointers to incomplete types. | |||
10648 | bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); | |||
10649 | bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); | |||
10650 | if (isLHSVoidPtr || isRHSVoidPtr) { | |||
10651 | if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); | |||
10652 | else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); | |||
10653 | else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); | |||
10654 | ||||
10655 | return !S.getLangOpts().CPlusPlus; | |||
10656 | } | |||
10657 | ||||
10658 | bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); | |||
10659 | bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); | |||
10660 | if (isLHSFuncPtr || isRHSFuncPtr) { | |||
10661 | if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); | |||
10662 | else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, | |||
10663 | RHSExpr); | |||
10664 | else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); | |||
10665 | ||||
10666 | return !S.getLangOpts().CPlusPlus; | |||
10667 | } | |||
10668 | ||||
10669 | if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) | |||
10670 | return false; | |||
10671 | if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) | |||
10672 | return false; | |||
10673 | ||||
10674 | return true; | |||
10675 | } | |||
10676 | ||||
10677 | /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string | |||
10678 | /// literal. | |||
10679 | static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, | |||
10680 | Expr *LHSExpr, Expr *RHSExpr) { | |||
10681 | StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); | |||
10682 | Expr* IndexExpr = RHSExpr; | |||
10683 | if (!StrExpr) { | |||
10684 | StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); | |||
10685 | IndexExpr = LHSExpr; | |||
10686 | } | |||
10687 | ||||
10688 | bool IsStringPlusInt = StrExpr && | |||
10689 | IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); | |||
10690 | if (!IsStringPlusInt || IndexExpr->isValueDependent()) | |||
10691 | return; | |||
10692 | ||||
10693 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | |||
10694 | Self.Diag(OpLoc, diag::warn_string_plus_int) | |||
10695 | << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); | |||
10696 | ||||
10697 | // Only print a fixit for "str" + int, not for int + "str". | |||
10698 | if (IndexExpr == RHSExpr) { | |||
10699 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | |||
10700 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | |||
10701 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | |||
10702 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | |||
10703 | << FixItHint::CreateInsertion(EndLoc, "]"); | |||
10704 | } else | |||
10705 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | |||
10706 | } | |||
10707 | ||||
10708 | /// Emit a warning when adding a char literal to a string. | |||
10709 | static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, | |||
10710 | Expr *LHSExpr, Expr *RHSExpr) { | |||
10711 | const Expr *StringRefExpr = LHSExpr; | |||
10712 | const CharacterLiteral *CharExpr = | |||
10713 | dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); | |||
10714 | ||||
10715 | if (!CharExpr) { | |||
10716 | CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); | |||
10717 | StringRefExpr = RHSExpr; | |||
10718 | } | |||
10719 | ||||
10720 | if (!CharExpr || !StringRefExpr) | |||
10721 | return; | |||
10722 | ||||
10723 | const QualType StringType = StringRefExpr->getType(); | |||
10724 | ||||
10725 | // Return if not a PointerType. | |||
10726 | if (!StringType->isAnyPointerType()) | |||
10727 | return; | |||
10728 | ||||
10729 | // Return if not a CharacterType. | |||
10730 | if (!StringType->getPointeeType()->isAnyCharacterType()) | |||
10731 | return; | |||
10732 | ||||
10733 | ASTContext &Ctx = Self.getASTContext(); | |||
10734 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | |||
10735 | ||||
10736 | const QualType CharType = CharExpr->getType(); | |||
10737 | if (!CharType->isAnyCharacterType() && | |||
10738 | CharType->isIntegerType() && | |||
10739 | llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { | |||
10740 | Self.Diag(OpLoc, diag::warn_string_plus_char) | |||
10741 | << DiagRange << Ctx.CharTy; | |||
10742 | } else { | |||
10743 | Self.Diag(OpLoc, diag::warn_string_plus_char) | |||
10744 | << DiagRange << CharExpr->getType(); | |||
10745 | } | |||
10746 | ||||
10747 | // Only print a fixit for str + char, not for char + str. | |||
10748 | if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { | |||
10749 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | |||
10750 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | |||
10751 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | |||
10752 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | |||
10753 | << FixItHint::CreateInsertion(EndLoc, "]"); | |||
10754 | } else { | |||
10755 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | |||
10756 | } | |||
10757 | } | |||
10758 | ||||
10759 | /// Emit error when two pointers are incompatible. | |||
10760 | static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, | |||
10761 | Expr *LHSExpr, Expr *RHSExpr) { | |||
10762 | assert(LHSExpr->getType()->isAnyPointerType())(static_cast <bool> (LHSExpr->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 10762, __extension__ __PRETTY_FUNCTION__ )); | |||
10763 | assert(RHSExpr->getType()->isAnyPointerType())(static_cast <bool> (RHSExpr->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 10763, __extension__ __PRETTY_FUNCTION__ )); | |||
10764 | S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) | |||
10765 | << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() | |||
10766 | << RHSExpr->getSourceRange(); | |||
10767 | } | |||
10768 | ||||
10769 | // C99 6.5.6 | |||
10770 | QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, | |||
10771 | SourceLocation Loc, BinaryOperatorKind Opc, | |||
10772 | QualType* CompLHSTy) { | |||
10773 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | |||
10774 | ||||
10775 | if (LHS.get()->getType()->isVectorType() || | |||
10776 | RHS.get()->getType()->isVectorType()) { | |||
10777 | QualType compType = CheckVectorOperands( | |||
10778 | LHS, RHS, Loc, CompLHSTy, | |||
10779 | /*AllowBothBool*/getLangOpts().AltiVec, | |||
10780 | /*AllowBoolConversions*/getLangOpts().ZVector); | |||
10781 | if (CompLHSTy) *CompLHSTy = compType; | |||
10782 | return compType; | |||
10783 | } | |||
10784 | ||||
10785 | if (LHS.get()->getType()->isConstantMatrixType() || | |||
10786 | RHS.get()->getType()->isConstantMatrixType()) { | |||
10787 | QualType compType = | |||
10788 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | |||
10789 | if (CompLHSTy) | |||
10790 | *CompLHSTy = compType; | |||
10791 | return compType; | |||
10792 | } | |||
10793 | ||||
10794 | QualType compType = UsualArithmeticConversions( | |||
10795 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | |||
10796 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
10797 | return QualType(); | |||
10798 | ||||
10799 | // Diagnose "string literal" '+' int and string '+' "char literal". | |||
10800 | if (Opc == BO_Add) { | |||
10801 | diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); | |||
10802 | diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); | |||
10803 | } | |||
10804 | ||||
10805 | // handle the common case first (both operands are arithmetic). | |||
10806 | if (!compType.isNull() && compType->isArithmeticType()) { | |||
10807 | if (CompLHSTy) *CompLHSTy = compType; | |||
10808 | return compType; | |||
10809 | } | |||
10810 | ||||
10811 | // Type-checking. Ultimately the pointer's going to be in PExp; | |||
10812 | // note that we bias towards the LHS being the pointer. | |||
10813 | Expr *PExp = LHS.get(), *IExp = RHS.get(); | |||
10814 | ||||
10815 | bool isObjCPointer; | |||
10816 | if (PExp->getType()->isPointerType()) { | |||
10817 | isObjCPointer = false; | |||
10818 | } else if (PExp->getType()->isObjCObjectPointerType()) { | |||
10819 | isObjCPointer = true; | |||
10820 | } else { | |||
10821 | std::swap(PExp, IExp); | |||
10822 | if (PExp->getType()->isPointerType()) { | |||
10823 | isObjCPointer = false; | |||
10824 | } else if (PExp->getType()->isObjCObjectPointerType()) { | |||
10825 | isObjCPointer = true; | |||
10826 | } else { | |||
10827 | return InvalidOperands(Loc, LHS, RHS); | |||
10828 | } | |||
10829 | } | |||
10830 | assert(PExp->getType()->isAnyPointerType())(static_cast <bool> (PExp->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("PExp->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 10830, __extension__ __PRETTY_FUNCTION__ )); | |||
10831 | ||||
10832 | if (!IExp->getType()->isIntegerType()) | |||
10833 | return InvalidOperands(Loc, LHS, RHS); | |||
10834 | ||||
10835 | // Adding to a null pointer results in undefined behavior. | |||
10836 | if (PExp->IgnoreParenCasts()->isNullPointerConstant( | |||
10837 | Context, Expr::NPC_ValueDependentIsNotNull)) { | |||
10838 | // In C++ adding zero to a null pointer is defined. | |||
10839 | Expr::EvalResult KnownVal; | |||
10840 | if (!getLangOpts().CPlusPlus || | |||
10841 | (!IExp->isValueDependent() && | |||
10842 | (!IExp->EvaluateAsInt(KnownVal, Context) || | |||
10843 | KnownVal.Val.getInt() != 0))) { | |||
10844 | // Check the conditions to see if this is the 'p = nullptr + n' idiom. | |||
10845 | bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( | |||
10846 | Context, BO_Add, PExp, IExp); | |||
10847 | diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); | |||
10848 | } | |||
10849 | } | |||
10850 | ||||
10851 | if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) | |||
10852 | return QualType(); | |||
10853 | ||||
10854 | if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) | |||
10855 | return QualType(); | |||
10856 | ||||
10857 | // Check array bounds for pointer arithemtic | |||
10858 | CheckArrayAccess(PExp, IExp); | |||
10859 | ||||
10860 | if (CompLHSTy) { | |||
10861 | QualType LHSTy = Context.isPromotableBitField(LHS.get()); | |||
10862 | if (LHSTy.isNull()) { | |||
10863 | LHSTy = LHS.get()->getType(); | |||
10864 | if (LHSTy->isPromotableIntegerType()) | |||
10865 | LHSTy = Context.getPromotedIntegerType(LHSTy); | |||
10866 | } | |||
10867 | *CompLHSTy = LHSTy; | |||
10868 | } | |||
10869 | ||||
10870 | return PExp->getType(); | |||
10871 | } | |||
10872 | ||||
10873 | // C99 6.5.6 | |||
10874 | QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, | |||
10875 | SourceLocation Loc, | |||
10876 | QualType* CompLHSTy) { | |||
10877 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | |||
10878 | ||||
10879 | if (LHS.get()->getType()->isVectorType() || | |||
10880 | RHS.get()->getType()->isVectorType()) { | |||
10881 | QualType compType = CheckVectorOperands( | |||
10882 | LHS, RHS, Loc, CompLHSTy, | |||
10883 | /*AllowBothBool*/getLangOpts().AltiVec, | |||
10884 | /*AllowBoolConversions*/getLangOpts().ZVector); | |||
10885 | if (CompLHSTy) *CompLHSTy = compType; | |||
10886 | return compType; | |||
10887 | } | |||
10888 | ||||
10889 | if (LHS.get()->getType()->isConstantMatrixType() || | |||
10890 | RHS.get()->getType()->isConstantMatrixType()) { | |||
10891 | QualType compType = | |||
10892 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | |||
10893 | if (CompLHSTy) | |||
10894 | *CompLHSTy = compType; | |||
10895 | return compType; | |||
10896 | } | |||
10897 | ||||
10898 | QualType compType = UsualArithmeticConversions( | |||
10899 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | |||
10900 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
10901 | return QualType(); | |||
10902 | ||||
10903 | // Enforce type constraints: C99 6.5.6p3. | |||
10904 | ||||
10905 | // Handle the common case first (both operands are arithmetic). | |||
10906 | if (!compType.isNull() && compType->isArithmeticType()) { | |||
10907 | if (CompLHSTy) *CompLHSTy = compType; | |||
10908 | return compType; | |||
10909 | } | |||
10910 | ||||
10911 | // Either ptr - int or ptr - ptr. | |||
10912 | if (LHS.get()->getType()->isAnyPointerType()) { | |||
10913 | QualType lpointee = LHS.get()->getType()->getPointeeType(); | |||
10914 | ||||
10915 | // Diagnose bad cases where we step over interface counts. | |||
10916 | if (LHS.get()->getType()->isObjCObjectPointerType() && | |||
10917 | checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) | |||
10918 | return QualType(); | |||
10919 | ||||
10920 | // The result type of a pointer-int computation is the pointer type. | |||
10921 | if (RHS.get()->getType()->isIntegerType()) { | |||
10922 | // Subtracting from a null pointer should produce a warning. | |||
10923 | // The last argument to the diagnose call says this doesn't match the | |||
10924 | // GNU int-to-pointer idiom. | |||
10925 | if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, | |||
10926 | Expr::NPC_ValueDependentIsNotNull)) { | |||
10927 | // In C++ adding zero to a null pointer is defined. | |||
10928 | Expr::EvalResult KnownVal; | |||
10929 | if (!getLangOpts().CPlusPlus || | |||
10930 | (!RHS.get()->isValueDependent() && | |||
10931 | (!RHS.get()->EvaluateAsInt(KnownVal, Context) || | |||
10932 | KnownVal.Val.getInt() != 0))) { | |||
10933 | diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); | |||
10934 | } | |||
10935 | } | |||
10936 | ||||
10937 | if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) | |||
10938 | return QualType(); | |||
10939 | ||||
10940 | // Check array bounds for pointer arithemtic | |||
10941 | CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, | |||
10942 | /*AllowOnePastEnd*/true, /*IndexNegated*/true); | |||
10943 | ||||
10944 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | |||
10945 | return LHS.get()->getType(); | |||
10946 | } | |||
10947 | ||||
10948 | // Handle pointer-pointer subtractions. | |||
10949 | if (const PointerType *RHSPTy | |||
10950 | = RHS.get()->getType()->getAs<PointerType>()) { | |||
10951 | QualType rpointee = RHSPTy->getPointeeType(); | |||
10952 | ||||
10953 | if (getLangOpts().CPlusPlus) { | |||
10954 | // Pointee types must be the same: C++ [expr.add] | |||
10955 | if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { | |||
10956 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | |||
10957 | } | |||
10958 | } else { | |||
10959 | // Pointee types must be compatible C99 6.5.6p3 | |||
10960 | if (!Context.typesAreCompatible( | |||
10961 | Context.getCanonicalType(lpointee).getUnqualifiedType(), | |||
10962 | Context.getCanonicalType(rpointee).getUnqualifiedType())) { | |||
10963 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | |||
10964 | return QualType(); | |||
10965 | } | |||
10966 | } | |||
10967 | ||||
10968 | if (!checkArithmeticBinOpPointerOperands(*this, Loc, | |||
10969 | LHS.get(), RHS.get())) | |||
10970 | return QualType(); | |||
10971 | ||||
10972 | bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( | |||
10973 | Context, Expr::NPC_ValueDependentIsNotNull); | |||
10974 | bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( | |||
10975 | Context, Expr::NPC_ValueDependentIsNotNull); | |||
10976 | ||||
10977 | // Subtracting nullptr or from nullptr is suspect | |||
10978 | if (LHSIsNullPtr) | |||
10979 | diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); | |||
10980 | if (RHSIsNullPtr) | |||
10981 | diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); | |||
10982 | ||||
10983 | // The pointee type may have zero size. As an extension, a structure or | |||
10984 | // union may have zero size or an array may have zero length. In this | |||
10985 | // case subtraction does not make sense. | |||
10986 | if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { | |||
10987 | CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); | |||
10988 | if (ElementSize.isZero()) { | |||
10989 | Diag(Loc,diag::warn_sub_ptr_zero_size_types) | |||
10990 | << rpointee.getUnqualifiedType() | |||
10991 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
10992 | } | |||
10993 | } | |||
10994 | ||||
10995 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | |||
10996 | return Context.getPointerDiffType(); | |||
10997 | } | |||
10998 | } | |||
10999 | ||||
11000 | return InvalidOperands(Loc, LHS, RHS); | |||
11001 | } | |||
11002 | ||||
11003 | static bool isScopedEnumerationType(QualType T) { | |||
11004 | if (const EnumType *ET = T->getAs<EnumType>()) | |||
11005 | return ET->getDecl()->isScoped(); | |||
11006 | return false; | |||
11007 | } | |||
11008 | ||||
11009 | static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, | |||
11010 | SourceLocation Loc, BinaryOperatorKind Opc, | |||
11011 | QualType LHSType) { | |||
11012 | // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), | |||
11013 | // so skip remaining warnings as we don't want to modify values within Sema. | |||
11014 | if (S.getLangOpts().OpenCL) | |||
11015 | return; | |||
11016 | ||||
11017 | // Check right/shifter operand | |||
11018 | Expr::EvalResult RHSResult; | |||
11019 | if (RHS.get()->isValueDependent() || | |||
11020 | !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) | |||
11021 | return; | |||
11022 | llvm::APSInt Right = RHSResult.Val.getInt(); | |||
11023 | ||||
11024 | if (Right.isNegative()) { | |||
11025 | S.DiagRuntimeBehavior(Loc, RHS.get(), | |||
11026 | S.PDiag(diag::warn_shift_negative) | |||
11027 | << RHS.get()->getSourceRange()); | |||
11028 | return; | |||
11029 | } | |||
11030 | ||||
11031 | QualType LHSExprType = LHS.get()->getType(); | |||
11032 | uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); | |||
11033 | if (LHSExprType->isBitIntType()) | |||
11034 | LeftSize = S.Context.getIntWidth(LHSExprType); | |||
11035 | else if (LHSExprType->isFixedPointType()) { | |||
11036 | auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); | |||
11037 | LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); | |||
11038 | } | |||
11039 | llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); | |||
11040 | if (Right.uge(LeftBits)) { | |||
11041 | S.DiagRuntimeBehavior(Loc, RHS.get(), | |||
11042 | S.PDiag(diag::warn_shift_gt_typewidth) | |||
11043 | << RHS.get()->getSourceRange()); | |||
11044 | return; | |||
11045 | } | |||
11046 | ||||
11047 | // FIXME: We probably need to handle fixed point types specially here. | |||
11048 | if (Opc != BO_Shl || LHSExprType->isFixedPointType()) | |||
11049 | return; | |||
11050 | ||||
11051 | // When left shifting an ICE which is signed, we can check for overflow which | |||
11052 | // according to C++ standards prior to C++2a has undefined behavior | |||
11053 | // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one | |||
11054 | // more than the maximum value representable in the result type, so never | |||
11055 | // warn for those. (FIXME: Unsigned left-shift overflow in a constant | |||
11056 | // expression is still probably a bug.) | |||
11057 | Expr::EvalResult LHSResult; | |||
11058 | if (LHS.get()->isValueDependent() || | |||
11059 | LHSType->hasUnsignedIntegerRepresentation() || | |||
11060 | !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) | |||
11061 | return; | |||
11062 | llvm::APSInt Left = LHSResult.Val.getInt(); | |||
11063 | ||||
11064 | // If LHS does not have a signed type and non-negative value | |||
11065 | // then, the behavior is undefined before C++2a. Warn about it. | |||
11066 | if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && | |||
11067 | !S.getLangOpts().CPlusPlus20) { | |||
11068 | S.DiagRuntimeBehavior(Loc, LHS.get(), | |||
11069 | S.PDiag(diag::warn_shift_lhs_negative) | |||
11070 | << LHS.get()->getSourceRange()); | |||
11071 | return; | |||
11072 | } | |||
11073 | ||||
11074 | llvm::APInt ResultBits = | |||
11075 | static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); | |||
11076 | if (LeftBits.uge(ResultBits)) | |||
11077 | return; | |||
11078 | llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); | |||
11079 | Result = Result.shl(Right); | |||
11080 | ||||
11081 | // Print the bit representation of the signed integer as an unsigned | |||
11082 | // hexadecimal number. | |||
11083 | SmallString<40> HexResult; | |||
11084 | Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); | |||
11085 | ||||
11086 | // If we are only missing a sign bit, this is less likely to result in actual | |||
11087 | // bugs -- if the result is cast back to an unsigned type, it will have the | |||
11088 | // expected value. Thus we place this behind a different warning that can be | |||
11089 | // turned off separately if needed. | |||
11090 | if (LeftBits == ResultBits - 1) { | |||
11091 | S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) | |||
11092 | << HexResult << LHSType | |||
11093 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
11094 | return; | |||
11095 | } | |||
11096 | ||||
11097 | S.Diag(Loc, diag::warn_shift_result_gt_typewidth) | |||
11098 | << HexResult.str() << Result.getMinSignedBits() << LHSType | |||
11099 | << Left.getBitWidth() << LHS.get()->getSourceRange() | |||
11100 | << RHS.get()->getSourceRange(); | |||
11101 | } | |||
11102 | ||||
11103 | /// Return the resulting type when a vector is shifted | |||
11104 | /// by a scalar or vector shift amount. | |||
11105 | static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, | |||
11106 | SourceLocation Loc, bool IsCompAssign) { | |||
11107 | // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. | |||
11108 | if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && | |||
11109 | !LHS.get()->getType()->isVectorType()) { | |||
11110 | S.Diag(Loc, diag::err_shift_rhs_only_vector) | |||
11111 | << RHS.get()->getType() << LHS.get()->getType() | |||
11112 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
11113 | return QualType(); | |||
11114 | } | |||
11115 | ||||
11116 | if (!IsCompAssign) { | |||
11117 | LHS = S.UsualUnaryConversions(LHS.get()); | |||
11118 | if (LHS.isInvalid()) return QualType(); | |||
11119 | } | |||
11120 | ||||
11121 | RHS = S.UsualUnaryConversions(RHS.get()); | |||
11122 | if (RHS.isInvalid()) return QualType(); | |||
11123 | ||||
11124 | QualType LHSType = LHS.get()->getType(); | |||
11125 | // Note that LHS might be a scalar because the routine calls not only in | |||
11126 | // OpenCL case. | |||
11127 | const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); | |||
11128 | QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; | |||
11129 | ||||
11130 | // Note that RHS might not be a vector. | |||
11131 | QualType RHSType = RHS.get()->getType(); | |||
11132 | const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); | |||
11133 | QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; | |||
11134 | ||||
11135 | // The operands need to be integers. | |||
11136 | if (!LHSEleType->isIntegerType()) { | |||
11137 | S.Diag(Loc, diag::err_typecheck_expect_int) | |||
11138 | << LHS.get()->getType() << LHS.get()->getSourceRange(); | |||
11139 | return QualType(); | |||
11140 | } | |||
11141 | ||||
11142 | if (!RHSEleType->isIntegerType()) { | |||
11143 | S.Diag(Loc, diag::err_typecheck_expect_int) | |||
11144 | << RHS.get()->getType() << RHS.get()->getSourceRange(); | |||
11145 | return QualType(); | |||
11146 | } | |||
11147 | ||||
11148 | if (!LHSVecTy) { | |||
11149 | assert(RHSVecTy)(static_cast <bool> (RHSVecTy) ? void (0) : __assert_fail ("RHSVecTy", "clang/lib/Sema/SemaExpr.cpp", 11149, __extension__ __PRETTY_FUNCTION__)); | |||
11150 | if (IsCompAssign) | |||
11151 | return RHSType; | |||
11152 | if (LHSEleType != RHSEleType) { | |||
11153 | LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); | |||
11154 | LHSEleType = RHSEleType; | |||
11155 | } | |||
11156 | QualType VecTy = | |||
11157 | S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); | |||
11158 | LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); | |||
11159 | LHSType = VecTy; | |||
11160 | } else if (RHSVecTy) { | |||
11161 | // OpenCL v1.1 s6.3.j says that for vector types, the operators | |||
11162 | // are applied component-wise. So if RHS is a vector, then ensure | |||
11163 | // that the number of elements is the same as LHS... | |||
11164 | if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { | |||
11165 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) | |||
11166 | << LHS.get()->getType() << RHS.get()->getType() | |||
11167 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
11168 | return QualType(); | |||
11169 | } | |||
11170 | if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { | |||
11171 | const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); | |||
11172 | const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); | |||
11173 | if (LHSBT != RHSBT && | |||
11174 | S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { | |||
11175 | S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) | |||
11176 | << LHS.get()->getType() << RHS.get()->getType() | |||
11177 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
11178 | } | |||
11179 | } | |||
11180 | } else { | |||
11181 | // ...else expand RHS to match the number of elements in LHS. | |||
11182 | QualType VecTy = | |||
11183 | S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); | |||
11184 | RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); | |||
11185 | } | |||
11186 | ||||
11187 | return LHSType; | |||
11188 | } | |||
11189 | ||||
11190 | // C99 6.5.7 | |||
11191 | QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, | |||
11192 | SourceLocation Loc, BinaryOperatorKind Opc, | |||
11193 | bool IsCompAssign) { | |||
11194 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | |||
11195 | ||||
11196 | // Vector shifts promote their scalar inputs to vector type. | |||
11197 | if (LHS.get()->getType()->isVectorType() || | |||
11198 | RHS.get()->getType()->isVectorType()) { | |||
11199 | if (LangOpts.ZVector) { | |||
11200 | // The shift operators for the z vector extensions work basically | |||
11201 | // like general shifts, except that neither the LHS nor the RHS is | |||
11202 | // allowed to be a "vector bool". | |||
11203 | if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) | |||
11204 | if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) | |||
11205 | return InvalidOperands(Loc, LHS, RHS); | |||
11206 | if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) | |||
11207 | if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) | |||
11208 | return InvalidOperands(Loc, LHS, RHS); | |||
11209 | } | |||
11210 | return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); | |||
11211 | } | |||
11212 | ||||
11213 | // Shifts don't perform usual arithmetic conversions, they just do integer | |||
11214 | // promotions on each operand. C99 6.5.7p3 | |||
11215 | ||||
11216 | // For the LHS, do usual unary conversions, but then reset them away | |||
11217 | // if this is a compound assignment. | |||
11218 | ExprResult OldLHS = LHS; | |||
11219 | LHS = UsualUnaryConversions(LHS.get()); | |||
11220 | if (LHS.isInvalid()) | |||
11221 | return QualType(); | |||
11222 | QualType LHSType = LHS.get()->getType(); | |||
11223 | if (IsCompAssign) LHS = OldLHS; | |||
11224 | ||||
11225 | // The RHS is simpler. | |||
11226 | RHS = UsualUnaryConversions(RHS.get()); | |||
11227 | if (RHS.isInvalid()) | |||
11228 | return QualType(); | |||
11229 | QualType RHSType = RHS.get()->getType(); | |||
11230 | ||||
11231 | // C99 6.5.7p2: Each of the operands shall have integer type. | |||
11232 | // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. | |||
11233 | if ((!LHSType->isFixedPointOrIntegerType() && | |||
11234 | !LHSType->hasIntegerRepresentation()) || | |||
11235 | !RHSType->hasIntegerRepresentation()) | |||
11236 | return InvalidOperands(Loc, LHS, RHS); | |||
11237 | ||||
11238 | // C++0x: Don't allow scoped enums. FIXME: Use something better than | |||
11239 | // hasIntegerRepresentation() above instead of this. | |||
11240 | if (isScopedEnumerationType(LHSType) || | |||
11241 | isScopedEnumerationType(RHSType)) { | |||
11242 | return InvalidOperands(Loc, LHS, RHS); | |||
11243 | } | |||
11244 | DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); | |||
11245 | ||||
11246 | // "The type of the result is that of the promoted left operand." | |||
11247 | return LHSType; | |||
11248 | } | |||
11249 | ||||
11250 | /// Diagnose bad pointer comparisons. | |||
11251 | static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, | |||
11252 | ExprResult &LHS, ExprResult &RHS, | |||
11253 | bool IsError) { | |||
11254 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers | |||
11255 | : diag::ext_typecheck_comparison_of_distinct_pointers) | |||
11256 | << LHS.get()->getType() << RHS.get()->getType() | |||
11257 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
11258 | } | |||
11259 | ||||
11260 | /// Returns false if the pointers are converted to a composite type, | |||
11261 | /// true otherwise. | |||
11262 | static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, | |||
11263 | ExprResult &LHS, ExprResult &RHS) { | |||
11264 | // C++ [expr.rel]p2: | |||
11265 | // [...] Pointer conversions (4.10) and qualification | |||
11266 | // conversions (4.4) are performed on pointer operands (or on | |||
11267 | // a pointer operand and a null pointer constant) to bring | |||
11268 | // them to their composite pointer type. [...] | |||
11269 | // | |||
11270 | // C++ [expr.eq]p1 uses the same notion for (in)equality | |||
11271 | // comparisons of pointers. | |||
11272 | ||||
11273 | QualType LHSType = LHS.get()->getType(); | |||
11274 | QualType RHSType = RHS.get()->getType(); | |||
11275 | assert(LHSType->isPointerType() || RHSType->isPointerType() ||(static_cast <bool> (LHSType->isPointerType() || RHSType ->isPointerType() || LHSType->isMemberPointerType() || RHSType ->isMemberPointerType()) ? void (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 11276, __extension__ __PRETTY_FUNCTION__ )) | |||
11276 | LHSType->isMemberPointerType() || RHSType->isMemberPointerType())(static_cast <bool> (LHSType->isPointerType() || RHSType ->isPointerType() || LHSType->isMemberPointerType() || RHSType ->isMemberPointerType()) ? void (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 11276, __extension__ __PRETTY_FUNCTION__ )); | |||
11277 | ||||
11278 | QualType T = S.FindCompositePointerType(Loc, LHS, RHS); | |||
11279 | if (T.isNull()) { | |||
11280 | if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && | |||
11281 | (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) | |||
11282 | diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); | |||
11283 | else | |||
11284 | S.InvalidOperands(Loc, LHS, RHS); | |||
11285 | return true; | |||
11286 | } | |||
11287 | ||||
11288 | return false; | |||
11289 | } | |||
11290 | ||||
11291 | static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, | |||
11292 | ExprResult &LHS, | |||
11293 | ExprResult &RHS, | |||
11294 | bool IsError) { | |||
11295 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void | |||
11296 | : diag::ext_typecheck_comparison_of_fptr_to_void) | |||
11297 | << LHS.get()->getType() << RHS.get()->getType() | |||
11298 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
11299 | } | |||
11300 | ||||
11301 | static bool isObjCObjectLiteral(ExprResult &E) { | |||
11302 | switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { | |||
11303 | case Stmt::ObjCArrayLiteralClass: | |||
11304 | case Stmt::ObjCDictionaryLiteralClass: | |||
11305 | case Stmt::ObjCStringLiteralClass: | |||
11306 | case Stmt::ObjCBoxedExprClass: | |||
11307 | return true; | |||
11308 | default: | |||
11309 | // Note that ObjCBoolLiteral is NOT an object literal! | |||
11310 | return false; | |||
11311 | } | |||
11312 | } | |||
11313 | ||||
11314 | static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { | |||
11315 | const ObjCObjectPointerType *Type = | |||
11316 | LHS->getType()->getAs<ObjCObjectPointerType>(); | |||
11317 | ||||
11318 | // If this is not actually an Objective-C object, bail out. | |||
11319 | if (!Type) | |||
11320 | return false; | |||
11321 | ||||
11322 | // Get the LHS object's interface type. | |||
11323 | QualType InterfaceType = Type->getPointeeType(); | |||
11324 | ||||
11325 | // If the RHS isn't an Objective-C object, bail out. | |||
11326 | if (!RHS->getType()->isObjCObjectPointerType()) | |||
11327 | return false; | |||
11328 | ||||
11329 | // Try to find the -isEqual: method. | |||
11330 | Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); | |||
11331 | ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, | |||
11332 | InterfaceType, | |||
11333 | /*IsInstance=*/true); | |||
11334 | if (!Method) { | |||
11335 | if (Type->isObjCIdType()) { | |||
11336 | // For 'id', just check the global pool. | |||
11337 | Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), | |||
11338 | /*receiverId=*/true); | |||
11339 | } else { | |||
11340 | // Check protocols. | |||
11341 | Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, | |||
11342 | /*IsInstance=*/true); | |||
11343 | } | |||
11344 | } | |||
11345 | ||||
11346 | if (!Method) | |||
11347 | return false; | |||
11348 | ||||
11349 | QualType T = Method->parameters()[0]->getType(); | |||
11350 | if (!T->isObjCObjectPointerType()) | |||
11351 | return false; | |||
11352 | ||||
11353 | QualType R = Method->getReturnType(); | |||
11354 | if (!R->isScalarType()) | |||
11355 | return false; | |||
11356 | ||||
11357 | return true; | |||
11358 | } | |||
11359 | ||||
11360 | Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { | |||
11361 | FromE = FromE->IgnoreParenImpCasts(); | |||
11362 | switch (FromE->getStmtClass()) { | |||
11363 | default: | |||
11364 | break; | |||
11365 | case Stmt::ObjCStringLiteralClass: | |||
11366 | // "string literal" | |||
11367 | return LK_String; | |||
11368 | case Stmt::ObjCArrayLiteralClass: | |||
11369 | // "array literal" | |||
11370 | return LK_Array; | |||
11371 | case Stmt::ObjCDictionaryLiteralClass: | |||
11372 | // "dictionary literal" | |||
11373 | return LK_Dictionary; | |||
11374 | case Stmt::BlockExprClass: | |||
11375 | return LK_Block; | |||
11376 | case Stmt::ObjCBoxedExprClass: { | |||
11377 | Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); | |||
11378 | switch (Inner->getStmtClass()) { | |||
11379 | case Stmt::IntegerLiteralClass: | |||
11380 | case Stmt::FloatingLiteralClass: | |||
11381 | case Stmt::CharacterLiteralClass: | |||
11382 | case Stmt::ObjCBoolLiteralExprClass: | |||
11383 | case Stmt::CXXBoolLiteralExprClass: | |||
11384 | // "numeric literal" | |||
11385 | return LK_Numeric; | |||
11386 | case Stmt::ImplicitCastExprClass: { | |||
11387 | CastKind CK = cast<CastExpr>(Inner)->getCastKind(); | |||
11388 | // Boolean literals can be represented by implicit casts. | |||
11389 | if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) | |||
11390 | return LK_Numeric; | |||
11391 | break; | |||
11392 | } | |||
11393 | default: | |||
11394 | break; | |||
11395 | } | |||
11396 | return LK_Boxed; | |||
11397 | } | |||
11398 | } | |||
11399 | return LK_None; | |||
11400 | } | |||
11401 | ||||
11402 | static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, | |||
11403 | ExprResult &LHS, ExprResult &RHS, | |||
11404 | BinaryOperator::Opcode Opc){ | |||
11405 | Expr *Literal; | |||
11406 | Expr *Other; | |||
11407 | if (isObjCObjectLiteral(LHS)) { | |||
11408 | Literal = LHS.get(); | |||
11409 | Other = RHS.get(); | |||
11410 | } else { | |||
11411 | Literal = RHS.get(); | |||
11412 | Other = LHS.get(); | |||
11413 | } | |||
11414 | ||||
11415 | // Don't warn on comparisons against nil. | |||
11416 | Other = Other->IgnoreParenCasts(); | |||
11417 | if (Other->isNullPointerConstant(S.getASTContext(), | |||
11418 | Expr::NPC_ValueDependentIsNotNull)) | |||
11419 | return; | |||
11420 | ||||
11421 | // This should be kept in sync with warn_objc_literal_comparison. | |||
11422 | // LK_String should always be after the other literals, since it has its own | |||
11423 | // warning flag. | |||
11424 | Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); | |||
11425 | assert(LiteralKind != Sema::LK_Block)(static_cast <bool> (LiteralKind != Sema::LK_Block) ? void (0) : __assert_fail ("LiteralKind != Sema::LK_Block", "clang/lib/Sema/SemaExpr.cpp" , 11425, __extension__ __PRETTY_FUNCTION__)); | |||
11426 | if (LiteralKind == Sema::LK_None) { | |||
11427 | llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind" , "clang/lib/Sema/SemaExpr.cpp", 11427); | |||
11428 | } | |||
11429 | ||||
11430 | if (LiteralKind == Sema::LK_String) | |||
11431 | S.Diag(Loc, diag::warn_objc_string_literal_comparison) | |||
11432 | << Literal->getSourceRange(); | |||
11433 | else | |||
11434 | S.Diag(Loc, diag::warn_objc_literal_comparison) | |||
11435 | << LiteralKind << Literal->getSourceRange(); | |||
11436 | ||||
11437 | if (BinaryOperator::isEqualityOp(Opc) && | |||
11438 | hasIsEqualMethod(S, LHS.get(), RHS.get())) { | |||
11439 | SourceLocation Start = LHS.get()->getBeginLoc(); | |||
11440 | SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); | |||
11441 | CharSourceRange OpRange = | |||
11442 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | |||
11443 | ||||
11444 | S.Diag(Loc, diag::note_objc_literal_comparison_isequal) | |||
11445 | << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") | |||
11446 | << FixItHint::CreateReplacement(OpRange, " isEqual:") | |||
11447 | << FixItHint::CreateInsertion(End, "]"); | |||
11448 | } | |||
11449 | } | |||
11450 | ||||
11451 | /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. | |||
11452 | static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, | |||
11453 | ExprResult &RHS, SourceLocation Loc, | |||
11454 | BinaryOperatorKind Opc) { | |||
11455 | // Check that left hand side is !something. | |||
11456 | UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); | |||
11457 | if (!UO || UO->getOpcode() != UO_LNot) return; | |||
11458 | ||||
11459 | // Only check if the right hand side is non-bool arithmetic type. | |||
11460 | if (RHS.get()->isKnownToHaveBooleanValue()) return; | |||
11461 | ||||
11462 | // Make sure that the something in !something is not bool. | |||
11463 | Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); | |||
11464 | if (SubExpr->isKnownToHaveBooleanValue()) return; | |||
11465 | ||||
11466 | // Emit warning. | |||
11467 | bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; | |||
11468 | S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) | |||
11469 | << Loc << IsBitwiseOp; | |||
11470 | ||||
11471 | // First note suggest !(x < y) | |||
11472 | SourceLocation FirstOpen = SubExpr->getBeginLoc(); | |||
11473 | SourceLocation FirstClose = RHS.get()->getEndLoc(); | |||
11474 | FirstClose = S.getLocForEndOfToken(FirstClose); | |||
11475 | if (FirstClose.isInvalid()) | |||
11476 | FirstOpen = SourceLocation(); | |||
11477 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) | |||
11478 | << IsBitwiseOp | |||
11479 | << FixItHint::CreateInsertion(FirstOpen, "(") | |||
11480 | << FixItHint::CreateInsertion(FirstClose, ")"); | |||
11481 | ||||
11482 | // Second note suggests (!x) < y | |||
11483 | SourceLocation SecondOpen = LHS.get()->getBeginLoc(); | |||
11484 | SourceLocation SecondClose = LHS.get()->getEndLoc(); | |||
11485 | SecondClose = S.getLocForEndOfToken(SecondClose); | |||
11486 | if (SecondClose.isInvalid()) | |||
11487 | SecondOpen = SourceLocation(); | |||
11488 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) | |||
11489 | << FixItHint::CreateInsertion(SecondOpen, "(") | |||
11490 | << FixItHint::CreateInsertion(SecondClose, ")"); | |||
11491 | } | |||
11492 | ||||
11493 | // Returns true if E refers to a non-weak array. | |||
11494 | static bool checkForArray(const Expr *E) { | |||
11495 | const ValueDecl *D = nullptr; | |||
11496 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { | |||
11497 | D = DR->getDecl(); | |||
11498 | } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { | |||
11499 | if (Mem->isImplicitAccess()) | |||
11500 | D = Mem->getMemberDecl(); | |||
11501 | } | |||
11502 | if (!D) | |||
11503 | return false; | |||
11504 | return D->getType()->isArrayType() && !D->isWeak(); | |||
11505 | } | |||
11506 | ||||
11507 | /// Diagnose some forms of syntactically-obvious tautological comparison. | |||
11508 | static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, | |||
11509 | Expr *LHS, Expr *RHS, | |||
11510 | BinaryOperatorKind Opc) { | |||
11511 | Expr *LHSStripped = LHS->IgnoreParenImpCasts(); | |||
11512 | Expr *RHSStripped = RHS->IgnoreParenImpCasts(); | |||
11513 | ||||
11514 | QualType LHSType = LHS->getType(); | |||
11515 | QualType RHSType = RHS->getType(); | |||
11516 | if (LHSType->hasFloatingRepresentation() || | |||
11517 | (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || | |||
11518 | S.inTemplateInstantiation()) | |||
11519 | return; | |||
11520 | ||||
11521 | // Comparisons between two array types are ill-formed for operator<=>, so | |||
11522 | // we shouldn't emit any additional warnings about it. | |||
11523 | if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) | |||
11524 | return; | |||
11525 | ||||
11526 | // For non-floating point types, check for self-comparisons of the form | |||
11527 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | |||
11528 | // often indicate logic errors in the program. | |||
11529 | // | |||
11530 | // NOTE: Don't warn about comparison expressions resulting from macro | |||
11531 | // expansion. Also don't warn about comparisons which are only self | |||
11532 | // comparisons within a template instantiation. The warnings should catch | |||
11533 | // obvious cases in the definition of the template anyways. The idea is to | |||
11534 | // warn when the typed comparison operator will always evaluate to the same | |||
11535 | // result. | |||
11536 | ||||
11537 | // Used for indexing into %select in warn_comparison_always | |||
11538 | enum { | |||
11539 | AlwaysConstant, | |||
11540 | AlwaysTrue, | |||
11541 | AlwaysFalse, | |||
11542 | AlwaysEqual, // std::strong_ordering::equal from operator<=> | |||
11543 | }; | |||
11544 | ||||
11545 | // C++2a [depr.array.comp]: | |||
11546 | // Equality and relational comparisons ([expr.eq], [expr.rel]) between two | |||
11547 | // operands of array type are deprecated. | |||
11548 | if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && | |||
11549 | RHSStripped->getType()->isArrayType()) { | |||
11550 | S.Diag(Loc, diag::warn_depr_array_comparison) | |||
11551 | << LHS->getSourceRange() << RHS->getSourceRange() | |||
11552 | << LHSStripped->getType() << RHSStripped->getType(); | |||
11553 | // Carry on to produce the tautological comparison warning, if this | |||
11554 | // expression is potentially-evaluated, we can resolve the array to a | |||
11555 | // non-weak declaration, and so on. | |||
11556 | } | |||
11557 | ||||
11558 | if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { | |||
11559 | if (Expr::isSameComparisonOperand(LHS, RHS)) { | |||
11560 | unsigned Result; | |||
11561 | switch (Opc) { | |||
11562 | case BO_EQ: | |||
11563 | case BO_LE: | |||
11564 | case BO_GE: | |||
11565 | Result = AlwaysTrue; | |||
11566 | break; | |||
11567 | case BO_NE: | |||
11568 | case BO_LT: | |||
11569 | case BO_GT: | |||
11570 | Result = AlwaysFalse; | |||
11571 | break; | |||
11572 | case BO_Cmp: | |||
11573 | Result = AlwaysEqual; | |||
11574 | break; | |||
11575 | default: | |||
11576 | Result = AlwaysConstant; | |||
11577 | break; | |||
11578 | } | |||
11579 | S.DiagRuntimeBehavior(Loc, nullptr, | |||
11580 | S.PDiag(diag::warn_comparison_always) | |||
11581 | << 0 /*self-comparison*/ | |||
11582 | << Result); | |||
11583 | } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { | |||
11584 | // What is it always going to evaluate to? | |||
11585 | unsigned Result; | |||
11586 | switch (Opc) { | |||
11587 | case BO_EQ: // e.g. array1 == array2 | |||
11588 | Result = AlwaysFalse; | |||
11589 | break; | |||
11590 | case BO_NE: // e.g. array1 != array2 | |||
11591 | Result = AlwaysTrue; | |||
11592 | break; | |||
11593 | default: // e.g. array1 <= array2 | |||
11594 | // The best we can say is 'a constant' | |||
11595 | Result = AlwaysConstant; | |||
11596 | break; | |||
11597 | } | |||
11598 | S.DiagRuntimeBehavior(Loc, nullptr, | |||
11599 | S.PDiag(diag::warn_comparison_always) | |||
11600 | << 1 /*array comparison*/ | |||
11601 | << Result); | |||
11602 | } | |||
11603 | } | |||
11604 | ||||
11605 | if (isa<CastExpr>(LHSStripped)) | |||
11606 | LHSStripped = LHSStripped->IgnoreParenCasts(); | |||
11607 | if (isa<CastExpr>(RHSStripped)) | |||
11608 | RHSStripped = RHSStripped->IgnoreParenCasts(); | |||
11609 | ||||
11610 | // Warn about comparisons against a string constant (unless the other | |||
11611 | // operand is null); the user probably wants string comparison function. | |||
11612 | Expr *LiteralString = nullptr; | |||
11613 | Expr *LiteralStringStripped = nullptr; | |||
11614 | if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && | |||
11615 | !RHSStripped->isNullPointerConstant(S.Context, | |||
11616 | Expr::NPC_ValueDependentIsNull)) { | |||
11617 | LiteralString = LHS; | |||
11618 | LiteralStringStripped = LHSStripped; | |||
11619 | } else if ((isa<StringLiteral>(RHSStripped) || | |||
11620 | isa<ObjCEncodeExpr>(RHSStripped)) && | |||
11621 | !LHSStripped->isNullPointerConstant(S.Context, | |||
11622 | Expr::NPC_ValueDependentIsNull)) { | |||
11623 | LiteralString = RHS; | |||
11624 | LiteralStringStripped = RHSStripped; | |||
11625 | } | |||
11626 | ||||
11627 | if (LiteralString) { | |||
11628 | S.DiagRuntimeBehavior(Loc, nullptr, | |||
11629 | S.PDiag(diag::warn_stringcompare) | |||
11630 | << isa<ObjCEncodeExpr>(LiteralStringStripped) | |||
11631 | << LiteralString->getSourceRange()); | |||
11632 | } | |||
11633 | } | |||
11634 | ||||
11635 | static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { | |||
11636 | switch (CK) { | |||
11637 | default: { | |||
11638 | #ifndef NDEBUG | |||
11639 | llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) | |||
11640 | << "\n"; | |||
11641 | #endif | |||
11642 | llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "clang/lib/Sema/SemaExpr.cpp" , 11642); | |||
11643 | } | |||
11644 | case CK_UserDefinedConversion: | |||
11645 | return ICK_Identity; | |||
11646 | case CK_LValueToRValue: | |||
11647 | return ICK_Lvalue_To_Rvalue; | |||
11648 | case CK_ArrayToPointerDecay: | |||
11649 | return ICK_Array_To_Pointer; | |||
11650 | case CK_FunctionToPointerDecay: | |||
11651 | return ICK_Function_To_Pointer; | |||
11652 | case CK_IntegralCast: | |||
11653 | return ICK_Integral_Conversion; | |||
11654 | case CK_FloatingCast: | |||
11655 | return ICK_Floating_Conversion; | |||
11656 | case CK_IntegralToFloating: | |||
11657 | case CK_FloatingToIntegral: | |||
11658 | return ICK_Floating_Integral; | |||
11659 | case CK_IntegralComplexCast: | |||
11660 | case CK_FloatingComplexCast: | |||
11661 | case CK_FloatingComplexToIntegralComplex: | |||
11662 | case CK_IntegralComplexToFloatingComplex: | |||
11663 | return ICK_Complex_Conversion; | |||
11664 | case CK_FloatingComplexToReal: | |||
11665 | case CK_FloatingRealToComplex: | |||
11666 | case CK_IntegralComplexToReal: | |||
11667 | case CK_IntegralRealToComplex: | |||
11668 | return ICK_Complex_Real; | |||
11669 | } | |||
11670 | } | |||
11671 | ||||
11672 | static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, | |||
11673 | QualType FromType, | |||
11674 | SourceLocation Loc) { | |||
11675 | // Check for a narrowing implicit conversion. | |||
11676 | StandardConversionSequence SCS; | |||
11677 | SCS.setAsIdentityConversion(); | |||
11678 | SCS.setToType(0, FromType); | |||
11679 | SCS.setToType(1, ToType); | |||
11680 | if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | |||
11681 | SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); | |||
11682 | ||||
11683 | APValue PreNarrowingValue; | |||
11684 | QualType PreNarrowingType; | |||
11685 | switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, | |||
11686 | PreNarrowingType, | |||
11687 | /*IgnoreFloatToIntegralConversion*/ true)) { | |||
11688 | case NK_Dependent_Narrowing: | |||
11689 | // Implicit conversion to a narrower type, but the expression is | |||
11690 | // value-dependent so we can't tell whether it's actually narrowing. | |||
11691 | case NK_Not_Narrowing: | |||
11692 | return false; | |||
11693 | ||||
11694 | case NK_Constant_Narrowing: | |||
11695 | // Implicit conversion to a narrower type, and the value is not a constant | |||
11696 | // expression. | |||
11697 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | |||
11698 | << /*Constant*/ 1 | |||
11699 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; | |||
11700 | return true; | |||
11701 | ||||
11702 | case NK_Variable_Narrowing: | |||
11703 | // Implicit conversion to a narrower type, and the value is not a constant | |||
11704 | // expression. | |||
11705 | case NK_Type_Narrowing: | |||
11706 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | |||
11707 | << /*Constant*/ 0 << FromType << ToType; | |||
11708 | // TODO: It's not a constant expression, but what if the user intended it | |||
11709 | // to be? Can we produce notes to help them figure out why it isn't? | |||
11710 | return true; | |||
11711 | } | |||
11712 | llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch", "clang/lib/Sema/SemaExpr.cpp", 11712); | |||
11713 | } | |||
11714 | ||||
11715 | static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, | |||
11716 | ExprResult &LHS, | |||
11717 | ExprResult &RHS, | |||
11718 | SourceLocation Loc) { | |||
11719 | QualType LHSType = LHS.get()->getType(); | |||
11720 | QualType RHSType = RHS.get()->getType(); | |||
11721 | // Dig out the original argument type and expression before implicit casts | |||
11722 | // were applied. These are the types/expressions we need to check the | |||
11723 | // [expr.spaceship] requirements against. | |||
11724 | ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); | |||
11725 | ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); | |||
11726 | QualType LHSStrippedType = LHSStripped.get()->getType(); | |||
11727 | QualType RHSStrippedType = RHSStripped.get()->getType(); | |||
11728 | ||||
11729 | // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the | |||
11730 | // other is not, the program is ill-formed. | |||
11731 | if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { | |||
11732 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | |||
11733 | return QualType(); | |||
11734 | } | |||
11735 | ||||
11736 | // FIXME: Consider combining this with checkEnumArithmeticConversions. | |||
11737 | int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + | |||
11738 | RHSStrippedType->isEnumeralType(); | |||
11739 | if (NumEnumArgs == 1) { | |||
11740 | bool LHSIsEnum = LHSStrippedType->isEnumeralType(); | |||
11741 | QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; | |||
11742 | if (OtherTy->hasFloatingRepresentation()) { | |||
11743 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | |||
11744 | return QualType(); | |||
11745 | } | |||
11746 | } | |||
11747 | if (NumEnumArgs == 2) { | |||
11748 | // C++2a [expr.spaceship]p5: If both operands have the same enumeration | |||
11749 | // type E, the operator yields the result of converting the operands | |||
11750 | // to the underlying type of E and applying <=> to the converted operands. | |||
11751 | if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { | |||
11752 | S.InvalidOperands(Loc, LHS, RHS); | |||
11753 | return QualType(); | |||
11754 | } | |||
11755 | QualType IntType = | |||
11756 | LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); | |||
11757 | assert(IntType->isArithmeticType())(static_cast <bool> (IntType->isArithmeticType()) ? void (0) : __assert_fail ("IntType->isArithmeticType()", "clang/lib/Sema/SemaExpr.cpp" , 11757, __extension__ __PRETTY_FUNCTION__)); | |||
11758 | ||||
11759 | // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we | |||
11760 | // promote the boolean type, and all other promotable integer types, to | |||
11761 | // avoid this. | |||
11762 | if (IntType->isPromotableIntegerType()) | |||
11763 | IntType = S.Context.getPromotedIntegerType(IntType); | |||
11764 | ||||
11765 | LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); | |||
11766 | RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); | |||
11767 | LHSType = RHSType = IntType; | |||
11768 | } | |||
11769 | ||||
11770 | // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the | |||
11771 | // usual arithmetic conversions are applied to the operands. | |||
11772 | QualType Type = | |||
11773 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | |||
11774 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
11775 | return QualType(); | |||
11776 | if (Type.isNull()) | |||
11777 | return S.InvalidOperands(Loc, LHS, RHS); | |||
11778 | ||||
11779 | Optional<ComparisonCategoryType> CCT = | |||
11780 | getComparisonCategoryForBuiltinCmp(Type); | |||
11781 | if (!CCT) | |||
11782 | return S.InvalidOperands(Loc, LHS, RHS); | |||
11783 | ||||
11784 | bool HasNarrowing = checkThreeWayNarrowingConversion( | |||
11785 | S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); | |||
11786 | HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, | |||
11787 | RHS.get()->getBeginLoc()); | |||
11788 | if (HasNarrowing) | |||
11789 | return QualType(); | |||
11790 | ||||
11791 | assert(!Type.isNull() && "composite type for <=> has not been set")(static_cast <bool> (!Type.isNull() && "composite type for <=> has not been set" ) ? void (0) : __assert_fail ("!Type.isNull() && \"composite type for <=> has not been set\"" , "clang/lib/Sema/SemaExpr.cpp", 11791, __extension__ __PRETTY_FUNCTION__ )); | |||
11792 | ||||
11793 | return S.CheckComparisonCategoryType( | |||
11794 | *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); | |||
11795 | } | |||
11796 | ||||
11797 | static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, | |||
11798 | ExprResult &RHS, | |||
11799 | SourceLocation Loc, | |||
11800 | BinaryOperatorKind Opc) { | |||
11801 | if (Opc == BO_Cmp) | |||
11802 | return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); | |||
11803 | ||||
11804 | // C99 6.5.8p3 / C99 6.5.9p4 | |||
11805 | QualType Type = | |||
11806 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | |||
11807 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
11808 | return QualType(); | |||
11809 | if (Type.isNull()) | |||
11810 | return S.InvalidOperands(Loc, LHS, RHS); | |||
11811 | assert(Type->isArithmeticType() || Type->isEnumeralType())(static_cast <bool> (Type->isArithmeticType() || Type ->isEnumeralType()) ? void (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()" , "clang/lib/Sema/SemaExpr.cpp", 11811, __extension__ __PRETTY_FUNCTION__ )); | |||
11812 | ||||
11813 | if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) | |||
11814 | return S.InvalidOperands(Loc, LHS, RHS); | |||
11815 | ||||
11816 | // Check for comparisons of floating point operands using != and ==. | |||
11817 | if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) | |||
11818 | S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); | |||
11819 | ||||
11820 | // The result of comparisons is 'bool' in C++, 'int' in C. | |||
11821 | return S.Context.getLogicalOperationType(); | |||
11822 | } | |||
11823 | ||||
11824 | void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { | |||
11825 | if (!NullE.get()->getType()->isAnyPointerType()) | |||
11826 | return; | |||
11827 | int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; | |||
11828 | if (!E.get()->getType()->isAnyPointerType() && | |||
11829 | E.get()->isNullPointerConstant(Context, | |||
11830 | Expr::NPC_ValueDependentIsNotNull) == | |||
11831 | Expr::NPCK_ZeroExpression) { | |||
11832 | if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { | |||
11833 | if (CL->getValue() == 0) | |||
11834 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | |||
11835 | << NullValue | |||
11836 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | |||
11837 | NullValue ? "NULL" : "(void *)0"); | |||
11838 | } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { | |||
11839 | TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); | |||
11840 | QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); | |||
11841 | if (T == Context.CharTy) | |||
11842 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | |||
11843 | << NullValue | |||
11844 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | |||
11845 | NullValue ? "NULL" : "(void *)0"); | |||
11846 | } | |||
11847 | } | |||
11848 | } | |||
11849 | ||||
11850 | // C99 6.5.8, C++ [expr.rel] | |||
11851 | QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, | |||
11852 | SourceLocation Loc, | |||
11853 | BinaryOperatorKind Opc) { | |||
11854 | bool IsRelational = BinaryOperator::isRelationalOp(Opc); | |||
11855 | bool IsThreeWay = Opc == BO_Cmp; | |||
11856 | bool IsOrdered = IsRelational || IsThreeWay; | |||
11857 | auto IsAnyPointerType = [](ExprResult E) { | |||
11858 | QualType Ty = E.get()->getType(); | |||
11859 | return Ty->isPointerType() || Ty->isMemberPointerType(); | |||
11860 | }; | |||
11861 | ||||
11862 | // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer | |||
11863 | // type, array-to-pointer, ..., conversions are performed on both operands to | |||
11864 | // bring them to their composite type. | |||
11865 | // Otherwise, all comparisons expect an rvalue, so convert to rvalue before | |||
11866 | // any type-related checks. | |||
11867 | if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { | |||
11868 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
11869 | if (LHS.isInvalid()) | |||
11870 | return QualType(); | |||
11871 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
11872 | if (RHS.isInvalid()) | |||
11873 | return QualType(); | |||
11874 | } else { | |||
11875 | LHS = DefaultLvalueConversion(LHS.get()); | |||
11876 | if (LHS.isInvalid()) | |||
11877 | return QualType(); | |||
11878 | RHS = DefaultLvalueConversion(RHS.get()); | |||
11879 | if (RHS.isInvalid()) | |||
11880 | return QualType(); | |||
11881 | } | |||
11882 | ||||
11883 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); | |||
11884 | if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { | |||
11885 | CheckPtrComparisonWithNullChar(LHS, RHS); | |||
11886 | CheckPtrComparisonWithNullChar(RHS, LHS); | |||
11887 | } | |||
11888 | ||||
11889 | // Handle vector comparisons separately. | |||
11890 | if (LHS.get()->getType()->isVectorType() || | |||
11891 | RHS.get()->getType()->isVectorType()) | |||
11892 | return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); | |||
11893 | ||||
11894 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | |||
11895 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | |||
11896 | ||||
11897 | QualType LHSType = LHS.get()->getType(); | |||
11898 | QualType RHSType = RHS.get()->getType(); | |||
11899 | if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && | |||
11900 | (RHSType->isArithmeticType() || RHSType->isEnumeralType())) | |||
11901 | return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); | |||
11902 | ||||
11903 | const Expr::NullPointerConstantKind LHSNullKind = | |||
11904 | LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | |||
11905 | const Expr::NullPointerConstantKind RHSNullKind = | |||
11906 | RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | |||
11907 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; | |||
11908 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; | |||
11909 | ||||
11910 | auto computeResultTy = [&]() { | |||
11911 | if (Opc != BO_Cmp) | |||
11912 | return Context.getLogicalOperationType(); | |||
11913 | assert(getLangOpts().CPlusPlus)(static_cast <bool> (getLangOpts().CPlusPlus) ? void (0 ) : __assert_fail ("getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp" , 11913, __extension__ __PRETTY_FUNCTION__)); | |||
11914 | assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))(static_cast <bool> (Context.hasSameType(LHS.get()-> getType(), RHS.get()->getType())) ? void (0) : __assert_fail ("Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())" , "clang/lib/Sema/SemaExpr.cpp", 11914, __extension__ __PRETTY_FUNCTION__ )); | |||
11915 | ||||
11916 | QualType CompositeTy = LHS.get()->getType(); | |||
11917 | assert(!CompositeTy->isReferenceType())(static_cast <bool> (!CompositeTy->isReferenceType() ) ? void (0) : __assert_fail ("!CompositeTy->isReferenceType()" , "clang/lib/Sema/SemaExpr.cpp", 11917, __extension__ __PRETTY_FUNCTION__ )); | |||
11918 | ||||
11919 | Optional<ComparisonCategoryType> CCT = | |||
11920 | getComparisonCategoryForBuiltinCmp(CompositeTy); | |||
11921 | if (!CCT) | |||
11922 | return InvalidOperands(Loc, LHS, RHS); | |||
11923 | ||||
11924 | if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { | |||
11925 | // P0946R0: Comparisons between a null pointer constant and an object | |||
11926 | // pointer result in std::strong_equality, which is ill-formed under | |||
11927 | // P1959R0. | |||
11928 | Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) | |||
11929 | << (LHSIsNull ? LHS.get()->getSourceRange() | |||
11930 | : RHS.get()->getSourceRange()); | |||
11931 | return QualType(); | |||
11932 | } | |||
11933 | ||||
11934 | return CheckComparisonCategoryType( | |||
11935 | *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); | |||
11936 | }; | |||
11937 | ||||
11938 | if (!IsOrdered && LHSIsNull != RHSIsNull) { | |||
11939 | bool IsEquality = Opc == BO_EQ; | |||
11940 | if (RHSIsNull) | |||
11941 | DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, | |||
11942 | RHS.get()->getSourceRange()); | |||
11943 | else | |||
11944 | DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, | |||
11945 | LHS.get()->getSourceRange()); | |||
11946 | } | |||
11947 | ||||
11948 | if (IsOrdered && LHSType->isFunctionPointerType() && | |||
11949 | RHSType->isFunctionPointerType()) { | |||
11950 | // Valid unless a relational comparison of function pointers | |||
11951 | bool IsError = Opc == BO_Cmp; | |||
11952 | auto DiagID = | |||
11953 | IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers | |||
11954 | : getLangOpts().CPlusPlus | |||
11955 | ? diag::warn_typecheck_ordered_comparison_of_function_pointers | |||
11956 | : diag::ext_typecheck_ordered_comparison_of_function_pointers; | |||
11957 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() | |||
11958 | << RHS.get()->getSourceRange(); | |||
11959 | if (IsError) | |||
11960 | return QualType(); | |||
11961 | } | |||
11962 | ||||
11963 | if ((LHSType->isIntegerType() && !LHSIsNull) || | |||
11964 | (RHSType->isIntegerType() && !RHSIsNull)) { | |||
11965 | // Skip normal pointer conversion checks in this case; we have better | |||
11966 | // diagnostics for this below. | |||
11967 | } else if (getLangOpts().CPlusPlus) { | |||
11968 | // Equality comparison of a function pointer to a void pointer is invalid, | |||
11969 | // but we allow it as an extension. | |||
11970 | // FIXME: If we really want to allow this, should it be part of composite | |||
11971 | // pointer type computation so it works in conditionals too? | |||
11972 | if (!IsOrdered && | |||
11973 | ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || | |||
11974 | (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { | |||
11975 | // This is a gcc extension compatibility comparison. | |||
11976 | // In a SFINAE context, we treat this as a hard error to maintain | |||
11977 | // conformance with the C++ standard. | |||
11978 | diagnoseFunctionPointerToVoidComparison( | |||
11979 | *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); | |||
11980 | ||||
11981 | if (isSFINAEContext()) | |||
11982 | return QualType(); | |||
11983 | ||||
11984 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
11985 | return computeResultTy(); | |||
11986 | } | |||
11987 | ||||
11988 | // C++ [expr.eq]p2: | |||
11989 | // If at least one operand is a pointer [...] bring them to their | |||
11990 | // composite pointer type. | |||
11991 | // C++ [expr.spaceship]p6 | |||
11992 | // If at least one of the operands is of pointer type, [...] bring them | |||
11993 | // to their composite pointer type. | |||
11994 | // C++ [expr.rel]p2: | |||
11995 | // If both operands are pointers, [...] bring them to their composite | |||
11996 | // pointer type. | |||
11997 | // For <=>, the only valid non-pointer types are arrays and functions, and | |||
11998 | // we already decayed those, so this is really the same as the relational | |||
11999 | // comparison rule. | |||
12000 | if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= | |||
12001 | (IsOrdered ? 2 : 1) && | |||
12002 | (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || | |||
12003 | RHSType->isObjCObjectPointerType()))) { | |||
12004 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | |||
12005 | return QualType(); | |||
12006 | return computeResultTy(); | |||
12007 | } | |||
12008 | } else if (LHSType->isPointerType() && | |||
12009 | RHSType->isPointerType()) { // C99 6.5.8p2 | |||
12010 | // All of the following pointer-related warnings are GCC extensions, except | |||
12011 | // when handling null pointer constants. | |||
12012 | QualType LCanPointeeTy = | |||
12013 | LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | |||
12014 | QualType RCanPointeeTy = | |||
12015 | RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | |||
12016 | ||||
12017 | // C99 6.5.9p2 and C99 6.5.8p2 | |||
12018 | if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), | |||
12019 | RCanPointeeTy.getUnqualifiedType())) { | |||
12020 | if (IsRelational) { | |||
12021 | // Pointers both need to point to complete or incomplete types | |||
12022 | if ((LCanPointeeTy->isIncompleteType() != | |||
12023 | RCanPointeeTy->isIncompleteType()) && | |||
12024 | !getLangOpts().C11) { | |||
12025 | Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) | |||
12026 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() | |||
12027 | << LHSType << RHSType << LCanPointeeTy->isIncompleteType() | |||
12028 | << RCanPointeeTy->isIncompleteType(); | |||
12029 | } | |||
12030 | } | |||
12031 | } else if (!IsRelational && | |||
12032 | (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { | |||
12033 | // Valid unless comparison between non-null pointer and function pointer | |||
12034 | if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) | |||
12035 | && !LHSIsNull && !RHSIsNull) | |||
12036 | diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, | |||
12037 | /*isError*/false); | |||
12038 | } else { | |||
12039 | // Invalid | |||
12040 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); | |||
12041 | } | |||
12042 | if (LCanPointeeTy != RCanPointeeTy) { | |||
12043 | // Treat NULL constant as a special case in OpenCL. | |||
12044 | if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { | |||
12045 | if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { | |||
12046 | Diag(Loc, | |||
12047 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | |||
12048 | << LHSType << RHSType << 0 /* comparison */ | |||
12049 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
12050 | } | |||
12051 | } | |||
12052 | LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); | |||
12053 | LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); | |||
12054 | CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion | |||
12055 | : CK_BitCast; | |||
12056 | if (LHSIsNull && !RHSIsNull) | |||
12057 | LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); | |||
12058 | else | |||
12059 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); | |||
12060 | } | |||
12061 | return computeResultTy(); | |||
12062 | } | |||
12063 | ||||
12064 | if (getLangOpts().CPlusPlus) { | |||
12065 | // C++ [expr.eq]p4: | |||
12066 | // Two operands of type std::nullptr_t or one operand of type | |||
12067 | // std::nullptr_t and the other a null pointer constant compare equal. | |||
12068 | if (!IsOrdered && LHSIsNull && RHSIsNull) { | |||
12069 | if (LHSType->isNullPtrType()) { | |||
12070 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
12071 | return computeResultTy(); | |||
12072 | } | |||
12073 | if (RHSType->isNullPtrType()) { | |||
12074 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
12075 | return computeResultTy(); | |||
12076 | } | |||
12077 | } | |||
12078 | ||||
12079 | // Comparison of Objective-C pointers and block pointers against nullptr_t. | |||
12080 | // These aren't covered by the composite pointer type rules. | |||
12081 | if (!IsOrdered && RHSType->isNullPtrType() && | |||
12082 | (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { | |||
12083 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
12084 | return computeResultTy(); | |||
12085 | } | |||
12086 | if (!IsOrdered && LHSType->isNullPtrType() && | |||
12087 | (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { | |||
12088 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
12089 | return computeResultTy(); | |||
12090 | } | |||
12091 | ||||
12092 | if (IsRelational && | |||
12093 | ((LHSType->isNullPtrType() && RHSType->isPointerType()) || | |||
12094 | (RHSType->isNullPtrType() && LHSType->isPointerType()))) { | |||
12095 | // HACK: Relational comparison of nullptr_t against a pointer type is | |||
12096 | // invalid per DR583, but we allow it within std::less<> and friends, | |||
12097 | // since otherwise common uses of it break. | |||
12098 | // FIXME: Consider removing this hack once LWG fixes std::less<> and | |||
12099 | // friends to have std::nullptr_t overload candidates. | |||
12100 | DeclContext *DC = CurContext; | |||
12101 | if (isa<FunctionDecl>(DC)) | |||
12102 | DC = DC->getParent(); | |||
12103 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { | |||
12104 | if (CTSD->isInStdNamespace() && | |||
12105 | llvm::StringSwitch<bool>(CTSD->getName()) | |||
12106 | .Cases("less", "less_equal", "greater", "greater_equal", true) | |||
12107 | .Default(false)) { | |||
12108 | if (RHSType->isNullPtrType()) | |||
12109 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
12110 | else | |||
12111 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
12112 | return computeResultTy(); | |||
12113 | } | |||
12114 | } | |||
12115 | } | |||
12116 | ||||
12117 | // C++ [expr.eq]p2: | |||
12118 | // If at least one operand is a pointer to member, [...] bring them to | |||
12119 | // their composite pointer type. | |||
12120 | if (!IsOrdered && | |||
12121 | (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { | |||
12122 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | |||
12123 | return QualType(); | |||
12124 | else | |||
12125 | return computeResultTy(); | |||
12126 | } | |||
12127 | } | |||
12128 | ||||
12129 | // Handle block pointer types. | |||
12130 | if (!IsOrdered && LHSType->isBlockPointerType() && | |||
12131 | RHSType->isBlockPointerType()) { | |||
12132 | QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); | |||
12133 | QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); | |||
12134 | ||||
12135 | if (!LHSIsNull && !RHSIsNull && | |||
12136 | !Context.typesAreCompatible(lpointee, rpointee)) { | |||
12137 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | |||
12138 | << LHSType << RHSType << LHS.get()->getSourceRange() | |||
12139 | << RHS.get()->getSourceRange(); | |||
12140 | } | |||
12141 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
12142 | return computeResultTy(); | |||
12143 | } | |||
12144 | ||||
12145 | // Allow block pointers to be compared with null pointer constants. | |||
12146 | if (!IsOrdered | |||
12147 | && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) | |||
12148 | || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { | |||
12149 | if (!LHSIsNull && !RHSIsNull) { | |||
12150 | if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() | |||
12151 | ->getPointeeType()->isVoidType()) | |||
12152 | || (LHSType->isPointerType() && LHSType->castAs<PointerType>() | |||
12153 | ->getPointeeType()->isVoidType()))) | |||
12154 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | |||
12155 | << LHSType << RHSType << LHS.get()->getSourceRange() | |||
12156 | << RHS.get()->getSourceRange(); | |||
12157 | } | |||
12158 | if (LHSIsNull && !RHSIsNull) | |||
12159 | LHS = ImpCastExprToType(LHS.get(), RHSType, | |||
12160 | RHSType->isPointerType() ? CK_BitCast | |||
12161 | : CK_AnyPointerToBlockPointerCast); | |||
12162 | else | |||
12163 | RHS = ImpCastExprToType(RHS.get(), LHSType, | |||
12164 | LHSType->isPointerType() ? CK_BitCast | |||
12165 | : CK_AnyPointerToBlockPointerCast); | |||
12166 | return computeResultTy(); | |||
12167 | } | |||
12168 | ||||
12169 | if (LHSType->isObjCObjectPointerType() || | |||
12170 | RHSType->isObjCObjectPointerType()) { | |||
12171 | const PointerType *LPT = LHSType->getAs<PointerType>(); | |||
12172 | const PointerType *RPT = RHSType->getAs<PointerType>(); | |||
12173 | if (LPT || RPT) { | |||
12174 | bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; | |||
12175 | bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; | |||
12176 | ||||
12177 | if (!LPtrToVoid && !RPtrToVoid && | |||
12178 | !Context.typesAreCompatible(LHSType, RHSType)) { | |||
12179 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | |||
12180 | /*isError*/false); | |||
12181 | } | |||
12182 | // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than | |||
12183 | // the RHS, but we have test coverage for this behavior. | |||
12184 | // FIXME: Consider using convertPointersToCompositeType in C++. | |||
12185 | if (LHSIsNull && !RHSIsNull) { | |||
12186 | Expr *E = LHS.get(); | |||
12187 | if (getLangOpts().ObjCAutoRefCount) | |||
12188 | CheckObjCConversion(SourceRange(), RHSType, E, | |||
12189 | CCK_ImplicitConversion); | |||
12190 | LHS = ImpCastExprToType(E, RHSType, | |||
12191 | RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | |||
12192 | } | |||
12193 | else { | |||
12194 | Expr *E = RHS.get(); | |||
12195 | if (getLangOpts().ObjCAutoRefCount) | |||
12196 | CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, | |||
12197 | /*Diagnose=*/true, | |||
12198 | /*DiagnoseCFAudited=*/false, Opc); | |||
12199 | RHS = ImpCastExprToType(E, LHSType, | |||
12200 | LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | |||
12201 | } | |||
12202 | return computeResultTy(); | |||
12203 | } | |||
12204 | if (LHSType->isObjCObjectPointerType() && | |||
12205 | RHSType->isObjCObjectPointerType()) { | |||
12206 | if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) | |||
12207 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | |||
12208 | /*isError*/false); | |||
12209 | if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) | |||
12210 | diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); | |||
12211 | ||||
12212 | if (LHSIsNull && !RHSIsNull) | |||
12213 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | |||
12214 | else | |||
12215 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
12216 | return computeResultTy(); | |||
12217 | } | |||
12218 | ||||
12219 | if (!IsOrdered && LHSType->isBlockPointerType() && | |||
12220 | RHSType->isBlockCompatibleObjCPointerType(Context)) { | |||
12221 | LHS = ImpCastExprToType(LHS.get(), RHSType, | |||
12222 | CK_BlockPointerToObjCPointerCast); | |||
12223 | return computeResultTy(); | |||
12224 | } else if (!IsOrdered && | |||
12225 | LHSType->isBlockCompatibleObjCPointerType(Context) && | |||
12226 | RHSType->isBlockPointerType()) { | |||
12227 | RHS = ImpCastExprToType(RHS.get(), LHSType, | |||
12228 | CK_BlockPointerToObjCPointerCast); | |||
12229 | return computeResultTy(); | |||
12230 | } | |||
12231 | } | |||
12232 | if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || | |||
12233 | (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { | |||
12234 | unsigned DiagID = 0; | |||
12235 | bool isError = false; | |||
12236 | if (LangOpts.DebuggerSupport) { | |||
12237 | // Under a debugger, allow the comparison of pointers to integers, | |||
12238 | // since users tend to want to compare addresses. | |||
12239 | } else if ((LHSIsNull && LHSType->isIntegerType()) || | |||
12240 | (RHSIsNull && RHSType->isIntegerType())) { | |||
12241 | if (IsOrdered) { | |||
12242 | isError = getLangOpts().CPlusPlus; | |||
12243 | DiagID = | |||
12244 | isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero | |||
12245 | : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; | |||
12246 | } | |||
12247 | } else if (getLangOpts().CPlusPlus) { | |||
12248 | DiagID = diag::err_typecheck_comparison_of_pointer_integer; | |||
12249 | isError = true; | |||
12250 | } else if (IsOrdered) | |||
12251 | DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; | |||
12252 | else | |||
12253 | DiagID = diag::ext_typecheck_comparison_of_pointer_integer; | |||
12254 | ||||
12255 | if (DiagID) { | |||
12256 | Diag(Loc, DiagID) | |||
12257 | << LHSType << RHSType << LHS.get()->getSourceRange() | |||
12258 | << RHS.get()->getSourceRange(); | |||
12259 | if (isError) | |||
12260 | return QualType(); | |||
12261 | } | |||
12262 | ||||
12263 | if (LHSType->isIntegerType()) | |||
12264 | LHS = ImpCastExprToType(LHS.get(), RHSType, | |||
12265 | LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | |||
12266 | else | |||
12267 | RHS = ImpCastExprToType(RHS.get(), LHSType, | |||
12268 | RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | |||
12269 | return computeResultTy(); | |||
12270 | } | |||
12271 | ||||
12272 | // Handle block pointers. | |||
12273 | if (!IsOrdered && RHSIsNull | |||
12274 | && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { | |||
12275 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
12276 | return computeResultTy(); | |||
12277 | } | |||
12278 | if (!IsOrdered && LHSIsNull | |||
12279 | && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { | |||
12280 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
12281 | return computeResultTy(); | |||
12282 | } | |||
12283 | ||||
12284 | if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { | |||
12285 | if (LHSType->isClkEventT() && RHSType->isClkEventT()) { | |||
12286 | return computeResultTy(); | |||
12287 | } | |||
12288 | ||||
12289 | if (LHSType->isQueueT() && RHSType->isQueueT()) { | |||
12290 | return computeResultTy(); | |||
12291 | } | |||
12292 | ||||
12293 | if (LHSIsNull && RHSType->isQueueT()) { | |||
12294 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
12295 | return computeResultTy(); | |||
12296 | } | |||
12297 | ||||
12298 | if (LHSType->isQueueT() && RHSIsNull) { | |||
12299 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
12300 | return computeResultTy(); | |||
12301 | } | |||
12302 | } | |||
12303 | ||||
12304 | return InvalidOperands(Loc, LHS, RHS); | |||
12305 | } | |||
12306 | ||||
12307 | // Return a signed ext_vector_type that is of identical size and number of | |||
12308 | // elements. For floating point vectors, return an integer type of identical | |||
12309 | // size and number of elements. In the non ext_vector_type case, search from | |||
12310 | // the largest type to the smallest type to avoid cases where long long == long, | |||
12311 | // where long gets picked over long long. | |||
12312 | QualType Sema::GetSignedVectorType(QualType V) { | |||
12313 | const VectorType *VTy = V->castAs<VectorType>(); | |||
12314 | unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); | |||
12315 | ||||
12316 | if (isa<ExtVectorType>(VTy)) { | |||
12317 | if (TypeSize == Context.getTypeSize(Context.CharTy)) | |||
12318 | return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); | |||
12319 | if (TypeSize == Context.getTypeSize(Context.ShortTy)) | |||
12320 | return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); | |||
12321 | if (TypeSize == Context.getTypeSize(Context.IntTy)) | |||
12322 | return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); | |||
12323 | if (TypeSize == Context.getTypeSize(Context.Int128Ty)) | |||
12324 | return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements()); | |||
12325 | if (TypeSize == Context.getTypeSize(Context.LongTy)) | |||
12326 | return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); | |||
12327 | assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&(static_cast <bool> (TypeSize == Context.getTypeSize(Context .LongLongTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "clang/lib/Sema/SemaExpr.cpp", 12328, __extension__ __PRETTY_FUNCTION__ )) | |||
12328 | "Unhandled vector element size in vector compare")(static_cast <bool> (TypeSize == Context.getTypeSize(Context .LongLongTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "clang/lib/Sema/SemaExpr.cpp", 12328, __extension__ __PRETTY_FUNCTION__ )); | |||
12329 | return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); | |||
12330 | } | |||
12331 | ||||
12332 | if (TypeSize == Context.getTypeSize(Context.Int128Ty)) | |||
12333 | return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(), | |||
12334 | VectorType::GenericVector); | |||
12335 | if (TypeSize == Context.getTypeSize(Context.LongLongTy)) | |||
12336 | return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), | |||
12337 | VectorType::GenericVector); | |||
12338 | if (TypeSize == Context.getTypeSize(Context.LongTy)) | |||
12339 | return Context.getVectorType(Context.LongTy, VTy->getNumElements(), | |||
12340 | VectorType::GenericVector); | |||
12341 | if (TypeSize == Context.getTypeSize(Context.IntTy)) | |||
12342 | return Context.getVectorType(Context.IntTy, VTy->getNumElements(), | |||
12343 | VectorType::GenericVector); | |||
12344 | if (TypeSize == Context.getTypeSize(Context.ShortTy)) | |||
12345 | return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), | |||
12346 | VectorType::GenericVector); | |||
12347 | assert(TypeSize == Context.getTypeSize(Context.CharTy) &&(static_cast <bool> (TypeSize == Context.getTypeSize(Context .CharTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "clang/lib/Sema/SemaExpr.cpp", 12348, __extension__ __PRETTY_FUNCTION__ )) | |||
12348 | "Unhandled vector element size in vector compare")(static_cast <bool> (TypeSize == Context.getTypeSize(Context .CharTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "clang/lib/Sema/SemaExpr.cpp", 12348, __extension__ __PRETTY_FUNCTION__ )); | |||
12349 | return Context.getVectorType(Context.CharTy, VTy->getNumElements(), | |||
12350 | VectorType::GenericVector); | |||
12351 | } | |||
12352 | ||||
12353 | /// CheckVectorCompareOperands - vector comparisons are a clang extension that | |||
12354 | /// operates on extended vector types. Instead of producing an IntTy result, | |||
12355 | /// like a scalar comparison, a vector comparison produces a vector of integer | |||
12356 | /// types. | |||
12357 | QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, | |||
12358 | SourceLocation Loc, | |||
12359 | BinaryOperatorKind Opc) { | |||
12360 | if (Opc == BO_Cmp) { | |||
12361 | Diag(Loc, diag::err_three_way_vector_comparison); | |||
12362 | return QualType(); | |||
12363 | } | |||
12364 | ||||
12365 | // Check to make sure we're operating on vectors of the same type and width, | |||
12366 | // Allowing one side to be a scalar of element type. | |||
12367 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, | |||
12368 | /*AllowBothBool*/true, | |||
12369 | /*AllowBoolConversions*/getLangOpts().ZVector); | |||
12370 | if (vType.isNull()) | |||
12371 | return vType; | |||
12372 | ||||
12373 | QualType LHSType = LHS.get()->getType(); | |||
12374 | ||||
12375 | // Determine the return type of a vector compare. By default clang will return | |||
12376 | // a scalar for all vector compares except vector bool and vector pixel. | |||
12377 | // With the gcc compiler we will always return a vector type and with the xl | |||
12378 | // compiler we will always return a scalar type. This switch allows choosing | |||
12379 | // which behavior is prefered. | |||
12380 | if (getLangOpts().AltiVec) { | |||
12381 | switch (getLangOpts().getAltivecSrcCompat()) { | |||
12382 | case LangOptions::AltivecSrcCompatKind::Mixed: | |||
12383 | // If AltiVec, the comparison results in a numeric type, i.e. | |||
12384 | // bool for C++, int for C | |||
12385 | if (vType->castAs<VectorType>()->getVectorKind() == | |||
12386 | VectorType::AltiVecVector) | |||
12387 | return Context.getLogicalOperationType(); | |||
12388 | else | |||
12389 | Diag(Loc, diag::warn_deprecated_altivec_src_compat); | |||
12390 | break; | |||
12391 | case LangOptions::AltivecSrcCompatKind::GCC: | |||
12392 | // For GCC we always return the vector type. | |||
12393 | break; | |||
12394 | case LangOptions::AltivecSrcCompatKind::XL: | |||
12395 | return Context.getLogicalOperationType(); | |||
12396 | break; | |||
12397 | } | |||
12398 | } | |||
12399 | ||||
12400 | // For non-floating point types, check for self-comparisons of the form | |||
12401 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | |||
12402 | // often indicate logic errors in the program. | |||
12403 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | |||
12404 | ||||
12405 | // Check for comparisons of floating point operands using != and ==. | |||
12406 | if (BinaryOperator::isEqualityOp(Opc) && | |||
12407 | LHSType->hasFloatingRepresentation()) { | |||
12408 | assert(RHS.get()->getType()->hasFloatingRepresentation())(static_cast <bool> (RHS.get()->getType()->hasFloatingRepresentation ()) ? void (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()" , "clang/lib/Sema/SemaExpr.cpp", 12408, __extension__ __PRETTY_FUNCTION__ )); | |||
12409 | CheckFloatComparison(Loc, LHS.get(), RHS.get()); | |||
12410 | } | |||
12411 | ||||
12412 | // Return a signed type for the vector. | |||
12413 | return GetSignedVectorType(vType); | |||
12414 | } | |||
12415 | ||||
12416 | static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, | |||
12417 | const ExprResult &XorRHS, | |||
12418 | const SourceLocation Loc) { | |||
12419 | // Do not diagnose macros. | |||
12420 | if (Loc.isMacroID()) | |||
12421 | return; | |||
12422 | ||||
12423 | // Do not diagnose if both LHS and RHS are macros. | |||
12424 | if (XorLHS.get()->getExprLoc().isMacroID() && | |||
12425 | XorRHS.get()->getExprLoc().isMacroID()) | |||
12426 | return; | |||
12427 | ||||
12428 | bool Negative = false; | |||
12429 | bool ExplicitPlus = false; | |||
12430 | const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); | |||
12431 | const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); | |||
12432 | ||||
12433 | if (!LHSInt) | |||
12434 | return; | |||
12435 | if (!RHSInt) { | |||
12436 | // Check negative literals. | |||
12437 | if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { | |||
12438 | UnaryOperatorKind Opc = UO->getOpcode(); | |||
12439 | if (Opc != UO_Minus && Opc != UO_Plus) | |||
12440 | return; | |||
12441 | RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); | |||
12442 | if (!RHSInt) | |||
12443 | return; | |||
12444 | Negative = (Opc == UO_Minus); | |||
12445 | ExplicitPlus = !Negative; | |||
12446 | } else { | |||
12447 | return; | |||
12448 | } | |||
12449 | } | |||
12450 | ||||
12451 | const llvm::APInt &LeftSideValue = LHSInt->getValue(); | |||
12452 | llvm::APInt RightSideValue = RHSInt->getValue(); | |||
12453 | if (LeftSideValue != 2 && LeftSideValue != 10) | |||
12454 | return; | |||
12455 | ||||
12456 | if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) | |||
12457 | return; | |||
12458 | ||||
12459 | CharSourceRange ExprRange = CharSourceRange::getCharRange( | |||
12460 | LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); | |||
12461 | llvm::StringRef ExprStr = | |||
12462 | Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); | |||
12463 | ||||
12464 | CharSourceRange XorRange = | |||
12465 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | |||
12466 | llvm::StringRef XorStr = | |||
12467 | Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); | |||
12468 | // Do not diagnose if xor keyword/macro is used. | |||
12469 | if (XorStr == "xor") | |||
12470 | return; | |||
12471 | ||||
12472 | std::string LHSStr = std::string(Lexer::getSourceText( | |||
12473 | CharSourceRange::getTokenRange(LHSInt->getSourceRange()), | |||
12474 | S.getSourceManager(), S.getLangOpts())); | |||
12475 | std::string RHSStr = std::string(Lexer::getSourceText( | |||
12476 | CharSourceRange::getTokenRange(RHSInt->getSourceRange()), | |||
12477 | S.getSourceManager(), S.getLangOpts())); | |||
12478 | ||||
12479 | if (Negative) { | |||
12480 | RightSideValue = -RightSideValue; | |||
12481 | RHSStr = "-" + RHSStr; | |||
12482 | } else if (ExplicitPlus) { | |||
12483 | RHSStr = "+" + RHSStr; | |||
12484 | } | |||
12485 | ||||
12486 | StringRef LHSStrRef = LHSStr; | |||
12487 | StringRef RHSStrRef = RHSStr; | |||
12488 | // Do not diagnose literals with digit separators, binary, hexadecimal, octal | |||
12489 | // literals. | |||
12490 | if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || | |||
12491 | RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || | |||
12492 | LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || | |||
12493 | RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || | |||
12494 | (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || | |||
12495 | (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || | |||
12496 | LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) | |||
12497 | return; | |||
12498 | ||||
12499 | bool SuggestXor = | |||
12500 | S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); | |||
12501 | const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; | |||
12502 | int64_t RightSideIntValue = RightSideValue.getSExtValue(); | |||
12503 | if (LeftSideValue == 2 && RightSideIntValue >= 0) { | |||
12504 | std::string SuggestedExpr = "1 << " + RHSStr; | |||
12505 | bool Overflow = false; | |||
12506 | llvm::APInt One = (LeftSideValue - 1); | |||
12507 | llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); | |||
12508 | if (Overflow) { | |||
12509 | if (RightSideIntValue < 64) | |||
12510 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | |||
12511 | << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) | |||
12512 | << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); | |||
12513 | else if (RightSideIntValue == 64) | |||
12514 | S.Diag(Loc, diag::warn_xor_used_as_pow) | |||
12515 | << ExprStr << toString(XorValue, 10, true); | |||
12516 | else | |||
12517 | return; | |||
12518 | } else { | |||
12519 | S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) | |||
12520 | << ExprStr << toString(XorValue, 10, true) << SuggestedExpr | |||
12521 | << toString(PowValue, 10, true) | |||
12522 | << FixItHint::CreateReplacement( | |||
12523 | ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); | |||
12524 | } | |||
12525 | ||||
12526 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) | |||
12527 | << ("0x2 ^ " + RHSStr) << SuggestXor; | |||
12528 | } else if (LeftSideValue == 10) { | |||
12529 | std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); | |||
12530 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | |||
12531 | << ExprStr << toString(XorValue, 10, true) << SuggestedValue | |||
12532 | << FixItHint::CreateReplacement(ExprRange, SuggestedValue); | |||
12533 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) | |||
12534 | << ("0xA ^ " + RHSStr) << SuggestXor; | |||
12535 | } | |||
12536 | } | |||
12537 | ||||
12538 | QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, | |||
12539 | SourceLocation Loc) { | |||
12540 | // Ensure that either both operands are of the same vector type, or | |||
12541 | // one operand is of a vector type and the other is of its element type. | |||
12542 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, | |||
12543 | /*AllowBothBool*/true, | |||
12544 | /*AllowBoolConversions*/false); | |||
12545 | if (vType.isNull()) | |||
12546 | return InvalidOperands(Loc, LHS, RHS); | |||
12547 | if (getLangOpts().OpenCL && | |||
12548 | getLangOpts().getOpenCLCompatibleVersion() < 120 && | |||
12549 | vType->hasFloatingRepresentation()) | |||
12550 | return InvalidOperands(Loc, LHS, RHS); | |||
12551 | // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the | |||
12552 | // usage of the logical operators && and || with vectors in C. This | |||
12553 | // check could be notionally dropped. | |||
12554 | if (!getLangOpts().CPlusPlus && | |||
12555 | !(isa<ExtVectorType>(vType->getAs<VectorType>()))) | |||
12556 | return InvalidLogicalVectorOperands(Loc, LHS, RHS); | |||
12557 | ||||
12558 | return GetSignedVectorType(LHS.get()->getType()); | |||
12559 | } | |||
12560 | ||||
12561 | QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, | |||
12562 | SourceLocation Loc, | |||
12563 | bool IsCompAssign) { | |||
12564 | if (!IsCompAssign) { | |||
12565 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
12566 | if (LHS.isInvalid()) | |||
12567 | return QualType(); | |||
12568 | } | |||
12569 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
12570 | if (RHS.isInvalid()) | |||
12571 | return QualType(); | |||
12572 | ||||
12573 | // For conversion purposes, we ignore any qualifiers. | |||
12574 | // For example, "const float" and "float" are equivalent. | |||
12575 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | |||
12576 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | |||
12577 | ||||
12578 | const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); | |||
12579 | const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); | |||
12580 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast <bool> ((LHSMatType || RHSMatType) && "At least one operand must be a matrix") ? void (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "clang/lib/Sema/SemaExpr.cpp", 12580, __extension__ __PRETTY_FUNCTION__ )); | |||
12581 | ||||
12582 | if (Context.hasSameType(LHSType, RHSType)) | |||
12583 | return LHSType; | |||
12584 | ||||
12585 | // Type conversion may change LHS/RHS. Keep copies to the original results, in | |||
12586 | // case we have to return InvalidOperands. | |||
12587 | ExprResult OriginalLHS = LHS; | |||
12588 | ExprResult OriginalRHS = RHS; | |||
12589 | if (LHSMatType && !RHSMatType) { | |||
12590 | RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); | |||
12591 | if (!RHS.isInvalid()) | |||
12592 | return LHSType; | |||
12593 | ||||
12594 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | |||
12595 | } | |||
12596 | ||||
12597 | if (!LHSMatType && RHSMatType) { | |||
12598 | LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); | |||
12599 | if (!LHS.isInvalid()) | |||
12600 | return RHSType; | |||
12601 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | |||
12602 | } | |||
12603 | ||||
12604 | return InvalidOperands(Loc, LHS, RHS); | |||
12605 | } | |||
12606 | ||||
12607 | QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, | |||
12608 | SourceLocation Loc, | |||
12609 | bool IsCompAssign) { | |||
12610 | if (!IsCompAssign) { | |||
12611 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
12612 | if (LHS.isInvalid()) | |||
12613 | return QualType(); | |||
12614 | } | |||
12615 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
12616 | if (RHS.isInvalid()) | |||
12617 | return QualType(); | |||
12618 | ||||
12619 | auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); | |||
12620 | auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); | |||
12621 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast <bool> ((LHSMatType || RHSMatType) && "At least one operand must be a matrix") ? void (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "clang/lib/Sema/SemaExpr.cpp", 12621, __extension__ __PRETTY_FUNCTION__ )); | |||
12622 | ||||
12623 | if (LHSMatType && RHSMatType) { | |||
12624 | if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) | |||
12625 | return InvalidOperands(Loc, LHS, RHS); | |||
12626 | ||||
12627 | if (!Context.hasSameType(LHSMatType->getElementType(), | |||
12628 | RHSMatType->getElementType())) | |||
12629 | return InvalidOperands(Loc, LHS, RHS); | |||
12630 | ||||
12631 | return Context.getConstantMatrixType(LHSMatType->getElementType(), | |||
12632 | LHSMatType->getNumRows(), | |||
12633 | RHSMatType->getNumColumns()); | |||
12634 | } | |||
12635 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); | |||
12636 | } | |||
12637 | ||||
12638 | inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, | |||
12639 | SourceLocation Loc, | |||
12640 | BinaryOperatorKind Opc) { | |||
12641 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | |||
12642 | ||||
12643 | bool IsCompAssign = | |||
12644 | Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; | |||
12645 | ||||
12646 | if (LHS.get()->getType()->isVectorType() || | |||
12647 | RHS.get()->getType()->isVectorType()) { | |||
12648 | if (LHS.get()->getType()->hasIntegerRepresentation() && | |||
12649 | RHS.get()->getType()->hasIntegerRepresentation()) | |||
12650 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | |||
12651 | /*AllowBothBool*/true, | |||
12652 | /*AllowBoolConversions*/getLangOpts().ZVector); | |||
12653 | return InvalidOperands(Loc, LHS, RHS); | |||
12654 | } | |||
12655 | ||||
12656 | if (Opc == BO_And) | |||
12657 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | |||
12658 | ||||
12659 | if (LHS.get()->getType()->hasFloatingRepresentation() || | |||
12660 | RHS.get()->getType()->hasFloatingRepresentation()) | |||
12661 | return InvalidOperands(Loc, LHS, RHS); | |||
12662 | ||||
12663 | ExprResult LHSResult = LHS, RHSResult = RHS; | |||
12664 | QualType compType = UsualArithmeticConversions( | |||
12665 | LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); | |||
12666 | if (LHSResult.isInvalid() || RHSResult.isInvalid()) | |||
12667 | return QualType(); | |||
12668 | LHS = LHSResult.get(); | |||
12669 | RHS = RHSResult.get(); | |||
12670 | ||||
12671 | if (Opc == BO_Xor) | |||
12672 | diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); | |||
12673 | ||||
12674 | if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) | |||
12675 | return compType; | |||
12676 | return InvalidOperands(Loc, LHS, RHS); | |||
12677 | } | |||
12678 | ||||
12679 | // C99 6.5.[13,14] | |||
12680 | inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, | |||
12681 | SourceLocation Loc, | |||
12682 | BinaryOperatorKind Opc) { | |||
12683 | // Check vector operands differently. | |||
12684 | if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) | |||
12685 | return CheckVectorLogicalOperands(LHS, RHS, Loc); | |||
12686 | ||||
12687 | bool EnumConstantInBoolContext = false; | |||
12688 | for (const ExprResult &HS : {LHS, RHS}) { | |||
12689 | if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { | |||
12690 | const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); | |||
12691 | if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) | |||
12692 | EnumConstantInBoolContext = true; | |||
12693 | } | |||
12694 | } | |||
12695 | ||||
12696 | if (EnumConstantInBoolContext) | |||
12697 | Diag(Loc, diag::warn_enum_constant_in_bool_context); | |||
12698 | ||||
12699 | // Diagnose cases where the user write a logical and/or but probably meant a | |||
12700 | // bitwise one. We do this when the LHS is a non-bool integer and the RHS | |||
12701 | // is a constant. | |||
12702 | if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && | |||
12703 | !LHS.get()->getType()->isBooleanType() && | |||
12704 | RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && | |||
12705 | // Don't warn in macros or template instantiations. | |||
12706 | !Loc.isMacroID() && !inTemplateInstantiation()) { | |||
12707 | // If the RHS can be constant folded, and if it constant folds to something | |||
12708 | // that isn't 0 or 1 (which indicate a potential logical operation that | |||
12709 | // happened to fold to true/false) then warn. | |||
12710 | // Parens on the RHS are ignored. | |||
12711 | Expr::EvalResult EVResult; | |||
12712 | if (RHS.get()->EvaluateAsInt(EVResult, Context)) { | |||
12713 | llvm::APSInt Result = EVResult.Val.getInt(); | |||
12714 | if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && | |||
12715 | !RHS.get()->getExprLoc().isMacroID()) || | |||
12716 | (Result != 0 && Result != 1)) { | |||
12717 | Diag(Loc, diag::warn_logical_instead_of_bitwise) | |||
12718 | << RHS.get()->getSourceRange() | |||
12719 | << (Opc == BO_LAnd ? "&&" : "||"); | |||
12720 | // Suggest replacing the logical operator with the bitwise version | |||
12721 | Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) | |||
12722 | << (Opc == BO_LAnd ? "&" : "|") | |||
12723 | << FixItHint::CreateReplacement(SourceRange( | |||
12724 | Loc, getLocForEndOfToken(Loc)), | |||
12725 | Opc == BO_LAnd ? "&" : "|"); | |||
12726 | if (Opc == BO_LAnd) | |||
12727 | // Suggest replacing "Foo() && kNonZero" with "Foo()" | |||
12728 | Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) | |||
12729 | << FixItHint::CreateRemoval( | |||
12730 | SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), | |||
12731 | RHS.get()->getEndLoc())); | |||
12732 | } | |||
12733 | } | |||
12734 | } | |||
12735 | ||||
12736 | if (!Context.getLangOpts().CPlusPlus) { | |||
12737 | // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do | |||
12738 | // not operate on the built-in scalar and vector float types. | |||
12739 | if (Context.getLangOpts().OpenCL && | |||
12740 | Context.getLangOpts().OpenCLVersion < 120) { | |||
12741 | if (LHS.get()->getType()->isFloatingType() || | |||
12742 | RHS.get()->getType()->isFloatingType()) | |||
12743 | return InvalidOperands(Loc, LHS, RHS); | |||
12744 | } | |||
12745 | ||||
12746 | LHS = UsualUnaryConversions(LHS.get()); | |||
12747 | if (LHS.isInvalid()) | |||
12748 | return QualType(); | |||
12749 | ||||
12750 | RHS = UsualUnaryConversions(RHS.get()); | |||
12751 | if (RHS.isInvalid()) | |||
12752 | return QualType(); | |||
12753 | ||||
12754 | if (!LHS.get()->getType()->isScalarType() || | |||
12755 | !RHS.get()->getType()->isScalarType()) | |||
12756 | return InvalidOperands(Loc, LHS, RHS); | |||
12757 | ||||
12758 | return Context.IntTy; | |||
12759 | } | |||
12760 | ||||
12761 | // The following is safe because we only use this method for | |||
12762 | // non-overloadable operands. | |||
12763 | ||||
12764 | // C++ [expr.log.and]p1 | |||
12765 | // C++ [expr.log.or]p1 | |||
12766 | // The operands are both contextually converted to type bool. | |||
12767 | ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); | |||
12768 | if (LHSRes.isInvalid()) | |||
12769 | return InvalidOperands(Loc, LHS, RHS); | |||
12770 | LHS = LHSRes; | |||
12771 | ||||
12772 | ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); | |||
12773 | if (RHSRes.isInvalid()) | |||
12774 | return InvalidOperands(Loc, LHS, RHS); | |||
12775 | RHS = RHSRes; | |||
12776 | ||||
12777 | // C++ [expr.log.and]p2 | |||
12778 | // C++ [expr.log.or]p2 | |||
12779 | // The result is a bool. | |||
12780 | return Context.BoolTy; | |||
12781 | } | |||
12782 | ||||
12783 | static bool IsReadonlyMessage(Expr *E, Sema &S) { | |||
12784 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | |||
12785 | if (!ME) return false; | |||
12786 | if (!isa<FieldDecl>(ME->getMemberDecl())) return false; | |||
12787 | ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( | |||
12788 | ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); | |||
12789 | if (!Base) return false; | |||
12790 | return Base->getMethodDecl() != nullptr; | |||
12791 | } | |||
12792 | ||||
12793 | /// Is the given expression (which must be 'const') a reference to a | |||
12794 | /// variable which was originally non-const, but which has become | |||
12795 | /// 'const' due to being captured within a block? | |||
12796 | enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; | |||
12797 | static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { | |||
12798 | assert(E->isLValue() && E->getType().isConstQualified())(static_cast <bool> (E->isLValue() && E-> getType().isConstQualified()) ? void (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()" , "clang/lib/Sema/SemaExpr.cpp", 12798, __extension__ __PRETTY_FUNCTION__ )); | |||
12799 | E = E->IgnoreParens(); | |||
12800 | ||||
12801 | // Must be a reference to a declaration from an enclosing scope. | |||
12802 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | |||
12803 | if (!DRE) return NCCK_None; | |||
12804 | if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; | |||
12805 | ||||
12806 | // The declaration must be a variable which is not declared 'const'. | |||
12807 | VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); | |||
12808 | if (!var) return NCCK_None; | |||
12809 | if (var->getType().isConstQualified()) return NCCK_None; | |||
12810 | assert(var->hasLocalStorage() && "capture added 'const' to non-local?")(static_cast <bool> (var->hasLocalStorage() && "capture added 'const' to non-local?") ? void (0) : __assert_fail ("var->hasLocalStorage() && \"capture added 'const' to non-local?\"" , "clang/lib/Sema/SemaExpr.cpp", 12810, __extension__ __PRETTY_FUNCTION__ )); | |||
12811 | ||||
12812 | // Decide whether the first capture was for a block or a lambda. | |||
12813 | DeclContext *DC = S.CurContext, *Prev = nullptr; | |||
12814 | // Decide whether the first capture was for a block or a lambda. | |||
12815 | while (DC) { | |||
12816 | // For init-capture, it is possible that the variable belongs to the | |||
12817 | // template pattern of the current context. | |||
12818 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) | |||
12819 | if (var->isInitCapture() && | |||
12820 | FD->getTemplateInstantiationPattern() == var->getDeclContext()) | |||
12821 | break; | |||
12822 | if (DC == var->getDeclContext()) | |||
12823 | break; | |||
12824 | Prev = DC; | |||
12825 | DC = DC->getParent(); | |||
12826 | } | |||
12827 | // Unless we have an init-capture, we've gone one step too far. | |||
12828 | if (!var->isInitCapture()) | |||
12829 | DC = Prev; | |||
12830 | return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); | |||
12831 | } | |||
12832 | ||||
12833 | static bool IsTypeModifiable(QualType Ty, bool IsDereference) { | |||
12834 | Ty = Ty.getNonReferenceType(); | |||
12835 | if (IsDereference && Ty->isPointerType()) | |||
12836 | Ty = Ty->getPointeeType(); | |||
12837 | return !Ty.isConstQualified(); | |||
12838 | } | |||
12839 | ||||
12840 | // Update err_typecheck_assign_const and note_typecheck_assign_const | |||
12841 | // when this enum is changed. | |||
12842 | enum { | |||
12843 | ConstFunction, | |||
12844 | ConstVariable, | |||
12845 | ConstMember, | |||
12846 | ConstMethod, | |||
12847 | NestedConstMember, | |||
12848 | ConstUnknown, // Keep as last element | |||
12849 | }; | |||
12850 | ||||
12851 | /// Emit the "read-only variable not assignable" error and print notes to give | |||
12852 | /// more information about why the variable is not assignable, such as pointing | |||
12853 | /// to the declaration of a const variable, showing that a method is const, or | |||
12854 | /// that the function is returning a const reference. | |||
12855 | static void DiagnoseConstAssignment(Sema &S, const Expr *E, | |||
12856 | SourceLocation Loc) { | |||
12857 | SourceRange ExprRange = E->getSourceRange(); | |||
12858 | ||||
12859 | // Only emit one error on the first const found. All other consts will emit | |||
12860 | // a note to the error. | |||
12861 | bool DiagnosticEmitted = false; | |||
12862 | ||||
12863 | // Track if the current expression is the result of a dereference, and if the | |||
12864 | // next checked expression is the result of a dereference. | |||
12865 | bool IsDereference = false; | |||
12866 | bool NextIsDereference = false; | |||
12867 | ||||
12868 | // Loop to process MemberExpr chains. | |||
12869 | while (true) { | |||
12870 | IsDereference = NextIsDereference; | |||
12871 | ||||
12872 | E = E->IgnoreImplicit()->IgnoreParenImpCasts(); | |||
12873 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | |||
12874 | NextIsDereference = ME->isArrow(); | |||
12875 | const ValueDecl *VD = ME->getMemberDecl(); | |||
12876 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { | |||
12877 | // Mutable fields can be modified even if the class is const. | |||
12878 | if (Field->isMutable()) { | |||
12879 | assert(DiagnosticEmitted && "Expected diagnostic not emitted.")(static_cast <bool> (DiagnosticEmitted && "Expected diagnostic not emitted." ) ? void (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\"" , "clang/lib/Sema/SemaExpr.cpp", 12879, __extension__ __PRETTY_FUNCTION__ )); | |||
12880 | break; | |||
12881 | } | |||
12882 | ||||
12883 | if (!IsTypeModifiable(Field->getType(), IsDereference)) { | |||
12884 | if (!DiagnosticEmitted) { | |||
12885 | S.Diag(Loc, diag::err_typecheck_assign_const) | |||
12886 | << ExprRange << ConstMember << false /*static*/ << Field | |||
12887 | << Field->getType(); | |||
12888 | DiagnosticEmitted = true; | |||
12889 | } | |||
12890 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | |||
12891 | << ConstMember << false /*static*/ << Field << Field->getType() | |||
12892 | << Field->getSourceRange(); | |||
12893 | } | |||
12894 | E = ME->getBase(); | |||
12895 | continue; | |||
12896 | } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { | |||
12897 | if (VDecl->getType().isConstQualified()) { | |||
12898 | if (!DiagnosticEmitted) { | |||
12899 | S.Diag(Loc, diag::err_typecheck_assign_const) | |||
12900 | << ExprRange << ConstMember << true /*static*/ << VDecl | |||
12901 | << VDecl->getType(); | |||
12902 | DiagnosticEmitted = true; | |||
12903 | } | |||
12904 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | |||
12905 | << ConstMember << true /*static*/ << VDecl << VDecl->getType() | |||
12906 | << VDecl->getSourceRange(); | |||
12907 | } | |||
12908 | // Static fields do not inherit constness from parents. | |||
12909 | break; | |||
12910 | } | |||
12911 | break; // End MemberExpr | |||
12912 | } else if (const ArraySubscriptExpr *ASE = | |||
12913 | dyn_cast<ArraySubscriptExpr>(E)) { | |||
12914 | E = ASE->getBase()->IgnoreParenImpCasts(); | |||
12915 | continue; | |||
12916 | } else if (const ExtVectorElementExpr *EVE = | |||
12917 | dyn_cast<ExtVectorElementExpr>(E)) { | |||
12918 | E = EVE->getBase()->IgnoreParenImpCasts(); | |||
12919 | continue; | |||
12920 | } | |||
12921 | break; | |||
12922 | } | |||
12923 | ||||
12924 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | |||
12925 | // Function calls | |||
12926 | const FunctionDecl *FD = CE->getDirectCallee(); | |||
12927 | if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { | |||
12928 | if (!DiagnosticEmitted) { | |||
12929 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | |||
12930 | << ConstFunction << FD; | |||
12931 | DiagnosticEmitted = true; | |||
12932 | } | |||
12933 | S.Diag(FD->getReturnTypeSourceRange().getBegin(), | |||
12934 | diag::note_typecheck_assign_const) | |||
12935 | << ConstFunction << FD << FD->getReturnType() | |||
12936 | << FD->getReturnTypeSourceRange(); | |||
12937 | } | |||
12938 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
12939 | // Point to variable declaration. | |||
12940 | if (const ValueDecl *VD = DRE->getDecl()) { | |||
12941 | if (!IsTypeModifiable(VD->getType(), IsDereference)) { | |||
12942 | if (!DiagnosticEmitted) { | |||
12943 | S.Diag(Loc, diag::err_typecheck_assign_const) | |||
12944 | << ExprRange << ConstVariable << VD << VD->getType(); | |||
12945 | DiagnosticEmitted = true; | |||
12946 | } | |||
12947 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | |||
12948 | << ConstVariable << VD << VD->getType() << VD->getSourceRange(); | |||
12949 | } | |||
12950 | } | |||
12951 | } else if (isa<CXXThisExpr>(E)) { | |||
12952 | if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { | |||
12953 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { | |||
12954 | if (MD->isConst()) { | |||
12955 | if (!DiagnosticEmitted) { | |||
12956 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | |||
12957 | << ConstMethod << MD; | |||
12958 | DiagnosticEmitted = true; | |||
12959 | } | |||
12960 | S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) | |||
12961 | << ConstMethod << MD << MD->getSourceRange(); | |||
12962 | } | |||
12963 | } | |||
12964 | } | |||
12965 | } | |||
12966 | ||||
12967 | if (DiagnosticEmitted) | |||
12968 | return; | |||
12969 | ||||
12970 | // Can't determine a more specific message, so display the generic error. | |||
12971 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; | |||
12972 | } | |||
12973 | ||||
12974 | enum OriginalExprKind { | |||
12975 | OEK_Variable, | |||
12976 | OEK_Member, | |||
12977 | OEK_LValue | |||
12978 | }; | |||
12979 | ||||
12980 | static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, | |||
12981 | const RecordType *Ty, | |||
12982 | SourceLocation Loc, SourceRange Range, | |||
12983 | OriginalExprKind OEK, | |||
12984 | bool &DiagnosticEmitted) { | |||
12985 | std::vector<const RecordType *> RecordTypeList; | |||
12986 | RecordTypeList.push_back(Ty); | |||
12987 | unsigned NextToCheckIndex = 0; | |||
12988 | // We walk the record hierarchy breadth-first to ensure that we print | |||
12989 | // diagnostics in field nesting order. | |||
12990 | while (RecordTypeList.size() > NextToCheckIndex) { | |||
12991 | bool IsNested = NextToCheckIndex > 0; | |||
12992 | for (const FieldDecl *Field : | |||
12993 | RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { | |||
12994 | // First, check every field for constness. | |||
12995 | QualType FieldTy = Field->getType(); | |||
12996 | if (FieldTy.isConstQualified()) { | |||
12997 | if (!DiagnosticEmitted) { | |||
12998 | S.Diag(Loc, diag::err_typecheck_assign_const) | |||
12999 | << Range << NestedConstMember << OEK << VD | |||
13000 | << IsNested << Field; | |||
13001 | DiagnosticEmitted = true; | |||
13002 | } | |||
13003 | S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) | |||
13004 | << NestedConstMember << IsNested << Field | |||
13005 | << FieldTy << Field->getSourceRange(); | |||
13006 | } | |||
13007 | ||||
13008 | // Then we append it to the list to check next in order. | |||
13009 | FieldTy = FieldTy.getCanonicalType(); | |||
13010 | if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { | |||
13011 | if (!llvm::is_contained(RecordTypeList, FieldRecTy)) | |||
13012 | RecordTypeList.push_back(FieldRecTy); | |||
13013 | } | |||
13014 | } | |||
13015 | ++NextToCheckIndex; | |||
13016 | } | |||
13017 | } | |||
13018 | ||||
13019 | /// Emit an error for the case where a record we are trying to assign to has a | |||
13020 | /// const-qualified field somewhere in its hierarchy. | |||
13021 | static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, | |||
13022 | SourceLocation Loc) { | |||
13023 | QualType Ty = E->getType(); | |||
13024 | assert(Ty->isRecordType() && "lvalue was not record?")(static_cast <bool> (Ty->isRecordType() && "lvalue was not record?" ) ? void (0) : __assert_fail ("Ty->isRecordType() && \"lvalue was not record?\"" , "clang/lib/Sema/SemaExpr.cpp", 13024, __extension__ __PRETTY_FUNCTION__ )); | |||
13025 | SourceRange Range = E->getSourceRange(); | |||
13026 | const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); | |||
13027 | bool DiagEmitted = false; | |||
13028 | ||||
13029 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) | |||
13030 | DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, | |||
13031 | Range, OEK_Member, DiagEmitted); | |||
13032 | else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | |||
13033 | DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, | |||
13034 | Range, OEK_Variable, DiagEmitted); | |||
13035 | else | |||
13036 | DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, | |||
13037 | Range, OEK_LValue, DiagEmitted); | |||
13038 | if (!DiagEmitted) | |||
13039 | DiagnoseConstAssignment(S, E, Loc); | |||
13040 | } | |||
13041 | ||||
13042 | /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, | |||
13043 | /// emit an error and return true. If so, return false. | |||
13044 | static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { | |||
13045 | assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!E->hasPlaceholderType(BuiltinType ::PseudoObject)) ? void (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)" , "clang/lib/Sema/SemaExpr.cpp", 13045, __extension__ __PRETTY_FUNCTION__ )); | |||
13046 | ||||
13047 | S.CheckShadowingDeclModification(E, Loc); | |||
13048 | ||||
13049 | SourceLocation OrigLoc = Loc; | |||
13050 | Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, | |||
13051 | &Loc); | |||
13052 | if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) | |||
13053 | IsLV = Expr::MLV_InvalidMessageExpression; | |||
13054 | if (IsLV == Expr::MLV_Valid) | |||
13055 | return false; | |||
13056 | ||||
13057 | unsigned DiagID = 0; | |||
13058 | bool NeedType = false; | |||
13059 | switch (IsLV) { // C99 6.5.16p2 | |||
13060 | case Expr::MLV_ConstQualified: | |||
13061 | // Use a specialized diagnostic when we're assigning to an object | |||
13062 | // from an enclosing function or block. | |||
13063 | if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { | |||
13064 | if (NCCK == NCCK_Block) | |||
13065 | DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; | |||
13066 | else | |||
13067 | DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; | |||
13068 | break; | |||
13069 | } | |||
13070 | ||||
13071 | // In ARC, use some specialized diagnostics for occasions where we | |||
13072 | // infer 'const'. These are always pseudo-strong variables. | |||
13073 | if (S.getLangOpts().ObjCAutoRefCount) { | |||
13074 | DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); | |||
13075 | if (declRef && isa<VarDecl>(declRef->getDecl())) { | |||
13076 | VarDecl *var = cast<VarDecl>(declRef->getDecl()); | |||
13077 | ||||
13078 | // Use the normal diagnostic if it's pseudo-__strong but the | |||
13079 | // user actually wrote 'const'. | |||
13080 | if (var->isARCPseudoStrong() && | |||
13081 | (!var->getTypeSourceInfo() || | |||
13082 | !var->getTypeSourceInfo()->getType().isConstQualified())) { | |||
13083 | // There are three pseudo-strong cases: | |||
13084 | // - self | |||
13085 | ObjCMethodDecl *method = S.getCurMethodDecl(); | |||
13086 | if (method && var == method->getSelfDecl()) { | |||
13087 | DiagID = method->isClassMethod() | |||
13088 | ? diag::err_typecheck_arc_assign_self_class_method | |||
13089 | : diag::err_typecheck_arc_assign_self; | |||
13090 | ||||
13091 | // - Objective-C externally_retained attribute. | |||
13092 | } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || | |||
13093 | isa<ParmVarDecl>(var)) { | |||
13094 | DiagID = diag::err_typecheck_arc_assign_externally_retained; | |||
13095 | ||||
13096 | // - fast enumeration variables | |||
13097 | } else { | |||
13098 | DiagID = diag::err_typecheck_arr_assign_enumeration; | |||
13099 | } | |||
13100 | ||||
13101 | SourceRange Assign; | |||
13102 | if (Loc != OrigLoc) | |||
13103 | Assign = SourceRange(OrigLoc, OrigLoc); | |||
13104 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | |||
13105 | // We need to preserve the AST regardless, so migration tool | |||
13106 | // can do its job. | |||
13107 | return false; | |||
13108 | } | |||
13109 | } | |||
13110 | } | |||
13111 | ||||
13112 | // If none of the special cases above are triggered, then this is a | |||
13113 | // simple const assignment. | |||
13114 | if (DiagID == 0) { | |||
13115 | DiagnoseConstAssignment(S, E, Loc); | |||
13116 | return true; | |||
13117 | } | |||
13118 | ||||
13119 | break; | |||
13120 | case Expr::MLV_ConstAddrSpace: | |||
13121 | DiagnoseConstAssignment(S, E, Loc); | |||
13122 | return true; | |||
13123 | case Expr::MLV_ConstQualifiedField: | |||
13124 | DiagnoseRecursiveConstFields(S, E, Loc); | |||
13125 | return true; | |||
13126 | case Expr::MLV_ArrayType: | |||
13127 | case Expr::MLV_ArrayTemporary: | |||
13128 | DiagID = diag::err_typecheck_array_not_modifiable_lvalue; | |||
13129 | NeedType = true; | |||
13130 | break; | |||
13131 | case Expr::MLV_NotObjectType: | |||
13132 | DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; | |||
13133 | NeedType = true; | |||
13134 | break; | |||
13135 | case Expr::MLV_LValueCast: | |||
13136 | DiagID = diag::err_typecheck_lvalue_casts_not_supported; | |||
13137 | break; | |||
13138 | case Expr::MLV_Valid: | |||
13139 | llvm_unreachable("did not take early return for MLV_Valid")::llvm::llvm_unreachable_internal("did not take early return for MLV_Valid" , "clang/lib/Sema/SemaExpr.cpp", 13139); | |||
13140 | case Expr::MLV_InvalidExpression: | |||
13141 | case Expr::MLV_MemberFunction: | |||
13142 | case Expr::MLV_ClassTemporary: | |||
13143 | DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; | |||
13144 | break; | |||
13145 | case Expr::MLV_IncompleteType: | |||
13146 | case Expr::MLV_IncompleteVoidType: | |||
13147 | return S.RequireCompleteType(Loc, E->getType(), | |||
13148 | diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); | |||
13149 | case Expr::MLV_DuplicateVectorComponents: | |||
13150 | DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; | |||
13151 | break; | |||
13152 | case Expr::MLV_NoSetterProperty: | |||
13153 | llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently" , "clang/lib/Sema/SemaExpr.cpp", 13153); | |||
13154 | case Expr::MLV_InvalidMessageExpression: | |||
13155 | DiagID = diag::err_readonly_message_assignment; | |||
13156 | break; | |||
13157 | case Expr::MLV_SubObjCPropertySetting: | |||
13158 | DiagID = diag::err_no_subobject_property_setting; | |||
13159 | break; | |||
13160 | } | |||
13161 | ||||
13162 | SourceRange Assign; | |||
13163 | if (Loc != OrigLoc) | |||
13164 | Assign = SourceRange(OrigLoc, OrigLoc); | |||
13165 | if (NeedType) | |||
13166 | S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; | |||
13167 | else | |||
13168 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | |||
13169 | return true; | |||
13170 | } | |||
13171 | ||||
13172 | static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, | |||
13173 | SourceLocation Loc, | |||
13174 | Sema &Sema) { | |||
13175 | if (Sema.inTemplateInstantiation()) | |||
13176 | return; | |||
13177 | if (Sema.isUnevaluatedContext()) | |||
13178 | return; | |||
13179 | if (Loc.isInvalid() || Loc.isMacroID()) | |||
13180 | return; | |||
13181 | if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) | |||
13182 | return; | |||
13183 | ||||
13184 | // C / C++ fields | |||
13185 | MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); | |||
13186 | MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); | |||
13187 | if (ML && MR) { | |||
13188 | if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) | |||
13189 | return; | |||
13190 | const ValueDecl *LHSDecl = | |||
13191 | cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); | |||
13192 | const ValueDecl *RHSDecl = | |||
13193 | cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); | |||
13194 | if (LHSDecl != RHSDecl) | |||
13195 | return; | |||
13196 | if (LHSDecl->getType().isVolatileQualified()) | |||
13197 | return; | |||
13198 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | |||
13199 | if (RefTy->getPointeeType().isVolatileQualified()) | |||
13200 | return; | |||
13201 | ||||
13202 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; | |||
13203 | } | |||
13204 | ||||
13205 | // Objective-C instance variables | |||
13206 | ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); | |||
13207 | ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); | |||
13208 | if (OL && OR && OL->getDecl() == OR->getDecl()) { | |||
13209 | DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); | |||
13210 | DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); | |||
13211 | if (RL && RR && RL->getDecl() == RR->getDecl()) | |||
13212 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; | |||
13213 | } | |||
13214 | } | |||
13215 | ||||
13216 | // C99 6.5.16.1 | |||
13217 | QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, | |||
13218 | SourceLocation Loc, | |||
13219 | QualType CompoundType) { | |||
13220 | assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!LHSExpr->hasPlaceholderType(BuiltinType ::PseudoObject)) ? void (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)" , "clang/lib/Sema/SemaExpr.cpp", 13220, __extension__ __PRETTY_FUNCTION__ )); | |||
13221 | ||||
13222 | // Verify that LHS is a modifiable lvalue, and emit error if not. | |||
13223 | if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) | |||
13224 | return QualType(); | |||
13225 | ||||
13226 | QualType LHSType = LHSExpr->getType(); | |||
13227 | QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : | |||
13228 | CompoundType; | |||
13229 | // OpenCL v1.2 s6.1.1.1 p2: | |||
13230 | // The half data type can only be used to declare a pointer to a buffer that | |||
13231 | // contains half values | |||
13232 | if (getLangOpts().OpenCL && | |||
13233 | !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && | |||
13234 | LHSType->isHalfType()) { | |||
13235 | Diag(Loc, diag::err_opencl_half_load_store) << 1 | |||
13236 | << LHSType.getUnqualifiedType(); | |||
13237 | return QualType(); | |||
13238 | } | |||
13239 | ||||
13240 | AssignConvertType ConvTy; | |||
13241 | if (CompoundType.isNull()) { | |||
13242 | Expr *RHSCheck = RHS.get(); | |||
13243 | ||||
13244 | CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); | |||
13245 | ||||
13246 | QualType LHSTy(LHSType); | |||
13247 | ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); | |||
13248 | if (RHS.isInvalid()) | |||
13249 | return QualType(); | |||
13250 | // Special case of NSObject attributes on c-style pointer types. | |||
13251 | if (ConvTy == IncompatiblePointer && | |||
13252 | ((Context.isObjCNSObjectType(LHSType) && | |||
13253 | RHSType->isObjCObjectPointerType()) || | |||
13254 | (Context.isObjCNSObjectType(RHSType) && | |||
13255 | LHSType->isObjCObjectPointerType()))) | |||
13256 | ConvTy = Compatible; | |||
13257 | ||||
13258 | if (ConvTy == Compatible && | |||
13259 | LHSType->isObjCObjectType()) | |||
13260 | Diag(Loc, diag::err_objc_object_assignment) | |||
13261 | << LHSType; | |||
13262 | ||||
13263 | // If the RHS is a unary plus or minus, check to see if they = and + are | |||
13264 | // right next to each other. If so, the user may have typo'd "x =+ 4" | |||
13265 | // instead of "x += 4". | |||
13266 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) | |||
13267 | RHSCheck = ICE->getSubExpr(); | |||
13268 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { | |||
13269 | if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && | |||
13270 | Loc.isFileID() && UO->getOperatorLoc().isFileID() && | |||
13271 | // Only if the two operators are exactly adjacent. | |||
13272 | Loc.getLocWithOffset(1) == UO->getOperatorLoc() && | |||
13273 | // And there is a space or other character before the subexpr of the | |||
13274 | // unary +/-. We don't want to warn on "x=-1". | |||
13275 | Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && | |||
13276 | UO->getSubExpr()->getBeginLoc().isFileID()) { | |||
13277 | Diag(Loc, diag::warn_not_compound_assign) | |||
13278 | << (UO->getOpcode() == UO_Plus ? "+" : "-") | |||
13279 | << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); | |||
13280 | } | |||
13281 | } | |||
13282 | ||||
13283 | if (ConvTy == Compatible) { | |||
13284 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { | |||
13285 | // Warn about retain cycles where a block captures the LHS, but | |||
13286 | // not if the LHS is a simple variable into which the block is | |||
13287 | // being stored...unless that variable can be captured by reference! | |||
13288 | const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); | |||
13289 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); | |||
13290 | if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) | |||
13291 | checkRetainCycles(LHSExpr, RHS.get()); | |||
13292 | } | |||
13293 | ||||
13294 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || | |||
13295 | LHSType.isNonWeakInMRRWithObjCWeak(Context)) { | |||
13296 | // It is safe to assign a weak reference into a strong variable. | |||
13297 | // Although this code can still have problems: | |||
13298 | // id x = self.weakProp; | |||
13299 | // id y = self.weakProp; | |||
13300 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | |||
13301 | // paths through the function. This should be revisited if | |||
13302 | // -Wrepeated-use-of-weak is made flow-sensitive. | |||
13303 | // For ObjCWeak only, we do not warn if the assign is to a non-weak | |||
13304 | // variable, which will be valid for the current autorelease scope. | |||
13305 | if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | |||
13306 | RHS.get()->getBeginLoc())) | |||
13307 | getCurFunction()->markSafeWeakUse(RHS.get()); | |||
13308 | ||||
13309 | } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { | |||
13310 | checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); | |||
13311 | } | |||
13312 | } | |||
13313 | } else { | |||
13314 | // Compound assignment "x += y" | |||
13315 | ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); | |||
13316 | } | |||
13317 | ||||
13318 | if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, | |||
13319 | RHS.get(), AA_Assigning)) | |||
13320 | return QualType(); | |||
13321 | ||||
13322 | CheckForNullPointerDereference(*this, LHSExpr); | |||
13323 | ||||
13324 | if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { | |||
13325 | if (CompoundType.isNull()) { | |||
13326 | // C++2a [expr.ass]p5: | |||
13327 | // A simple-assignment whose left operand is of a volatile-qualified | |||
13328 | // type is deprecated unless the assignment is either a discarded-value | |||
13329 | // expression or an unevaluated operand | |||
13330 | ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); | |||
13331 | } else { | |||
13332 | // C++2a [expr.ass]p6: | |||
13333 | // [Compound-assignment] expressions are deprecated if E1 has | |||
13334 | // volatile-qualified type | |||
13335 | Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; | |||
13336 | } | |||
13337 | } | |||
13338 | ||||
13339 | // C99 6.5.16p3: The type of an assignment expression is the type of the | |||
13340 | // left operand unless the left operand has qualified type, in which case | |||
13341 | // it is the unqualified version of the type of the left operand. | |||
13342 | // C99 6.5.16.1p2: In simple assignment, the value of the right operand | |||
13343 | // is converted to the type of the assignment expression (above). | |||
13344 | // C++ 5.17p1: the type of the assignment expression is that of its left | |||
13345 | // operand. | |||
13346 | return (getLangOpts().CPlusPlus | |||
13347 | ? LHSType : LHSType.getUnqualifiedType()); | |||
13348 | } | |||
13349 | ||||
13350 | // Only ignore explicit casts to void. | |||
13351 | static bool IgnoreCommaOperand(const Expr *E) { | |||
13352 | E = E->IgnoreParens(); | |||
13353 | ||||
13354 | if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { | |||
13355 | if (CE->getCastKind() == CK_ToVoid) { | |||
13356 | return true; | |||
13357 | } | |||
13358 | ||||
13359 | // static_cast<void> on a dependent type will not show up as CK_ToVoid. | |||
13360 | if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && | |||
13361 | CE->getSubExpr()->getType()->isDependentType()) { | |||
13362 | return true; | |||
13363 | } | |||
13364 | } | |||
13365 | ||||
13366 | return false; | |||
13367 | } | |||
13368 | ||||
13369 | // Look for instances where it is likely the comma operator is confused with | |||
13370 | // another operator. There is an explicit list of acceptable expressions for | |||
13371 | // the left hand side of the comma operator, otherwise emit a warning. | |||
13372 | void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { | |||
13373 | // No warnings in macros | |||
13374 | if (Loc.isMacroID()) | |||
13375 | return; | |||
13376 | ||||
13377 | // Don't warn in template instantiations. | |||
13378 | if (inTemplateInstantiation()) | |||
13379 | return; | |||
13380 | ||||
13381 | // Scope isn't fine-grained enough to explicitly list the specific cases, so | |||
13382 | // instead, skip more than needed, then call back into here with the | |||
13383 | // CommaVisitor in SemaStmt.cpp. | |||
13384 | // The listed locations are the initialization and increment portions | |||
13385 | // of a for loop. The additional checks are on the condition of | |||
13386 | // if statements, do/while loops, and for loops. | |||
13387 | // Differences in scope flags for C89 mode requires the extra logic. | |||
13388 | const unsigned ForIncrementFlags = | |||
13389 | getLangOpts().C99 || getLangOpts().CPlusPlus | |||
13390 | ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope | |||
13391 | : Scope::ContinueScope | Scope::BreakScope; | |||
13392 | const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; | |||
13393 | const unsigned ScopeFlags = getCurScope()->getFlags(); | |||
13394 | if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || | |||
13395 | (ScopeFlags & ForInitFlags) == ForInitFlags) | |||
13396 | return; | |||
13397 | ||||
13398 | // If there are multiple comma operators used together, get the RHS of the | |||
13399 | // of the comma operator as the LHS. | |||
13400 | while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { | |||
13401 | if (BO->getOpcode() != BO_Comma) | |||
13402 | break; | |||
13403 | LHS = BO->getRHS(); | |||
13404 | } | |||
13405 | ||||
13406 | // Only allow some expressions on LHS to not warn. | |||
13407 | if (IgnoreCommaOperand(LHS)) | |||
13408 | return; | |||
13409 | ||||
13410 | Diag(Loc, diag::warn_comma_operator); | |||
13411 | Diag(LHS->getBeginLoc(), diag::note_cast_to_void) | |||
13412 | << LHS->getSourceRange() | |||
13413 | << FixItHint::CreateInsertion(LHS->getBeginLoc(), | |||
13414 | LangOpts.CPlusPlus ? "static_cast<void>(" | |||
13415 | : "(void)(") | |||
13416 | << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), | |||
13417 | ")"); | |||
13418 | } | |||
13419 | ||||
13420 | // C99 6.5.17 | |||
13421 | static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, | |||
13422 | SourceLocation Loc) { | |||
13423 | LHS = S.CheckPlaceholderExpr(LHS.get()); | |||
13424 | RHS = S.CheckPlaceholderExpr(RHS.get()); | |||
13425 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
13426 | return QualType(); | |||
13427 | ||||
13428 | // C's comma performs lvalue conversion (C99 6.3.2.1) on both its | |||
13429 | // operands, but not unary promotions. | |||
13430 | // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). | |||
13431 | ||||
13432 | // So we treat the LHS as a ignored value, and in C++ we allow the | |||
13433 | // containing site to determine what should be done with the RHS. | |||
13434 | LHS = S.IgnoredValueConversions(LHS.get()); | |||
13435 | if (LHS.isInvalid()) | |||
13436 | return QualType(); | |||
13437 | ||||
13438 | S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); | |||
13439 | ||||
13440 | if (!S.getLangOpts().CPlusPlus) { | |||
13441 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
13442 | if (RHS.isInvalid()) | |||
13443 | return QualType(); | |||
13444 | if (!RHS.get()->getType()->isVoidType()) | |||
13445 | S.RequireCompleteType(Loc, RHS.get()->getType(), | |||
13446 | diag::err_incomplete_type); | |||
13447 | } | |||
13448 | ||||
13449 | if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) | |||
13450 | S.DiagnoseCommaOperator(LHS.get(), Loc); | |||
13451 | ||||
13452 | return RHS.get()->getType(); | |||
13453 | } | |||
13454 | ||||
13455 | /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine | |||
13456 | /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. | |||
13457 | static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, | |||
13458 | ExprValueKind &VK, | |||
13459 | ExprObjectKind &OK, | |||
13460 | SourceLocation OpLoc, | |||
13461 | bool IsInc, bool IsPrefix) { | |||
13462 | if (Op->isTypeDependent()) | |||
13463 | return S.Context.DependentTy; | |||
13464 | ||||
13465 | QualType ResType = Op->getType(); | |||
13466 | // Atomic types can be used for increment / decrement where the non-atomic | |||
13467 | // versions can, so ignore the _Atomic() specifier for the purpose of | |||
13468 | // checking. | |||
13469 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | |||
13470 | ResType = ResAtomicType->getValueType(); | |||
13471 | ||||
13472 | assert(!ResType.isNull() && "no type for increment/decrement expression")(static_cast <bool> (!ResType.isNull() && "no type for increment/decrement expression" ) ? void (0) : __assert_fail ("!ResType.isNull() && \"no type for increment/decrement expression\"" , "clang/lib/Sema/SemaExpr.cpp", 13472, __extension__ __PRETTY_FUNCTION__ )); | |||
13473 | ||||
13474 | if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { | |||
13475 | // Decrement of bool is not allowed. | |||
13476 | if (!IsInc) { | |||
13477 | S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); | |||
13478 | return QualType(); | |||
13479 | } | |||
13480 | // Increment of bool sets it to true, but is deprecated. | |||
13481 | S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool | |||
13482 | : diag::warn_increment_bool) | |||
13483 | << Op->getSourceRange(); | |||
13484 | } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { | |||
13485 | // Error on enum increments and decrements in C++ mode | |||
13486 | S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; | |||
13487 | return QualType(); | |||
13488 | } else if (ResType->isRealType()) { | |||
13489 | // OK! | |||
13490 | } else if (ResType->isPointerType()) { | |||
13491 | // C99 6.5.2.4p2, 6.5.6p2 | |||
13492 | if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) | |||
13493 | return QualType(); | |||
13494 | } else if (ResType->isObjCObjectPointerType()) { | |||
13495 | // On modern runtimes, ObjC pointer arithmetic is forbidden. | |||
13496 | // Otherwise, we just need a complete type. | |||
13497 | if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || | |||
13498 | checkArithmeticOnObjCPointer(S, OpLoc, Op)) | |||
13499 | return QualType(); | |||
13500 | } else if (ResType->isAnyComplexType()) { | |||
13501 | // C99 does not support ++/-- on complex types, we allow as an extension. | |||
13502 | S.Diag(OpLoc, diag::ext_integer_increment_complex) | |||
13503 | << ResType << Op->getSourceRange(); | |||
13504 | } else if (ResType->isPlaceholderType()) { | |||
13505 | ExprResult PR = S.CheckPlaceholderExpr(Op); | |||
13506 | if (PR.isInvalid()) return QualType(); | |||
13507 | return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, | |||
13508 | IsInc, IsPrefix); | |||
13509 | } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { | |||
13510 | // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) | |||
13511 | } else if (S.getLangOpts().ZVector && ResType->isVectorType() && | |||
13512 | (ResType->castAs<VectorType>()->getVectorKind() != | |||
13513 | VectorType::AltiVecBool)) { | |||
13514 | // The z vector extensions allow ++ and -- for non-bool vectors. | |||
13515 | } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && | |||
13516 | ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { | |||
13517 | // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. | |||
13518 | } else { | |||
13519 | S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) | |||
13520 | << ResType << int(IsInc) << Op->getSourceRange(); | |||
13521 | return QualType(); | |||
13522 | } | |||
13523 | // At this point, we know we have a real, complex or pointer type. | |||
13524 | // Now make sure the operand is a modifiable lvalue. | |||
13525 | if (CheckForModifiableLvalue(Op, OpLoc, S)) | |||
13526 | return QualType(); | |||
13527 | if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { | |||
13528 | // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: | |||
13529 | // An operand with volatile-qualified type is deprecated | |||
13530 | S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) | |||
13531 | << IsInc << ResType; | |||
13532 | } | |||
13533 | // In C++, a prefix increment is the same type as the operand. Otherwise | |||
13534 | // (in C or with postfix), the increment is the unqualified type of the | |||
13535 | // operand. | |||
13536 | if (IsPrefix && S.getLangOpts().CPlusPlus) { | |||
13537 | VK = VK_LValue; | |||
13538 | OK = Op->getObjectKind(); | |||
13539 | return ResType; | |||
13540 | } else { | |||
13541 | VK = VK_PRValue; | |||
13542 | return ResType.getUnqualifiedType(); | |||
13543 | } | |||
13544 | } | |||
13545 | ||||
13546 | ||||
13547 | /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). | |||
13548 | /// This routine allows us to typecheck complex/recursive expressions | |||
13549 | /// where the declaration is needed for type checking. We only need to | |||
13550 | /// handle cases when the expression references a function designator | |||
13551 | /// or is an lvalue. Here are some examples: | |||
13552 | /// - &(x) => x | |||
13553 | /// - &*****f => f for f a function designator. | |||
13554 | /// - &s.xx => s | |||
13555 | /// - &s.zz[1].yy -> s, if zz is an array | |||
13556 | /// - *(x + 1) -> x, if x is an array | |||
13557 | /// - &"123"[2] -> 0 | |||
13558 | /// - & __real__ x -> x | |||
13559 | /// | |||
13560 | /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to | |||
13561 | /// members. | |||
13562 | static ValueDecl *getPrimaryDecl(Expr *E) { | |||
13563 | switch (E->getStmtClass()) { | |||
13564 | case Stmt::DeclRefExprClass: | |||
13565 | return cast<DeclRefExpr>(E)->getDecl(); | |||
13566 | case Stmt::MemberExprClass: | |||
13567 | // If this is an arrow operator, the address is an offset from | |||
13568 | // the base's value, so the object the base refers to is | |||
13569 | // irrelevant. | |||
13570 | if (cast<MemberExpr>(E)->isArrow()) | |||
13571 | return nullptr; | |||
13572 | // Otherwise, the expression refers to a part of the base | |||
13573 | return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); | |||
13574 | case Stmt::ArraySubscriptExprClass: { | |||
13575 | // FIXME: This code shouldn't be necessary! We should catch the implicit | |||
13576 | // promotion of register arrays earlier. | |||
13577 | Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); | |||
13578 | if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { | |||
13579 | if (ICE->getSubExpr()->getType()->isArrayType()) | |||
13580 | return getPrimaryDecl(ICE->getSubExpr()); | |||
13581 | } | |||
13582 | return nullptr; | |||
13583 | } | |||
13584 | case Stmt::UnaryOperatorClass: { | |||
13585 | UnaryOperator *UO = cast<UnaryOperator>(E); | |||
13586 | ||||
13587 | switch(UO->getOpcode()) { | |||
13588 | case UO_Real: | |||
13589 | case UO_Imag: | |||
13590 | case UO_Extension: | |||
13591 | return getPrimaryDecl(UO->getSubExpr()); | |||
13592 | default: | |||
13593 | return nullptr; | |||
13594 | } | |||
13595 | } | |||
13596 | case Stmt::ParenExprClass: | |||
13597 | return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); | |||
13598 | case Stmt::ImplicitCastExprClass: | |||
13599 | // If the result of an implicit cast is an l-value, we care about | |||
13600 | // the sub-expression; otherwise, the result here doesn't matter. | |||
13601 | return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); | |||
13602 | case Stmt::CXXUuidofExprClass: | |||
13603 | return cast<CXXUuidofExpr>(E)->getGuidDecl(); | |||
13604 | default: | |||
13605 | return nullptr; | |||
13606 | } | |||
13607 | } | |||
13608 | ||||
13609 | namespace { | |||
13610 | enum { | |||
13611 | AO_Bit_Field = 0, | |||
13612 | AO_Vector_Element = 1, | |||
13613 | AO_Property_Expansion = 2, | |||
13614 | AO_Register_Variable = 3, | |||
13615 | AO_Matrix_Element = 4, | |||
13616 | AO_No_Error = 5 | |||
13617 | }; | |||
13618 | } | |||
13619 | /// Diagnose invalid operand for address of operations. | |||
13620 | /// | |||
13621 | /// \param Type The type of operand which cannot have its address taken. | |||
13622 | static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, | |||
13623 | Expr *E, unsigned Type) { | |||
13624 | S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); | |||
13625 | } | |||
13626 | ||||
13627 | /// CheckAddressOfOperand - The operand of & must be either a function | |||
13628 | /// designator or an lvalue designating an object. If it is an lvalue, the | |||
13629 | /// object cannot be declared with storage class register or be a bit field. | |||
13630 | /// Note: The usual conversions are *not* applied to the operand of the & | |||
13631 | /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. | |||
13632 | /// In C++, the operand might be an overloaded function name, in which case | |||
13633 | /// we allow the '&' but retain the overloaded-function type. | |||
13634 | QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { | |||
13635 | if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ | |||
13636 | if (PTy->getKind() == BuiltinType::Overload) { | |||
13637 | Expr *E = OrigOp.get()->IgnoreParens(); | |||
13638 | if (!isa<OverloadExpr>(E)) { | |||
13639 | assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)(static_cast <bool> (cast<UnaryOperator>(E)->getOpcode () == UO_AddrOf) ? void (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf" , "clang/lib/Sema/SemaExpr.cpp", 13639, __extension__ __PRETTY_FUNCTION__ )); | |||
13640 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) | |||
13641 | << OrigOp.get()->getSourceRange(); | |||
13642 | return QualType(); | |||
13643 | } | |||
13644 | ||||
13645 | OverloadExpr *Ovl = cast<OverloadExpr>(E); | |||
13646 | if (isa<UnresolvedMemberExpr>(Ovl)) | |||
13647 | if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { | |||
13648 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | |||
13649 | << OrigOp.get()->getSourceRange(); | |||
13650 | return QualType(); | |||
13651 | } | |||
13652 | ||||
13653 | return Context.OverloadTy; | |||
13654 | } | |||
13655 | ||||
13656 | if (PTy->getKind() == BuiltinType::UnknownAny) | |||
13657 | return Context.UnknownAnyTy; | |||
13658 | ||||
13659 | if (PTy->getKind() == BuiltinType::BoundMember) { | |||
13660 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | |||
13661 | << OrigOp.get()->getSourceRange(); | |||
13662 | return QualType(); | |||
13663 | } | |||
13664 | ||||
13665 | OrigOp = CheckPlaceholderExpr(OrigOp.get()); | |||
13666 | if (OrigOp.isInvalid()) return QualType(); | |||
13667 | } | |||
13668 | ||||
13669 | if (OrigOp.get()->isTypeDependent()) | |||
13670 | return Context.DependentTy; | |||
13671 | ||||
13672 | assert(!OrigOp.get()->hasPlaceholderType())(static_cast <bool> (!OrigOp.get()->hasPlaceholderType ()) ? void (0) : __assert_fail ("!OrigOp.get()->hasPlaceholderType()" , "clang/lib/Sema/SemaExpr.cpp", 13672, __extension__ __PRETTY_FUNCTION__ )); | |||
13673 | ||||
13674 | // Make sure to ignore parentheses in subsequent checks | |||
13675 | Expr *op = OrigOp.get()->IgnoreParens(); | |||
13676 | ||||
13677 | // In OpenCL captures for blocks called as lambda functions | |||
13678 | // are located in the private address space. Blocks used in | |||
13679 | // enqueue_kernel can be located in a different address space | |||
13680 | // depending on a vendor implementation. Thus preventing | |||
13681 | // taking an address of the capture to avoid invalid AS casts. | |||
13682 | if (LangOpts.OpenCL) { | |||
13683 | auto* VarRef = dyn_cast<DeclRefExpr>(op); | |||
13684 | if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { | |||
13685 | Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); | |||
13686 | return QualType(); | |||
13687 | } | |||
13688 | } | |||
13689 | ||||
13690 | if (getLangOpts().C99) { | |||
13691 | // Implement C99-only parts of addressof rules. | |||
13692 | if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { | |||
13693 | if (uOp->getOpcode() == UO_Deref) | |||
13694 | // Per C99 6.5.3.2, the address of a deref always returns a valid result | |||
13695 | // (assuming the deref expression is valid). | |||
13696 | return uOp->getSubExpr()->getType(); | |||
13697 | } | |||
13698 | // Technically, there should be a check for array subscript | |||
13699 | // expressions here, but the result of one is always an lvalue anyway. | |||
13700 | } | |||
13701 | ValueDecl *dcl = getPrimaryDecl(op); | |||
13702 | ||||
13703 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) | |||
13704 | if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | |||
13705 | op->getBeginLoc())) | |||
13706 | return QualType(); | |||
13707 | ||||
13708 | Expr::LValueClassification lval = op->ClassifyLValue(Context); | |||
13709 | unsigned AddressOfError = AO_No_Error; | |||
13710 | ||||
13711 | if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { | |||
13712 | bool sfinae = (bool)isSFINAEContext(); | |||
13713 | Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary | |||
13714 | : diag::ext_typecheck_addrof_temporary) | |||
13715 | << op->getType() << op->getSourceRange(); | |||
13716 | if (sfinae) | |||
13717 | return QualType(); | |||
13718 | // Materialize the temporary as an lvalue so that we can take its address. | |||
13719 | OrigOp = op = | |||
13720 | CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); | |||
13721 | } else if (isa<ObjCSelectorExpr>(op)) { | |||
13722 | return Context.getPointerType(op->getType()); | |||
13723 | } else if (lval == Expr::LV_MemberFunction) { | |||
13724 | // If it's an instance method, make a member pointer. | |||
13725 | // The expression must have exactly the form &A::foo. | |||
13726 | ||||
13727 | // If the underlying expression isn't a decl ref, give up. | |||
13728 | if (!isa<DeclRefExpr>(op)) { | |||
13729 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | |||
13730 | << OrigOp.get()->getSourceRange(); | |||
13731 | return QualType(); | |||
13732 | } | |||
13733 | DeclRefExpr *DRE = cast<DeclRefExpr>(op); | |||
13734 | CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); | |||
13735 | ||||
13736 | // The id-expression was parenthesized. | |||
13737 | if (OrigOp.get() != DRE) { | |||
13738 | Diag(OpLoc, diag::err_parens_pointer_member_function) | |||
13739 | << OrigOp.get()->getSourceRange(); | |||
13740 | ||||
13741 | // The method was named without a qualifier. | |||
13742 | } else if (!DRE->getQualifier()) { | |||
13743 | if (MD->getParent()->getName().empty()) | |||
13744 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | |||
13745 | << op->getSourceRange(); | |||
13746 | else { | |||
13747 | SmallString<32> Str; | |||
13748 | StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); | |||
13749 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | |||
13750 | << op->getSourceRange() | |||
13751 | << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); | |||
13752 | } | |||
13753 | } | |||
13754 | ||||
13755 | // Taking the address of a dtor is illegal per C++ [class.dtor]p2. | |||
13756 | if (isa<CXXDestructorDecl>(MD)) | |||
13757 | Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); | |||
13758 | ||||
13759 | QualType MPTy = Context.getMemberPointerType( | |||
13760 | op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); | |||
13761 | // Under the MS ABI, lock down the inheritance model now. | |||
13762 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
13763 | (void)isCompleteType(OpLoc, MPTy); | |||
13764 | return MPTy; | |||
13765 | } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { | |||
13766 | // C99 6.5.3.2p1 | |||
13767 | // The operand must be either an l-value or a function designator | |||
13768 | if (!op->getType()->isFunctionType()) { | |||
13769 | // Use a special diagnostic for loads from property references. | |||
13770 | if (isa<PseudoObjectExpr>(op)) { | |||
13771 | AddressOfError = AO_Property_Expansion; | |||
13772 | } else { | |||
13773 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) | |||
13774 | << op->getType() << op->getSourceRange(); | |||
13775 | return QualType(); | |||
13776 | } | |||
13777 | } | |||
13778 | } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 | |||
13779 | // The operand cannot be a bit-field | |||
13780 | AddressOfError = AO_Bit_Field; | |||
13781 | } else if (op->getObjectKind() == OK_VectorComponent) { | |||
13782 | // The operand cannot be an element of a vector | |||
13783 | AddressOfError = AO_Vector_Element; | |||
13784 | } else if (op->getObjectKind() == OK_MatrixComponent) { | |||
13785 | // The operand cannot be an element of a matrix. | |||
13786 | AddressOfError = AO_Matrix_Element; | |||
13787 | } else if (dcl) { // C99 6.5.3.2p1 | |||
13788 | // We have an lvalue with a decl. Make sure the decl is not declared | |||
13789 | // with the register storage-class specifier. | |||
13790 | if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { | |||
13791 | // in C++ it is not error to take address of a register | |||
13792 | // variable (c++03 7.1.1P3) | |||
13793 | if (vd->getStorageClass() == SC_Register && | |||
13794 | !getLangOpts().CPlusPlus) { | |||
13795 | AddressOfError = AO_Register_Variable; | |||
13796 | } | |||
13797 | } else if (isa<MSPropertyDecl>(dcl)) { | |||
13798 | AddressOfError = AO_Property_Expansion; | |||
13799 | } else if (isa<FunctionTemplateDecl>(dcl)) { | |||
13800 | return Context.OverloadTy; | |||
13801 | } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { | |||
13802 | // Okay: we can take the address of a field. | |||
13803 | // Could be a pointer to member, though, if there is an explicit | |||
13804 | // scope qualifier for the class. | |||
13805 | if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { | |||
13806 | DeclContext *Ctx = dcl->getDeclContext(); | |||
13807 | if (Ctx && Ctx->isRecord()) { | |||
13808 | if (dcl->getType()->isReferenceType()) { | |||
13809 | Diag(OpLoc, | |||
13810 | diag::err_cannot_form_pointer_to_member_of_reference_type) | |||
13811 | << dcl->getDeclName() << dcl->getType(); | |||
13812 | return QualType(); | |||
13813 | } | |||
13814 | ||||
13815 | while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) | |||
13816 | Ctx = Ctx->getParent(); | |||
13817 | ||||
13818 | QualType MPTy = Context.getMemberPointerType( | |||
13819 | op->getType(), | |||
13820 | Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); | |||
13821 | // Under the MS ABI, lock down the inheritance model now. | |||
13822 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
13823 | (void)isCompleteType(OpLoc, MPTy); | |||
13824 | return MPTy; | |||
13825 | } | |||
13826 | } | |||
13827 | } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && | |||
13828 | !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) | |||
13829 | llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type" , "clang/lib/Sema/SemaExpr.cpp", 13829); | |||
13830 | } | |||
13831 | ||||
13832 | if (AddressOfError != AO_No_Error) { | |||
13833 | diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); | |||
13834 | return QualType(); | |||
13835 | } | |||
13836 | ||||
13837 | if (lval == Expr::LV_IncompleteVoidType) { | |||
13838 | // Taking the address of a void variable is technically illegal, but we | |||
13839 | // allow it in cases which are otherwise valid. | |||
13840 | // Example: "extern void x; void* y = &x;". | |||
13841 | Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); | |||
13842 | } | |||
13843 | ||||
13844 | // If the operand has type "type", the result has type "pointer to type". | |||
13845 | if (op->getType()->isObjCObjectType()) | |||
13846 | return Context.getObjCObjectPointerType(op->getType()); | |||
13847 | ||||
13848 | CheckAddressOfPackedMember(op); | |||
13849 | ||||
13850 | return Context.getPointerType(op->getType()); | |||
13851 | } | |||
13852 | ||||
13853 | static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { | |||
13854 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); | |||
13855 | if (!DRE) | |||
13856 | return; | |||
13857 | const Decl *D = DRE->getDecl(); | |||
13858 | if (!D) | |||
13859 | return; | |||
13860 | const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); | |||
13861 | if (!Param) | |||
13862 | return; | |||
13863 | if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) | |||
13864 | if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) | |||
13865 | return; | |||
13866 | if (FunctionScopeInfo *FD = S.getCurFunction()) | |||
13867 | if (!FD->ModifiedNonNullParams.count(Param)) | |||
13868 | FD->ModifiedNonNullParams.insert(Param); | |||
13869 | } | |||
13870 | ||||
13871 | /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). | |||
13872 | static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, | |||
13873 | SourceLocation OpLoc) { | |||
13874 | if (Op->isTypeDependent()) | |||
13875 | return S.Context.DependentTy; | |||
13876 | ||||
13877 | ExprResult ConvResult = S.UsualUnaryConversions(Op); | |||
13878 | if (ConvResult.isInvalid()) | |||
13879 | return QualType(); | |||
13880 | Op = ConvResult.get(); | |||
13881 | QualType OpTy = Op->getType(); | |||
13882 | QualType Result; | |||
13883 | ||||
13884 | if (isa<CXXReinterpretCastExpr>(Op)) { | |||
13885 | QualType OpOrigType = Op->IgnoreParenCasts()->getType(); | |||
13886 | S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, | |||
13887 | Op->getSourceRange()); | |||
13888 | } | |||
13889 | ||||
13890 | if (const PointerType *PT = OpTy->getAs<PointerType>()) | |||
13891 | { | |||
13892 | Result = PT->getPointeeType(); | |||
13893 | } | |||
13894 | else if (const ObjCObjectPointerType *OPT = | |||
13895 | OpTy->getAs<ObjCObjectPointerType>()) | |||
13896 | Result = OPT->getPointeeType(); | |||
13897 | else { | |||
13898 | ExprResult PR = S.CheckPlaceholderExpr(Op); | |||
13899 | if (PR.isInvalid()) return QualType(); | |||
13900 | if (PR.get() != Op) | |||
13901 | return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); | |||
13902 | } | |||
13903 | ||||
13904 | if (Result.isNull()) { | |||
13905 | S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) | |||
13906 | << OpTy << Op->getSourceRange(); | |||
13907 | return QualType(); | |||
13908 | } | |||
13909 | ||||
13910 | // Note that per both C89 and C99, indirection is always legal, even if Result | |||
13911 | // is an incomplete type or void. It would be possible to warn about | |||
13912 | // dereferencing a void pointer, but it's completely well-defined, and such a | |||
13913 | // warning is unlikely to catch any mistakes. In C++, indirection is not valid | |||
13914 | // for pointers to 'void' but is fine for any other pointer type: | |||
13915 | // | |||
13916 | // C++ [expr.unary.op]p1: | |||
13917 | // [...] the expression to which [the unary * operator] is applied shall | |||
13918 | // be a pointer to an object type, or a pointer to a function type | |||
13919 | if (S.getLangOpts().CPlusPlus && Result->isVoidType()) | |||
13920 | S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) | |||
13921 | << OpTy << Op->getSourceRange(); | |||
13922 | ||||
13923 | // Dereferences are usually l-values... | |||
13924 | VK = VK_LValue; | |||
13925 | ||||
13926 | // ...except that certain expressions are never l-values in C. | |||
13927 | if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) | |||
13928 | VK = VK_PRValue; | |||
13929 | ||||
13930 | return Result; | |||
13931 | } | |||
13932 | ||||
13933 | BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { | |||
13934 | BinaryOperatorKind Opc; | |||
13935 | switch (Kind) { | |||
13936 | default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "clang/lib/Sema/SemaExpr.cpp" , 13936); | |||
13937 | case tok::periodstar: Opc = BO_PtrMemD; break; | |||
13938 | case tok::arrowstar: Opc = BO_PtrMemI; break; | |||
13939 | case tok::star: Opc = BO_Mul; break; | |||
13940 | case tok::slash: Opc = BO_Div; break; | |||
13941 | case tok::percent: Opc = BO_Rem; break; | |||
13942 | case tok::plus: Opc = BO_Add; break; | |||
13943 | case tok::minus: Opc = BO_Sub; break; | |||
13944 | case tok::lessless: Opc = BO_Shl; break; | |||
13945 | case tok::greatergreater: Opc = BO_Shr; break; | |||
13946 | case tok::lessequal: Opc = BO_LE; break; | |||
13947 | case tok::less: Opc = BO_LT; break; | |||
13948 | case tok::greaterequal: Opc = BO_GE; break; | |||
13949 | case tok::greater: Opc = BO_GT; break; | |||
13950 | case tok::exclaimequal: Opc = BO_NE; break; | |||
13951 | case tok::equalequal: Opc = BO_EQ; break; | |||
13952 | case tok::spaceship: Opc = BO_Cmp; break; | |||
13953 | case tok::amp: Opc = BO_And; break; | |||
13954 | case tok::caret: Opc = BO_Xor; break; | |||
13955 | case tok::pipe: Opc = BO_Or; break; | |||
13956 | case tok::ampamp: Opc = BO_LAnd; break; | |||
13957 | case tok::pipepipe: Opc = BO_LOr; break; | |||
13958 | case tok::equal: Opc = BO_Assign; break; | |||
13959 | case tok::starequal: Opc = BO_MulAssign; break; | |||
13960 | case tok::slashequal: Opc = BO_DivAssign; break; | |||
13961 | case tok::percentequal: Opc = BO_RemAssign; break; | |||
13962 | case tok::plusequal: Opc = BO_AddAssign; break; | |||
13963 | case tok::minusequal: Opc = BO_SubAssign; break; | |||
13964 | case tok::lesslessequal: Opc = BO_ShlAssign; break; | |||
13965 | case tok::greatergreaterequal: Opc = BO_ShrAssign; break; | |||
13966 | case tok::ampequal: Opc = BO_AndAssign; break; | |||
13967 | case tok::caretequal: Opc = BO_XorAssign; break; | |||
13968 | case tok::pipeequal: Opc = BO_OrAssign; break; | |||
13969 | case tok::comma: Opc = BO_Comma; break; | |||
13970 | } | |||
13971 | return Opc; | |||
13972 | } | |||
13973 | ||||
13974 | static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( | |||
13975 | tok::TokenKind Kind) { | |||
13976 | UnaryOperatorKind Opc; | |||
13977 | switch (Kind) { | |||
13978 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp" , 13978); | |||
13979 | case tok::plusplus: Opc = UO_PreInc; break; | |||
13980 | case tok::minusminus: Opc = UO_PreDec; break; | |||
13981 | case tok::amp: Opc = UO_AddrOf; break; | |||
13982 | case tok::star: Opc = UO_Deref; break; | |||
13983 | case tok::plus: Opc = UO_Plus; break; | |||
13984 | case tok::minus: Opc = UO_Minus; break; | |||
13985 | case tok::tilde: Opc = UO_Not; break; | |||
13986 | case tok::exclaim: Opc = UO_LNot; break; | |||
13987 | case tok::kw___real: Opc = UO_Real; break; | |||
13988 | case tok::kw___imag: Opc = UO_Imag; break; | |||
13989 | case tok::kw___extension__: Opc = UO_Extension; break; | |||
13990 | } | |||
13991 | return Opc; | |||
13992 | } | |||
13993 | ||||
13994 | /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. | |||
13995 | /// This warning suppressed in the event of macro expansions. | |||
13996 | static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, | |||
13997 | SourceLocation OpLoc, bool IsBuiltin) { | |||
13998 | if (S.inTemplateInstantiation()) | |||
13999 | return; | |||
14000 | if (S.isUnevaluatedContext()) | |||
14001 | return; | |||
14002 | if (OpLoc.isInvalid() || OpLoc.isMacroID()) | |||
14003 | return; | |||
14004 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); | |||
14005 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); | |||
14006 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); | |||
14007 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); | |||
14008 | if (!LHSDeclRef || !RHSDeclRef || | |||
14009 | LHSDeclRef->getLocation().isMacroID() || | |||
14010 | RHSDeclRef->getLocation().isMacroID()) | |||
14011 | return; | |||
14012 | const ValueDecl *LHSDecl = | |||
14013 | cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); | |||
14014 | const ValueDecl *RHSDecl = | |||
14015 | cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); | |||
14016 | if (LHSDecl != RHSDecl) | |||
14017 | return; | |||
14018 | if (LHSDecl->getType().isVolatileQualified()) | |||
14019 | return; | |||
14020 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | |||
14021 | if (RefTy->getPointeeType().isVolatileQualified()) | |||
14022 | return; | |||
14023 | ||||
14024 | S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin | |||
14025 | : diag::warn_self_assignment_overloaded) | |||
14026 | << LHSDeclRef->getType() << LHSExpr->getSourceRange() | |||
14027 | << RHSExpr->getSourceRange(); | |||
14028 | } | |||
14029 | ||||
14030 | /// Check if a bitwise-& is performed on an Objective-C pointer. This | |||
14031 | /// is usually indicative of introspection within the Objective-C pointer. | |||
14032 | static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, | |||
14033 | SourceLocation OpLoc) { | |||
14034 | if (!S.getLangOpts().ObjC) | |||
14035 | return; | |||
14036 | ||||
14037 | const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; | |||
14038 | const Expr *LHS = L.get(); | |||
14039 | const Expr *RHS = R.get(); | |||
14040 | ||||
14041 | if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | |||
14042 | ObjCPointerExpr = LHS; | |||
14043 | OtherExpr = RHS; | |||
14044 | } | |||
14045 | else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | |||
14046 | ObjCPointerExpr = RHS; | |||
14047 | OtherExpr = LHS; | |||
14048 | } | |||
14049 | ||||
14050 | // This warning is deliberately made very specific to reduce false | |||
14051 | // positives with logic that uses '&' for hashing. This logic mainly | |||
14052 | // looks for code trying to introspect into tagged pointers, which | |||
14053 | // code should generally never do. | |||
14054 | if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { | |||
14055 | unsigned Diag = diag::warn_objc_pointer_masking; | |||
14056 | // Determine if we are introspecting the result of performSelectorXXX. | |||
14057 | const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); | |||
14058 | // Special case messages to -performSelector and friends, which | |||
14059 | // can return non-pointer values boxed in a pointer value. | |||
14060 | // Some clients may wish to silence warnings in this subcase. | |||
14061 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { | |||
14062 | Selector S = ME->getSelector(); | |||
14063 | StringRef SelArg0 = S.getNameForSlot(0); | |||
14064 | if (SelArg0.startswith("performSelector")) | |||
14065 | Diag = diag::warn_objc_pointer_masking_performSelector; | |||
14066 | } | |||
14067 | ||||
14068 | S.Diag(OpLoc, Diag) | |||
14069 | << ObjCPointerExpr->getSourceRange(); | |||
14070 | } | |||
14071 | } | |||
14072 | ||||
14073 | static NamedDecl *getDeclFromExpr(Expr *E) { | |||
14074 | if (!E) | |||
14075 | return nullptr; | |||
14076 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) | |||
14077 | return DRE->getDecl(); | |||
14078 | if (auto *ME = dyn_cast<MemberExpr>(E)) | |||
14079 | return ME->getMemberDecl(); | |||
14080 | if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) | |||
14081 | return IRE->getDecl(); | |||
14082 | return nullptr; | |||
14083 | } | |||
14084 | ||||
14085 | // This helper function promotes a binary operator's operands (which are of a | |||
14086 | // half vector type) to a vector of floats and then truncates the result to | |||
14087 | // a vector of either half or short. | |||
14088 | static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, | |||
14089 | BinaryOperatorKind Opc, QualType ResultTy, | |||
14090 | ExprValueKind VK, ExprObjectKind OK, | |||
14091 | bool IsCompAssign, SourceLocation OpLoc, | |||
14092 | FPOptionsOverride FPFeatures) { | |||
14093 | auto &Context = S.getASTContext(); | |||
14094 | assert((isVector(ResultTy, Context.HalfTy) ||(static_cast <bool> ((isVector(ResultTy, Context.HalfTy ) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short" ) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "clang/lib/Sema/SemaExpr.cpp", 14096, __extension__ __PRETTY_FUNCTION__ )) | |||
14095 | isVector(ResultTy, Context.ShortTy)) &&(static_cast <bool> ((isVector(ResultTy, Context.HalfTy ) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short" ) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "clang/lib/Sema/SemaExpr.cpp", 14096, __extension__ __PRETTY_FUNCTION__ )) | |||
14096 | "Result must be a vector of half or short")(static_cast <bool> ((isVector(ResultTy, Context.HalfTy ) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short" ) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "clang/lib/Sema/SemaExpr.cpp", 14096, __extension__ __PRETTY_FUNCTION__ )); | |||
14097 | assert(isVector(LHS.get()->getType(), Context.HalfTy) &&(static_cast <bool> (isVector(LHS.get()->getType(), Context .HalfTy) && isVector(RHS.get()->getType(), Context .HalfTy) && "both operands expected to be a half vector" ) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "clang/lib/Sema/SemaExpr.cpp", 14099, __extension__ __PRETTY_FUNCTION__ )) | |||
14098 | isVector(RHS.get()->getType(), Context.HalfTy) &&(static_cast <bool> (isVector(LHS.get()->getType(), Context .HalfTy) && isVector(RHS.get()->getType(), Context .HalfTy) && "both operands expected to be a half vector" ) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "clang/lib/Sema/SemaExpr.cpp", 14099, __extension__ __PRETTY_FUNCTION__ )) | |||
14099 | "both operands expected to be a half vector")(static_cast <bool> (isVector(LHS.get()->getType(), Context .HalfTy) && isVector(RHS.get()->getType(), Context .HalfTy) && "both operands expected to be a half vector" ) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "clang/lib/Sema/SemaExpr.cpp", 14099, __extension__ __PRETTY_FUNCTION__ )); | |||
14100 | ||||
14101 | RHS = convertVector(RHS.get(), Context.FloatTy, S); | |||
14102 | QualType BinOpResTy = RHS.get()->getType(); | |||
14103 | ||||
14104 | // If Opc is a comparison, ResultType is a vector of shorts. In that case, | |||
14105 | // change BinOpResTy to a vector of ints. | |||
14106 | if (isVector(ResultTy, Context.ShortTy)) | |||
14107 | BinOpResTy = S.GetSignedVectorType(BinOpResTy); | |||
14108 | ||||
14109 | if (IsCompAssign) | |||
14110 | return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, | |||
14111 | ResultTy, VK, OK, OpLoc, FPFeatures, | |||
14112 | BinOpResTy, BinOpResTy); | |||
14113 | ||||
14114 | LHS = convertVector(LHS.get(), Context.FloatTy, S); | |||
14115 | auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, | |||
14116 | BinOpResTy, VK, OK, OpLoc, FPFeatures); | |||
14117 | return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); | |||
14118 | } | |||
14119 | ||||
14120 | static std::pair<ExprResult, ExprResult> | |||
14121 | CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, | |||
14122 | Expr *RHSExpr) { | |||
14123 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | |||
14124 | if (!S.Context.isDependenceAllowed()) { | |||
14125 | // C cannot handle TypoExpr nodes on either side of a binop because it | |||
14126 | // doesn't handle dependent types properly, so make sure any TypoExprs have | |||
14127 | // been dealt with before checking the operands. | |||
14128 | LHS = S.CorrectDelayedTyposInExpr(LHS); | |||
14129 | RHS = S.CorrectDelayedTyposInExpr( | |||
14130 | RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, | |||
14131 | [Opc, LHS](Expr *E) { | |||
14132 | if (Opc != BO_Assign) | |||
14133 | return ExprResult(E); | |||
14134 | // Avoid correcting the RHS to the same Expr as the LHS. | |||
14135 | Decl *D = getDeclFromExpr(E); | |||
14136 | return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; | |||
14137 | }); | |||
14138 | } | |||
14139 | return std::make_pair(LHS, RHS); | |||
14140 | } | |||
14141 | ||||
14142 | /// Returns true if conversion between vectors of halfs and vectors of floats | |||
14143 | /// is needed. | |||
14144 | static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, | |||
14145 | Expr *E0, Expr *E1 = nullptr) { | |||
14146 | if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || | |||
14147 | Ctx.getTargetInfo().useFP16ConversionIntrinsics()) | |||
14148 | return false; | |||
14149 | ||||
14150 | auto HasVectorOfHalfType = [&Ctx](Expr *E) { | |||
14151 | QualType Ty = E->IgnoreImplicit()->getType(); | |||
14152 | ||||
14153 | // Don't promote half precision neon vectors like float16x4_t in arm_neon.h | |||
14154 | // to vectors of floats. Although the element type of the vectors is __fp16, | |||
14155 | // the vectors shouldn't be treated as storage-only types. See the | |||
14156 | // discussion here: https://reviews.llvm.org/rG825235c140e7 | |||
14157 | if (const VectorType *VT = Ty->getAs<VectorType>()) { | |||
14158 | if (VT->getVectorKind() == VectorType::NeonVector) | |||
14159 | return false; | |||
14160 | return VT->getElementType().getCanonicalType() == Ctx.HalfTy; | |||
14161 | } | |||
14162 | return false; | |||
14163 | }; | |||
14164 | ||||
14165 | return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); | |||
14166 | } | |||
14167 | ||||
14168 | /// CreateBuiltinBinOp - Creates a new built-in binary operation with | |||
14169 | /// operator @p Opc at location @c TokLoc. This routine only supports | |||
14170 | /// built-in operations; ActOnBinOp handles overloaded operators. | |||
14171 | ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, | |||
14172 | BinaryOperatorKind Opc, | |||
14173 | Expr *LHSExpr, Expr *RHSExpr) { | |||
14174 | if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { | |||
14175 | // The syntax only allows initializer lists on the RHS of assignment, | |||
14176 | // so we don't need to worry about accepting invalid code for | |||
14177 | // non-assignment operators. | |||
14178 | // C++11 5.17p9: | |||
14179 | // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning | |||
14180 | // of x = {} is x = T(). | |||
14181 | InitializationKind Kind = InitializationKind::CreateDirectList( | |||
14182 | RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | |||
14183 | InitializedEntity Entity = | |||
14184 | InitializedEntity::InitializeTemporary(LHSExpr->getType()); | |||
14185 | InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); | |||
14186 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); | |||
14187 | if (Init.isInvalid()) | |||
14188 | return Init; | |||
14189 | RHSExpr = Init.get(); | |||
14190 | } | |||
14191 | ||||
14192 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | |||
14193 | QualType ResultTy; // Result type of the binary operator. | |||
14194 | // The following two variables are used for compound assignment operators | |||
14195 | QualType CompLHSTy; // Type of LHS after promotions for computation | |||
14196 | QualType CompResultTy; // Type of computation result | |||
14197 | ExprValueKind VK = VK_PRValue; | |||
14198 | ExprObjectKind OK = OK_Ordinary; | |||
14199 | bool ConvertHalfVec = false; | |||
14200 | ||||
14201 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | |||
14202 | if (!LHS.isUsable() || !RHS.isUsable()) | |||
14203 | return ExprError(); | |||
14204 | ||||
14205 | if (getLangOpts().OpenCL) { | |||
14206 | QualType LHSTy = LHSExpr->getType(); | |||
14207 | QualType RHSTy = RHSExpr->getType(); | |||
14208 | // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by | |||
14209 | // the ATOMIC_VAR_INIT macro. | |||
14210 | if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { | |||
14211 | SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | |||
14212 | if (BO_Assign == Opc) | |||
14213 | Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; | |||
14214 | else | |||
14215 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | |||
14216 | return ExprError(); | |||
14217 | } | |||
14218 | ||||
14219 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | |||
14220 | // only with a builtin functions and therefore should be disallowed here. | |||
14221 | if (LHSTy->isImageType() || RHSTy->isImageType() || | |||
14222 | LHSTy->isSamplerT() || RHSTy->isSamplerT() || | |||
14223 | LHSTy->isPipeType() || RHSTy->isPipeType() || | |||
14224 | LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { | |||
14225 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | |||
14226 | return ExprError(); | |||
14227 | } | |||
14228 | } | |||
14229 | ||||
14230 | checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); | |||
14231 | checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); | |||
14232 | ||||
14233 | switch (Opc) { | |||
14234 | case BO_Assign: | |||
14235 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); | |||
14236 | if (getLangOpts().CPlusPlus && | |||
14237 | LHS.get()->getObjectKind() != OK_ObjCProperty) { | |||
14238 | VK = LHS.get()->getValueKind(); | |||
14239 | OK = LHS.get()->getObjectKind(); | |||
14240 | } | |||
14241 | if (!ResultTy.isNull()) { | |||
14242 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | |||
14243 | DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); | |||
14244 | ||||
14245 | // Avoid copying a block to the heap if the block is assigned to a local | |||
14246 | // auto variable that is declared in the same scope as the block. This | |||
14247 | // optimization is unsafe if the local variable is declared in an outer | |||
14248 | // scope. For example: | |||
14249 | // | |||
14250 | // BlockTy b; | |||
14251 | // { | |||
14252 | // b = ^{...}; | |||
14253 | // } | |||
14254 | // // It is unsafe to invoke the block here if it wasn't copied to the | |||
14255 | // // heap. | |||
14256 | // b(); | |||
14257 | ||||
14258 | if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) | |||
14259 | if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) | |||
14260 | if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) | |||
14261 | if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) | |||
14262 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | |||
14263 | ||||
14264 | if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) | |||
14265 | checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), | |||
14266 | NTCUC_Assignment, NTCUK_Copy); | |||
14267 | } | |||
14268 | RecordModifiableNonNullParam(*this, LHS.get()); | |||
14269 | break; | |||
14270 | case BO_PtrMemD: | |||
14271 | case BO_PtrMemI: | |||
14272 | ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, | |||
14273 | Opc == BO_PtrMemI); | |||
14274 | break; | |||
14275 | case BO_Mul: | |||
14276 | case BO_Div: | |||
14277 | ConvertHalfVec = true; | |||
14278 | ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, | |||
14279 | Opc == BO_Div); | |||
14280 | break; | |||
14281 | case BO_Rem: | |||
14282 | ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); | |||
14283 | break; | |||
14284 | case BO_Add: | |||
14285 | ConvertHalfVec = true; | |||
14286 | ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); | |||
14287 | break; | |||
14288 | case BO_Sub: | |||
14289 | ConvertHalfVec = true; | |||
14290 | ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); | |||
14291 | break; | |||
14292 | case BO_Shl: | |||
14293 | case BO_Shr: | |||
14294 | ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); | |||
14295 | break; | |||
14296 | case BO_LE: | |||
14297 | case BO_LT: | |||
14298 | case BO_GE: | |||
14299 | case BO_GT: | |||
14300 | ConvertHalfVec = true; | |||
14301 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | |||
14302 | break; | |||
14303 | case BO_EQ: | |||
14304 | case BO_NE: | |||
14305 | ConvertHalfVec = true; | |||
14306 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | |||
14307 | break; | |||
14308 | case BO_Cmp: | |||
14309 | ConvertHalfVec = true; | |||
14310 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | |||
14311 | assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())(static_cast <bool> (ResultTy.isNull() || ResultTy-> getAsCXXRecordDecl()) ? void (0) : __assert_fail ("ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()" , "clang/lib/Sema/SemaExpr.cpp", 14311, __extension__ __PRETTY_FUNCTION__ )); | |||
14312 | break; | |||
14313 | case BO_And: | |||
14314 | checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); | |||
14315 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
14316 | case BO_Xor: | |||
14317 | case BO_Or: | |||
14318 | ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | |||
14319 | break; | |||
14320 | case BO_LAnd: | |||
14321 | case BO_LOr: | |||
14322 | ConvertHalfVec = true; | |||
14323 | ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); | |||
14324 | break; | |||
14325 | case BO_MulAssign: | |||
14326 | case BO_DivAssign: | |||
14327 | ConvertHalfVec = true; | |||
14328 | CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, | |||
14329 | Opc == BO_DivAssign); | |||
14330 | CompLHSTy = CompResultTy; | |||
14331 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
14332 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
14333 | break; | |||
14334 | case BO_RemAssign: | |||
14335 | CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); | |||
14336 | CompLHSTy = CompResultTy; | |||
14337 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
14338 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
14339 | break; | |||
14340 | case BO_AddAssign: | |||
14341 | ConvertHalfVec = true; | |||
14342 | CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); | |||
14343 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
14344 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
14345 | break; | |||
14346 | case BO_SubAssign: | |||
14347 | ConvertHalfVec = true; | |||
14348 | CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); | |||
14349 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
14350 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
14351 | break; | |||
14352 | case BO_ShlAssign: | |||
14353 | case BO_ShrAssign: | |||
14354 | CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); | |||
14355 | CompLHSTy = CompResultTy; | |||
14356 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
14357 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
14358 | break; | |||
14359 | case BO_AndAssign: | |||
14360 | case BO_OrAssign: // fallthrough | |||
14361 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | |||
14362 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
14363 | case BO_XorAssign: | |||
14364 | CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | |||
14365 | CompLHSTy = CompResultTy; | |||
14366 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
14367 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
14368 | break; | |||
14369 | case BO_Comma: | |||
14370 | ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); | |||
14371 | if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { | |||
14372 | VK = RHS.get()->getValueKind(); | |||
14373 | OK = RHS.get()->getObjectKind(); | |||
14374 | } | |||
14375 | break; | |||
14376 | } | |||
14377 | if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) | |||
14378 | return ExprError(); | |||
14379 | ||||
14380 | // Some of the binary operations require promoting operands of half vector to | |||
14381 | // float vectors and truncating the result back to half vector. For now, we do | |||
14382 | // this only when HalfArgsAndReturn is set (that is, when the target is arm or | |||
14383 | // arm64). | |||
14384 | assert((static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "clang/lib/Sema/SemaExpr.cpp", 14387, __extension__ __PRETTY_FUNCTION__ )) | |||
14385 | (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "clang/lib/Sema/SemaExpr.cpp", 14387, __extension__ __PRETTY_FUNCTION__ )) | |||
14386 | isVector(LHS.get()->getType(), Context.HalfTy)) &&(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "clang/lib/Sema/SemaExpr.cpp", 14387, __extension__ __PRETTY_FUNCTION__ )) | |||
14387 | "both sides are half vectors or neither sides are")(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "clang/lib/Sema/SemaExpr.cpp", 14387, __extension__ __PRETTY_FUNCTION__ )); | |||
14388 | ConvertHalfVec = | |||
14389 | needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); | |||
14390 | ||||
14391 | // Check for array bounds violations for both sides of the BinaryOperator | |||
14392 | CheckArrayAccess(LHS.get()); | |||
14393 | CheckArrayAccess(RHS.get()); | |||
14394 | ||||
14395 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { | |||
14396 | NamedDecl *ObjectSetClass = LookupSingleName(TUScope, | |||
14397 | &Context.Idents.get("object_setClass"), | |||
14398 | SourceLocation(), LookupOrdinaryName); | |||
14399 | if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { | |||
14400 | SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); | |||
14401 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) | |||
14402 | << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), | |||
14403 | "object_setClass(") | |||
14404 | << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), | |||
14405 | ",") | |||
14406 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | |||
14407 | } | |||
14408 | else | |||
14409 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); | |||
14410 | } | |||
14411 | else if (const ObjCIvarRefExpr *OIRE = | |||
14412 | dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) | |||
14413 | DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); | |||
14414 | ||||
14415 | // Opc is not a compound assignment if CompResultTy is null. | |||
14416 | if (CompResultTy.isNull()) { | |||
14417 | if (ConvertHalfVec) | |||
14418 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, | |||
14419 | OpLoc, CurFPFeatureOverrides()); | |||
14420 | return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, | |||
14421 | VK, OK, OpLoc, CurFPFeatureOverrides()); | |||
14422 | } | |||
14423 | ||||
14424 | // Handle compound assignments. | |||
14425 | if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != | |||
14426 | OK_ObjCProperty) { | |||
14427 | VK = VK_LValue; | |||
14428 | OK = LHS.get()->getObjectKind(); | |||
14429 | } | |||
14430 | ||||
14431 | // The LHS is not converted to the result type for fixed-point compound | |||
14432 | // assignment as the common type is computed on demand. Reset the CompLHSTy | |||
14433 | // to the LHS type we would have gotten after unary conversions. | |||
14434 | if (CompResultTy->isFixedPointType()) | |||
14435 | CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); | |||
14436 | ||||
14437 | if (ConvertHalfVec) | |||
14438 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, | |||
14439 | OpLoc, CurFPFeatureOverrides()); | |||
14440 | ||||
14441 | return CompoundAssignOperator::Create( | |||
14442 | Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, | |||
14443 | CurFPFeatureOverrides(), CompLHSTy, CompResultTy); | |||
14444 | } | |||
14445 | ||||
14446 | /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison | |||
14447 | /// operators are mixed in a way that suggests that the programmer forgot that | |||
14448 | /// comparison operators have higher precedence. The most typical example of | |||
14449 | /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". | |||
14450 | static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, | |||
14451 | SourceLocation OpLoc, Expr *LHSExpr, | |||
14452 | Expr *RHSExpr) { | |||
14453 | BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); | |||
14454 | BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); | |||
14455 | ||||
14456 | // Check that one of the sides is a comparison operator and the other isn't. | |||
14457 | bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); | |||
14458 | bool isRightComp = RHSBO && RHSBO->isComparisonOp(); | |||
14459 | if (isLeftComp == isRightComp) | |||
14460 | return; | |||
14461 | ||||
14462 | // Bitwise operations are sometimes used as eager logical ops. | |||
14463 | // Don't diagnose this. | |||
14464 | bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); | |||
14465 | bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); | |||
14466 | if (isLeftBitwise || isRightBitwise) | |||
14467 | return; | |||
14468 | ||||
14469 | SourceRange DiagRange = isLeftComp | |||
14470 | ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) | |||
14471 | : SourceRange(OpLoc, RHSExpr->getEndLoc()); | |||
14472 | StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); | |||
14473 | SourceRange ParensRange = | |||
14474 | isLeftComp | |||
14475 | ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) | |||
14476 | : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); | |||
14477 | ||||
14478 | Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) | |||
14479 | << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; | |||
14480 | SuggestParentheses(Self, OpLoc, | |||
14481 | Self.PDiag(diag::note_precedence_silence) << OpStr, | |||
14482 | (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); | |||
14483 | SuggestParentheses(Self, OpLoc, | |||
14484 | Self.PDiag(diag::note_precedence_bitwise_first) | |||
14485 | << BinaryOperator::getOpcodeStr(Opc), | |||
14486 | ParensRange); | |||
14487 | } | |||
14488 | ||||
14489 | /// It accepts a '&&' expr that is inside a '||' one. | |||
14490 | /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression | |||
14491 | /// in parentheses. | |||
14492 | static void | |||
14493 | EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, | |||
14494 | BinaryOperator *Bop) { | |||
14495 | assert(Bop->getOpcode() == BO_LAnd)(static_cast <bool> (Bop->getOpcode() == BO_LAnd) ? void (0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "clang/lib/Sema/SemaExpr.cpp" , 14495, __extension__ __PRETTY_FUNCTION__)); | |||
14496 | Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) | |||
14497 | << Bop->getSourceRange() << OpLoc; | |||
14498 | SuggestParentheses(Self, Bop->getOperatorLoc(), | |||
14499 | Self.PDiag(diag::note_precedence_silence) | |||
14500 | << Bop->getOpcodeStr(), | |||
14501 | Bop->getSourceRange()); | |||
14502 | } | |||
14503 | ||||
14504 | /// Returns true if the given expression can be evaluated as a constant | |||
14505 | /// 'true'. | |||
14506 | static bool EvaluatesAsTrue(Sema &S, Expr *E) { | |||
14507 | bool Res; | |||
14508 | return !E->isValueDependent() && | |||
14509 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; | |||
14510 | } | |||
14511 | ||||
14512 | /// Returns true if the given expression can be evaluated as a constant | |||
14513 | /// 'false'. | |||
14514 | static bool EvaluatesAsFalse(Sema &S, Expr *E) { | |||
14515 | bool Res; | |||
14516 | return !E->isValueDependent() && | |||
14517 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; | |||
14518 | } | |||
14519 | ||||
14520 | /// Look for '&&' in the left hand of a '||' expr. | |||
14521 | static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, | |||
14522 | Expr *LHSExpr, Expr *RHSExpr) { | |||
14523 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { | |||
14524 | if (Bop->getOpcode() == BO_LAnd) { | |||
14525 | // If it's "a && b || 0" don't warn since the precedence doesn't matter. | |||
14526 | if (EvaluatesAsFalse(S, RHSExpr)) | |||
14527 | return; | |||
14528 | // If it's "1 && a || b" don't warn since the precedence doesn't matter. | |||
14529 | if (!EvaluatesAsTrue(S, Bop->getLHS())) | |||
14530 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | |||
14531 | } else if (Bop->getOpcode() == BO_LOr) { | |||
14532 | if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { | |||
14533 | // If it's "a || b && 1 || c" we didn't warn earlier for | |||
14534 | // "a || b && 1", but warn now. | |||
14535 | if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) | |||
14536 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); | |||
14537 | } | |||
14538 | } | |||
14539 | } | |||
14540 | } | |||
14541 | ||||
14542 | /// Look for '&&' in the right hand of a '||' expr. | |||
14543 | static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, | |||
14544 | Expr *LHSExpr, Expr *RHSExpr) { | |||
14545 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { | |||
14546 | if (Bop->getOpcode() == BO_LAnd) { | |||
14547 | // If it's "0 || a && b" don't warn since the precedence doesn't matter. | |||
14548 | if (EvaluatesAsFalse(S, LHSExpr)) | |||
14549 | return; | |||
14550 | // If it's "a || b && 1" don't warn since the precedence doesn't matter. | |||
14551 | if (!EvaluatesAsTrue(S, Bop->getRHS())) | |||
14552 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | |||
14553 | } | |||
14554 | } | |||
14555 | } | |||
14556 | ||||
14557 | /// Look for bitwise op in the left or right hand of a bitwise op with | |||
14558 | /// lower precedence and emit a diagnostic together with a fixit hint that wraps | |||
14559 | /// the '&' expression in parentheses. | |||
14560 | static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, | |||
14561 | SourceLocation OpLoc, Expr *SubExpr) { | |||
14562 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | |||
14563 | if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { | |||
14564 | S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) | |||
14565 | << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) | |||
14566 | << Bop->getSourceRange() << OpLoc; | |||
14567 | SuggestParentheses(S, Bop->getOperatorLoc(), | |||
14568 | S.PDiag(diag::note_precedence_silence) | |||
14569 | << Bop->getOpcodeStr(), | |||
14570 | Bop->getSourceRange()); | |||
14571 | } | |||
14572 | } | |||
14573 | } | |||
14574 | ||||
14575 | static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, | |||
14576 | Expr *SubExpr, StringRef Shift) { | |||
14577 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | |||
14578 | if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { | |||
14579 | StringRef Op = Bop->getOpcodeStr(); | |||
14580 | S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) | |||
14581 | << Bop->getSourceRange() << OpLoc << Shift << Op; | |||
14582 | SuggestParentheses(S, Bop->getOperatorLoc(), | |||
14583 | S.PDiag(diag::note_precedence_silence) << Op, | |||
14584 | Bop->getSourceRange()); | |||
14585 | } | |||
14586 | } | |||
14587 | } | |||
14588 | ||||
14589 | static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, | |||
14590 | Expr *LHSExpr, Expr *RHSExpr) { | |||
14591 | CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); | |||
14592 | if (!OCE) | |||
14593 | return; | |||
14594 | ||||
14595 | FunctionDecl *FD = OCE->getDirectCallee(); | |||
14596 | if (!FD || !FD->isOverloadedOperator()) | |||
14597 | return; | |||
14598 | ||||
14599 | OverloadedOperatorKind Kind = FD->getOverloadedOperator(); | |||
14600 | if (Kind != OO_LessLess && Kind != OO_GreaterGreater) | |||
14601 | return; | |||
14602 | ||||
14603 | S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) | |||
14604 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() | |||
14605 | << (Kind == OO_LessLess); | |||
14606 | SuggestParentheses(S, OCE->getOperatorLoc(), | |||
14607 | S.PDiag(diag::note_precedence_silence) | |||
14608 | << (Kind == OO_LessLess ? "<<" : ">>"), | |||
14609 | OCE->getSourceRange()); | |||
14610 | SuggestParentheses( | |||
14611 | S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), | |||
14612 | SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); | |||
14613 | } | |||
14614 | ||||
14615 | /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky | |||
14616 | /// precedence. | |||
14617 | static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, | |||
14618 | SourceLocation OpLoc, Expr *LHSExpr, | |||
14619 | Expr *RHSExpr){ | |||
14620 | // Diagnose "arg1 'bitwise' arg2 'eq' arg3". | |||
14621 | if (BinaryOperator::isBitwiseOp(Opc)) | |||
14622 | DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); | |||
14623 | ||||
14624 | // Diagnose "arg1 & arg2 | arg3" | |||
14625 | if ((Opc == BO_Or || Opc == BO_Xor) && | |||
14626 | !OpLoc.isMacroID()/* Don't warn in macros. */) { | |||
14627 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); | |||
14628 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); | |||
14629 | } | |||
14630 | ||||
14631 | // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. | |||
14632 | // We don't warn for 'assert(a || b && "bad")' since this is safe. | |||
14633 | if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { | |||
14634 | DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); | |||
14635 | DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); | |||
14636 | } | |||
14637 | ||||
14638 | if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) | |||
14639 | || Opc == BO_Shr) { | |||
14640 | StringRef Shift = BinaryOperator::getOpcodeStr(Opc); | |||
14641 | DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); | |||
14642 | DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); | |||
14643 | } | |||
14644 | ||||
14645 | // Warn on overloaded shift operators and comparisons, such as: | |||
14646 | // cout << 5 == 4; | |||
14647 | if (BinaryOperator::isComparisonOp(Opc)) | |||
14648 | DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); | |||
14649 | } | |||
14650 | ||||
14651 | // Binary Operators. 'Tok' is the token for the operator. | |||
14652 | ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, | |||
14653 | tok::TokenKind Kind, | |||
14654 | Expr *LHSExpr, Expr *RHSExpr) { | |||
14655 | BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); | |||
14656 | assert(LHSExpr && "ActOnBinOp(): missing left expression")(static_cast <bool> (LHSExpr && "ActOnBinOp(): missing left expression" ) ? void (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\"" , "clang/lib/Sema/SemaExpr.cpp", 14656, __extension__ __PRETTY_FUNCTION__ )); | |||
14657 | assert(RHSExpr && "ActOnBinOp(): missing right expression")(static_cast <bool> (RHSExpr && "ActOnBinOp(): missing right expression" ) ? void (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\"" , "clang/lib/Sema/SemaExpr.cpp", 14657, __extension__ __PRETTY_FUNCTION__ )); | |||
14658 | ||||
14659 | // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" | |||
14660 | DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); | |||
14661 | ||||
14662 | return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); | |||
14663 | } | |||
14664 | ||||
14665 | void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, | |||
14666 | UnresolvedSetImpl &Functions) { | |||
14667 | OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); | |||
14668 | if (OverOp != OO_None && OverOp != OO_Equal) | |||
14669 | LookupOverloadedOperatorName(OverOp, S, Functions); | |||
14670 | ||||
14671 | // In C++20 onwards, we may have a second operator to look up. | |||
14672 | if (getLangOpts().CPlusPlus20) { | |||
14673 | if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) | |||
14674 | LookupOverloadedOperatorName(ExtraOp, S, Functions); | |||
14675 | } | |||
14676 | } | |||
14677 | ||||
14678 | /// Build an overloaded binary operator expression in the given scope. | |||
14679 | static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, | |||
14680 | BinaryOperatorKind Opc, | |||
14681 | Expr *LHS, Expr *RHS) { | |||
14682 | switch (Opc) { | |||
14683 | case BO_Assign: | |||
14684 | case BO_DivAssign: | |||
14685 | case BO_RemAssign: | |||
14686 | case BO_SubAssign: | |||
14687 | case BO_AndAssign: | |||
14688 | case BO_OrAssign: | |||
14689 | case BO_XorAssign: | |||
14690 | DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); | |||
14691 | CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); | |||
14692 | break; | |||
14693 | default: | |||
14694 | break; | |||
14695 | } | |||
14696 | ||||
14697 | // Find all of the overloaded operators visible from this point. | |||
14698 | UnresolvedSet<16> Functions; | |||
14699 | S.LookupBinOp(Sc, OpLoc, Opc, Functions); | |||
14700 | ||||
14701 | // Build the (potentially-overloaded, potentially-dependent) | |||
14702 | // binary operation. | |||
14703 | return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); | |||
14704 | } | |||
14705 | ||||
14706 | ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, | |||
14707 | BinaryOperatorKind Opc, | |||
14708 | Expr *LHSExpr, Expr *RHSExpr) { | |||
14709 | ExprResult LHS, RHS; | |||
14710 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | |||
14711 | if (!LHS.isUsable() || !RHS.isUsable()) | |||
14712 | return ExprError(); | |||
14713 | LHSExpr = LHS.get(); | |||
14714 | RHSExpr = RHS.get(); | |||
14715 | ||||
14716 | // We want to end up calling one of checkPseudoObjectAssignment | |||
14717 | // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if | |||
14718 | // both expressions are overloadable or either is type-dependent), | |||
14719 | // or CreateBuiltinBinOp (in any other case). We also want to get | |||
14720 | // any placeholder types out of the way. | |||
14721 | ||||
14722 | // Handle pseudo-objects in the LHS. | |||
14723 | if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { | |||
14724 | // Assignments with a pseudo-object l-value need special analysis. | |||
14725 | if (pty->getKind() == BuiltinType::PseudoObject && | |||
14726 | BinaryOperator::isAssignmentOp(Opc)) | |||
14727 | return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
14728 | ||||
14729 | // Don't resolve overloads if the other type is overloadable. | |||
14730 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { | |||
14731 | // We can't actually test that if we still have a placeholder, | |||
14732 | // though. Fortunately, none of the exceptions we see in that | |||
14733 | // code below are valid when the LHS is an overload set. Note | |||
14734 | // that an overload set can be dependently-typed, but it never | |||
14735 | // instantiates to having an overloadable type. | |||
14736 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | |||
14737 | if (resolvedRHS.isInvalid()) return ExprError(); | |||
14738 | RHSExpr = resolvedRHS.get(); | |||
14739 | ||||
14740 | if (RHSExpr->isTypeDependent() || | |||
14741 | RHSExpr->getType()->isOverloadableType()) | |||
14742 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
14743 | } | |||
14744 | ||||
14745 | // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function | |||
14746 | // template, diagnose the missing 'template' keyword instead of diagnosing | |||
14747 | // an invalid use of a bound member function. | |||
14748 | // | |||
14749 | // Note that "A::x < b" might be valid if 'b' has an overloadable type due | |||
14750 | // to C++1z [over.over]/1.4, but we already checked for that case above. | |||
14751 | if (Opc == BO_LT && inTemplateInstantiation() && | |||
14752 | (pty->getKind() == BuiltinType::BoundMember || | |||
14753 | pty->getKind() == BuiltinType::Overload)) { | |||
14754 | auto *OE = dyn_cast<OverloadExpr>(LHSExpr); | |||
14755 | if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && | |||
14756 | std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { | |||
14757 | return isa<FunctionTemplateDecl>(ND); | |||
14758 | })) { | |||
14759 | Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() | |||
14760 | : OE->getNameLoc(), | |||
14761 | diag::err_template_kw_missing) | |||
14762 | << OE->getName().getAsString() << ""; | |||
14763 | return ExprError(); | |||
14764 | } | |||
14765 | } | |||
14766 | ||||
14767 | ExprResult LHS = CheckPlaceholderExpr(LHSExpr); | |||
14768 | if (LHS.isInvalid()) return ExprError(); | |||
14769 | LHSExpr = LHS.get(); | |||
14770 | } | |||
14771 | ||||
14772 | // Handle pseudo-objects in the RHS. | |||
14773 | if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { | |||
14774 | // An overload in the RHS can potentially be resolved by the type | |||
14775 | // being assigned to. | |||
14776 | if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { | |||
14777 | if (getLangOpts().CPlusPlus && | |||
14778 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || | |||
14779 | LHSExpr->getType()->isOverloadableType())) | |||
14780 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
14781 | ||||
14782 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | |||
14783 | } | |||
14784 | ||||
14785 | // Don't resolve overloads if the other type is overloadable. | |||
14786 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && | |||
14787 | LHSExpr->getType()->isOverloadableType()) | |||
14788 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
14789 | ||||
14790 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | |||
14791 | if (!resolvedRHS.isUsable()) return ExprError(); | |||
14792 | RHSExpr = resolvedRHS.get(); | |||
14793 | } | |||
14794 | ||||
14795 | if (getLangOpts().CPlusPlus) { | |||
14796 | // If either expression is type-dependent, always build an | |||
14797 | // overloaded op. | |||
14798 | if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) | |||
14799 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
14800 | ||||
14801 | // Otherwise, build an overloaded op if either expression has an | |||
14802 | // overloadable type. | |||
14803 | if (LHSExpr->getType()->isOverloadableType() || | |||
14804 | RHSExpr->getType()->isOverloadableType()) | |||
14805 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
14806 | } | |||
14807 | ||||
14808 | if (getLangOpts().RecoveryAST && | |||
14809 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { | |||
14810 | assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp" , 14810, __extension__ __PRETTY_FUNCTION__)); | |||
14811 | assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&(static_cast <bool> ((LHSExpr->containsErrors() || RHSExpr ->containsErrors()) && "Should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 14812, __extension__ __PRETTY_FUNCTION__ )) | |||
14812 | "Should only occur in error-recovery path.")(static_cast <bool> ((LHSExpr->containsErrors() || RHSExpr ->containsErrors()) && "Should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 14812, __extension__ __PRETTY_FUNCTION__ )); | |||
14813 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) | |||
14814 | // C [6.15.16] p3: | |||
14815 | // An assignment expression has the value of the left operand after the | |||
14816 | // assignment, but is not an lvalue. | |||
14817 | return CompoundAssignOperator::Create( | |||
14818 | Context, LHSExpr, RHSExpr, Opc, | |||
14819 | LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, | |||
14820 | OpLoc, CurFPFeatureOverrides()); | |||
14821 | QualType ResultType; | |||
14822 | switch (Opc) { | |||
14823 | case BO_Assign: | |||
14824 | ResultType = LHSExpr->getType().getUnqualifiedType(); | |||
14825 | break; | |||
14826 | case BO_LT: | |||
14827 | case BO_GT: | |||
14828 | case BO_LE: | |||
14829 | case BO_GE: | |||
14830 | case BO_EQ: | |||
14831 | case BO_NE: | |||
14832 | case BO_LAnd: | |||
14833 | case BO_LOr: | |||
14834 | // These operators have a fixed result type regardless of operands. | |||
14835 | ResultType = Context.IntTy; | |||
14836 | break; | |||
14837 | case BO_Comma: | |||
14838 | ResultType = RHSExpr->getType(); | |||
14839 | break; | |||
14840 | default: | |||
14841 | ResultType = Context.DependentTy; | |||
14842 | break; | |||
14843 | } | |||
14844 | return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, | |||
14845 | VK_PRValue, OK_Ordinary, OpLoc, | |||
14846 | CurFPFeatureOverrides()); | |||
14847 | } | |||
14848 | ||||
14849 | // Build a built-in binary operation. | |||
14850 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | |||
14851 | } | |||
14852 | ||||
14853 | static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { | |||
14854 | if (T.isNull() || T->isDependentType()) | |||
14855 | return false; | |||
14856 | ||||
14857 | if (!T->isPromotableIntegerType()) | |||
14858 | return true; | |||
14859 | ||||
14860 | return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); | |||
14861 | } | |||
14862 | ||||
14863 | ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, | |||
14864 | UnaryOperatorKind Opc, | |||
14865 | Expr *InputExpr) { | |||
14866 | ExprResult Input = InputExpr; | |||
14867 | ExprValueKind VK = VK_PRValue; | |||
14868 | ExprObjectKind OK = OK_Ordinary; | |||
14869 | QualType resultType; | |||
14870 | bool CanOverflow = false; | |||
14871 | ||||
14872 | bool ConvertHalfVec = false; | |||
14873 | if (getLangOpts().OpenCL) { | |||
14874 | QualType Ty = InputExpr->getType(); | |||
14875 | // The only legal unary operation for atomics is '&'. | |||
14876 | if ((Opc != UO_AddrOf && Ty->isAtomicType()) || | |||
14877 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | |||
14878 | // only with a builtin functions and therefore should be disallowed here. | |||
14879 | (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() | |||
14880 | || Ty->isBlockPointerType())) { | |||
14881 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
14882 | << InputExpr->getType() | |||
14883 | << Input.get()->getSourceRange()); | |||
14884 | } | |||
14885 | } | |||
14886 | ||||
14887 | switch (Opc) { | |||
14888 | case UO_PreInc: | |||
14889 | case UO_PreDec: | |||
14890 | case UO_PostInc: | |||
14891 | case UO_PostDec: | |||
14892 | resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, | |||
14893 | OpLoc, | |||
14894 | Opc == UO_PreInc || | |||
14895 | Opc == UO_PostInc, | |||
14896 | Opc == UO_PreInc || | |||
14897 | Opc == UO_PreDec); | |||
14898 | CanOverflow = isOverflowingIntegerType(Context, resultType); | |||
14899 | break; | |||
14900 | case UO_AddrOf: | |||
14901 | resultType = CheckAddressOfOperand(Input, OpLoc); | |||
14902 | CheckAddressOfNoDeref(InputExpr); | |||
14903 | RecordModifiableNonNullParam(*this, InputExpr); | |||
14904 | break; | |||
14905 | case UO_Deref: { | |||
14906 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | |||
14907 | if (Input.isInvalid()) return ExprError(); | |||
14908 | resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); | |||
14909 | break; | |||
14910 | } | |||
14911 | case UO_Plus: | |||
14912 | case UO_Minus: | |||
14913 | CanOverflow = Opc == UO_Minus && | |||
14914 | isOverflowingIntegerType(Context, Input.get()->getType()); | |||
14915 | Input = UsualUnaryConversions(Input.get()); | |||
14916 | if (Input.isInvalid()) return ExprError(); | |||
14917 | // Unary plus and minus require promoting an operand of half vector to a | |||
14918 | // float vector and truncating the result back to a half vector. For now, we | |||
14919 | // do this only when HalfArgsAndReturns is set (that is, when the target is | |||
14920 | // arm or arm64). | |||
14921 | ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); | |||
14922 | ||||
14923 | // If the operand is a half vector, promote it to a float vector. | |||
14924 | if (ConvertHalfVec) | |||
14925 | Input = convertVector(Input.get(), Context.FloatTy, *this); | |||
14926 | resultType = Input.get()->getType(); | |||
14927 | if (resultType->isDependentType()) | |||
14928 | break; | |||
14929 | if (resultType->isArithmeticType()) // C99 6.5.3.3p1 | |||
14930 | break; | |||
14931 | else if (resultType->isVectorType() && | |||
14932 | // The z vector extensions don't allow + or - with bool vectors. | |||
14933 | (!Context.getLangOpts().ZVector || | |||
14934 | resultType->castAs<VectorType>()->getVectorKind() != | |||
14935 | VectorType::AltiVecBool)) | |||
14936 | break; | |||
14937 | else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 | |||
14938 | Opc == UO_Plus && | |||
14939 | resultType->isPointerType()) | |||
14940 | break; | |||
14941 | ||||
14942 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
14943 | << resultType << Input.get()->getSourceRange()); | |||
14944 | ||||
14945 | case UO_Not: // bitwise complement | |||
14946 | Input = UsualUnaryConversions(Input.get()); | |||
14947 | if (Input.isInvalid()) | |||
14948 | return ExprError(); | |||
14949 | resultType = Input.get()->getType(); | |||
14950 | if (resultType->isDependentType()) | |||
14951 | break; | |||
14952 | // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. | |||
14953 | if (resultType->isComplexType() || resultType->isComplexIntegerType()) | |||
14954 | // C99 does not support '~' for complex conjugation. | |||
14955 | Diag(OpLoc, diag::ext_integer_complement_complex) | |||
14956 | << resultType << Input.get()->getSourceRange(); | |||
14957 | else if (resultType->hasIntegerRepresentation()) | |||
14958 | break; | |||
14959 | else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { | |||
14960 | // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate | |||
14961 | // on vector float types. | |||
14962 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | |||
14963 | if (!T->isIntegerType()) | |||
14964 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
14965 | << resultType << Input.get()->getSourceRange()); | |||
14966 | } else { | |||
14967 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
14968 | << resultType << Input.get()->getSourceRange()); | |||
14969 | } | |||
14970 | break; | |||
14971 | ||||
14972 | case UO_LNot: // logical negation | |||
14973 | // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). | |||
14974 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | |||
14975 | if (Input.isInvalid()) return ExprError(); | |||
14976 | resultType = Input.get()->getType(); | |||
14977 | ||||
14978 | // Though we still have to promote half FP to float... | |||
14979 | if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { | |||
14980 | Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); | |||
14981 | resultType = Context.FloatTy; | |||
14982 | } | |||
14983 | ||||
14984 | if (resultType->isDependentType()) | |||
14985 | break; | |||
14986 | if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { | |||
14987 | // C99 6.5.3.3p1: ok, fallthrough; | |||
14988 | if (Context.getLangOpts().CPlusPlus) { | |||
14989 | // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: | |||
14990 | // operand contextually converted to bool. | |||
14991 | Input = ImpCastExprToType(Input.get(), Context.BoolTy, | |||
14992 | ScalarTypeToBooleanCastKind(resultType)); | |||
14993 | } else if (Context.getLangOpts().OpenCL && | |||
14994 | Context.getLangOpts().OpenCLVersion < 120) { | |||
14995 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | |||
14996 | // operate on scalar float types. | |||
14997 | if (!resultType->isIntegerType() && !resultType->isPointerType()) | |||
14998 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
14999 | << resultType << Input.get()->getSourceRange()); | |||
15000 | } | |||
15001 | } else if (resultType->isExtVectorType()) { | |||
15002 | if (Context.getLangOpts().OpenCL && | |||
15003 | Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { | |||
15004 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | |||
15005 | // operate on vector float types. | |||
15006 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | |||
15007 | if (!T->isIntegerType()) | |||
15008 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
15009 | << resultType << Input.get()->getSourceRange()); | |||
15010 | } | |||
15011 | // Vector logical not returns the signed variant of the operand type. | |||
15012 | resultType = GetSignedVectorType(resultType); | |||
15013 | break; | |||
15014 | } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { | |||
15015 | const VectorType *VTy = resultType->castAs<VectorType>(); | |||
15016 | if (VTy->getVectorKind() != VectorType::GenericVector) | |||
15017 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
15018 | << resultType << Input.get()->getSourceRange()); | |||
15019 | ||||
15020 | // Vector logical not returns the signed variant of the operand type. | |||
15021 | resultType = GetSignedVectorType(resultType); | |||
15022 | break; | |||
15023 | } else { | |||
15024 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
15025 | << resultType << Input.get()->getSourceRange()); | |||
15026 | } | |||
15027 | ||||
15028 | // LNot always has type int. C99 6.5.3.3p5. | |||
15029 | // In C++, it's bool. C++ 5.3.1p8 | |||
15030 | resultType = Context.getLogicalOperationType(); | |||
15031 | break; | |||
15032 | case UO_Real: | |||
15033 | case UO_Imag: | |||
15034 | resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); | |||
15035 | // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary | |||
15036 | // complex l-values to ordinary l-values and all other values to r-values. | |||
15037 | if (Input.isInvalid()) return ExprError(); | |||
15038 | if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { | |||
15039 | if (Input.get()->isGLValue() && | |||
15040 | Input.get()->getObjectKind() == OK_Ordinary) | |||
15041 | VK = Input.get()->getValueKind(); | |||
15042 | } else if (!getLangOpts().CPlusPlus) { | |||
15043 | // In C, a volatile scalar is read by __imag. In C++, it is not. | |||
15044 | Input = DefaultLvalueConversion(Input.get()); | |||
15045 | } | |||
15046 | break; | |||
15047 | case UO_Extension: | |||
15048 | resultType = Input.get()->getType(); | |||
15049 | VK = Input.get()->getValueKind(); | |||
15050 | OK = Input.get()->getObjectKind(); | |||
15051 | break; | |||
15052 | case UO_Coawait: | |||
15053 | // It's unnecessary to represent the pass-through operator co_await in the | |||
15054 | // AST; just return the input expression instead. | |||
15055 | assert(!Input.get()->getType()->isDependentType() &&(static_cast <bool> (!Input.get()->getType()->isDependentType () && "the co_await expression must be non-dependant before " "building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "clang/lib/Sema/SemaExpr.cpp", 15057, __extension__ __PRETTY_FUNCTION__ )) | |||
15056 | "the co_await expression must be non-dependant before "(static_cast <bool> (!Input.get()->getType()->isDependentType () && "the co_await expression must be non-dependant before " "building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "clang/lib/Sema/SemaExpr.cpp", 15057, __extension__ __PRETTY_FUNCTION__ )) | |||
15057 | "building operator co_await")(static_cast <bool> (!Input.get()->getType()->isDependentType () && "the co_await expression must be non-dependant before " "building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "clang/lib/Sema/SemaExpr.cpp", 15057, __extension__ __PRETTY_FUNCTION__ )); | |||
15058 | return Input; | |||
15059 | } | |||
15060 | if (resultType.isNull() || Input.isInvalid()) | |||
15061 | return ExprError(); | |||
15062 | ||||
15063 | // Check for array bounds violations in the operand of the UnaryOperator, | |||
15064 | // except for the '*' and '&' operators that have to be handled specially | |||
15065 | // by CheckArrayAccess (as there are special cases like &array[arraysize] | |||
15066 | // that are explicitly defined as valid by the standard). | |||
15067 | if (Opc != UO_AddrOf && Opc != UO_Deref) | |||
15068 | CheckArrayAccess(Input.get()); | |||
15069 | ||||
15070 | auto *UO = | |||
15071 | UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, | |||
15072 | OpLoc, CanOverflow, CurFPFeatureOverrides()); | |||
15073 | ||||
15074 | if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && | |||
15075 | !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && | |||
15076 | !isUnevaluatedContext()) | |||
15077 | ExprEvalContexts.back().PossibleDerefs.insert(UO); | |||
15078 | ||||
15079 | // Convert the result back to a half vector. | |||
15080 | if (ConvertHalfVec) | |||
15081 | return convertVector(UO, Context.HalfTy, *this); | |||
15082 | return UO; | |||
15083 | } | |||
15084 | ||||
15085 | /// Determine whether the given expression is a qualified member | |||
15086 | /// access expression, of a form that could be turned into a pointer to member | |||
15087 | /// with the address-of operator. | |||
15088 | bool Sema::isQualifiedMemberAccess(Expr *E) { | |||
15089 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
15090 | if (!DRE->getQualifier()) | |||
15091 | return false; | |||
15092 | ||||
15093 | ValueDecl *VD = DRE->getDecl(); | |||
15094 | if (!VD->isCXXClassMember()) | |||
15095 | return false; | |||
15096 | ||||
15097 | if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) | |||
15098 | return true; | |||
15099 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) | |||
15100 | return Method->isInstance(); | |||
15101 | ||||
15102 | return false; | |||
15103 | } | |||
15104 | ||||
15105 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { | |||
15106 | if (!ULE->getQualifier()) | |||
15107 | return false; | |||
15108 | ||||
15109 | for (NamedDecl *D : ULE->decls()) { | |||
15110 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { | |||
15111 | if (Method->isInstance()) | |||
15112 | return true; | |||
15113 | } else { | |||
15114 | // Overload set does not contain methods. | |||
15115 | break; | |||
15116 | } | |||
15117 | } | |||
15118 | ||||
15119 | return false; | |||
15120 | } | |||
15121 | ||||
15122 | return false; | |||
15123 | } | |||
15124 | ||||
15125 | ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, | |||
15126 | UnaryOperatorKind Opc, Expr *Input) { | |||
15127 | // First things first: handle placeholders so that the | |||
15128 | // overloaded-operator check considers the right type. | |||
15129 | if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { | |||
15130 | // Increment and decrement of pseudo-object references. | |||
15131 | if (pty->getKind() == BuiltinType::PseudoObject && | |||
15132 | UnaryOperator::isIncrementDecrementOp(Opc)) | |||
15133 | return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); | |||
15134 | ||||
15135 | // extension is always a builtin operator. | |||
15136 | if (Opc == UO_Extension) | |||
15137 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | |||
15138 | ||||
15139 | // & gets special logic for several kinds of placeholder. | |||
15140 | // The builtin code knows what to do. | |||
15141 | if (Opc == UO_AddrOf && | |||
15142 | (pty->getKind() == BuiltinType::Overload || | |||
15143 | pty->getKind() == BuiltinType::UnknownAny || | |||
15144 | pty->getKind() == BuiltinType::BoundMember)) | |||
15145 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | |||
15146 | ||||
15147 | // Anything else needs to be handled now. | |||
15148 | ExprResult Result = CheckPlaceholderExpr(Input); | |||
15149 | if (Result.isInvalid()) return ExprError(); | |||
15150 | Input = Result.get(); | |||
15151 | } | |||
15152 | ||||
15153 | if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && | |||
15154 | UnaryOperator::getOverloadedOperator(Opc) != OO_None && | |||
15155 | !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { | |||
15156 | // Find all of the overloaded operators visible from this point. | |||
15157 | UnresolvedSet<16> Functions; | |||
15158 | OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); | |||
15159 | if (S && OverOp != OO_None) | |||
15160 | LookupOverloadedOperatorName(OverOp, S, Functions); | |||
15161 | ||||
15162 | return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); | |||
15163 | } | |||
15164 | ||||
15165 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | |||
15166 | } | |||
15167 | ||||
15168 | // Unary Operators. 'Tok' is the token for the operator. | |||
15169 | ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, | |||
15170 | tok::TokenKind Op, Expr *Input) { | |||
15171 | return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); | |||
15172 | } | |||
15173 | ||||
15174 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". | |||
15175 | ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, | |||
15176 | LabelDecl *TheDecl) { | |||
15177 | TheDecl->markUsed(Context); | |||
15178 | // Create the AST node. The address of a label always has type 'void*'. | |||
15179 | return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, | |||
15180 | Context.getPointerType(Context.VoidTy)); | |||
15181 | } | |||
15182 | ||||
15183 | void Sema::ActOnStartStmtExpr() { | |||
15184 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | |||
15185 | } | |||
15186 | ||||
15187 | void Sema::ActOnStmtExprError() { | |||
15188 | // Note that function is also called by TreeTransform when leaving a | |||
15189 | // StmtExpr scope without rebuilding anything. | |||
15190 | ||||
15191 | DiscardCleanupsInEvaluationContext(); | |||
15192 | PopExpressionEvaluationContext(); | |||
15193 | } | |||
15194 | ||||
15195 | ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, | |||
15196 | SourceLocation RPLoc) { | |||
15197 | return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); | |||
15198 | } | |||
15199 | ||||
15200 | ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, | |||
15201 | SourceLocation RPLoc, unsigned TemplateDepth) { | |||
15202 | assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")(static_cast <bool> (SubStmt && isa<CompoundStmt >(SubStmt) && "Invalid action invocation!") ? void (0) : __assert_fail ("SubStmt && isa<CompoundStmt>(SubStmt) && \"Invalid action invocation!\"" , "clang/lib/Sema/SemaExpr.cpp", 15202, __extension__ __PRETTY_FUNCTION__ )); | |||
15203 | CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); | |||
15204 | ||||
15205 | if (hasAnyUnrecoverableErrorsInThisFunction()) | |||
15206 | DiscardCleanupsInEvaluationContext(); | |||
15207 | assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "clang/lib/Sema/SemaExpr.cpp", 15208, __extension__ __PRETTY_FUNCTION__ )) | |||
15208 | "cleanups within StmtExpr not correctly bound!")(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "clang/lib/Sema/SemaExpr.cpp", 15208, __extension__ __PRETTY_FUNCTION__ )); | |||
15209 | PopExpressionEvaluationContext(); | |||
15210 | ||||
15211 | // FIXME: there are a variety of strange constraints to enforce here, for | |||
15212 | // example, it is not possible to goto into a stmt expression apparently. | |||
15213 | // More semantic analysis is needed. | |||
15214 | ||||
15215 | // If there are sub-stmts in the compound stmt, take the type of the last one | |||
15216 | // as the type of the stmtexpr. | |||
15217 | QualType Ty = Context.VoidTy; | |||
15218 | bool StmtExprMayBindToTemp = false; | |||
15219 | if (!Compound->body_empty()) { | |||
15220 | // For GCC compatibility we get the last Stmt excluding trailing NullStmts. | |||
15221 | if (const auto *LastStmt = | |||
15222 | dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { | |||
15223 | if (const Expr *Value = LastStmt->getExprStmt()) { | |||
15224 | StmtExprMayBindToTemp = true; | |||
15225 | Ty = Value->getType(); | |||
15226 | } | |||
15227 | } | |||
15228 | } | |||
15229 | ||||
15230 | // FIXME: Check that expression type is complete/non-abstract; statement | |||
15231 | // expressions are not lvalues. | |||
15232 | Expr *ResStmtExpr = | |||
15233 | new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); | |||
15234 | if (StmtExprMayBindToTemp) | |||
15235 | return MaybeBindToTemporary(ResStmtExpr); | |||
15236 | return ResStmtExpr; | |||
15237 | } | |||
15238 | ||||
15239 | ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { | |||
15240 | if (ER.isInvalid()) | |||
15241 | return ExprError(); | |||
15242 | ||||
15243 | // Do function/array conversion on the last expression, but not | |||
15244 | // lvalue-to-rvalue. However, initialize an unqualified type. | |||
15245 | ER = DefaultFunctionArrayConversion(ER.get()); | |||
15246 | if (ER.isInvalid()) | |||
15247 | return ExprError(); | |||
15248 | Expr *E = ER.get(); | |||
15249 | ||||
15250 | if (E->isTypeDependent()) | |||
15251 | return E; | |||
15252 | ||||
15253 | // In ARC, if the final expression ends in a consume, splice | |||
15254 | // the consume out and bind it later. In the alternate case | |||
15255 | // (when dealing with a retainable type), the result | |||
15256 | // initialization will create a produce. In both cases the | |||
15257 | // result will be +1, and we'll need to balance that out with | |||
15258 | // a bind. | |||
15259 | auto *Cast = dyn_cast<ImplicitCastExpr>(E); | |||
15260 | if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) | |||
15261 | return Cast->getSubExpr(); | |||
15262 | ||||
15263 | // FIXME: Provide a better location for the initialization. | |||
15264 | return PerformCopyInitialization( | |||
15265 | InitializedEntity::InitializeStmtExprResult( | |||
15266 | E->getBeginLoc(), E->getType().getUnqualifiedType()), | |||
15267 | SourceLocation(), E); | |||
15268 | } | |||
15269 | ||||
15270 | ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, | |||
15271 | TypeSourceInfo *TInfo, | |||
15272 | ArrayRef<OffsetOfComponent> Components, | |||
15273 | SourceLocation RParenLoc) { | |||
15274 | QualType ArgTy = TInfo->getType(); | |||
15275 | bool Dependent = ArgTy->isDependentType(); | |||
15276 | SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); | |||
15277 | ||||
15278 | // We must have at least one component that refers to the type, and the first | |||
15279 | // one is known to be a field designator. Verify that the ArgTy represents | |||
15280 | // a struct/union/class. | |||
15281 | if (!Dependent && !ArgTy->isRecordType()) | |||
15282 | return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) | |||
15283 | << ArgTy << TypeRange); | |||
15284 | ||||
15285 | // Type must be complete per C99 7.17p3 because a declaring a variable | |||
15286 | // with an incomplete type would be ill-formed. | |||
15287 | if (!Dependent | |||
15288 | && RequireCompleteType(BuiltinLoc, ArgTy, | |||
15289 | diag::err_offsetof_incomplete_type, TypeRange)) | |||
15290 | return ExprError(); | |||
15291 | ||||
15292 | bool DidWarnAboutNonPOD = false; | |||
15293 | QualType CurrentType = ArgTy; | |||
15294 | SmallVector<OffsetOfNode, 4> Comps; | |||
15295 | SmallVector<Expr*, 4> Exprs; | |||
15296 | for (const OffsetOfComponent &OC : Components) { | |||
15297 | if (OC.isBrackets) { | |||
15298 | // Offset of an array sub-field. TODO: Should we allow vector elements? | |||
15299 | if (!CurrentType->isDependentType()) { | |||
15300 | const ArrayType *AT = Context.getAsArrayType(CurrentType); | |||
15301 | if(!AT) | |||
15302 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) | |||
15303 | << CurrentType); | |||
15304 | CurrentType = AT->getElementType(); | |||
15305 | } else | |||
15306 | CurrentType = Context.DependentTy; | |||
15307 | ||||
15308 | ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); | |||
15309 | if (IdxRval.isInvalid()) | |||
15310 | return ExprError(); | |||
15311 | Expr *Idx = IdxRval.get(); | |||
15312 | ||||
15313 | // The expression must be an integral expression. | |||
15314 | // FIXME: An integral constant expression? | |||
15315 | if (!Idx->isTypeDependent() && !Idx->isValueDependent() && | |||
15316 | !Idx->getType()->isIntegerType()) | |||
15317 | return ExprError( | |||
15318 | Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) | |||
15319 | << Idx->getSourceRange()); | |||
15320 | ||||
15321 | // Record this array index. | |||
15322 | Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); | |||
15323 | Exprs.push_back(Idx); | |||
15324 | continue; | |||
15325 | } | |||
15326 | ||||
15327 | // Offset of a field. | |||
15328 | if (CurrentType->isDependentType()) { | |||
15329 | // We have the offset of a field, but we can't look into the dependent | |||
15330 | // type. Just record the identifier of the field. | |||
15331 | Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); | |||
15332 | CurrentType = Context.DependentTy; | |||
15333 | continue; | |||
15334 | } | |||
15335 | ||||
15336 | // We need to have a complete type to look into. | |||
15337 | if (RequireCompleteType(OC.LocStart, CurrentType, | |||
15338 | diag::err_offsetof_incomplete_type)) | |||
15339 | return ExprError(); | |||
15340 | ||||
15341 | // Look for the designated field. | |||
15342 | const RecordType *RC = CurrentType->getAs<RecordType>(); | |||
15343 | if (!RC) | |||
15344 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) | |||
15345 | << CurrentType); | |||
15346 | RecordDecl *RD = RC->getDecl(); | |||
15347 | ||||
15348 | // C++ [lib.support.types]p5: | |||
15349 | // The macro offsetof accepts a restricted set of type arguments in this | |||
15350 | // International Standard. type shall be a POD structure or a POD union | |||
15351 | // (clause 9). | |||
15352 | // C++11 [support.types]p4: | |||
15353 | // If type is not a standard-layout class (Clause 9), the results are | |||
15354 | // undefined. | |||
15355 | if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { | |||
15356 | bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); | |||
15357 | unsigned DiagID = | |||
15358 | LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type | |||
15359 | : diag::ext_offsetof_non_pod_type; | |||
15360 | ||||
15361 | if (!IsSafe && !DidWarnAboutNonPOD && | |||
15362 | DiagRuntimeBehavior(BuiltinLoc, nullptr, | |||
15363 | PDiag(DiagID) | |||
15364 | << SourceRange(Components[0].LocStart, OC.LocEnd) | |||
15365 | << CurrentType)) | |||
15366 | DidWarnAboutNonPOD = true; | |||
15367 | } | |||
15368 | ||||
15369 | // Look for the field. | |||
15370 | LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); | |||
15371 | LookupQualifiedName(R, RD); | |||
15372 | FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); | |||
15373 | IndirectFieldDecl *IndirectMemberDecl = nullptr; | |||
15374 | if (!MemberDecl) { | |||
15375 | if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) | |||
15376 | MemberDecl = IndirectMemberDecl->getAnonField(); | |||
15377 | } | |||
15378 | ||||
15379 | if (!MemberDecl) | |||
15380 | return ExprError(Diag(BuiltinLoc, diag::err_no_member) | |||
15381 | << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, | |||
15382 | OC.LocEnd)); | |||
15383 | ||||
15384 | // C99 7.17p3: | |||
15385 | // (If the specified member is a bit-field, the behavior is undefined.) | |||
15386 | // | |||
15387 | // We diagnose this as an error. | |||
15388 | if (MemberDecl->isBitField()) { | |||
15389 | Diag(OC.LocEnd, diag::err_offsetof_bitfield) | |||
15390 | << MemberDecl->getDeclName() | |||
15391 | << SourceRange(BuiltinLoc, RParenLoc); | |||
15392 | Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); | |||
15393 | return ExprError(); | |||
15394 | } | |||
15395 | ||||
15396 | RecordDecl *Parent = MemberDecl->getParent(); | |||
15397 | if (IndirectMemberDecl) | |||
15398 | Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); | |||
15399 | ||||
15400 | // If the member was found in a base class, introduce OffsetOfNodes for | |||
15401 | // the base class indirections. | |||
15402 | CXXBasePaths Paths; | |||
15403 | if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), | |||
15404 | Paths)) { | |||
15405 | if (Paths.getDetectedVirtual()) { | |||
15406 | Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) | |||
15407 | << MemberDecl->getDeclName() | |||
15408 | << SourceRange(BuiltinLoc, RParenLoc); | |||
15409 | return ExprError(); | |||
15410 | } | |||
15411 | ||||
15412 | CXXBasePath &Path = Paths.front(); | |||
15413 | for (const CXXBasePathElement &B : Path) | |||
15414 | Comps.push_back(OffsetOfNode(B.Base)); | |||
15415 | } | |||
15416 | ||||
15417 | if (IndirectMemberDecl) { | |||
15418 | for (auto *FI : IndirectMemberDecl->chain()) { | |||
15419 | assert(isa<FieldDecl>(FI))(static_cast <bool> (isa<FieldDecl>(FI)) ? void ( 0) : __assert_fail ("isa<FieldDecl>(FI)", "clang/lib/Sema/SemaExpr.cpp" , 15419, __extension__ __PRETTY_FUNCTION__)); | |||
15420 | Comps.push_back(OffsetOfNode(OC.LocStart, | |||
15421 | cast<FieldDecl>(FI), OC.LocEnd)); | |||
15422 | } | |||
15423 | } else | |||
15424 | Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); | |||
15425 | ||||
15426 | CurrentType = MemberDecl->getType().getNonReferenceType(); | |||
15427 | } | |||
15428 | ||||
15429 | return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, | |||
15430 | Comps, Exprs, RParenLoc); | |||
15431 | } | |||
15432 | ||||
15433 | ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, | |||
15434 | SourceLocation BuiltinLoc, | |||
15435 | SourceLocation TypeLoc, | |||
15436 | ParsedType ParsedArgTy, | |||
15437 | ArrayRef<OffsetOfComponent> Components, | |||
15438 | SourceLocation RParenLoc) { | |||
15439 | ||||
15440 | TypeSourceInfo *ArgTInfo; | |||
15441 | QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); | |||
15442 | if (ArgTy.isNull()) | |||
15443 | return ExprError(); | |||
15444 | ||||
15445 | if (!ArgTInfo) | |||
15446 | ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); | |||
15447 | ||||
15448 | return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); | |||
15449 | } | |||
15450 | ||||
15451 | ||||
15452 | ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, | |||
15453 | Expr *CondExpr, | |||
15454 | Expr *LHSExpr, Expr *RHSExpr, | |||
15455 | SourceLocation RPLoc) { | |||
15456 | assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(static_cast <bool> ((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)") ? void (0) : __assert_fail ("(CondExpr && LHSExpr && RHSExpr) && \"Missing type argument(s)\"" , "clang/lib/Sema/SemaExpr.cpp", 15456, __extension__ __PRETTY_FUNCTION__ )); | |||
15457 | ||||
15458 | ExprValueKind VK = VK_PRValue; | |||
15459 | ExprObjectKind OK = OK_Ordinary; | |||
15460 | QualType resType; | |||
15461 | bool CondIsTrue = false; | |||
15462 | if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { | |||
15463 | resType = Context.DependentTy; | |||
15464 | } else { | |||
15465 | // The conditional expression is required to be a constant expression. | |||
15466 | llvm::APSInt condEval(32); | |||
15467 | ExprResult CondICE = VerifyIntegerConstantExpression( | |||
15468 | CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); | |||
15469 | if (CondICE.isInvalid()) | |||
15470 | return ExprError(); | |||
15471 | CondExpr = CondICE.get(); | |||
15472 | CondIsTrue = condEval.getZExtValue(); | |||
15473 | ||||
15474 | // If the condition is > zero, then the AST type is the same as the LHSExpr. | |||
15475 | Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; | |||
15476 | ||||
15477 | resType = ActiveExpr->getType(); | |||
15478 | VK = ActiveExpr->getValueKind(); | |||
15479 | OK = ActiveExpr->getObjectKind(); | |||
15480 | } | |||
15481 | ||||
15482 | return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, | |||
15483 | resType, VK, OK, RPLoc, CondIsTrue); | |||
15484 | } | |||
15485 | ||||
15486 | //===----------------------------------------------------------------------===// | |||
15487 | // Clang Extensions. | |||
15488 | //===----------------------------------------------------------------------===// | |||
15489 | ||||
15490 | /// ActOnBlockStart - This callback is invoked when a block literal is started. | |||
15491 | void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { | |||
15492 | BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); | |||
15493 | ||||
15494 | if (LangOpts.CPlusPlus) { | |||
15495 | MangleNumberingContext *MCtx; | |||
15496 | Decl *ManglingContextDecl; | |||
15497 | std::tie(MCtx, ManglingContextDecl) = | |||
15498 | getCurrentMangleNumberContext(Block->getDeclContext()); | |||
15499 | if (MCtx) { | |||
15500 | unsigned ManglingNumber = MCtx->getManglingNumber(Block); | |||
15501 | Block->setBlockMangling(ManglingNumber, ManglingContextDecl); | |||
15502 | } | |||
15503 | } | |||
15504 | ||||
15505 | PushBlockScope(CurScope, Block); | |||
15506 | CurContext->addDecl(Block); | |||
15507 | if (CurScope) | |||
15508 | PushDeclContext(CurScope, Block); | |||
15509 | else | |||
15510 | CurContext = Block; | |||
15511 | ||||
15512 | getCurBlock()->HasImplicitReturnType = true; | |||
15513 | ||||
15514 | // Enter a new evaluation context to insulate the block from any | |||
15515 | // cleanups from the enclosing full-expression. | |||
15516 | PushExpressionEvaluationContext( | |||
15517 | ExpressionEvaluationContext::PotentiallyEvaluated); | |||
15518 | } | |||
15519 | ||||
15520 | void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, | |||
15521 | Scope *CurScope) { | |||
15522 | assert(ParamInfo.getIdentifier() == nullptr &&(static_cast <bool> (ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!") ? void (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "clang/lib/Sema/SemaExpr.cpp", 15523, __extension__ __PRETTY_FUNCTION__ )) | |||
15523 | "block-id should have no identifier!")(static_cast <bool> (ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!") ? void (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "clang/lib/Sema/SemaExpr.cpp", 15523, __extension__ __PRETTY_FUNCTION__ )); | |||
15524 | assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral)(static_cast <bool> (ParamInfo.getContext() == DeclaratorContext ::BlockLiteral) ? void (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteral" , "clang/lib/Sema/SemaExpr.cpp", 15524, __extension__ __PRETTY_FUNCTION__ )); | |||
15525 | BlockScopeInfo *CurBlock = getCurBlock(); | |||
15526 | ||||
15527 | TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); | |||
15528 | QualType T = Sig->getType(); | |||
15529 | ||||
15530 | // FIXME: We should allow unexpanded parameter packs here, but that would, | |||
15531 | // in turn, make the block expression contain unexpanded parameter packs. | |||
15532 | if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { | |||
15533 | // Drop the parameters. | |||
15534 | FunctionProtoType::ExtProtoInfo EPI; | |||
15535 | EPI.HasTrailingReturn = false; | |||
15536 | EPI.TypeQuals.addConst(); | |||
15537 | T = Context.getFunctionType(Context.DependentTy, None, EPI); | |||
15538 | Sig = Context.getTrivialTypeSourceInfo(T); | |||
15539 | } | |||
15540 | ||||
15541 | // GetTypeForDeclarator always produces a function type for a block | |||
15542 | // literal signature. Furthermore, it is always a FunctionProtoType | |||
15543 | // unless the function was written with a typedef. | |||
15544 | assert(T->isFunctionType() &&(static_cast <bool> (T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? void (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "clang/lib/Sema/SemaExpr.cpp", 15545, __extension__ __PRETTY_FUNCTION__ )) | |||
15545 | "GetTypeForDeclarator made a non-function block signature")(static_cast <bool> (T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? void (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "clang/lib/Sema/SemaExpr.cpp", 15545, __extension__ __PRETTY_FUNCTION__ )); | |||
15546 | ||||
15547 | // Look for an explicit signature in that function type. | |||
15548 | FunctionProtoTypeLoc ExplicitSignature; | |||
15549 | ||||
15550 | if ((ExplicitSignature = Sig->getTypeLoc() | |||
15551 | .getAsAdjusted<FunctionProtoTypeLoc>())) { | |||
15552 | ||||
15553 | // Check whether that explicit signature was synthesized by | |||
15554 | // GetTypeForDeclarator. If so, don't save that as part of the | |||
15555 | // written signature. | |||
15556 | if (ExplicitSignature.getLocalRangeBegin() == | |||
15557 | ExplicitSignature.getLocalRangeEnd()) { | |||
15558 | // This would be much cheaper if we stored TypeLocs instead of | |||
15559 | // TypeSourceInfos. | |||
15560 | TypeLoc Result = ExplicitSignature.getReturnLoc(); | |||
15561 | unsigned Size = Result.getFullDataSize(); | |||
15562 | Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); | |||
15563 | Sig->getTypeLoc().initializeFullCopy(Result, Size); | |||
15564 | ||||
15565 | ExplicitSignature = FunctionProtoTypeLoc(); | |||
15566 | } | |||
15567 | } | |||
15568 | ||||
15569 | CurBlock->TheDecl->setSignatureAsWritten(Sig); | |||
15570 | CurBlock->FunctionType = T; | |||
15571 | ||||
15572 | const auto *Fn = T->castAs<FunctionType>(); | |||
15573 | QualType RetTy = Fn->getReturnType(); | |||
15574 | bool isVariadic = | |||
15575 | (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); | |||
15576 | ||||
15577 | CurBlock->TheDecl->setIsVariadic(isVariadic); | |||
15578 | ||||
15579 | // Context.DependentTy is used as a placeholder for a missing block | |||
15580 | // return type. TODO: what should we do with declarators like: | |||
15581 | // ^ * { ... } | |||
15582 | // If the answer is "apply template argument deduction".... | |||
15583 | if (RetTy != Context.DependentTy) { | |||
15584 | CurBlock->ReturnType = RetTy; | |||
15585 | CurBlock->TheDecl->setBlockMissingReturnType(false); | |||
15586 | CurBlock->HasImplicitReturnType = false; | |||
15587 | } | |||
15588 | ||||
15589 | // Push block parameters from the declarator if we had them. | |||
15590 | SmallVector<ParmVarDecl*, 8> Params; | |||
15591 | if (ExplicitSignature) { | |||
15592 | for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { | |||
15593 | ParmVarDecl *Param = ExplicitSignature.getParam(I); | |||
15594 | if (Param->getIdentifier() == nullptr && !Param->isImplicit() && | |||
15595 | !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { | |||
15596 | // Diagnose this as an extension in C17 and earlier. | |||
15597 | if (!getLangOpts().C2x) | |||
15598 | Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); | |||
15599 | } | |||
15600 | Params.push_back(Param); | |||
15601 | } | |||
15602 | ||||
15603 | // Fake up parameter variables if we have a typedef, like | |||
15604 | // ^ fntype { ... } | |||
15605 | } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { | |||
15606 | for (const auto &I : Fn->param_types()) { | |||
15607 | ParmVarDecl *Param = BuildParmVarDeclForTypedef( | |||
15608 | CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); | |||
15609 | Params.push_back(Param); | |||
15610 | } | |||
15611 | } | |||
15612 | ||||
15613 | // Set the parameters on the block decl. | |||
15614 | if (!Params.empty()) { | |||
15615 | CurBlock->TheDecl->setParams(Params); | |||
15616 | CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), | |||
15617 | /*CheckParameterNames=*/false); | |||
15618 | } | |||
15619 | ||||
15620 | // Finally we can process decl attributes. | |||
15621 | ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); | |||
15622 | ||||
15623 | // Put the parameter variables in scope. | |||
15624 | for (auto AI : CurBlock->TheDecl->parameters()) { | |||
15625 | AI->setOwningFunction(CurBlock->TheDecl); | |||
15626 | ||||
15627 | // If this has an identifier, add it to the scope stack. | |||
15628 | if (AI->getIdentifier()) { | |||
15629 | CheckShadow(CurBlock->TheScope, AI); | |||
15630 | ||||
15631 | PushOnScopeChains(AI, CurBlock->TheScope); | |||
15632 | } | |||
15633 | } | |||
15634 | } | |||
15635 | ||||
15636 | /// ActOnBlockError - If there is an error parsing a block, this callback | |||
15637 | /// is invoked to pop the information about the block from the action impl. | |||
15638 | void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { | |||
15639 | // Leave the expression-evaluation context. | |||
15640 | DiscardCleanupsInEvaluationContext(); | |||
15641 | PopExpressionEvaluationContext(); | |||
15642 | ||||
15643 | // Pop off CurBlock, handle nested blocks. | |||
15644 | PopDeclContext(); | |||
15645 | PopFunctionScopeInfo(); | |||
15646 | } | |||
15647 | ||||
15648 | /// ActOnBlockStmtExpr - This is called when the body of a block statement | |||
15649 | /// literal was successfully completed. ^(int x){...} | |||
15650 | ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, | |||
15651 | Stmt *Body, Scope *CurScope) { | |||
15652 | // If blocks are disabled, emit an error. | |||
15653 | if (!LangOpts.Blocks) | |||
15654 | Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; | |||
15655 | ||||
15656 | // Leave the expression-evaluation context. | |||
15657 | if (hasAnyUnrecoverableErrorsInThisFunction()) | |||
15658 | DiscardCleanupsInEvaluationContext(); | |||
15659 | assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "clang/lib/Sema/SemaExpr.cpp", 15660, __extension__ __PRETTY_FUNCTION__ )) | |||
15660 | "cleanups within block not correctly bound!")(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "clang/lib/Sema/SemaExpr.cpp", 15660, __extension__ __PRETTY_FUNCTION__ )); | |||
15661 | PopExpressionEvaluationContext(); | |||
15662 | ||||
15663 | BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); | |||
15664 | BlockDecl *BD = BSI->TheDecl; | |||
15665 | ||||
15666 | if (BSI->HasImplicitReturnType) | |||
15667 | deduceClosureReturnType(*BSI); | |||
15668 | ||||
15669 | QualType RetTy = Context.VoidTy; | |||
15670 | if (!BSI->ReturnType.isNull()) | |||
15671 | RetTy = BSI->ReturnType; | |||
15672 | ||||
15673 | bool NoReturn = BD->hasAttr<NoReturnAttr>(); | |||
15674 | QualType BlockTy; | |||
15675 | ||||
15676 | // If the user wrote a function type in some form, try to use that. | |||
15677 | if (!BSI->FunctionType.isNull()) { | |||
15678 | const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); | |||
15679 | ||||
15680 | FunctionType::ExtInfo Ext = FTy->getExtInfo(); | |||
15681 | if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); | |||
15682 | ||||
15683 | // Turn protoless block types into nullary block types. | |||
15684 | if (isa<FunctionNoProtoType>(FTy)) { | |||
15685 | FunctionProtoType::ExtProtoInfo EPI; | |||
15686 | EPI.ExtInfo = Ext; | |||
15687 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | |||
15688 | ||||
15689 | // Otherwise, if we don't need to change anything about the function type, | |||
15690 | // preserve its sugar structure. | |||
15691 | } else if (FTy->getReturnType() == RetTy && | |||
15692 | (!NoReturn || FTy->getNoReturnAttr())) { | |||
15693 | BlockTy = BSI->FunctionType; | |||
15694 | ||||
15695 | // Otherwise, make the minimal modifications to the function type. | |||
15696 | } else { | |||
15697 | const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); | |||
15698 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | |||
15699 | EPI.TypeQuals = Qualifiers(); | |||
15700 | EPI.ExtInfo = Ext; | |||
15701 | BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); | |||
15702 | } | |||
15703 | ||||
15704 | // If we don't have a function type, just build one from nothing. | |||
15705 | } else { | |||
15706 | FunctionProtoType::ExtProtoInfo EPI; | |||
15707 | EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); | |||
15708 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | |||
15709 | } | |||
15710 | ||||
15711 | DiagnoseUnusedParameters(BD->parameters()); | |||
15712 | BlockTy = Context.getBlockPointerType(BlockTy); | |||
15713 | ||||
15714 | // If needed, diagnose invalid gotos and switches in the block. | |||
15715 | if (getCurFunction()->NeedsScopeChecking() && | |||
15716 | !PP.isCodeCompletionEnabled()) | |||
15717 | DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); | |||
15718 | ||||
15719 | BD->setBody(cast<CompoundStmt>(Body)); | |||
15720 | ||||
15721 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | |||
15722 | DiagnoseUnguardedAvailabilityViolations(BD); | |||
15723 | ||||
15724 | // Try to apply the named return value optimization. We have to check again | |||
15725 | // if we can do this, though, because blocks keep return statements around | |||
15726 | // to deduce an implicit return type. | |||
15727 | if (getLangOpts().CPlusPlus && RetTy->isRecordType() && | |||
15728 | !BD->isDependentContext()) | |||
15729 | computeNRVO(Body, BSI); | |||
15730 | ||||
15731 | if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || | |||
15732 | RetTy.hasNonTrivialToPrimitiveCopyCUnion()) | |||
15733 | checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, | |||
15734 | NTCUK_Destruct|NTCUK_Copy); | |||
15735 | ||||
15736 | PopDeclContext(); | |||
15737 | ||||
15738 | // Set the captured variables on the block. | |||
15739 | SmallVector<BlockDecl::Capture, 4> Captures; | |||
15740 | for (Capture &Cap : BSI->Captures) { | |||
15741 | if (Cap.isInvalid() || Cap.isThisCapture()) | |||
15742 | continue; | |||
15743 | ||||
15744 | VarDecl *Var = Cap.getVariable(); | |||
15745 | Expr *CopyExpr = nullptr; | |||
15746 | if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { | |||
15747 | if (const RecordType *Record = | |||
15748 | Cap.getCaptureType()->getAs<RecordType>()) { | |||
15749 | // The capture logic needs the destructor, so make sure we mark it. | |||
15750 | // Usually this is unnecessary because most local variables have | |||
15751 | // their destructors marked at declaration time, but parameters are | |||
15752 | // an exception because it's technically only the call site that | |||
15753 | // actually requires the destructor. | |||
15754 | if (isa<ParmVarDecl>(Var)) | |||
15755 | FinalizeVarWithDestructor(Var, Record); | |||
15756 | ||||
15757 | // Enter a separate potentially-evaluated context while building block | |||
15758 | // initializers to isolate their cleanups from those of the block | |||
15759 | // itself. | |||
15760 | // FIXME: Is this appropriate even when the block itself occurs in an | |||
15761 | // unevaluated operand? | |||
15762 | EnterExpressionEvaluationContext EvalContext( | |||
15763 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); | |||
15764 | ||||
15765 | SourceLocation Loc = Cap.getLocation(); | |||
15766 | ||||
15767 | ExprResult Result = BuildDeclarationNameExpr( | |||
15768 | CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); | |||
15769 | ||||
15770 | // According to the blocks spec, the capture of a variable from | |||
15771 | // the stack requires a const copy constructor. This is not true | |||
15772 | // of the copy/move done to move a __block variable to the heap. | |||
15773 | if (!Result.isInvalid() && | |||
15774 | !Result.get()->getType().isConstQualified()) { | |||
15775 | Result = ImpCastExprToType(Result.get(), | |||
15776 | Result.get()->getType().withConst(), | |||
15777 | CK_NoOp, VK_LValue); | |||
15778 | } | |||
15779 | ||||
15780 | if (!Result.isInvalid()) { | |||
15781 | Result = PerformCopyInitialization( | |||
15782 | InitializedEntity::InitializeBlock(Var->getLocation(), | |||
15783 | Cap.getCaptureType()), | |||
15784 | Loc, Result.get()); | |||
15785 | } | |||
15786 | ||||
15787 | // Build a full-expression copy expression if initialization | |||
15788 | // succeeded and used a non-trivial constructor. Recover from | |||
15789 | // errors by pretending that the copy isn't necessary. | |||
15790 | if (!Result.isInvalid() && | |||
15791 | !cast<CXXConstructExpr>(Result.get())->getConstructor() | |||
15792 | ->isTrivial()) { | |||
15793 | Result = MaybeCreateExprWithCleanups(Result); | |||
15794 | CopyExpr = Result.get(); | |||
15795 | } | |||
15796 | } | |||
15797 | } | |||
15798 | ||||
15799 | BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), | |||
15800 | CopyExpr); | |||
15801 | Captures.push_back(NewCap); | |||
15802 | } | |||
15803 | BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); | |||
15804 | ||||
15805 | // Pop the block scope now but keep it alive to the end of this function. | |||
15806 | AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | |||
15807 | PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); | |||
15808 | ||||
15809 | BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); | |||
15810 | ||||
15811 | // If the block isn't obviously global, i.e. it captures anything at | |||
15812 | // all, then we need to do a few things in the surrounding context: | |||
15813 | if (Result->getBlockDecl()->hasCaptures()) { | |||
15814 | // First, this expression has a new cleanup object. | |||
15815 | ExprCleanupObjects.push_back(Result->getBlockDecl()); | |||
15816 | Cleanup.setExprNeedsCleanups(true); | |||
15817 | ||||
15818 | // It also gets a branch-protected scope if any of the captured | |||
15819 | // variables needs destruction. | |||
15820 | for (const auto &CI : Result->getBlockDecl()->captures()) { | |||
15821 | const VarDecl *var = CI.getVariable(); | |||
15822 | if (var->getType().isDestructedType() != QualType::DK_none) { | |||
15823 | setFunctionHasBranchProtectedScope(); | |||
15824 | break; | |||
15825 | } | |||
15826 | } | |||
15827 | } | |||
15828 | ||||
15829 | if (getCurFunction()) | |||
15830 | getCurFunction()->addBlock(BD); | |||
15831 | ||||
15832 | return Result; | |||
15833 | } | |||
15834 | ||||
15835 | ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, | |||
15836 | SourceLocation RPLoc) { | |||
15837 | TypeSourceInfo *TInfo; | |||
15838 | GetTypeFromParser(Ty, &TInfo); | |||
15839 | return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); | |||
15840 | } | |||
15841 | ||||
15842 | ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, | |||
15843 | Expr *E, TypeSourceInfo *TInfo, | |||
15844 | SourceLocation RPLoc) { | |||
15845 | Expr *OrigExpr = E; | |||
15846 | bool IsMS = false; | |||
15847 | ||||
15848 | // CUDA device code does not support varargs. | |||
15849 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { | |||
15850 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { | |||
15851 | CUDAFunctionTarget T = IdentifyCUDATarget(F); | |||
15852 | if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) | |||
15853 | return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); | |||
15854 | } | |||
15855 | } | |||
15856 | ||||
15857 | // NVPTX does not support va_arg expression. | |||
15858 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && | |||
15859 | Context.getTargetInfo().getTriple().isNVPTX()) | |||
15860 | targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); | |||
15861 | ||||
15862 | // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() | |||
15863 | // as Microsoft ABI on an actual Microsoft platform, where | |||
15864 | // __builtin_ms_va_list and __builtin_va_list are the same.) | |||
15865 | if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && | |||
15866 | Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { | |||
15867 | QualType MSVaListType = Context.getBuiltinMSVaListType(); | |||
15868 | if (Context.hasSameType(MSVaListType, E->getType())) { | |||
15869 | if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) | |||
15870 | return ExprError(); | |||
15871 | IsMS = true; | |||
15872 | } | |||
15873 | } | |||
15874 | ||||
15875 | // Get the va_list type | |||
15876 | QualType VaListType = Context.getBuiltinVaListType(); | |||
15877 | if (!IsMS) { | |||
15878 | if (VaListType->isArrayType()) { | |||
15879 | // Deal with implicit array decay; for example, on x86-64, | |||
15880 | // va_list is an array, but it's supposed to decay to | |||
15881 | // a pointer for va_arg. | |||
15882 | VaListType = Context.getArrayDecayedType(VaListType); | |||
15883 | // Make sure the input expression also decays appropriately. | |||
15884 | ExprResult Result = UsualUnaryConversions(E); | |||
15885 | if (Result.isInvalid()) | |||
15886 | return ExprError(); | |||
15887 | E = Result.get(); | |||
15888 | } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { | |||
15889 | // If va_list is a record type and we are compiling in C++ mode, | |||
15890 | // check the argument using reference binding. | |||
15891 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | |||
15892 | Context, Context.getLValueReferenceType(VaListType), false); | |||
15893 | ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); | |||
15894 | if (Init.isInvalid()) | |||
15895 | return ExprError(); | |||
15896 | E = Init.getAs<Expr>(); | |||
15897 | } else { | |||
15898 | // Otherwise, the va_list argument must be an l-value because | |||
15899 | // it is modified by va_arg. | |||
15900 | if (!E->isTypeDependent() && | |||
15901 | CheckForModifiableLvalue(E, BuiltinLoc, *this)) | |||
15902 | return ExprError(); | |||
15903 | } | |||
15904 | } | |||
15905 | ||||
15906 | if (!IsMS && !E->isTypeDependent() && | |||
15907 | !Context.hasSameType(VaListType, E->getType())) | |||
15908 | return ExprError( | |||
15909 | Diag(E->getBeginLoc(), | |||
15910 | diag::err_first_argument_to_va_arg_not_of_type_va_list) | |||
15911 | << OrigExpr->getType() << E->getSourceRange()); | |||
15912 | ||||
15913 | if (!TInfo->getType()->isDependentType()) { | |||
15914 | if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), | |||
15915 | diag::err_second_parameter_to_va_arg_incomplete, | |||
15916 | TInfo->getTypeLoc())) | |||
15917 | return ExprError(); | |||
15918 | ||||
15919 | if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), | |||
15920 | TInfo->getType(), | |||
15921 | diag::err_second_parameter_to_va_arg_abstract, | |||
15922 | TInfo->getTypeLoc())) | |||
15923 | return ExprError(); | |||
15924 | ||||
15925 | if (!TInfo->getType().isPODType(Context)) { | |||
15926 | Diag(TInfo->getTypeLoc().getBeginLoc(), | |||
15927 | TInfo->getType()->isObjCLifetimeType() | |||
15928 | ? diag::warn_second_parameter_to_va_arg_ownership_qualified | |||
15929 | : diag::warn_second_parameter_to_va_arg_not_pod) | |||
15930 | << TInfo->getType() | |||
15931 | << TInfo->getTypeLoc().getSourceRange(); | |||
15932 | } | |||
15933 | ||||
15934 | // Check for va_arg where arguments of the given type will be promoted | |||
15935 | // (i.e. this va_arg is guaranteed to have undefined behavior). | |||
15936 | QualType PromoteType; | |||
15937 | if (TInfo->getType()->isPromotableIntegerType()) { | |||
15938 | PromoteType = Context.getPromotedIntegerType(TInfo->getType()); | |||
15939 | // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, | |||
15940 | // and C2x 7.16.1.1p2 says, in part: | |||
15941 | // If type is not compatible with the type of the actual next argument | |||
15942 | // (as promoted according to the default argument promotions), the | |||
15943 | // behavior is undefined, except for the following cases: | |||
15944 | // - both types are pointers to qualified or unqualified versions of | |||
15945 | // compatible types; | |||
15946 | // - one type is a signed integer type, the other type is the | |||
15947 | // corresponding unsigned integer type, and the value is | |||
15948 | // representable in both types; | |||
15949 | // - one type is pointer to qualified or unqualified void and the | |||
15950 | // other is a pointer to a qualified or unqualified character type. | |||
15951 | // Given that type compatibility is the primary requirement (ignoring | |||
15952 | // qualifications), you would think we could call typesAreCompatible() | |||
15953 | // directly to test this. However, in C++, that checks for *same type*, | |||
15954 | // which causes false positives when passing an enumeration type to | |||
15955 | // va_arg. Instead, get the underlying type of the enumeration and pass | |||
15956 | // that. | |||
15957 | QualType UnderlyingType = TInfo->getType(); | |||
15958 | if (const auto *ET = UnderlyingType->getAs<EnumType>()) | |||
15959 | UnderlyingType = ET->getDecl()->getIntegerType(); | |||
15960 | if (Context.typesAreCompatible(PromoteType, UnderlyingType, | |||
15961 | /*CompareUnqualified*/ true)) | |||
15962 | PromoteType = QualType(); | |||
15963 | ||||
15964 | // If the types are still not compatible, we need to test whether the | |||
15965 | // promoted type and the underlying type are the same except for | |||
15966 | // signedness. Ask the AST for the correctly corresponding type and see | |||
15967 | // if that's compatible. | |||
15968 | if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && | |||
15969 | PromoteType->isUnsignedIntegerType() != | |||
15970 | UnderlyingType->isUnsignedIntegerType()) { | |||
15971 | UnderlyingType = | |||
15972 | UnderlyingType->isUnsignedIntegerType() | |||
15973 | ? Context.getCorrespondingSignedType(UnderlyingType) | |||
15974 | : Context.getCorrespondingUnsignedType(UnderlyingType); | |||
15975 | if (Context.typesAreCompatible(PromoteType, UnderlyingType, | |||
15976 | /*CompareUnqualified*/ true)) | |||
15977 | PromoteType = QualType(); | |||
15978 | } | |||
15979 | } | |||
15980 | if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) | |||
15981 | PromoteType = Context.DoubleTy; | |||
15982 | if (!PromoteType.isNull()) | |||
15983 | DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, | |||
15984 | PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) | |||
15985 | << TInfo->getType() | |||
15986 | << PromoteType | |||
15987 | << TInfo->getTypeLoc().getSourceRange()); | |||
15988 | } | |||
15989 | ||||
15990 | QualType T = TInfo->getType().getNonLValueExprType(Context); | |||
15991 | return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); | |||
15992 | } | |||
15993 | ||||
15994 | ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { | |||
15995 | // The type of __null will be int or long, depending on the size of | |||
15996 | // pointers on the target. | |||
15997 | QualType Ty; | |||
15998 | unsigned pw = Context.getTargetInfo().getPointerWidth(0); | |||
15999 | if (pw == Context.getTargetInfo().getIntWidth()) | |||
16000 | Ty = Context.IntTy; | |||
16001 | else if (pw == Context.getTargetInfo().getLongWidth()) | |||
16002 | Ty = Context.LongTy; | |||
16003 | else if (pw == Context.getTargetInfo().getLongLongWidth()) | |||
16004 | Ty = Context.LongLongTy; | |||
16005 | else { | |||
16006 | llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!" , "clang/lib/Sema/SemaExpr.cpp", 16006); | |||
16007 | } | |||
16008 | ||||
16009 | return new (Context) GNUNullExpr(Ty, TokenLoc); | |||
16010 | } | |||
16011 | ||||
16012 | ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, | |||
16013 | SourceLocation BuiltinLoc, | |||
16014 | SourceLocation RPLoc) { | |||
16015 | return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); | |||
16016 | } | |||
16017 | ||||
16018 | ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, | |||
16019 | SourceLocation BuiltinLoc, | |||
16020 | SourceLocation RPLoc, | |||
16021 | DeclContext *ParentContext) { | |||
16022 | return new (Context) | |||
16023 | SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); | |||
16024 | } | |||
16025 | ||||
16026 | bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, | |||
16027 | bool Diagnose) { | |||
16028 | if (!getLangOpts().ObjC) | |||
16029 | return false; | |||
16030 | ||||
16031 | const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); | |||
16032 | if (!PT) | |||
16033 | return false; | |||
16034 | const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); | |||
16035 | ||||
16036 | // Ignore any parens, implicit casts (should only be | |||
16037 | // array-to-pointer decays), and not-so-opaque values. The last is | |||
16038 | // important for making this trigger for property assignments. | |||
16039 | Expr *SrcExpr = Exp->IgnoreParenImpCasts(); | |||
16040 | if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) | |||
16041 | if (OV->getSourceExpr()) | |||
16042 | SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); | |||
16043 | ||||
16044 | if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { | |||
16045 | if (!PT->isObjCIdType() && | |||
16046 | !(ID && ID->getIdentifier()->isStr("NSString"))) | |||
16047 | return false; | |||
16048 | if (!SL->isAscii()) | |||
16049 | return false; | |||
16050 | ||||
16051 | if (Diagnose) { | |||
16052 | Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) | |||
16053 | << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); | |||
16054 | Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); | |||
16055 | } | |||
16056 | return true; | |||
16057 | } | |||
16058 | ||||
16059 | if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || | |||
16060 | isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || | |||
16061 | isa<CXXBoolLiteralExpr>(SrcExpr)) && | |||
16062 | !SrcExpr->isNullPointerConstant( | |||
16063 | getASTContext(), Expr::NPC_NeverValueDependent)) { | |||
16064 | if (!ID || !ID->getIdentifier()->isStr("NSNumber")) | |||
16065 | return false; | |||
16066 | if (Diagnose) { | |||
16067 | Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) | |||
16068 | << /*number*/1 | |||
16069 | << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); | |||
16070 | Expr *NumLit = | |||
16071 | BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); | |||
16072 | if (NumLit) | |||
16073 | Exp = NumLit; | |||
16074 | } | |||
16075 | return true; | |||
16076 | } | |||
16077 | ||||
16078 | return false; | |||
16079 | } | |||
16080 | ||||
16081 | static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, | |||
16082 | const Expr *SrcExpr) { | |||
16083 | if (!DstType->isFunctionPointerType() || | |||
16084 | !SrcExpr->getType()->isFunctionType()) | |||
16085 | return false; | |||
16086 | ||||
16087 | auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); | |||
16088 | if (!DRE) | |||
16089 | return false; | |||
16090 | ||||
16091 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); | |||
16092 | if (!FD) | |||
16093 | return false; | |||
16094 | ||||
16095 | return !S.checkAddressOfFunctionIsAvailable(FD, | |||
16096 | /*Complain=*/true, | |||
16097 | SrcExpr->getBeginLoc()); | |||
16098 | } | |||
16099 | ||||
16100 | bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, | |||
16101 | SourceLocation Loc, | |||
16102 | QualType DstType, QualType SrcType, | |||
16103 | Expr *SrcExpr, AssignmentAction Action, | |||
16104 | bool *Complained) { | |||
16105 | if (Complained) | |||
16106 | *Complained = false; | |||
16107 | ||||
16108 | // Decode the result (notice that AST's are still created for extensions). | |||
16109 | bool CheckInferredResultType = false; | |||
16110 | bool isInvalid = false; | |||
16111 | unsigned DiagKind = 0; | |||
16112 | ConversionFixItGenerator ConvHints; | |||
16113 | bool MayHaveConvFixit = false; | |||
16114 | bool MayHaveFunctionDiff = false; | |||
16115 | const ObjCInterfaceDecl *IFace = nullptr; | |||
16116 | const ObjCProtocolDecl *PDecl = nullptr; | |||
16117 | ||||
16118 | switch (ConvTy) { | |||
16119 | case Compatible: | |||
16120 | DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); | |||
16121 | return false; | |||
16122 | ||||
16123 | case PointerToInt: | |||
16124 | if (getLangOpts().CPlusPlus) { | |||
16125 | DiagKind = diag::err_typecheck_convert_pointer_int; | |||
16126 | isInvalid = true; | |||
16127 | } else { | |||
16128 | DiagKind = diag::ext_typecheck_convert_pointer_int; | |||
16129 | } | |||
16130 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
16131 | MayHaveConvFixit = true; | |||
16132 | break; | |||
16133 | case IntToPointer: | |||
16134 | if (getLangOpts().CPlusPlus) { | |||
16135 | DiagKind = diag::err_typecheck_convert_int_pointer; | |||
16136 | isInvalid = true; | |||
16137 | } else { | |||
16138 | DiagKind = diag::ext_typecheck_convert_int_pointer; | |||
16139 | } | |||
16140 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
16141 | MayHaveConvFixit = true; | |||
16142 | break; | |||
16143 | case IncompatibleFunctionPointer: | |||
16144 | if (getLangOpts().CPlusPlus) { | |||
16145 | DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; | |||
16146 | isInvalid = true; | |||
16147 | } else { | |||
16148 | DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; | |||
16149 | } | |||
16150 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
16151 | MayHaveConvFixit = true; | |||
16152 | break; | |||
16153 | case IncompatiblePointer: | |||
16154 | if (Action == AA_Passing_CFAudited) { | |||
16155 | DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; | |||
16156 | } else if (getLangOpts().CPlusPlus) { | |||
16157 | DiagKind = diag::err_typecheck_convert_incompatible_pointer; | |||
16158 | isInvalid = true; | |||
16159 | } else { | |||
16160 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer; | |||
16161 | } | |||
16162 | CheckInferredResultType = DstType->isObjCObjectPointerType() && | |||
16163 | SrcType->isObjCObjectPointerType(); | |||
16164 | if (!CheckInferredResultType) { | |||
16165 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
16166 | } else if (CheckInferredResultType) { | |||
16167 | SrcType = SrcType.getUnqualifiedType(); | |||
16168 | DstType = DstType.getUnqualifiedType(); | |||
16169 | } | |||
16170 | MayHaveConvFixit = true; | |||
16171 | break; | |||
16172 | case IncompatiblePointerSign: | |||
16173 | if (getLangOpts().CPlusPlus) { | |||
16174 | DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; | |||
16175 | isInvalid = true; | |||
16176 | } else { | |||
16177 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; | |||
16178 | } | |||
16179 | break; | |||
16180 | case FunctionVoidPointer: | |||
16181 | if (getLangOpts().CPlusPlus) { | |||
16182 | DiagKind = diag::err_typecheck_convert_pointer_void_func; | |||
16183 | isInvalid = true; | |||
16184 | } else { | |||
16185 | DiagKind = diag::ext_typecheck_convert_pointer_void_func; | |||
16186 | } | |||
16187 | break; | |||
16188 | case IncompatiblePointerDiscardsQualifiers: { | |||
16189 | // Perform array-to-pointer decay if necessary. | |||
16190 | if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); | |||
16191 | ||||
16192 | isInvalid = true; | |||
16193 | ||||
16194 | Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); | |||
16195 | Qualifiers rhq = DstType->getPointeeType().getQualifiers(); | |||
16196 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) { | |||
16197 | DiagKind = diag::err_typecheck_incompatible_address_space; | |||
16198 | break; | |||
16199 | ||||
16200 | } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { | |||
16201 | DiagKind = diag::err_typecheck_incompatible_ownership; | |||
16202 | break; | |||
16203 | } | |||
16204 | ||||
16205 | llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!" , "clang/lib/Sema/SemaExpr.cpp", 16205); | |||
16206 | // fallthrough | |||
16207 | } | |||
16208 | case CompatiblePointerDiscardsQualifiers: | |||
16209 | // If the qualifiers lost were because we were applying the | |||
16210 | // (deprecated) C++ conversion from a string literal to a char* | |||
16211 | // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: | |||
16212 | // Ideally, this check would be performed in | |||
16213 | // checkPointerTypesForAssignment. However, that would require a | |||
16214 | // bit of refactoring (so that the second argument is an | |||
16215 | // expression, rather than a type), which should be done as part | |||
16216 | // of a larger effort to fix checkPointerTypesForAssignment for | |||
16217 | // C++ semantics. | |||
16218 | if (getLangOpts().CPlusPlus && | |||
16219 | IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) | |||
16220 | return false; | |||
16221 | if (getLangOpts().CPlusPlus) { | |||
16222 | DiagKind = diag::err_typecheck_convert_discards_qualifiers; | |||
16223 | isInvalid = true; | |||
16224 | } else { | |||
16225 | DiagKind = diag::ext_typecheck_convert_discards_qualifiers; | |||
16226 | } | |||
16227 | ||||
16228 | break; | |||
16229 | case IncompatibleNestedPointerQualifiers: | |||
16230 | if (getLangOpts().CPlusPlus) { | |||
16231 | isInvalid = true; | |||
16232 | DiagKind = diag::err_nested_pointer_qualifier_mismatch; | |||
16233 | } else { | |||
16234 | DiagKind = diag::ext_nested_pointer_qualifier_mismatch; | |||
16235 | } | |||
16236 | break; | |||
16237 | case IncompatibleNestedPointerAddressSpaceMismatch: | |||
16238 | DiagKind = diag::err_typecheck_incompatible_nested_address_space; | |||
16239 | isInvalid = true; | |||
16240 | break; | |||
16241 | case IntToBlockPointer: | |||
16242 | DiagKind = diag::err_int_to_block_pointer; | |||
16243 | isInvalid = true; | |||
16244 | break; | |||
16245 | case IncompatibleBlockPointer: | |||
16246 | DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; | |||
16247 | isInvalid = true; | |||
16248 | break; | |||
16249 | case IncompatibleObjCQualifiedId: { | |||
16250 | if (SrcType->isObjCQualifiedIdType()) { | |||
16251 | const ObjCObjectPointerType *srcOPT = | |||
16252 | SrcType->castAs<ObjCObjectPointerType>(); | |||
16253 | for (auto *srcProto : srcOPT->quals()) { | |||
16254 | PDecl = srcProto; | |||
16255 | break; | |||
16256 | } | |||
16257 | if (const ObjCInterfaceType *IFaceT = | |||
16258 | DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | |||
16259 | IFace = IFaceT->getDecl(); | |||
16260 | } | |||
16261 | else if (DstType->isObjCQualifiedIdType()) { | |||
16262 | const ObjCObjectPointerType *dstOPT = | |||
16263 | DstType->castAs<ObjCObjectPointerType>(); | |||
16264 | for (auto *dstProto : dstOPT->quals()) { | |||
16265 | PDecl = dstProto; | |||
16266 | break; | |||
16267 | } | |||
16268 | if (const ObjCInterfaceType *IFaceT = | |||
16269 | SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | |||
16270 | IFace = IFaceT->getDecl(); | |||
16271 | } | |||
16272 | if (getLangOpts().CPlusPlus) { | |||
16273 | DiagKind = diag::err_incompatible_qualified_id; | |||
16274 | isInvalid = true; | |||
16275 | } else { | |||
16276 | DiagKind = diag::warn_incompatible_qualified_id; | |||
16277 | } | |||
16278 | break; | |||
16279 | } | |||
16280 | case IncompatibleVectors: | |||
16281 | if (getLangOpts().CPlusPlus) { | |||
16282 | DiagKind = diag::err_incompatible_vectors; | |||
16283 | isInvalid = true; | |||
16284 | } else { | |||
16285 | DiagKind = diag::warn_incompatible_vectors; | |||
16286 | } | |||
16287 | break; | |||
16288 | case IncompatibleObjCWeakRef: | |||
16289 | DiagKind = diag::err_arc_weak_unavailable_assign; | |||
16290 | isInvalid = true; | |||
16291 | break; | |||
16292 | case Incompatible: | |||
16293 | if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { | |||
16294 | if (Complained) | |||
16295 | *Complained = true; | |||
16296 | return true; | |||
16297 | } | |||
16298 | ||||
16299 | DiagKind = diag::err_typecheck_convert_incompatible; | |||
16300 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
16301 | MayHaveConvFixit = true; | |||
16302 | isInvalid = true; | |||
16303 | MayHaveFunctionDiff = true; | |||
16304 | break; | |||
16305 | } | |||
16306 | ||||
16307 | QualType FirstType, SecondType; | |||
16308 | switch (Action) { | |||
16309 | case AA_Assigning: | |||
16310 | case AA_Initializing: | |||
16311 | // The destination type comes first. | |||
16312 | FirstType = DstType; | |||
16313 | SecondType = SrcType; | |||
16314 | break; | |||
16315 | ||||
16316 | case AA_Returning: | |||
16317 | case AA_Passing: | |||
16318 | case AA_Passing_CFAudited: | |||
16319 | case AA_Converting: | |||
16320 | case AA_Sending: | |||
16321 | case AA_Casting: | |||
16322 | // The source type comes first. | |||
16323 | FirstType = SrcType; | |||
16324 | SecondType = DstType; | |||
16325 | break; | |||
16326 | } | |||
16327 | ||||
16328 | PartialDiagnostic FDiag = PDiag(DiagKind); | |||
16329 | if (Action == AA_Passing_CFAudited) | |||
16330 | FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); | |||
16331 | else | |||
16332 | FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); | |||
16333 | ||||
16334 | if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || | |||
16335 | DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { | |||
16336 | auto isPlainChar = [](const clang::Type *Type) { | |||
16337 | return Type->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
16338 | Type->isSpecificBuiltinType(BuiltinType::Char_U); | |||
16339 | }; | |||
16340 | FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || | |||
16341 | isPlainChar(SecondType->getPointeeOrArrayElementType())); | |||
16342 | } | |||
16343 | ||||
16344 | // If we can fix the conversion, suggest the FixIts. | |||
16345 | if (!ConvHints.isNull()) { | |||
16346 | for (FixItHint &H : ConvHints.Hints) | |||
16347 | FDiag << H; | |||
16348 | } | |||
16349 | ||||
16350 | if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } | |||
16351 | ||||
16352 | if (MayHaveFunctionDiff) | |||
16353 | HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); | |||
16354 | ||||
16355 | Diag(Loc, FDiag); | |||
16356 | if ((DiagKind == diag::warn_incompatible_qualified_id || | |||
16357 | DiagKind == diag::err_incompatible_qualified_id) && | |||
16358 | PDecl && IFace && !IFace->hasDefinition()) | |||
16359 | Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) | |||
16360 | << IFace << PDecl; | |||
16361 | ||||
16362 | if (SecondType == Context.OverloadTy) | |||
16363 | NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, | |||
16364 | FirstType, /*TakingAddress=*/true); | |||
16365 | ||||
16366 | if (CheckInferredResultType) | |||
16367 | EmitRelatedResultTypeNote(SrcExpr); | |||
16368 | ||||
16369 | if (Action == AA_Returning && ConvTy == IncompatiblePointer) | |||
16370 | EmitRelatedResultTypeNoteForReturn(DstType); | |||
16371 | ||||
16372 | if (Complained) | |||
16373 | *Complained = true; | |||
16374 | return isInvalid; | |||
16375 | } | |||
16376 | ||||
16377 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | |||
16378 | llvm::APSInt *Result, | |||
16379 | AllowFoldKind CanFold) { | |||
16380 | class SimpleICEDiagnoser : public VerifyICEDiagnoser { | |||
16381 | public: | |||
16382 | SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, | |||
16383 | QualType T) override { | |||
16384 | return S.Diag(Loc, diag::err_ice_not_integral) | |||
16385 | << T << S.LangOpts.CPlusPlus; | |||
16386 | } | |||
16387 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | |||
16388 | return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; | |||
16389 | } | |||
16390 | } Diagnoser; | |||
16391 | ||||
16392 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | |||
16393 | } | |||
16394 | ||||
16395 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | |||
16396 | llvm::APSInt *Result, | |||
16397 | unsigned DiagID, | |||
16398 | AllowFoldKind CanFold) { | |||
16399 | class IDDiagnoser : public VerifyICEDiagnoser { | |||
16400 | unsigned DiagID; | |||
16401 | ||||
16402 | public: | |||
16403 | IDDiagnoser(unsigned DiagID) | |||
16404 | : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } | |||
16405 | ||||
16406 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | |||
16407 | return S.Diag(Loc, DiagID); | |||
16408 | } | |||
16409 | } Diagnoser(DiagID); | |||
16410 | ||||
16411 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | |||
16412 | } | |||
16413 | ||||
16414 | Sema::SemaDiagnosticBuilder | |||
16415 | Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, | |||
16416 | QualType T) { | |||
16417 | return diagnoseNotICE(S, Loc); | |||
16418 | } | |||
16419 | ||||
16420 | Sema::SemaDiagnosticBuilder | |||
16421 | Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { | |||
16422 | return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; | |||
16423 | } | |||
16424 | ||||
16425 | ExprResult | |||
16426 | Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, | |||
16427 | VerifyICEDiagnoser &Diagnoser, | |||
16428 | AllowFoldKind CanFold) { | |||
16429 | SourceLocation DiagLoc = E->getBeginLoc(); | |||
16430 | ||||
16431 | if (getLangOpts().CPlusPlus11) { | |||
16432 | // C++11 [expr.const]p5: | |||
16433 | // If an expression of literal class type is used in a context where an | |||
16434 | // integral constant expression is required, then that class type shall | |||
16435 | // have a single non-explicit conversion function to an integral or | |||
16436 | // unscoped enumeration type | |||
16437 | ExprResult Converted; | |||
16438 | class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { | |||
16439 | VerifyICEDiagnoser &BaseDiagnoser; | |||
16440 | public: | |||
16441 | CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) | |||
16442 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, | |||
16443 | BaseDiagnoser.Suppress, true), | |||
16444 | BaseDiagnoser(BaseDiagnoser) {} | |||
16445 | ||||
16446 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, | |||
16447 | QualType T) override { | |||
16448 | return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); | |||
16449 | } | |||
16450 | ||||
16451 | SemaDiagnosticBuilder diagnoseIncomplete( | |||
16452 | Sema &S, SourceLocation Loc, QualType T) override { | |||
16453 | return S.Diag(Loc, diag::err_ice_incomplete_type) << T; | |||
16454 | } | |||
16455 | ||||
16456 | SemaDiagnosticBuilder diagnoseExplicitConv( | |||
16457 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | |||
16458 | return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; | |||
16459 | } | |||
16460 | ||||
16461 | SemaDiagnosticBuilder noteExplicitConv( | |||
16462 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | |||
16463 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | |||
16464 | << ConvTy->isEnumeralType() << ConvTy; | |||
16465 | } | |||
16466 | ||||
16467 | SemaDiagnosticBuilder diagnoseAmbiguous( | |||
16468 | Sema &S, SourceLocation Loc, QualType T) override { | |||
16469 | return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; | |||
16470 | } | |||
16471 | ||||
16472 | SemaDiagnosticBuilder noteAmbiguous( | |||
16473 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | |||
16474 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | |||
16475 | << ConvTy->isEnumeralType() << ConvTy; | |||
16476 | } | |||
16477 | ||||
16478 | SemaDiagnosticBuilder diagnoseConversion( | |||
16479 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | |||
16480 | llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted" , "clang/lib/Sema/SemaExpr.cpp", 16480); | |||
16481 | } | |||
16482 | } ConvertDiagnoser(Diagnoser); | |||
16483 | ||||
16484 | Converted = PerformContextualImplicitConversion(DiagLoc, E, | |||
16485 | ConvertDiagnoser); | |||
16486 | if (Converted.isInvalid()) | |||
16487 | return Converted; | |||
16488 | E = Converted.get(); | |||
16489 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) | |||
16490 | return ExprError(); | |||
16491 | } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { | |||
16492 | // An ICE must be of integral or unscoped enumeration type. | |||
16493 | if (!Diagnoser.Suppress) | |||
16494 | Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) | |||
16495 | << E->getSourceRange(); | |||
16496 | return ExprError(); | |||
16497 | } | |||
16498 | ||||
16499 | ExprResult RValueExpr = DefaultLvalueConversion(E); | |||
16500 | if (RValueExpr.isInvalid()) | |||
16501 | return ExprError(); | |||
16502 | ||||
16503 | E = RValueExpr.get(); | |||
16504 | ||||
16505 | // Circumvent ICE checking in C++11 to avoid evaluating the expression twice | |||
16506 | // in the non-ICE case. | |||
16507 | if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { | |||
16508 | if (Result) | |||
16509 | *Result = E->EvaluateKnownConstIntCheckOverflow(Context); | |||
16510 | if (!isa<ConstantExpr>(E)) | |||
16511 | E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) | |||
16512 | : ConstantExpr::Create(Context, E); | |||
16513 | return E; | |||
16514 | } | |||
16515 | ||||
16516 | Expr::EvalResult EvalResult; | |||
16517 | SmallVector<PartialDiagnosticAt, 8> Notes; | |||
16518 | EvalResult.Diag = &Notes; | |||
16519 | ||||
16520 | // Try to evaluate the expression, and produce diagnostics explaining why it's | |||
16521 | // not a constant expression as a side-effect. | |||
16522 | bool Folded = | |||
16523 | E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && | |||
16524 | EvalResult.Val.isInt() && !EvalResult.HasSideEffects; | |||
16525 | ||||
16526 | if (!isa<ConstantExpr>(E)) | |||
16527 | E = ConstantExpr::Create(Context, E, EvalResult.Val); | |||
16528 | ||||
16529 | // In C++11, we can rely on diagnostics being produced for any expression | |||
16530 | // which is not a constant expression. If no diagnostics were produced, then | |||
16531 | // this is a constant expression. | |||
16532 | if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { | |||
16533 | if (Result) | |||
16534 | *Result = EvalResult.Val.getInt(); | |||
16535 | return E; | |||
16536 | } | |||
16537 | ||||
16538 | // If our only note is the usual "invalid subexpression" note, just point | |||
16539 | // the caret at its location rather than producing an essentially | |||
16540 | // redundant note. | |||
16541 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | |||
16542 | diag::note_invalid_subexpr_in_const_expr) { | |||
16543 | DiagLoc = Notes[0].first; | |||
16544 | Notes.clear(); | |||
16545 | } | |||
16546 | ||||
16547 | if (!Folded || !CanFold) { | |||
16548 | if (!Diagnoser.Suppress) { | |||
16549 | Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); | |||
16550 | for (const PartialDiagnosticAt &Note : Notes) | |||
16551 | Diag(Note.first, Note.second); | |||
16552 | } | |||
16553 | ||||
16554 | return ExprError(); | |||
16555 | } | |||
16556 | ||||
16557 | Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); | |||
16558 | for (const PartialDiagnosticAt &Note : Notes) | |||
16559 | Diag(Note.first, Note.second); | |||
16560 | ||||
16561 | if (Result) | |||
16562 | *Result = EvalResult.Val.getInt(); | |||
16563 | return E; | |||
16564 | } | |||
16565 | ||||
16566 | namespace { | |||
16567 | // Handle the case where we conclude a expression which we speculatively | |||
16568 | // considered to be unevaluated is actually evaluated. | |||
16569 | class TransformToPE : public TreeTransform<TransformToPE> { | |||
16570 | typedef TreeTransform<TransformToPE> BaseTransform; | |||
16571 | ||||
16572 | public: | |||
16573 | TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } | |||
16574 | ||||
16575 | // Make sure we redo semantic analysis | |||
16576 | bool AlwaysRebuild() { return true; } | |||
16577 | bool ReplacingOriginal() { return true; } | |||
16578 | ||||
16579 | // We need to special-case DeclRefExprs referring to FieldDecls which | |||
16580 | // are not part of a member pointer formation; normal TreeTransforming | |||
16581 | // doesn't catch this case because of the way we represent them in the AST. | |||
16582 | // FIXME: This is a bit ugly; is it really the best way to handle this | |||
16583 | // case? | |||
16584 | // | |||
16585 | // Error on DeclRefExprs referring to FieldDecls. | |||
16586 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | |||
16587 | if (isa<FieldDecl>(E->getDecl()) && | |||
16588 | !SemaRef.isUnevaluatedContext()) | |||
16589 | return SemaRef.Diag(E->getLocation(), | |||
16590 | diag::err_invalid_non_static_member_use) | |||
16591 | << E->getDecl() << E->getSourceRange(); | |||
16592 | ||||
16593 | return BaseTransform::TransformDeclRefExpr(E); | |||
16594 | } | |||
16595 | ||||
16596 | // Exception: filter out member pointer formation | |||
16597 | ExprResult TransformUnaryOperator(UnaryOperator *E) { | |||
16598 | if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) | |||
16599 | return E; | |||
16600 | ||||
16601 | return BaseTransform::TransformUnaryOperator(E); | |||
16602 | } | |||
16603 | ||||
16604 | // The body of a lambda-expression is in a separate expression evaluation | |||
16605 | // context so never needs to be transformed. | |||
16606 | // FIXME: Ideally we wouldn't transform the closure type either, and would | |||
16607 | // just recreate the capture expressions and lambda expression. | |||
16608 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { | |||
16609 | return SkipLambdaBody(E, Body); | |||
16610 | } | |||
16611 | }; | |||
16612 | } | |||
16613 | ||||
16614 | ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { | |||
16615 | assert(isUnevaluatedContext() &&(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "clang/lib/Sema/SemaExpr.cpp", 16616, __extension__ __PRETTY_FUNCTION__ )) | |||
16616 | "Should only transform unevaluated expressions")(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "clang/lib/Sema/SemaExpr.cpp", 16616, __extension__ __PRETTY_FUNCTION__ )); | |||
16617 | ExprEvalContexts.back().Context = | |||
16618 | ExprEvalContexts[ExprEvalContexts.size()-2].Context; | |||
16619 | if (isUnevaluatedContext()) | |||
16620 | return E; | |||
16621 | return TransformToPE(*this).TransformExpr(E); | |||
16622 | } | |||
16623 | ||||
16624 | TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { | |||
16625 | assert(isUnevaluatedContext() &&(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "clang/lib/Sema/SemaExpr.cpp", 16626, __extension__ __PRETTY_FUNCTION__ )) | |||
16626 | "Should only transform unevaluated expressions")(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "clang/lib/Sema/SemaExpr.cpp", 16626, __extension__ __PRETTY_FUNCTION__ )); | |||
16627 | ExprEvalContexts.back().Context = | |||
16628 | ExprEvalContexts[ExprEvalContexts.size() - 2].Context; | |||
16629 | if (isUnevaluatedContext()) | |||
16630 | return TInfo; | |||
16631 | return TransformToPE(*this).TransformType(TInfo); | |||
16632 | } | |||
16633 | ||||
16634 | void | |||
16635 | Sema::PushExpressionEvaluationContext( | |||
16636 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, | |||
16637 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | |||
16638 | ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, | |||
16639 | LambdaContextDecl, ExprContext); | |||
16640 | ||||
16641 | // Discarded statements and immediate contexts nested in other | |||
16642 | // discarded statements or immediate context are themselves | |||
16643 | // a discarded statement or an immediate context, respectively. | |||
16644 | ExprEvalContexts.back().InDiscardedStatement = | |||
16645 | ExprEvalContexts[ExprEvalContexts.size() - 2] | |||
16646 | .isDiscardedStatementContext(); | |||
16647 | ExprEvalContexts.back().InImmediateFunctionContext = | |||
16648 | ExprEvalContexts[ExprEvalContexts.size() - 2] | |||
16649 | .isImmediateFunctionContext(); | |||
16650 | ||||
16651 | Cleanup.reset(); | |||
16652 | if (!MaybeODRUseExprs.empty()) | |||
16653 | std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); | |||
16654 | } | |||
16655 | ||||
16656 | void | |||
16657 | Sema::PushExpressionEvaluationContext( | |||
16658 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, | |||
16659 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | |||
16660 | Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; | |||
16661 | PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); | |||
16662 | } | |||
16663 | ||||
16664 | namespace { | |||
16665 | ||||
16666 | const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { | |||
16667 | PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); | |||
16668 | if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { | |||
16669 | if (E->getOpcode() == UO_Deref) | |||
16670 | return CheckPossibleDeref(S, E->getSubExpr()); | |||
16671 | } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { | |||
16672 | return CheckPossibleDeref(S, E->getBase()); | |||
16673 | } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { | |||
16674 | return CheckPossibleDeref(S, E->getBase()); | |||
16675 | } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { | |||
16676 | QualType Inner; | |||
16677 | QualType Ty = E->getType(); | |||
16678 | if (const auto *Ptr = Ty->getAs<PointerType>()) | |||
16679 | Inner = Ptr->getPointeeType(); | |||
16680 | else if (const auto *Arr = S.Context.getAsArrayType(Ty)) | |||
16681 | Inner = Arr->getElementType(); | |||
16682 | else | |||
16683 | return nullptr; | |||
16684 | ||||
16685 | if (Inner->hasAttr(attr::NoDeref)) | |||
16686 | return E; | |||
16687 | } | |||
16688 | return nullptr; | |||
16689 | } | |||
16690 | ||||
16691 | } // namespace | |||
16692 | ||||
16693 | void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { | |||
16694 | for (const Expr *E : Rec.PossibleDerefs) { | |||
16695 | const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); | |||
16696 | if (DeclRef) { | |||
16697 | const ValueDecl *Decl = DeclRef->getDecl(); | |||
16698 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) | |||
16699 | << Decl->getName() << E->getSourceRange(); | |||
16700 | Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); | |||
16701 | } else { | |||
16702 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) | |||
16703 | << E->getSourceRange(); | |||
16704 | } | |||
16705 | } | |||
16706 | Rec.PossibleDerefs.clear(); | |||
16707 | } | |||
16708 | ||||
16709 | /// Check whether E, which is either a discarded-value expression or an | |||
16710 | /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, | |||
16711 | /// and if so, remove it from the list of volatile-qualified assignments that | |||
16712 | /// we are going to warn are deprecated. | |||
16713 | void Sema::CheckUnusedVolatileAssignment(Expr *E) { | |||
16714 | if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) | |||
16715 | return; | |||
16716 | ||||
16717 | // Note: ignoring parens here is not justified by the standard rules, but | |||
16718 | // ignoring parentheses seems like a more reasonable approach, and this only | |||
16719 | // drives a deprecation warning so doesn't affect conformance. | |||
16720 | if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { | |||
16721 | if (BO->getOpcode() == BO_Assign) { | |||
16722 | auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; | |||
16723 | llvm::erase_value(LHSs, BO->getLHS()); | |||
16724 | } | |||
16725 | } | |||
16726 | } | |||
16727 | ||||
16728 | ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { | |||
16729 | if (isUnevaluatedContext() || !E.isUsable() || !Decl || | |||
16730 | !Decl->isConsteval() || isConstantEvaluated() || | |||
16731 | RebuildingImmediateInvocation || isImmediateFunctionContext()) | |||
16732 | return E; | |||
16733 | ||||
16734 | /// Opportunistically remove the callee from ReferencesToConsteval if we can. | |||
16735 | /// It's OK if this fails; we'll also remove this in | |||
16736 | /// HandleImmediateInvocations, but catching it here allows us to avoid | |||
16737 | /// walking the AST looking for it in simple cases. | |||
16738 | if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) | |||
16739 | if (auto *DeclRef = | |||
16740 | dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) | |||
16741 | ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); | |||
16742 | ||||
16743 | E = MaybeCreateExprWithCleanups(E); | |||
16744 | ||||
16745 | ConstantExpr *Res = ConstantExpr::Create( | |||
16746 | getASTContext(), E.get(), | |||
16747 | ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), | |||
16748 | getASTContext()), | |||
16749 | /*IsImmediateInvocation*/ true); | |||
16750 | ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); | |||
16751 | return Res; | |||
16752 | } | |||
16753 | ||||
16754 | static void EvaluateAndDiagnoseImmediateInvocation( | |||
16755 | Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { | |||
16756 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; | |||
16757 | Expr::EvalResult Eval; | |||
16758 | Eval.Diag = &Notes; | |||
16759 | ConstantExpr *CE = Candidate.getPointer(); | |||
16760 | bool Result = CE->EvaluateAsConstantExpr( | |||
16761 | Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); | |||
16762 | if (!Result || !Notes.empty()) { | |||
16763 | Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); | |||
16764 | if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) | |||
16765 | InnerExpr = FunctionalCast->getSubExpr(); | |||
16766 | FunctionDecl *FD = nullptr; | |||
16767 | if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) | |||
16768 | FD = cast<FunctionDecl>(Call->getCalleeDecl()); | |||
16769 | else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) | |||
16770 | FD = Call->getConstructor(); | |||
16771 | else | |||
16772 | llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "clang/lib/Sema/SemaExpr.cpp" , 16772); | |||
16773 | assert(FD->isConsteval())(static_cast <bool> (FD->isConsteval()) ? void (0) : __assert_fail ("FD->isConsteval()", "clang/lib/Sema/SemaExpr.cpp" , 16773, __extension__ __PRETTY_FUNCTION__)); | |||
16774 | SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; | |||
16775 | for (auto &Note : Notes) | |||
16776 | SemaRef.Diag(Note.first, Note.second); | |||
16777 | return; | |||
16778 | } | |||
16779 | CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); | |||
16780 | } | |||
16781 | ||||
16782 | static void RemoveNestedImmediateInvocation( | |||
16783 | Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, | |||
16784 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { | |||
16785 | struct ComplexRemove : TreeTransform<ComplexRemove> { | |||
16786 | using Base = TreeTransform<ComplexRemove>; | |||
16787 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | |||
16788 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; | |||
16789 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator | |||
16790 | CurrentII; | |||
16791 | ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, | |||
16792 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, | |||
16793 | SmallVector<Sema::ImmediateInvocationCandidate, | |||
16794 | 4>::reverse_iterator Current) | |||
16795 | : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} | |||
16796 | void RemoveImmediateInvocation(ConstantExpr* E) { | |||
16797 | auto It = std::find_if(CurrentII, IISet.rend(), | |||
16798 | [E](Sema::ImmediateInvocationCandidate Elem) { | |||
16799 | return Elem.getPointer() == E; | |||
16800 | }); | |||
16801 | assert(It != IISet.rend() &&(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "clang/lib/Sema/SemaExpr.cpp", 16803, __extension__ __PRETTY_FUNCTION__ )) | |||
16802 | "ConstantExpr marked IsImmediateInvocation should "(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "clang/lib/Sema/SemaExpr.cpp", 16803, __extension__ __PRETTY_FUNCTION__ )) | |||
16803 | "be present")(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "clang/lib/Sema/SemaExpr.cpp", 16803, __extension__ __PRETTY_FUNCTION__ )); | |||
16804 | It->setInt(1); // Mark as deleted | |||
16805 | } | |||
16806 | ExprResult TransformConstantExpr(ConstantExpr *E) { | |||
16807 | if (!E->isImmediateInvocation()) | |||
16808 | return Base::TransformConstantExpr(E); | |||
16809 | RemoveImmediateInvocation(E); | |||
16810 | return Base::TransformExpr(E->getSubExpr()); | |||
16811 | } | |||
16812 | /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so | |||
16813 | /// we need to remove its DeclRefExpr from the DRSet. | |||
16814 | ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | |||
16815 | DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); | |||
16816 | return Base::TransformCXXOperatorCallExpr(E); | |||
16817 | } | |||
16818 | /// Base::TransformInitializer skip ConstantExpr so we need to visit them | |||
16819 | /// here. | |||
16820 | ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { | |||
16821 | if (!Init) | |||
16822 | return Init; | |||
16823 | /// ConstantExpr are the first layer of implicit node to be removed so if | |||
16824 | /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. | |||
16825 | if (auto *CE = dyn_cast<ConstantExpr>(Init)) | |||
16826 | if (CE->isImmediateInvocation()) | |||
16827 | RemoveImmediateInvocation(CE); | |||
16828 | return Base::TransformInitializer(Init, NotCopyInit); | |||
16829 | } | |||
16830 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | |||
16831 | DRSet.erase(E); | |||
16832 | return E; | |||
16833 | } | |||
16834 | bool AlwaysRebuild() { return false; } | |||
16835 | bool ReplacingOriginal() { return true; } | |||
16836 | bool AllowSkippingCXXConstructExpr() { | |||
16837 | bool Res = AllowSkippingFirstCXXConstructExpr; | |||
16838 | AllowSkippingFirstCXXConstructExpr = true; | |||
16839 | return Res; | |||
16840 | } | |||
16841 | bool AllowSkippingFirstCXXConstructExpr = true; | |||
16842 | } Transformer(SemaRef, Rec.ReferenceToConsteval, | |||
16843 | Rec.ImmediateInvocationCandidates, It); | |||
16844 | ||||
16845 | /// CXXConstructExpr with a single argument are getting skipped by | |||
16846 | /// TreeTransform in some situtation because they could be implicit. This | |||
16847 | /// can only occur for the top-level CXXConstructExpr because it is used | |||
16848 | /// nowhere in the expression being transformed therefore will not be rebuilt. | |||
16849 | /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from | |||
16850 | /// skipping the first CXXConstructExpr. | |||
16851 | if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) | |||
16852 | Transformer.AllowSkippingFirstCXXConstructExpr = false; | |||
16853 | ||||
16854 | ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); | |||
16855 | assert(Res.isUsable())(static_cast <bool> (Res.isUsable()) ? void (0) : __assert_fail ("Res.isUsable()", "clang/lib/Sema/SemaExpr.cpp", 16855, __extension__ __PRETTY_FUNCTION__)); | |||
16856 | Res = SemaRef.MaybeCreateExprWithCleanups(Res); | |||
16857 | It->getPointer()->setSubExpr(Res.get()); | |||
16858 | } | |||
16859 | ||||
16860 | static void | |||
16861 | HandleImmediateInvocations(Sema &SemaRef, | |||
16862 | Sema::ExpressionEvaluationContextRecord &Rec) { | |||
16863 | if ((Rec.ImmediateInvocationCandidates.size() == 0 && | |||
16864 | Rec.ReferenceToConsteval.size() == 0) || | |||
16865 | SemaRef.RebuildingImmediateInvocation) | |||
16866 | return; | |||
16867 | ||||
16868 | /// When we have more then 1 ImmediateInvocationCandidates we need to check | |||
16869 | /// for nested ImmediateInvocationCandidates. when we have only 1 we only | |||
16870 | /// need to remove ReferenceToConsteval in the immediate invocation. | |||
16871 | if (Rec.ImmediateInvocationCandidates.size() > 1) { | |||
16872 | ||||
16873 | /// Prevent sema calls during the tree transform from adding pointers that | |||
16874 | /// are already in the sets. | |||
16875 | llvm::SaveAndRestore<bool> DisableIITracking( | |||
16876 | SemaRef.RebuildingImmediateInvocation, true); | |||
16877 | ||||
16878 | /// Prevent diagnostic during tree transfrom as they are duplicates | |||
16879 | Sema::TentativeAnalysisScope DisableDiag(SemaRef); | |||
16880 | ||||
16881 | for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); | |||
16882 | It != Rec.ImmediateInvocationCandidates.rend(); It++) | |||
16883 | if (!It->getInt()) | |||
16884 | RemoveNestedImmediateInvocation(SemaRef, Rec, It); | |||
16885 | } else if (Rec.ImmediateInvocationCandidates.size() == 1 && | |||
16886 | Rec.ReferenceToConsteval.size()) { | |||
16887 | struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { | |||
16888 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | |||
16889 | SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} | |||
16890 | bool VisitDeclRefExpr(DeclRefExpr *E) { | |||
16891 | DRSet.erase(E); | |||
16892 | return DRSet.size(); | |||
16893 | } | |||
16894 | } Visitor(Rec.ReferenceToConsteval); | |||
16895 | Visitor.TraverseStmt( | |||
16896 | Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); | |||
16897 | } | |||
16898 | for (auto CE : Rec.ImmediateInvocationCandidates) | |||
16899 | if (!CE.getInt()) | |||
16900 | EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); | |||
16901 | for (auto DR : Rec.ReferenceToConsteval) { | |||
16902 | auto *FD = cast<FunctionDecl>(DR->getDecl()); | |||
16903 | SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) | |||
16904 | << FD; | |||
16905 | SemaRef.Diag(FD->getLocation(), diag::note_declared_at); | |||
16906 | } | |||
16907 | } | |||
16908 | ||||
16909 | void Sema::PopExpressionEvaluationContext() { | |||
16910 | ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); | |||
16911 | unsigned NumTypos = Rec.NumTypos; | |||
16912 | ||||
16913 | if (!Rec.Lambdas.empty()) { | |||
16914 | using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; | |||
16915 | if (!getLangOpts().CPlusPlus20 && | |||
16916 | (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || | |||
16917 | Rec.isUnevaluated() || | |||
16918 | (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { | |||
16919 | unsigned D; | |||
16920 | if (Rec.isUnevaluated()) { | |||
16921 | // C++11 [expr.prim.lambda]p2: | |||
16922 | // A lambda-expression shall not appear in an unevaluated operand | |||
16923 | // (Clause 5). | |||
16924 | D = diag::err_lambda_unevaluated_operand; | |||
16925 | } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { | |||
16926 | // C++1y [expr.const]p2: | |||
16927 | // A conditional-expression e is a core constant expression unless the | |||
16928 | // evaluation of e, following the rules of the abstract machine, would | |||
16929 | // evaluate [...] a lambda-expression. | |||
16930 | D = diag::err_lambda_in_constant_expression; | |||
16931 | } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { | |||
16932 | // C++17 [expr.prim.lamda]p2: | |||
16933 | // A lambda-expression shall not appear [...] in a template-argument. | |||
16934 | D = diag::err_lambda_in_invalid_context; | |||
16935 | } else | |||
16936 | llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message." , "clang/lib/Sema/SemaExpr.cpp", 16936); | |||
16937 | ||||
16938 | for (const auto *L : Rec.Lambdas) | |||
16939 | Diag(L->getBeginLoc(), D); | |||
16940 | } | |||
16941 | } | |||
16942 | ||||
16943 | WarnOnPendingNoDerefs(Rec); | |||
16944 | HandleImmediateInvocations(*this, Rec); | |||
16945 | ||||
16946 | // Warn on any volatile-qualified simple-assignments that are not discarded- | |||
16947 | // value expressions nor unevaluated operands (those cases get removed from | |||
16948 | // this list by CheckUnusedVolatileAssignment). | |||
16949 | for (auto *BO : Rec.VolatileAssignmentLHSs) | |||
16950 | Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) | |||
16951 | << BO->getType(); | |||
16952 | ||||
16953 | // When are coming out of an unevaluated context, clear out any | |||
16954 | // temporaries that we may have created as part of the evaluation of | |||
16955 | // the expression in that context: they aren't relevant because they | |||
16956 | // will never be constructed. | |||
16957 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { | |||
16958 | ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, | |||
16959 | ExprCleanupObjects.end()); | |||
16960 | Cleanup = Rec.ParentCleanup; | |||
16961 | CleanupVarDeclMarking(); | |||
16962 | std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); | |||
16963 | // Otherwise, merge the contexts together. | |||
16964 | } else { | |||
16965 | Cleanup.mergeFrom(Rec.ParentCleanup); | |||
16966 | MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), | |||
16967 | Rec.SavedMaybeODRUseExprs.end()); | |||
16968 | } | |||
16969 | ||||
16970 | // Pop the current expression evaluation context off the stack. | |||
16971 | ExprEvalContexts.pop_back(); | |||
16972 | ||||
16973 | // The global expression evaluation context record is never popped. | |||
16974 | ExprEvalContexts.back().NumTypos += NumTypos; | |||
16975 | } | |||
16976 | ||||
16977 | void Sema::DiscardCleanupsInEvaluationContext() { | |||
16978 | ExprCleanupObjects.erase( | |||
16979 | ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, | |||
16980 | ExprCleanupObjects.end()); | |||
16981 | Cleanup.reset(); | |||
16982 | MaybeODRUseExprs.clear(); | |||
16983 | } | |||
16984 | ||||
16985 | ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { | |||
16986 | ExprResult Result = CheckPlaceholderExpr(E); | |||
16987 | if (Result.isInvalid()) | |||
16988 | return ExprError(); | |||
16989 | E = Result.get(); | |||
16990 | if (!E->getType()->isVariablyModifiedType()) | |||
16991 | return E; | |||
16992 | return TransformToPotentiallyEvaluated(E); | |||
16993 | } | |||
16994 | ||||
16995 | /// Are we in a context that is potentially constant evaluated per C++20 | |||
16996 | /// [expr.const]p12? | |||
16997 | static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { | |||
16998 | /// C++2a [expr.const]p12: | |||
16999 | // An expression or conversion is potentially constant evaluated if it is | |||
17000 | switch (SemaRef.ExprEvalContexts.back().Context) { | |||
17001 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | |||
17002 | case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: | |||
17003 | ||||
17004 | // -- a manifestly constant-evaluated expression, | |||
17005 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | |||
17006 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | |||
17007 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | |||
17008 | // -- a potentially-evaluated expression, | |||
17009 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | |||
17010 | // -- an immediate subexpression of a braced-init-list, | |||
17011 | ||||
17012 | // -- [FIXME] an expression of the form & cast-expression that occurs | |||
17013 | // within a templated entity | |||
17014 | // -- a subexpression of one of the above that is not a subexpression of | |||
17015 | // a nested unevaluated operand. | |||
17016 | return true; | |||
17017 | ||||
17018 | case Sema::ExpressionEvaluationContext::Unevaluated: | |||
17019 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | |||
17020 | // Expressions in this context are never evaluated. | |||
17021 | return false; | |||
17022 | } | |||
17023 | llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "clang/lib/Sema/SemaExpr.cpp" , 17023); | |||
17024 | } | |||
17025 | ||||
17026 | /// Return true if this function has a calling convention that requires mangling | |||
17027 | /// in the size of the parameter pack. | |||
17028 | static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { | |||
17029 | // These manglings don't do anything on non-Windows or non-x86 platforms, so | |||
17030 | // we don't need parameter type sizes. | |||
17031 | const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); | |||
17032 | if (!TT.isOSWindows() || !TT.isX86()) | |||
17033 | return false; | |||
17034 | ||||
17035 | // If this is C++ and this isn't an extern "C" function, parameters do not | |||
17036 | // need to be complete. In this case, C++ mangling will apply, which doesn't | |||
17037 | // use the size of the parameters. | |||
17038 | if (S.getLangOpts().CPlusPlus && !FD->isExternC()) | |||
17039 | return false; | |||
17040 | ||||
17041 | // Stdcall, fastcall, and vectorcall need this special treatment. | |||
17042 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | |||
17043 | switch (CC) { | |||
17044 | case CC_X86StdCall: | |||
17045 | case CC_X86FastCall: | |||
17046 | case CC_X86VectorCall: | |||
17047 | return true; | |||
17048 | default: | |||
17049 | break; | |||
17050 | } | |||
17051 | return false; | |||
17052 | } | |||
17053 | ||||
17054 | /// Require that all of the parameter types of function be complete. Normally, | |||
17055 | /// parameter types are only required to be complete when a function is called | |||
17056 | /// or defined, but to mangle functions with certain calling conventions, the | |||
17057 | /// mangler needs to know the size of the parameter list. In this situation, | |||
17058 | /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles | |||
17059 | /// the function as _foo@0, i.e. zero bytes of parameters, which will usually | |||
17060 | /// result in a linker error. Clang doesn't implement this behavior, and instead | |||
17061 | /// attempts to error at compile time. | |||
17062 | static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, | |||
17063 | SourceLocation Loc) { | |||
17064 | class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { | |||
17065 | FunctionDecl *FD; | |||
17066 | ParmVarDecl *Param; | |||
17067 | ||||
17068 | public: | |||
17069 | ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) | |||
17070 | : FD(FD), Param(Param) {} | |||
17071 | ||||
17072 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | |||
17073 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | |||
17074 | StringRef CCName; | |||
17075 | switch (CC) { | |||
17076 | case CC_X86StdCall: | |||
17077 | CCName = "stdcall"; | |||
17078 | break; | |||
17079 | case CC_X86FastCall: | |||
17080 | CCName = "fastcall"; | |||
17081 | break; | |||
17082 | case CC_X86VectorCall: | |||
17083 | CCName = "vectorcall"; | |||
17084 | break; | |||
17085 | default: | |||
17086 | llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling" , "clang/lib/Sema/SemaExpr.cpp", 17086); | |||
17087 | } | |||
17088 | ||||
17089 | S.Diag(Loc, diag::err_cconv_incomplete_param_type) | |||
17090 | << Param->getDeclName() << FD->getDeclName() << CCName; | |||
17091 | } | |||
17092 | }; | |||
17093 | ||||
17094 | for (ParmVarDecl *Param : FD->parameters()) { | |||
17095 | ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); | |||
17096 | S.RequireCompleteType(Loc, Param->getType(), Diagnoser); | |||
17097 | } | |||
17098 | } | |||
17099 | ||||
17100 | namespace { | |||
17101 | enum class OdrUseContext { | |||
17102 | /// Declarations in this context are not odr-used. | |||
17103 | None, | |||
17104 | /// Declarations in this context are formally odr-used, but this is a | |||
17105 | /// dependent context. | |||
17106 | Dependent, | |||
17107 | /// Declarations in this context are odr-used but not actually used (yet). | |||
17108 | FormallyOdrUsed, | |||
17109 | /// Declarations in this context are used. | |||
17110 | Used | |||
17111 | }; | |||
17112 | } | |||
17113 | ||||
17114 | /// Are we within a context in which references to resolved functions or to | |||
17115 | /// variables result in odr-use? | |||
17116 | static OdrUseContext isOdrUseContext(Sema &SemaRef) { | |||
17117 | OdrUseContext Result; | |||
17118 | ||||
17119 | switch (SemaRef.ExprEvalContexts.back().Context) { | |||
17120 | case Sema::ExpressionEvaluationContext::Unevaluated: | |||
17121 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | |||
17122 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | |||
17123 | return OdrUseContext::None; | |||
17124 | ||||
17125 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | |||
17126 | case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: | |||
17127 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | |||
17128 | Result = OdrUseContext::Used; | |||
17129 | break; | |||
17130 | ||||
17131 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | |||
17132 | Result = OdrUseContext::FormallyOdrUsed; | |||
17133 | break; | |||
17134 | ||||
17135 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | |||
17136 | // A default argument formally results in odr-use, but doesn't actually | |||
17137 | // result in a use in any real sense until it itself is used. | |||
17138 | Result = OdrUseContext::FormallyOdrUsed; | |||
17139 | break; | |||
17140 | } | |||
17141 | ||||
17142 | if (SemaRef.CurContext->isDependentContext()) | |||
17143 | return OdrUseContext::Dependent; | |||
17144 | ||||
17145 | return Result; | |||
17146 | } | |||
17147 | ||||
17148 | static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { | |||
17149 | if (!Func->isConstexpr()) | |||
17150 | return false; | |||
17151 | ||||
17152 | if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) | |||
17153 | return true; | |||
17154 | auto *CCD = dyn_cast<CXXConstructorDecl>(Func); | |||
17155 | return CCD && CCD->getInheritedConstructor(); | |||
17156 | } | |||
17157 | ||||
17158 | /// Mark a function referenced, and check whether it is odr-used | |||
17159 | /// (C++ [basic.def.odr]p2, C99 6.9p3) | |||
17160 | void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, | |||
17161 | bool MightBeOdrUse) { | |||
17162 | assert(Func && "No function?")(static_cast <bool> (Func && "No function?") ? void (0) : __assert_fail ("Func && \"No function?\"", "clang/lib/Sema/SemaExpr.cpp" , 17162, __extension__ __PRETTY_FUNCTION__)); | |||
17163 | ||||
17164 | Func->setReferenced(); | |||
17165 | ||||
17166 | // Recursive functions aren't really used until they're used from some other | |||
17167 | // context. | |||
17168 | bool IsRecursiveCall = CurContext == Func; | |||
17169 | ||||
17170 | // C++11 [basic.def.odr]p3: | |||
17171 | // A function whose name appears as a potentially-evaluated expression is | |||
17172 | // odr-used if it is the unique lookup result or the selected member of a | |||
17173 | // set of overloaded functions [...]. | |||
17174 | // | |||
17175 | // We (incorrectly) mark overload resolution as an unevaluated context, so we | |||
17176 | // can just check that here. | |||
17177 | OdrUseContext OdrUse = | |||
17178 | MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; | |||
17179 | if (IsRecursiveCall && OdrUse == OdrUseContext::Used) | |||
17180 | OdrUse = OdrUseContext::FormallyOdrUsed; | |||
17181 | ||||
17182 | // Trivial default constructors and destructors are never actually used. | |||
17183 | // FIXME: What about other special members? | |||
17184 | if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && | |||
17185 | OdrUse == OdrUseContext::Used) { | |||
17186 | if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) | |||
17187 | if (Constructor->isDefaultConstructor()) | |||
17188 | OdrUse = OdrUseContext::FormallyOdrUsed; | |||
17189 | if (isa<CXXDestructorDecl>(Func)) | |||
17190 | OdrUse = OdrUseContext::FormallyOdrUsed; | |||
17191 | } | |||
17192 | ||||
17193 | // C++20 [expr.const]p12: | |||
17194 | // A function [...] is needed for constant evaluation if it is [...] a | |||
17195 | // constexpr function that is named by an expression that is potentially | |||
17196 | // constant evaluated | |||
17197 | bool NeededForConstantEvaluation = | |||
17198 | isPotentiallyConstantEvaluatedContext(*this) && | |||
17199 | isImplicitlyDefinableConstexprFunction(Func); | |||
17200 | ||||
17201 | // Determine whether we require a function definition to exist, per | |||
17202 | // C++11 [temp.inst]p3: | |||
17203 | // Unless a function template specialization has been explicitly | |||
17204 | // instantiated or explicitly specialized, the function template | |||
17205 | // specialization is implicitly instantiated when the specialization is | |||
17206 | // referenced in a context that requires a function definition to exist. | |||
17207 | // C++20 [temp.inst]p7: | |||
17208 | // The existence of a definition of a [...] function is considered to | |||
17209 | // affect the semantics of the program if the [...] function is needed for | |||
17210 | // constant evaluation by an expression | |||
17211 | // C++20 [basic.def.odr]p10: | |||
17212 | // Every program shall contain exactly one definition of every non-inline | |||
17213 | // function or variable that is odr-used in that program outside of a | |||
17214 | // discarded statement | |||
17215 | // C++20 [special]p1: | |||
17216 | // The implementation will implicitly define [defaulted special members] | |||
17217 | // if they are odr-used or needed for constant evaluation. | |||
17218 | // | |||
17219 | // Note that we skip the implicit instantiation of templates that are only | |||
17220 | // used in unused default arguments or by recursive calls to themselves. | |||
17221 | // This is formally non-conforming, but seems reasonable in practice. | |||
17222 | bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || | |||
17223 | NeededForConstantEvaluation); | |||
17224 | ||||
17225 | // C++14 [temp.expl.spec]p6: | |||
17226 | // If a template [...] is explicitly specialized then that specialization | |||
17227 | // shall be declared before the first use of that specialization that would | |||
17228 | // cause an implicit instantiation to take place, in every translation unit | |||
17229 | // in which such a use occurs | |||
17230 | if (NeedDefinition && | |||
17231 | (Func->getTemplateSpecializationKind() != TSK_Undeclared || | |||
17232 | Func->getMemberSpecializationInfo())) | |||
17233 | checkSpecializationVisibility(Loc, Func); | |||
17234 | ||||
17235 | if (getLangOpts().CUDA) | |||
17236 | CheckCUDACall(Loc, Func); | |||
17237 | ||||
17238 | if (getLangOpts().SYCLIsDevice) | |||
17239 | checkSYCLDeviceFunction(Loc, Func); | |||
17240 | ||||
17241 | // If we need a definition, try to create one. | |||
17242 | if (NeedDefinition && !Func->getBody()) { | |||
17243 | runWithSufficientStackSpace(Loc, [&] { | |||
17244 | if (CXXConstructorDecl *Constructor = | |||
17245 | dyn_cast<CXXConstructorDecl>(Func)) { | |||
17246 | Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); | |||
17247 | if (Constructor->isDefaulted() && !Constructor->isDeleted()) { | |||
17248 | if (Constructor->isDefaultConstructor()) { | |||
17249 | if (Constructor->isTrivial() && | |||
17250 | !Constructor->hasAttr<DLLExportAttr>()) | |||
17251 | return; | |||
17252 | DefineImplicitDefaultConstructor(Loc, Constructor); | |||
17253 | } else if (Constructor->isCopyConstructor()) { | |||
17254 | DefineImplicitCopyConstructor(Loc, Constructor); | |||
17255 | } else if (Constructor->isMoveConstructor()) { | |||
17256 | DefineImplicitMoveConstructor(Loc, Constructor); | |||
17257 | } | |||
17258 | } else if (Constructor->getInheritedConstructor()) { | |||
17259 | DefineInheritingConstructor(Loc, Constructor); | |||
17260 | } | |||
17261 | } else if (CXXDestructorDecl *Destructor = | |||
17262 | dyn_cast<CXXDestructorDecl>(Func)) { | |||
17263 | Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); | |||
17264 | if (Destructor->isDefaulted() && !Destructor->isDeleted()) { | |||
17265 | if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) | |||
17266 | return; | |||
17267 | DefineImplicitDestructor(Loc, Destructor); | |||
17268 | } | |||
17269 | if (Destructor->isVirtual() && getLangOpts().AppleKext) | |||
17270 | MarkVTableUsed(Loc, Destructor->getParent()); | |||
17271 | } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { | |||
17272 | if (MethodDecl->isOverloadedOperator() && | |||
17273 | MethodDecl->getOverloadedOperator() == OO_Equal) { | |||
17274 | MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); | |||
17275 | if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { | |||
17276 | if (MethodDecl->isCopyAssignmentOperator()) | |||
17277 | DefineImplicitCopyAssignment(Loc, MethodDecl); | |||
17278 | else if (MethodDecl->isMoveAssignmentOperator()) | |||
17279 | DefineImplicitMoveAssignment(Loc, MethodDecl); | |||
17280 | } | |||
17281 | } else if (isa<CXXConversionDecl>(MethodDecl) && | |||
17282 | MethodDecl->getParent()->isLambda()) { | |||
17283 | CXXConversionDecl *Conversion = | |||
17284 | cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); | |||
17285 | if (Conversion->isLambdaToBlockPointerConversion()) | |||
17286 | DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); | |||
17287 | else | |||
17288 | DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); | |||
17289 | } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) | |||
17290 | MarkVTableUsed(Loc, MethodDecl->getParent()); | |||
17291 | } | |||
17292 | ||||
17293 | if (Func->isDefaulted() && !Func->isDeleted()) { | |||
17294 | DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); | |||
17295 | if (DCK != DefaultedComparisonKind::None) | |||
17296 | DefineDefaultedComparison(Loc, Func, DCK); | |||
17297 | } | |||
17298 | ||||
17299 | // Implicit instantiation of function templates and member functions of | |||
17300 | // class templates. | |||
17301 | if (Func->isImplicitlyInstantiable()) { | |||
17302 | TemplateSpecializationKind TSK = | |||
17303 | Func->getTemplateSpecializationKindForInstantiation(); | |||
17304 | SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); | |||
17305 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | |||
17306 | if (FirstInstantiation) { | |||
17307 | PointOfInstantiation = Loc; | |||
17308 | if (auto *MSI = Func->getMemberSpecializationInfo()) | |||
17309 | MSI->setPointOfInstantiation(Loc); | |||
17310 | // FIXME: Notify listener. | |||
17311 | else | |||
17312 | Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); | |||
17313 | } else if (TSK != TSK_ImplicitInstantiation) { | |||
17314 | // Use the point of use as the point of instantiation, instead of the | |||
17315 | // point of explicit instantiation (which we track as the actual point | |||
17316 | // of instantiation). This gives better backtraces in diagnostics. | |||
17317 | PointOfInstantiation = Loc; | |||
17318 | } | |||
17319 | ||||
17320 | if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || | |||
17321 | Func->isConstexpr()) { | |||
17322 | if (isa<CXXRecordDecl>(Func->getDeclContext()) && | |||
17323 | cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && | |||
17324 | CodeSynthesisContexts.size()) | |||
17325 | PendingLocalImplicitInstantiations.push_back( | |||
17326 | std::make_pair(Func, PointOfInstantiation)); | |||
17327 | else if (Func->isConstexpr()) | |||
17328 | // Do not defer instantiations of constexpr functions, to avoid the | |||
17329 | // expression evaluator needing to call back into Sema if it sees a | |||
17330 | // call to such a function. | |||
17331 | InstantiateFunctionDefinition(PointOfInstantiation, Func); | |||
17332 | else { | |||
17333 | Func->setInstantiationIsPending(true); | |||
17334 | PendingInstantiations.push_back( | |||
17335 | std::make_pair(Func, PointOfInstantiation)); | |||
17336 | // Notify the consumer that a function was implicitly instantiated. | |||
17337 | Consumer.HandleCXXImplicitFunctionInstantiation(Func); | |||
17338 | } | |||
17339 | } | |||
17340 | } else { | |||
17341 | // Walk redefinitions, as some of them may be instantiable. | |||
17342 | for (auto i : Func->redecls()) { | |||
17343 | if (!i->isUsed(false) && i->isImplicitlyInstantiable()) | |||
17344 | MarkFunctionReferenced(Loc, i, MightBeOdrUse); | |||
17345 | } | |||
17346 | } | |||
17347 | }); | |||
17348 | } | |||
17349 | ||||
17350 | // C++14 [except.spec]p17: | |||
17351 | // An exception-specification is considered to be needed when: | |||
17352 | // - the function is odr-used or, if it appears in an unevaluated operand, | |||
17353 | // would be odr-used if the expression were potentially-evaluated; | |||
17354 | // | |||
17355 | // Note, we do this even if MightBeOdrUse is false. That indicates that the | |||
17356 | // function is a pure virtual function we're calling, and in that case the | |||
17357 | // function was selected by overload resolution and we need to resolve its | |||
17358 | // exception specification for a different reason. | |||
17359 | const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); | |||
17360 | if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) | |||
17361 | ResolveExceptionSpec(Loc, FPT); | |||
17362 | ||||
17363 | // If this is the first "real" use, act on that. | |||
17364 | if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { | |||
17365 | // Keep track of used but undefined functions. | |||
17366 | if (!Func->isDefined()) { | |||
17367 | if (mightHaveNonExternalLinkage(Func)) | |||
17368 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | |||
17369 | else if (Func->getMostRecentDecl()->isInlined() && | |||
17370 | !LangOpts.GNUInline && | |||
17371 | !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) | |||
17372 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | |||
17373 | else if (isExternalWithNoLinkageType(Func)) | |||
17374 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | |||
17375 | } | |||
17376 | ||||
17377 | // Some x86 Windows calling conventions mangle the size of the parameter | |||
17378 | // pack into the name. Computing the size of the parameters requires the | |||
17379 | // parameter types to be complete. Check that now. | |||
17380 | if (funcHasParameterSizeMangling(*this, Func)) | |||
17381 | CheckCompleteParameterTypesForMangler(*this, Func, Loc); | |||
17382 | ||||
17383 | // In the MS C++ ABI, the compiler emits destructor variants where they are | |||
17384 | // used. If the destructor is used here but defined elsewhere, mark the | |||
17385 | // virtual base destructors referenced. If those virtual base destructors | |||
17386 | // are inline, this will ensure they are defined when emitting the complete | |||
17387 | // destructor variant. This checking may be redundant if the destructor is | |||
17388 | // provided later in this TU. | |||
17389 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
17390 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { | |||
17391 | CXXRecordDecl *Parent = Dtor->getParent(); | |||
17392 | if (Parent->getNumVBases() > 0 && !Dtor->getBody()) | |||
17393 | CheckCompleteDestructorVariant(Loc, Dtor); | |||
17394 | } | |||
17395 | } | |||
17396 | ||||
17397 | Func->markUsed(Context); | |||
17398 | } | |||
17399 | } | |||
17400 | ||||
17401 | /// Directly mark a variable odr-used. Given a choice, prefer to use | |||
17402 | /// MarkVariableReferenced since it does additional checks and then | |||
17403 | /// calls MarkVarDeclODRUsed. | |||
17404 | /// If the variable must be captured: | |||
17405 | /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext | |||
17406 | /// - else capture it in the DeclContext that maps to the | |||
17407 | /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. | |||
17408 | static void | |||
17409 | MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, | |||
17410 | const unsigned *const FunctionScopeIndexToStopAt = nullptr) { | |||
17411 | // Keep track of used but undefined variables. | |||
17412 | // FIXME: We shouldn't suppress this warning for static data members. | |||
17413 | if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && | |||
17414 | (!Var->isExternallyVisible() || Var->isInline() || | |||
17415 | SemaRef.isExternalWithNoLinkageType(Var)) && | |||
17416 | !(Var->isStaticDataMember() && Var->hasInit())) { | |||
17417 | SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; | |||
17418 | if (old.isInvalid()) | |||
17419 | old = Loc; | |||
17420 | } | |||
17421 | QualType CaptureType, DeclRefType; | |||
17422 | if (SemaRef.LangOpts.OpenMP) | |||
17423 | SemaRef.tryCaptureOpenMPLambdas(Var); | |||
17424 | SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, | |||
17425 | /*EllipsisLoc*/ SourceLocation(), | |||
17426 | /*BuildAndDiagnose*/ true, | |||
17427 | CaptureType, DeclRefType, | |||
17428 | FunctionScopeIndexToStopAt); | |||
17429 | ||||
17430 | if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { | |||
17431 | auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); | |||
17432 | auto VarTarget = SemaRef.IdentifyCUDATarget(Var); | |||
17433 | auto UserTarget = SemaRef.IdentifyCUDATarget(FD); | |||
17434 | if (VarTarget == Sema::CVT_Host && | |||
17435 | (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || | |||
17436 | UserTarget == Sema::CFT_Global)) { | |||
17437 | // Diagnose ODR-use of host global variables in device functions. | |||
17438 | // Reference of device global variables in host functions is allowed | |||
17439 | // through shadow variables therefore it is not diagnosed. | |||
17440 | if (SemaRef.LangOpts.CUDAIsDevice) { | |||
17441 | SemaRef.targetDiag(Loc, diag::err_ref_bad_target) | |||
17442 | << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; | |||
17443 | SemaRef.targetDiag(Var->getLocation(), | |||
17444 | Var->getType().isConstQualified() | |||
17445 | ? diag::note_cuda_const_var_unpromoted | |||
17446 | : diag::note_cuda_host_var); | |||
17447 | } | |||
17448 | } else if (VarTarget == Sema::CVT_Device && | |||
17449 | (UserTarget == Sema::CFT_Host || | |||
17450 | UserTarget == Sema::CFT_HostDevice) && | |||
17451 | !Var->hasExternalStorage()) { | |||
17452 | // Record a CUDA/HIP device side variable if it is ODR-used | |||
17453 | // by host code. This is done conservatively, when the variable is | |||
17454 | // referenced in any of the following contexts: | |||
17455 | // - a non-function context | |||
17456 | // - a host function | |||
17457 | // - a host device function | |||
17458 | // This makes the ODR-use of the device side variable by host code to | |||
17459 | // be visible in the device compilation for the compiler to be able to | |||
17460 | // emit template variables instantiated by host code only and to | |||
17461 | // externalize the static device side variable ODR-used by host code. | |||
17462 | SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); | |||
17463 | } | |||
17464 | } | |||
17465 | ||||
17466 | Var->markUsed(SemaRef.Context); | |||
17467 | } | |||
17468 | ||||
17469 | void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, | |||
17470 | SourceLocation Loc, | |||
17471 | unsigned CapturingScopeIndex) { | |||
17472 | MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); | |||
17473 | } | |||
17474 | ||||
17475 | static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | |||
17476 | ValueDecl *var) { | |||
17477 | DeclContext *VarDC = var->getDeclContext(); | |||
17478 | ||||
17479 | // If the parameter still belongs to the translation unit, then | |||
17480 | // we're actually just using one parameter in the declaration of | |||
17481 | // the next. | |||
17482 | if (isa<ParmVarDecl>(var) && | |||
17483 | isa<TranslationUnitDecl>(VarDC)) | |||
17484 | return; | |||
17485 | ||||
17486 | // For C code, don't diagnose about capture if we're not actually in code | |||
17487 | // right now; it's impossible to write a non-constant expression outside of | |||
17488 | // function context, so we'll get other (more useful) diagnostics later. | |||
17489 | // | |||
17490 | // For C++, things get a bit more nasty... it would be nice to suppress this | |||
17491 | // diagnostic for certain cases like using a local variable in an array bound | |||
17492 | // for a member of a local class, but the correct predicate is not obvious. | |||
17493 | if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) | |||
17494 | return; | |||
17495 | ||||
17496 | unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; | |||
17497 | unsigned ContextKind = 3; // unknown | |||
17498 | if (isa<CXXMethodDecl>(VarDC) && | |||
17499 | cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { | |||
17500 | ContextKind = 2; | |||
17501 | } else if (isa<FunctionDecl>(VarDC)) { | |||
17502 | ContextKind = 0; | |||
17503 | } else if (isa<BlockDecl>(VarDC)) { | |||
17504 | ContextKind = 1; | |||
17505 | } | |||
17506 | ||||
17507 | S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) | |||
17508 | << var << ValueKind << ContextKind << VarDC; | |||
17509 | S.Diag(var->getLocation(), diag::note_entity_declared_at) | |||
17510 | << var; | |||
17511 | ||||
17512 | // FIXME: Add additional diagnostic info about class etc. which prevents | |||
17513 | // capture. | |||
17514 | } | |||
17515 | ||||
17516 | ||||
17517 | static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, | |||
17518 | bool &SubCapturesAreNested, | |||
17519 | QualType &CaptureType, | |||
17520 | QualType &DeclRefType) { | |||
17521 | // Check whether we've already captured it. | |||
17522 | if (CSI->CaptureMap.count(Var)) { | |||
17523 | // If we found a capture, any subcaptures are nested. | |||
17524 | SubCapturesAreNested = true; | |||
17525 | ||||
17526 | // Retrieve the capture type for this variable. | |||
17527 | CaptureType = CSI->getCapture(Var).getCaptureType(); | |||
17528 | ||||
17529 | // Compute the type of an expression that refers to this variable. | |||
17530 | DeclRefType = CaptureType.getNonReferenceType(); | |||
17531 | ||||
17532 | // Similarly to mutable captures in lambda, all the OpenMP captures by copy | |||
17533 | // are mutable in the sense that user can change their value - they are | |||
17534 | // private instances of the captured declarations. | |||
17535 | const Capture &Cap = CSI->getCapture(Var); | |||
17536 | if (Cap.isCopyCapture() && | |||
17537 | !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && | |||
17538 | !(isa<CapturedRegionScopeInfo>(CSI) && | |||
17539 | cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) | |||
17540 | DeclRefType.addConst(); | |||
17541 | return true; | |||
17542 | } | |||
17543 | return false; | |||
17544 | } | |||
17545 | ||||
17546 | // Only block literals, captured statements, and lambda expressions can | |||
17547 | // capture; other scopes don't work. | |||
17548 | static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, | |||
17549 | SourceLocation Loc, | |||
17550 | const bool Diagnose, Sema &S) { | |||
17551 | if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) | |||
17552 | return getLambdaAwareParentOfDeclContext(DC); | |||
17553 | else if (Var->hasLocalStorage()) { | |||
17554 | if (Diagnose) | |||
17555 | diagnoseUncapturableValueReference(S, Loc, Var); | |||
17556 | } | |||
17557 | return nullptr; | |||
17558 | } | |||
17559 | ||||
17560 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | |||
17561 | // certain types of variables (unnamed, variably modified types etc.) | |||
17562 | // so check for eligibility. | |||
17563 | static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, | |||
17564 | SourceLocation Loc, | |||
17565 | const bool Diagnose, Sema &S) { | |||
17566 | ||||
17567 | bool IsBlock = isa<BlockScopeInfo>(CSI); | |||
17568 | bool IsLambda = isa<LambdaScopeInfo>(CSI); | |||
17569 | ||||
17570 | // Lambdas are not allowed to capture unnamed variables | |||
17571 | // (e.g. anonymous unions). | |||
17572 | // FIXME: The C++11 rule don't actually state this explicitly, but I'm | |||
17573 | // assuming that's the intent. | |||
17574 | if (IsLambda && !Var->getDeclName()) { | |||
17575 | if (Diagnose) { | |||
17576 | S.Diag(Loc, diag::err_lambda_capture_anonymous_var); | |||
17577 | S.Diag(Var->getLocation(), diag::note_declared_at); | |||
17578 | } | |||
17579 | return false; | |||
17580 | } | |||
17581 | ||||
17582 | // Prohibit variably-modified types in blocks; they're difficult to deal with. | |||
17583 | if (Var->getType()->isVariablyModifiedType() && IsBlock) { | |||
17584 | if (Diagnose) { | |||
17585 | S.Diag(Loc, diag::err_ref_vm_type); | |||
17586 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
17587 | } | |||
17588 | return false; | |||
17589 | } | |||
17590 | // Prohibit structs with flexible array members too. | |||
17591 | // We cannot capture what is in the tail end of the struct. | |||
17592 | if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { | |||
17593 | if (VTTy->getDecl()->hasFlexibleArrayMember()) { | |||
17594 | if (Diagnose) { | |||
17595 | if (IsBlock) | |||
17596 | S.Diag(Loc, diag::err_ref_flexarray_type); | |||
17597 | else | |||
17598 | S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; | |||
17599 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
17600 | } | |||
17601 | return false; | |||
17602 | } | |||
17603 | } | |||
17604 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | |||
17605 | // Lambdas and captured statements are not allowed to capture __block | |||
17606 | // variables; they don't support the expected semantics. | |||
17607 | if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { | |||
17608 | if (Diagnose) { | |||
17609 | S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; | |||
17610 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
17611 | } | |||
17612 | return false; | |||
17613 | } | |||
17614 | // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks | |||
17615 | if (S.getLangOpts().OpenCL && IsBlock && | |||
17616 | Var->getType()->isBlockPointerType()) { | |||
17617 | if (Diagnose) | |||
17618 | S.Diag(Loc, diag::err_opencl_block_ref_block); | |||
17619 | return false; | |||
17620 | } | |||
17621 | ||||
17622 | return true; | |||
17623 | } | |||
17624 | ||||
17625 | // Returns true if the capture by block was successful. | |||
17626 | static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, | |||
17627 | SourceLocation Loc, | |||
17628 | const bool BuildAndDiagnose, | |||
17629 | QualType &CaptureType, | |||
17630 | QualType &DeclRefType, | |||
17631 | const bool Nested, | |||
17632 | Sema &S, bool Invalid) { | |||
17633 | bool ByRef = false; | |||
17634 | ||||
17635 | // Blocks are not allowed to capture arrays, excepting OpenCL. | |||
17636 | // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference | |||
17637 | // (decayed to pointers). | |||
17638 | if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { | |||
17639 | if (BuildAndDiagnose) { | |||
17640 | S.Diag(Loc, diag::err_ref_array_type); | |||
17641 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
17642 | Invalid = true; | |||
17643 | } else { | |||
17644 | return false; | |||
17645 | } | |||
17646 | } | |||
17647 | ||||
17648 | // Forbid the block-capture of autoreleasing variables. | |||
17649 | if (!Invalid && | |||
17650 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | |||
17651 | if (BuildAndDiagnose) { | |||
17652 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) | |||
17653 | << /*block*/ 0; | |||
17654 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
17655 | Invalid = true; | |||
17656 | } else { | |||
17657 | return false; | |||
17658 | } | |||
17659 | } | |||
17660 | ||||
17661 | // Warn about implicitly autoreleasing indirect parameters captured by blocks. | |||
17662 | if (const auto *PT = CaptureType->getAs<PointerType>()) { | |||
17663 | QualType PointeeTy = PT->getPointeeType(); | |||
17664 | ||||
17665 | if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && | |||
17666 | PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && | |||
17667 | !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { | |||
17668 | if (BuildAndDiagnose) { | |||
17669 | SourceLocation VarLoc = Var->getLocation(); | |||
17670 | S.Diag(Loc, diag::warn_block_capture_autoreleasing); | |||
17671 | S.Diag(VarLoc, diag::note_declare_parameter_strong); | |||
17672 | } | |||
17673 | } | |||
17674 | } | |||
17675 | ||||
17676 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | |||
17677 | if (HasBlocksAttr || CaptureType->isReferenceType() || | |||
17678 | (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { | |||
17679 | // Block capture by reference does not change the capture or | |||
17680 | // declaration reference types. | |||
17681 | ByRef = true; | |||
17682 | } else { | |||
17683 | // Block capture by copy introduces 'const'. | |||
17684 | CaptureType = CaptureType.getNonReferenceType().withConst(); | |||
17685 | DeclRefType = CaptureType; | |||
17686 | } | |||
17687 | ||||
17688 | // Actually capture the variable. | |||
17689 | if (BuildAndDiagnose) | |||
17690 | BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), | |||
17691 | CaptureType, Invalid); | |||
17692 | ||||
17693 | return !Invalid; | |||
17694 | } | |||
17695 | ||||
17696 | ||||
17697 | /// Capture the given variable in the captured region. | |||
17698 | static bool captureInCapturedRegion( | |||
17699 | CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, | |||
17700 | const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, | |||
17701 | const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, | |||
17702 | bool IsTopScope, Sema &S, bool Invalid) { | |||
17703 | // By default, capture variables by reference. | |||
17704 | bool ByRef = true; | |||
17705 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | |||
17706 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | |||
17707 | } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { | |||
17708 | // Using an LValue reference type is consistent with Lambdas (see below). | |||
17709 | if (S.isOpenMPCapturedDecl(Var)) { | |||
17710 | bool HasConst = DeclRefType.isConstQualified(); | |||
17711 | DeclRefType = DeclRefType.getUnqualifiedType(); | |||
17712 | // Don't lose diagnostics about assignments to const. | |||
17713 | if (HasConst) | |||
17714 | DeclRefType.addConst(); | |||
17715 | } | |||
17716 | // Do not capture firstprivates in tasks. | |||
17717 | if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != | |||
17718 | OMPC_unknown) | |||
17719 | return true; | |||
17720 | ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, | |||
17721 | RSI->OpenMPCaptureLevel); | |||
17722 | } | |||
17723 | ||||
17724 | if (ByRef) | |||
17725 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | |||
17726 | else | |||
17727 | CaptureType = DeclRefType; | |||
17728 | ||||
17729 | // Actually capture the variable. | |||
17730 | if (BuildAndDiagnose) | |||
17731 | RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, | |||
17732 | Loc, SourceLocation(), CaptureType, Invalid); | |||
17733 | ||||
17734 | return !Invalid; | |||
17735 | } | |||
17736 | ||||
17737 | /// Capture the given variable in the lambda. | |||
17738 | static bool captureInLambda(LambdaScopeInfo *LSI, | |||
17739 | VarDecl *Var, | |||
17740 | SourceLocation Loc, | |||
17741 | const bool BuildAndDiagnose, | |||
17742 | QualType &CaptureType, | |||
17743 | QualType &DeclRefType, | |||
17744 | const bool RefersToCapturedVariable, | |||
17745 | const Sema::TryCaptureKind Kind, | |||
17746 | SourceLocation EllipsisLoc, | |||
17747 | const bool IsTopScope, | |||
17748 | Sema &S, bool Invalid) { | |||
17749 | // Determine whether we are capturing by reference or by value. | |||
17750 | bool ByRef = false; | |||
17751 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | |||
17752 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | |||
17753 | } else { | |||
17754 | ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); | |||
17755 | } | |||
17756 | ||||
17757 | // Compute the type of the field that will capture this variable. | |||
17758 | if (ByRef) { | |||
17759 | // C++11 [expr.prim.lambda]p15: | |||
17760 | // An entity is captured by reference if it is implicitly or | |||
17761 | // explicitly captured but not captured by copy. It is | |||
17762 | // unspecified whether additional unnamed non-static data | |||
17763 | // members are declared in the closure type for entities | |||
17764 | // captured by reference. | |||
17765 | // | |||
17766 | // FIXME: It is not clear whether we want to build an lvalue reference | |||
17767 | // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears | |||
17768 | // to do the former, while EDG does the latter. Core issue 1249 will | |||
17769 | // clarify, but for now we follow GCC because it's a more permissive and | |||
17770 | // easily defensible position. | |||
17771 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | |||
17772 | } else { | |||
17773 | // C++11 [expr.prim.lambda]p14: | |||
17774 | // For each entity captured by copy, an unnamed non-static | |||
17775 | // data member is declared in the closure type. The | |||
17776 | // declaration order of these members is unspecified. The type | |||
17777 | // of such a data member is the type of the corresponding | |||
17778 | // captured entity if the entity is not a reference to an | |||
17779 | // object, or the referenced type otherwise. [Note: If the | |||
17780 | // captured entity is a reference to a function, the | |||
17781 | // corresponding data member is also a reference to a | |||
17782 | // function. - end note ] | |||
17783 | if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ | |||
17784 | if (!RefType->getPointeeType()->isFunctionType()) | |||
17785 | CaptureType = RefType->getPointeeType(); | |||
17786 | } | |||
17787 | ||||
17788 | // Forbid the lambda copy-capture of autoreleasing variables. | |||
17789 | if (!Invalid && | |||
17790 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | |||
17791 | if (BuildAndDiagnose) { | |||
17792 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; | |||
17793 | S.Diag(Var->getLocation(), diag::note_previous_decl) | |||
17794 | << Var->getDeclName(); | |||
17795 | Invalid = true; | |||
17796 | } else { | |||
17797 | return false; | |||
17798 | } | |||
17799 | } | |||
17800 | ||||
17801 | // Make sure that by-copy captures are of a complete and non-abstract type. | |||
17802 | if (!Invalid && BuildAndDiagnose) { | |||
17803 | if (!CaptureType->isDependentType() && | |||
17804 | S.RequireCompleteSizedType( | |||
17805 | Loc, CaptureType, | |||
17806 | diag::err_capture_of_incomplete_or_sizeless_type, | |||
17807 | Var->getDeclName())) | |||
17808 | Invalid = true; | |||
17809 | else if (S.RequireNonAbstractType(Loc, CaptureType, | |||
17810 | diag::err_capture_of_abstract_type)) | |||
17811 | Invalid = true; | |||
17812 | } | |||
17813 | } | |||
17814 | ||||
17815 | // Compute the type of a reference to this captured variable. | |||
17816 | if (ByRef) | |||
17817 | DeclRefType = CaptureType.getNonReferenceType(); | |||
17818 | else { | |||
17819 | // C++ [expr.prim.lambda]p5: | |||
17820 | // The closure type for a lambda-expression has a public inline | |||
17821 | // function call operator [...]. This function call operator is | |||
17822 | // declared const (9.3.1) if and only if the lambda-expression's | |||
17823 | // parameter-declaration-clause is not followed by mutable. | |||
17824 | DeclRefType = CaptureType.getNonReferenceType(); | |||
17825 | if (!LSI->Mutable && !CaptureType->isReferenceType()) | |||
17826 | DeclRefType.addConst(); | |||
17827 | } | |||
17828 | ||||
17829 | // Add the capture. | |||
17830 | if (BuildAndDiagnose) | |||
17831 | LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, | |||
17832 | Loc, EllipsisLoc, CaptureType, Invalid); | |||
17833 | ||||
17834 | return !Invalid; | |||
17835 | } | |||
17836 | ||||
17837 | static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { | |||
17838 | // Offer a Copy fix even if the type is dependent. | |||
17839 | if (Var->getType()->isDependentType()) | |||
17840 | return true; | |||
17841 | QualType T = Var->getType().getNonReferenceType(); | |||
17842 | if (T.isTriviallyCopyableType(Context)) | |||
17843 | return true; | |||
17844 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { | |||
17845 | ||||
17846 | if (!(RD = RD->getDefinition())) | |||
17847 | return false; | |||
17848 | if (RD->hasSimpleCopyConstructor()) | |||
17849 | return true; | |||
17850 | if (RD->hasUserDeclaredCopyConstructor()) | |||
17851 | for (CXXConstructorDecl *Ctor : RD->ctors()) | |||
17852 | if (Ctor->isCopyConstructor()) | |||
17853 | return !Ctor->isDeleted(); | |||
17854 | } | |||
17855 | return false; | |||
17856 | } | |||
17857 | ||||
17858 | /// Create up to 4 fix-its for explicit reference and value capture of \p Var or | |||
17859 | /// default capture. Fixes may be omitted if they aren't allowed by the | |||
17860 | /// standard, for example we can't emit a default copy capture fix-it if we | |||
17861 | /// already explicitly copy capture capture another variable. | |||
17862 | static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, | |||
17863 | VarDecl *Var) { | |||
17864 | assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None)(static_cast <bool> (LSI->ImpCaptureStyle == CapturingScopeInfo ::ImpCap_None) ? void (0) : __assert_fail ("LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None" , "clang/lib/Sema/SemaExpr.cpp", 17864, __extension__ __PRETTY_FUNCTION__ )); | |||
17865 | // Don't offer Capture by copy of default capture by copy fixes if Var is | |||
17866 | // known not to be copy constructible. | |||
17867 | bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); | |||
17868 | ||||
17869 | SmallString<32> FixBuffer; | |||
17870 | StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; | |||
17871 | if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { | |||
17872 | SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); | |||
17873 | if (ShouldOfferCopyFix) { | |||
17874 | // Offer fixes to insert an explicit capture for the variable. | |||
17875 | // [] -> [VarName] | |||
17876 | // [OtherCapture] -> [OtherCapture, VarName] | |||
17877 | FixBuffer.assign({Separator, Var->getName()}); | |||
17878 | Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) | |||
17879 | << Var << /*value*/ 0 | |||
17880 | << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); | |||
17881 | } | |||
17882 | // As above but capture by reference. | |||
17883 | FixBuffer.assign({Separator, "&", Var->getName()}); | |||
17884 | Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) | |||
17885 | << Var << /*reference*/ 1 | |||
17886 | << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); | |||
17887 | } | |||
17888 | ||||
17889 | // Only try to offer default capture if there are no captures excluding this | |||
17890 | // and init captures. | |||
17891 | // [this]: OK. | |||
17892 | // [X = Y]: OK. | |||
17893 | // [&A, &B]: Don't offer. | |||
17894 | // [A, B]: Don't offer. | |||
17895 | if (llvm::any_of(LSI->Captures, [](Capture &C) { | |||
17896 | return !C.isThisCapture() && !C.isInitCapture(); | |||
17897 | })) | |||
17898 | return; | |||
17899 | ||||
17900 | // The default capture specifiers, '=' or '&', must appear first in the | |||
17901 | // capture body. | |||
17902 | SourceLocation DefaultInsertLoc = | |||
17903 | LSI->IntroducerRange.getBegin().getLocWithOffset(1); | |||
17904 | ||||
17905 | if (ShouldOfferCopyFix) { | |||
17906 | bool CanDefaultCopyCapture = true; | |||
17907 | // [=, *this] OK since c++17 | |||
17908 | // [=, this] OK since c++20 | |||
17909 | if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) | |||
17910 | CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 | |||
17911 | ? LSI->getCXXThisCapture().isCopyCapture() | |||
17912 | : false; | |||
17913 | // We can't use default capture by copy if any captures already specified | |||
17914 | // capture by copy. | |||
17915 | if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { | |||
17916 | return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); | |||
17917 | })) { | |||
17918 | FixBuffer.assign({"=", Separator}); | |||
17919 | Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) | |||
17920 | << /*value*/ 0 | |||
17921 | << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); | |||
17922 | } | |||
17923 | } | |||
17924 | ||||
17925 | // We can't use default capture by reference if any captures already specified | |||
17926 | // capture by reference. | |||
17927 | if (llvm::none_of(LSI->Captures, [](Capture &C) { | |||
17928 | return !C.isInitCapture() && C.isReferenceCapture() && | |||
17929 | !C.isThisCapture(); | |||
17930 | })) { | |||
17931 | FixBuffer.assign({"&", Separator}); | |||
17932 | Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) | |||
17933 | << /*reference*/ 1 | |||
17934 | << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); | |||
17935 | } | |||
17936 | } | |||
17937 | ||||
17938 | bool Sema::tryCaptureVariable( | |||
17939 | VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, | |||
17940 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, | |||
17941 | QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { | |||
17942 | // An init-capture is notionally from the context surrounding its | |||
17943 | // declaration, but its parent DC is the lambda class. | |||
17944 | DeclContext *VarDC = Var->getDeclContext(); | |||
17945 | if (Var->isInitCapture()) | |||
17946 | VarDC = VarDC->getParent(); | |||
17947 | ||||
17948 | DeclContext *DC = CurContext; | |||
17949 | const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt | |||
17950 | ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; | |||
17951 | // We need to sync up the Declaration Context with the | |||
17952 | // FunctionScopeIndexToStopAt | |||
17953 | if (FunctionScopeIndexToStopAt) { | |||
17954 | unsigned FSIndex = FunctionScopes.size() - 1; | |||
17955 | while (FSIndex != MaxFunctionScopesIndex) { | |||
17956 | DC = getLambdaAwareParentOfDeclContext(DC); | |||
17957 | --FSIndex; | |||
17958 | } | |||
17959 | } | |||
17960 | ||||
17961 | ||||
17962 | // If the variable is declared in the current context, there is no need to | |||
17963 | // capture it. | |||
17964 | if (VarDC == DC) return true; | |||
17965 | ||||
17966 | // Capture global variables if it is required to use private copy of this | |||
17967 | // variable. | |||
17968 | bool IsGlobal = !Var->hasLocalStorage(); | |||
17969 | if (IsGlobal && | |||
17970 | !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, | |||
17971 | MaxFunctionScopesIndex))) | |||
17972 | return true; | |||
17973 | Var = Var->getCanonicalDecl(); | |||
17974 | ||||
17975 | // Walk up the stack to determine whether we can capture the variable, | |||
17976 | // performing the "simple" checks that don't depend on type. We stop when | |||
17977 | // we've either hit the declared scope of the variable or find an existing | |||
17978 | // capture of that variable. We start from the innermost capturing-entity | |||
17979 | // (the DC) and ensure that all intervening capturing-entities | |||
17980 | // (blocks/lambdas etc.) between the innermost capturer and the variable`s | |||
17981 | // declcontext can either capture the variable or have already captured | |||
17982 | // the variable. | |||
17983 | CaptureType = Var->getType(); | |||
17984 | DeclRefType = CaptureType.getNonReferenceType(); | |||
17985 | bool Nested = false; | |||
17986 | bool Explicit = (Kind != TryCapture_Implicit); | |||
17987 | unsigned FunctionScopesIndex = MaxFunctionScopesIndex; | |||
17988 | do { | |||
17989 | // Only block literals, captured statements, and lambda expressions can | |||
17990 | // capture; other scopes don't work. | |||
17991 | DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, | |||
17992 | ExprLoc, | |||
17993 | BuildAndDiagnose, | |||
17994 | *this); | |||
17995 | // We need to check for the parent *first* because, if we *have* | |||
17996 | // private-captured a global variable, we need to recursively capture it in | |||
17997 | // intermediate blocks, lambdas, etc. | |||
17998 | if (!ParentDC) { | |||
17999 | if (IsGlobal) { | |||
18000 | FunctionScopesIndex = MaxFunctionScopesIndex - 1; | |||
18001 | break; | |||
18002 | } | |||
18003 | return true; | |||
18004 | } | |||
18005 | ||||
18006 | FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; | |||
18007 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); | |||
18008 | ||||
18009 | ||||
18010 | // Check whether we've already captured it. | |||
18011 | if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, | |||
18012 | DeclRefType)) { | |||
18013 | CSI->getCapture(Var).markUsed(BuildAndDiagnose); | |||
18014 | break; | |||
18015 | } | |||
18016 | // If we are instantiating a generic lambda call operator body, | |||
18017 | // we do not want to capture new variables. What was captured | |||
18018 | // during either a lambdas transformation or initial parsing | |||
18019 | // should be used. | |||
18020 | if (isGenericLambdaCallOperatorSpecialization(DC)) { | |||
18021 | if (BuildAndDiagnose) { | |||
18022 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | |||
18023 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { | |||
18024 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | |||
18025 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
18026 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); | |||
18027 | buildLambdaCaptureFixit(*this, LSI, Var); | |||
18028 | } else | |||
18029 | diagnoseUncapturableValueReference(*this, ExprLoc, Var); | |||
18030 | } | |||
18031 | return true; | |||
18032 | } | |||
18033 | ||||
18034 | // Try to capture variable-length arrays types. | |||
18035 | if (Var->getType()->isVariablyModifiedType()) { | |||
18036 | // We're going to walk down into the type and look for VLA | |||
18037 | // expressions. | |||
18038 | QualType QTy = Var->getType(); | |||
18039 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | |||
18040 | QTy = PVD->getOriginalType(); | |||
18041 | captureVariablyModifiedType(Context, QTy, CSI); | |||
18042 | } | |||
18043 | ||||
18044 | if (getLangOpts().OpenMP) { | |||
18045 | if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | |||
18046 | // OpenMP private variables should not be captured in outer scope, so | |||
18047 | // just break here. Similarly, global variables that are captured in a | |||
18048 | // target region should not be captured outside the scope of the region. | |||
18049 | if (RSI->CapRegionKind == CR_OpenMP) { | |||
18050 | OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( | |||
18051 | Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); | |||
18052 | // If the variable is private (i.e. not captured) and has variably | |||
18053 | // modified type, we still need to capture the type for correct | |||
18054 | // codegen in all regions, associated with the construct. Currently, | |||
18055 | // it is captured in the innermost captured region only. | |||
18056 | if (IsOpenMPPrivateDecl != OMPC_unknown && | |||
18057 | Var->getType()->isVariablyModifiedType()) { | |||
18058 | QualType QTy = Var->getType(); | |||
18059 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | |||
18060 | QTy = PVD->getOriginalType(); | |||
18061 | for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); | |||
18062 | I < E; ++I) { | |||
18063 | auto *OuterRSI = cast<CapturedRegionScopeInfo>( | |||
18064 | FunctionScopes[FunctionScopesIndex - I]); | |||
18065 | assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&(static_cast <bool> (RSI->OpenMPLevel == OuterRSI-> OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "clang/lib/Sema/SemaExpr.cpp", 18067, __extension__ __PRETTY_FUNCTION__ )) | |||
18066 | "Wrong number of captured regions associated with the "(static_cast <bool> (RSI->OpenMPLevel == OuterRSI-> OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "clang/lib/Sema/SemaExpr.cpp", 18067, __extension__ __PRETTY_FUNCTION__ )) | |||
18067 | "OpenMP construct.")(static_cast <bool> (RSI->OpenMPLevel == OuterRSI-> OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "clang/lib/Sema/SemaExpr.cpp", 18067, __extension__ __PRETTY_FUNCTION__ )); | |||
18068 | captureVariablyModifiedType(Context, QTy, OuterRSI); | |||
18069 | } | |||
18070 | } | |||
18071 | bool IsTargetCap = | |||
18072 | IsOpenMPPrivateDecl != OMPC_private && | |||
18073 | isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, | |||
18074 | RSI->OpenMPCaptureLevel); | |||
18075 | // Do not capture global if it is not privatized in outer regions. | |||
18076 | bool IsGlobalCap = | |||
18077 | IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, | |||
18078 | RSI->OpenMPCaptureLevel); | |||
18079 | ||||
18080 | // When we detect target captures we are looking from inside the | |||
18081 | // target region, therefore we need to propagate the capture from the | |||
18082 | // enclosing region. Therefore, the capture is not initially nested. | |||
18083 | if (IsTargetCap) | |||
18084 | adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); | |||
18085 | ||||
18086 | if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || | |||
18087 | (IsGlobal && !IsGlobalCap)) { | |||
18088 | Nested = !IsTargetCap; | |||
18089 | bool HasConst = DeclRefType.isConstQualified(); | |||
18090 | DeclRefType = DeclRefType.getUnqualifiedType(); | |||
18091 | // Don't lose diagnostics about assignments to const. | |||
18092 | if (HasConst) | |||
18093 | DeclRefType.addConst(); | |||
18094 | CaptureType = Context.getLValueReferenceType(DeclRefType); | |||
18095 | break; | |||
18096 | } | |||
18097 | } | |||
18098 | } | |||
18099 | } | |||
18100 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { | |||
18101 | // No capture-default, and this is not an explicit capture | |||
18102 | // so cannot capture this variable. | |||
18103 | if (BuildAndDiagnose) { | |||
18104 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | |||
18105 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
18106 | auto *LSI = cast<LambdaScopeInfo>(CSI); | |||
18107 | if (LSI->Lambda) { | |||
18108 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); | |||
18109 | buildLambdaCaptureFixit(*this, LSI, Var); | |||
18110 | } | |||
18111 | // FIXME: If we error out because an outer lambda can not implicitly | |||
18112 | // capture a variable that an inner lambda explicitly captures, we | |||
18113 | // should have the inner lambda do the explicit capture - because | |||
18114 | // it makes for cleaner diagnostics later. This would purely be done | |||
18115 | // so that the diagnostic does not misleadingly claim that a variable | |||
18116 | // can not be captured by a lambda implicitly even though it is captured | |||
18117 | // explicitly. Suggestion: | |||
18118 | // - create const bool VariableCaptureWasInitiallyExplicit = Explicit | |||
18119 | // at the function head | |||
18120 | // - cache the StartingDeclContext - this must be a lambda | |||
18121 | // - captureInLambda in the innermost lambda the variable. | |||
18122 | } | |||
18123 | return true; | |||
18124 | } | |||
18125 | ||||
18126 | FunctionScopesIndex--; | |||
18127 | DC = ParentDC; | |||
18128 | Explicit = false; | |||
18129 | } while (!VarDC->Equals(DC)); | |||
18130 | ||||
18131 | // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) | |||
18132 | // computing the type of the capture at each step, checking type-specific | |||
18133 | // requirements, and adding captures if requested. | |||
18134 | // If the variable had already been captured previously, we start capturing | |||
18135 | // at the lambda nested within that one. | |||
18136 | bool Invalid = false; | |||
18137 | for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; | |||
18138 | ++I) { | |||
18139 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); | |||
18140 | ||||
18141 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | |||
18142 | // certain types of variables (unnamed, variably modified types etc.) | |||
18143 | // so check for eligibility. | |||
18144 | if (!Invalid) | |||
18145 | Invalid = | |||
18146 | !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); | |||
18147 | ||||
18148 | // After encountering an error, if we're actually supposed to capture, keep | |||
18149 | // capturing in nested contexts to suppress any follow-on diagnostics. | |||
18150 | if (Invalid && !BuildAndDiagnose) | |||
18151 | return true; | |||
18152 | ||||
18153 | if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { | |||
18154 | Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | |||
18155 | DeclRefType, Nested, *this, Invalid); | |||
18156 | Nested = true; | |||
18157 | } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | |||
18158 | Invalid = !captureInCapturedRegion( | |||
18159 | RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, | |||
18160 | Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); | |||
18161 | Nested = true; | |||
18162 | } else { | |||
18163 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | |||
18164 | Invalid = | |||
18165 | !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | |||
18166 | DeclRefType, Nested, Kind, EllipsisLoc, | |||
18167 | /*IsTopScope*/ I == N - 1, *this, Invalid); | |||
18168 | Nested = true; | |||
18169 | } | |||
18170 | ||||
18171 | if (Invalid && !BuildAndDiagnose) | |||
18172 | return true; | |||
18173 | } | |||
18174 | return Invalid; | |||
18175 | } | |||
18176 | ||||
18177 | bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, | |||
18178 | TryCaptureKind Kind, SourceLocation EllipsisLoc) { | |||
18179 | QualType CaptureType; | |||
18180 | QualType DeclRefType; | |||
18181 | return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, | |||
18182 | /*BuildAndDiagnose=*/true, CaptureType, | |||
18183 | DeclRefType, nullptr); | |||
18184 | } | |||
18185 | ||||
18186 | bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { | |||
18187 | QualType CaptureType; | |||
18188 | QualType DeclRefType; | |||
18189 | return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | |||
18190 | /*BuildAndDiagnose=*/false, CaptureType, | |||
18191 | DeclRefType, nullptr); | |||
18192 | } | |||
18193 | ||||
18194 | QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { | |||
18195 | QualType CaptureType; | |||
18196 | QualType DeclRefType; | |||
18197 | ||||
18198 | // Determine whether we can capture this variable. | |||
18199 | if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | |||
18200 | /*BuildAndDiagnose=*/false, CaptureType, | |||
18201 | DeclRefType, nullptr)) | |||
18202 | return QualType(); | |||
18203 | ||||
18204 | return DeclRefType; | |||
18205 | } | |||
18206 | ||||
18207 | namespace { | |||
18208 | // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. | |||
18209 | // The produced TemplateArgumentListInfo* points to data stored within this | |||
18210 | // object, so should only be used in contexts where the pointer will not be | |||
18211 | // used after the CopiedTemplateArgs object is destroyed. | |||
18212 | class CopiedTemplateArgs { | |||
18213 | bool HasArgs; | |||
18214 | TemplateArgumentListInfo TemplateArgStorage; | |||
18215 | public: | |||
18216 | template<typename RefExpr> | |||
18217 | CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { | |||
18218 | if (HasArgs) | |||
18219 | E->copyTemplateArgumentsInto(TemplateArgStorage); | |||
18220 | } | |||
18221 | operator TemplateArgumentListInfo*() | |||
18222 | #ifdef __has_cpp_attribute | |||
18223 | #if0 __has_cpp_attribute(clang::lifetimebound)1 | |||
18224 | [[clang::lifetimebound]] | |||
18225 | #endif | |||
18226 | #endif | |||
18227 | { | |||
18228 | return HasArgs ? &TemplateArgStorage : nullptr; | |||
18229 | } | |||
18230 | }; | |||
18231 | } | |||
18232 | ||||
18233 | /// Walk the set of potential results of an expression and mark them all as | |||
18234 | /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. | |||
18235 | /// | |||
18236 | /// \return A new expression if we found any potential results, ExprEmpty() if | |||
18237 | /// not, and ExprError() if we diagnosed an error. | |||
18238 | static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, | |||
18239 | NonOdrUseReason NOUR) { | |||
18240 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it is | |||
18241 | // an object that satisfies the requirements for appearing in a | |||
18242 | // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) | |||
18243 | // is immediately applied." This function handles the lvalue-to-rvalue | |||
18244 | // conversion part. | |||
18245 | // | |||
18246 | // If we encounter a node that claims to be an odr-use but shouldn't be, we | |||
18247 | // transform it into the relevant kind of non-odr-use node and rebuild the | |||
18248 | // tree of nodes leading to it. | |||
18249 | // | |||
18250 | // This is a mini-TreeTransform that only transforms a restricted subset of | |||
18251 | // nodes (and only certain operands of them). | |||
18252 | ||||
18253 | // Rebuild a subexpression. | |||
18254 | auto Rebuild = [&](Expr *Sub) { | |||
18255 | return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); | |||
18256 | }; | |||
18257 | ||||
18258 | // Check whether a potential result satisfies the requirements of NOUR. | |||
18259 | auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { | |||
18260 | // Any entity other than a VarDecl is always odr-used whenever it's named | |||
18261 | // in a potentially-evaluated expression. | |||
18262 | auto *VD = dyn_cast<VarDecl>(D); | |||
18263 | if (!VD) | |||
18264 | return true; | |||
18265 | ||||
18266 | // C++2a [basic.def.odr]p4: | |||
18267 | // A variable x whose name appears as a potentially-evalauted expression | |||
18268 | // e is odr-used by e unless | |||
18269 | // -- x is a reference that is usable in constant expressions, or | |||
18270 | // -- x is a variable of non-reference type that is usable in constant | |||
18271 | // expressions and has no mutable subobjects, and e is an element of | |||
18272 | // the set of potential results of an expression of | |||
18273 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | |||
18274 | // conversion is applied, or | |||
18275 | // -- x is a variable of non-reference type, and e is an element of the | |||
18276 | // set of potential results of a discarded-value expression to which | |||
18277 | // the lvalue-to-rvalue conversion is not applied | |||
18278 | // | |||
18279 | // We check the first bullet and the "potentially-evaluated" condition in | |||
18280 | // BuildDeclRefExpr. We check the type requirements in the second bullet | |||
18281 | // in CheckLValueToRValueConversionOperand below. | |||
18282 | switch (NOUR) { | |||
18283 | case NOUR_None: | |||
18284 | case NOUR_Unevaluated: | |||
18285 | llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason" , "clang/lib/Sema/SemaExpr.cpp", 18285); | |||
18286 | ||||
18287 | case NOUR_Constant: | |||
18288 | // Constant references were handled when they were built. | |||
18289 | if (VD->getType()->isReferenceType()) | |||
18290 | return true; | |||
18291 | if (auto *RD = VD->getType()->getAsCXXRecordDecl()) | |||
18292 | if (RD->hasMutableFields()) | |||
18293 | return true; | |||
18294 | if (!VD->isUsableInConstantExpressions(S.Context)) | |||
18295 | return true; | |||
18296 | break; | |||
18297 | ||||
18298 | case NOUR_Discarded: | |||
18299 | if (VD->getType()->isReferenceType()) | |||
18300 | return true; | |||
18301 | break; | |||
18302 | } | |||
18303 | return false; | |||
18304 | }; | |||
18305 | ||||
18306 | // Mark that this expression does not constitute an odr-use. | |||
18307 | auto MarkNotOdrUsed = [&] { | |||
18308 | S.MaybeODRUseExprs.remove(E); | |||
18309 | if (LambdaScopeInfo *LSI = S.getCurLambda()) | |||
18310 | LSI->markVariableExprAsNonODRUsed(E); | |||
18311 | }; | |||
18312 | ||||
18313 | // C++2a [basic.def.odr]p2: | |||
18314 | // The set of potential results of an expression e is defined as follows: | |||
18315 | switch (E->getStmtClass()) { | |||
18316 | // -- If e is an id-expression, ... | |||
18317 | case Expr::DeclRefExprClass: { | |||
18318 | auto *DRE = cast<DeclRefExpr>(E); | |||
18319 | if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) | |||
18320 | break; | |||
18321 | ||||
18322 | // Rebuild as a non-odr-use DeclRefExpr. | |||
18323 | MarkNotOdrUsed(); | |||
18324 | return DeclRefExpr::Create( | |||
18325 | S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), | |||
18326 | DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), | |||
18327 | DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), | |||
18328 | DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); | |||
18329 | } | |||
18330 | ||||
18331 | case Expr::FunctionParmPackExprClass: { | |||
18332 | auto *FPPE = cast<FunctionParmPackExpr>(E); | |||
18333 | // If any of the declarations in the pack is odr-used, then the expression | |||
18334 | // as a whole constitutes an odr-use. | |||
18335 | for (VarDecl *D : *FPPE) | |||
18336 | if (IsPotentialResultOdrUsed(D)) | |||
18337 | return ExprEmpty(); | |||
18338 | ||||
18339 | // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, | |||
18340 | // nothing cares about whether we marked this as an odr-use, but it might | |||
18341 | // be useful for non-compiler tools. | |||
18342 | MarkNotOdrUsed(); | |||
18343 | break; | |||
18344 | } | |||
18345 | ||||
18346 | // -- If e is a subscripting operation with an array operand... | |||
18347 | case Expr::ArraySubscriptExprClass: { | |||
18348 | auto *ASE = cast<ArraySubscriptExpr>(E); | |||
18349 | Expr *OldBase = ASE->getBase()->IgnoreImplicit(); | |||
18350 | if (!OldBase->getType()->isArrayType()) | |||
18351 | break; | |||
18352 | ExprResult Base = Rebuild(OldBase); | |||
18353 | if (!Base.isUsable()) | |||
18354 | return Base; | |||
18355 | Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); | |||
18356 | Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); | |||
18357 | SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. | |||
18358 | return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, | |||
18359 | ASE->getRBracketLoc()); | |||
18360 | } | |||
18361 | ||||
18362 | case Expr::MemberExprClass: { | |||
18363 | auto *ME = cast<MemberExpr>(E); | |||
18364 | // -- If e is a class member access expression [...] naming a non-static | |||
18365 | // data member... | |||
18366 | if (isa<FieldDecl>(ME->getMemberDecl())) { | |||
18367 | ExprResult Base = Rebuild(ME->getBase()); | |||
18368 | if (!Base.isUsable()) | |||
18369 | return Base; | |||
18370 | return MemberExpr::Create( | |||
18371 | S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), | |||
18372 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), | |||
18373 | ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), | |||
18374 | CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), | |||
18375 | ME->getObjectKind(), ME->isNonOdrUse()); | |||
18376 | } | |||
18377 | ||||
18378 | if (ME->getMemberDecl()->isCXXInstanceMember()) | |||
18379 | break; | |||
18380 | ||||
18381 | // -- If e is a class member access expression naming a static data member, | |||
18382 | // ... | |||
18383 | if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) | |||
18384 | break; | |||
18385 | ||||
18386 | // Rebuild as a non-odr-use MemberExpr. | |||
18387 | MarkNotOdrUsed(); | |||
18388 | return MemberExpr::Create( | |||
18389 | S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), | |||
18390 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), | |||
18391 | ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), | |||
18392 | ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); | |||
18393 | } | |||
18394 | ||||
18395 | case Expr::BinaryOperatorClass: { | |||
18396 | auto *BO = cast<BinaryOperator>(E); | |||
18397 | Expr *LHS = BO->getLHS(); | |||
18398 | Expr *RHS = BO->getRHS(); | |||
18399 | // -- If e is a pointer-to-member expression of the form e1 .* e2 ... | |||
18400 | if (BO->getOpcode() == BO_PtrMemD) { | |||
18401 | ExprResult Sub = Rebuild(LHS); | |||
18402 | if (!Sub.isUsable()) | |||
18403 | return Sub; | |||
18404 | LHS = Sub.get(); | |||
18405 | // -- If e is a comma expression, ... | |||
18406 | } else if (BO->getOpcode() == BO_Comma) { | |||
18407 | ExprResult Sub = Rebuild(RHS); | |||
18408 | if (!Sub.isUsable()) | |||
18409 | return Sub; | |||
18410 | RHS = Sub.get(); | |||
18411 | } else { | |||
18412 | break; | |||
18413 | } | |||
18414 | return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), | |||
18415 | LHS, RHS); | |||
18416 | } | |||
18417 | ||||
18418 | // -- If e has the form (e1)... | |||
18419 | case Expr::ParenExprClass: { | |||
18420 | auto *PE = cast<ParenExpr>(E); | |||
18421 | ExprResult Sub = Rebuild(PE->getSubExpr()); | |||
18422 | if (!Sub.isUsable()) | |||
18423 | return Sub; | |||
18424 | return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); | |||
18425 | } | |||
18426 | ||||
18427 | // -- If e is a glvalue conditional expression, ... | |||
18428 | // We don't apply this to a binary conditional operator. FIXME: Should we? | |||
18429 | case Expr::ConditionalOperatorClass: { | |||
18430 | auto *CO = cast<ConditionalOperator>(E); | |||
18431 | ExprResult LHS = Rebuild(CO->getLHS()); | |||
18432 | if (LHS.isInvalid()) | |||
18433 | return ExprError(); | |||
18434 | ExprResult RHS = Rebuild(CO->getRHS()); | |||
18435 | if (RHS.isInvalid()) | |||
18436 | return ExprError(); | |||
18437 | if (!LHS.isUsable() && !RHS.isUsable()) | |||
18438 | return ExprEmpty(); | |||
18439 | if (!LHS.isUsable()) | |||
18440 | LHS = CO->getLHS(); | |||
18441 | if (!RHS.isUsable()) | |||
18442 | RHS = CO->getRHS(); | |||
18443 | return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), | |||
18444 | CO->getCond(), LHS.get(), RHS.get()); | |||
18445 | } | |||
18446 | ||||
18447 | // [Clang extension] | |||
18448 | // -- If e has the form __extension__ e1... | |||
18449 | case Expr::UnaryOperatorClass: { | |||
18450 | auto *UO = cast<UnaryOperator>(E); | |||
18451 | if (UO->getOpcode() != UO_Extension) | |||
18452 | break; | |||
18453 | ExprResult Sub = Rebuild(UO->getSubExpr()); | |||
18454 | if (!Sub.isUsable()) | |||
18455 | return Sub; | |||
18456 | return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, | |||
18457 | Sub.get()); | |||
18458 | } | |||
18459 | ||||
18460 | // [Clang extension] | |||
18461 | // -- If e has the form _Generic(...), the set of potential results is the | |||
18462 | // union of the sets of potential results of the associated expressions. | |||
18463 | case Expr::GenericSelectionExprClass: { | |||
18464 | auto *GSE = cast<GenericSelectionExpr>(E); | |||
18465 | ||||
18466 | SmallVector<Expr *, 4> AssocExprs; | |||
18467 | bool AnyChanged = false; | |||
18468 | for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { | |||
18469 | ExprResult AssocExpr = Rebuild(OrigAssocExpr); | |||
18470 | if (AssocExpr.isInvalid()) | |||
18471 | return ExprError(); | |||
18472 | if (AssocExpr.isUsable()) { | |||
18473 | AssocExprs.push_back(AssocExpr.get()); | |||
18474 | AnyChanged = true; | |||
18475 | } else { | |||
18476 | AssocExprs.push_back(OrigAssocExpr); | |||
18477 | } | |||
18478 | } | |||
18479 | ||||
18480 | return AnyChanged ? S.CreateGenericSelectionExpr( | |||
18481 | GSE->getGenericLoc(), GSE->getDefaultLoc(), | |||
18482 | GSE->getRParenLoc(), GSE->getControllingExpr(), | |||
18483 | GSE->getAssocTypeSourceInfos(), AssocExprs) | |||
18484 | : ExprEmpty(); | |||
18485 | } | |||
18486 | ||||
18487 | // [Clang extension] | |||
18488 | // -- If e has the form __builtin_choose_expr(...), the set of potential | |||
18489 | // results is the union of the sets of potential results of the | |||
18490 | // second and third subexpressions. | |||
18491 | case Expr::ChooseExprClass: { | |||
18492 | auto *CE = cast<ChooseExpr>(E); | |||
18493 | ||||
18494 | ExprResult LHS = Rebuild(CE->getLHS()); | |||
18495 | if (LHS.isInvalid()) | |||
18496 | return ExprError(); | |||
18497 | ||||
18498 | ExprResult RHS = Rebuild(CE->getLHS()); | |||
18499 | if (RHS.isInvalid()) | |||
18500 | return ExprError(); | |||
18501 | ||||
18502 | if (!LHS.get() && !RHS.get()) | |||
18503 | return ExprEmpty(); | |||
18504 | if (!LHS.isUsable()) | |||
18505 | LHS = CE->getLHS(); | |||
18506 | if (!RHS.isUsable()) | |||
18507 | RHS = CE->getRHS(); | |||
18508 | ||||
18509 | return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), | |||
18510 | RHS.get(), CE->getRParenLoc()); | |||
18511 | } | |||
18512 | ||||
18513 | // Step through non-syntactic nodes. | |||
18514 | case Expr::ConstantExprClass: { | |||
18515 | auto *CE = cast<ConstantExpr>(E); | |||
18516 | ExprResult Sub = Rebuild(CE->getSubExpr()); | |||
18517 | if (!Sub.isUsable()) | |||
18518 | return Sub; | |||
18519 | return ConstantExpr::Create(S.Context, Sub.get()); | |||
18520 | } | |||
18521 | ||||
18522 | // We could mostly rely on the recursive rebuilding to rebuild implicit | |||
18523 | // casts, but not at the top level, so rebuild them here. | |||
18524 | case Expr::ImplicitCastExprClass: { | |||
18525 | auto *ICE = cast<ImplicitCastExpr>(E); | |||
18526 | // Only step through the narrow set of cast kinds we expect to encounter. | |||
18527 | // Anything else suggests we've left the region in which potential results | |||
18528 | // can be found. | |||
18529 | switch (ICE->getCastKind()) { | |||
18530 | case CK_NoOp: | |||
18531 | case CK_DerivedToBase: | |||
18532 | case CK_UncheckedDerivedToBase: { | |||
18533 | ExprResult Sub = Rebuild(ICE->getSubExpr()); | |||
18534 | if (!Sub.isUsable()) | |||
18535 | return Sub; | |||
18536 | CXXCastPath Path(ICE->path()); | |||
18537 | return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), | |||
18538 | ICE->getValueKind(), &Path); | |||
18539 | } | |||
18540 | ||||
18541 | default: | |||
18542 | break; | |||
18543 | } | |||
18544 | break; | |||
18545 | } | |||
18546 | ||||
18547 | default: | |||
18548 | break; | |||
18549 | } | |||
18550 | ||||
18551 | // Can't traverse through this node. Nothing to do. | |||
18552 | return ExprEmpty(); | |||
18553 | } | |||
18554 | ||||
18555 | ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { | |||
18556 | // Check whether the operand is or contains an object of non-trivial C union | |||
18557 | // type. | |||
18558 | if (E->getType().isVolatileQualified() && | |||
18559 | (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || | |||
18560 | E->getType().hasNonTrivialToPrimitiveCopyCUnion())) | |||
18561 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | |||
18562 | Sema::NTCUC_LValueToRValueVolatile, | |||
18563 | NTCUK_Destruct|NTCUK_Copy); | |||
18564 | ||||
18565 | // C++2a [basic.def.odr]p4: | |||
18566 | // [...] an expression of non-volatile-qualified non-class type to which | |||
18567 | // the lvalue-to-rvalue conversion is applied [...] | |||
18568 | if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) | |||
18569 | return E; | |||
18570 | ||||
18571 | ExprResult Result = | |||
18572 | rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); | |||
18573 | if (Result.isInvalid()) | |||
18574 | return ExprError(); | |||
18575 | return Result.get() ? Result : E; | |||
18576 | } | |||
18577 | ||||
18578 | ExprResult Sema::ActOnConstantExpression(ExprResult Res) { | |||
18579 | Res = CorrectDelayedTyposInExpr(Res); | |||
18580 | ||||
18581 | if (!Res.isUsable()) | |||
18582 | return Res; | |||
18583 | ||||
18584 | // If a constant-expression is a reference to a variable where we delay | |||
18585 | // deciding whether it is an odr-use, just assume we will apply the | |||
18586 | // lvalue-to-rvalue conversion. In the one case where this doesn't happen | |||
18587 | // (a non-type template argument), we have special handling anyway. | |||
18588 | return CheckLValueToRValueConversionOperand(Res.get()); | |||
18589 | } | |||
18590 | ||||
18591 | void Sema::CleanupVarDeclMarking() { | |||
18592 | // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive | |||
18593 | // call. | |||
18594 | MaybeODRUseExprSet LocalMaybeODRUseExprs; | |||
18595 | std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); | |||
18596 | ||||
18597 | for (Expr *E : LocalMaybeODRUseExprs) { | |||
18598 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
18599 | MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), | |||
18600 | DRE->getLocation(), *this); | |||
18601 | } else if (auto *ME = dyn_cast<MemberExpr>(E)) { | |||
18602 | MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), | |||
18603 | *this); | |||
18604 | } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { | |||
18605 | for (VarDecl *VD : *FP) | |||
18606 | MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); | |||
18607 | } else { | |||
18608 | llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "clang/lib/Sema/SemaExpr.cpp" , 18608); | |||
18609 | } | |||
18610 | } | |||
18611 | ||||
18612 | assert(MaybeODRUseExprs.empty() &&(static_cast <bool> (MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?") ? void (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "clang/lib/Sema/SemaExpr.cpp", 18613, __extension__ __PRETTY_FUNCTION__ )) | |||
18613 | "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")(static_cast <bool> (MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?") ? void (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "clang/lib/Sema/SemaExpr.cpp", 18613, __extension__ __PRETTY_FUNCTION__ )); | |||
18614 | } | |||
18615 | ||||
18616 | static void DoMarkVarDeclReferenced( | |||
18617 | Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, | |||
18618 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { | |||
18619 | assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>( E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "clang/lib/Sema/SemaExpr.cpp", 18621, __extension__ __PRETTY_FUNCTION__ )) | |||
18620 | isa<FunctionParmPackExpr>(E)) &&(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>( E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "clang/lib/Sema/SemaExpr.cpp", 18621, __extension__ __PRETTY_FUNCTION__ )) | |||
18621 | "Invalid Expr argument to DoMarkVarDeclReferenced")(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>( E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "clang/lib/Sema/SemaExpr.cpp", 18621, __extension__ __PRETTY_FUNCTION__ )); | |||
18622 | Var->setReferenced(); | |||
18623 | ||||
18624 | if (Var->isInvalidDecl()) | |||
18625 | return; | |||
18626 | ||||
18627 | auto *MSI = Var->getMemberSpecializationInfo(); | |||
18628 | TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() | |||
18629 | : Var->getTemplateSpecializationKind(); | |||
18630 | ||||
18631 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); | |||
18632 | bool UsableInConstantExpr = | |||
18633 | Var->mightBeUsableInConstantExpressions(SemaRef.Context); | |||
18634 | ||||
18635 | if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { | |||
18636 | RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; | |||
18637 | } | |||
18638 | ||||
18639 | // C++20 [expr.const]p12: | |||
18640 | // A variable [...] is needed for constant evaluation if it is [...] a | |||
18641 | // variable whose name appears as a potentially constant evaluated | |||
18642 | // expression that is either a contexpr variable or is of non-volatile | |||
18643 | // const-qualified integral type or of reference type | |||
18644 | bool NeededForConstantEvaluation = | |||
18645 | isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; | |||
18646 | ||||
18647 | bool NeedDefinition = | |||
18648 | OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; | |||
18649 | ||||
18650 | assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&(static_cast <bool> (!isa<VarTemplatePartialSpecializationDecl >(Var) && "Can't instantiate a partial template specialization." ) ? void (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "clang/lib/Sema/SemaExpr.cpp", 18651, __extension__ __PRETTY_FUNCTION__ )) | |||
18651 | "Can't instantiate a partial template specialization.")(static_cast <bool> (!isa<VarTemplatePartialSpecializationDecl >(Var) && "Can't instantiate a partial template specialization." ) ? void (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "clang/lib/Sema/SemaExpr.cpp", 18651, __extension__ __PRETTY_FUNCTION__ )); | |||
18652 | ||||
18653 | // If this might be a member specialization of a static data member, check | |||
18654 | // the specialization is visible. We already did the checks for variable | |||
18655 | // template specializations when we created them. | |||
18656 | if (NeedDefinition && TSK != TSK_Undeclared && | |||
18657 | !isa<VarTemplateSpecializationDecl>(Var)) | |||
18658 | SemaRef.checkSpecializationVisibility(Loc, Var); | |||
18659 | ||||
18660 | // Perform implicit instantiation of static data members, static data member | |||
18661 | // templates of class templates, and variable template specializations. Delay | |||
18662 | // instantiations of variable templates, except for those that could be used | |||
18663 | // in a constant expression. | |||
18664 | if (NeedDefinition && isTemplateInstantiation(TSK)) { | |||
18665 | // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit | |||
18666 | // instantiation declaration if a variable is usable in a constant | |||
18667 | // expression (among other cases). | |||
18668 | bool TryInstantiating = | |||
18669 | TSK == TSK_ImplicitInstantiation || | |||
18670 | (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); | |||
18671 | ||||
18672 | if (TryInstantiating) { | |||
18673 | SourceLocation PointOfInstantiation = | |||
18674 | MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); | |||
18675 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | |||
18676 | if (FirstInstantiation) { | |||
18677 | PointOfInstantiation = Loc; | |||
18678 | if (MSI) | |||
18679 | MSI->setPointOfInstantiation(PointOfInstantiation); | |||
18680 | // FIXME: Notify listener. | |||
18681 | else | |||
18682 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); | |||
18683 | } | |||
18684 | ||||
18685 | if (UsableInConstantExpr) { | |||
18686 | // Do not defer instantiations of variables that could be used in a | |||
18687 | // constant expression. | |||
18688 | SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { | |||
18689 | SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); | |||
18690 | }); | |||
18691 | ||||
18692 | // Re-set the member to trigger a recomputation of the dependence bits | |||
18693 | // for the expression. | |||
18694 | if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | |||
18695 | DRE->setDecl(DRE->getDecl()); | |||
18696 | else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) | |||
18697 | ME->setMemberDecl(ME->getMemberDecl()); | |||
18698 | } else if (FirstInstantiation || | |||
18699 | isa<VarTemplateSpecializationDecl>(Var)) { | |||
18700 | // FIXME: For a specialization of a variable template, we don't | |||
18701 | // distinguish between "declaration and type implicitly instantiated" | |||
18702 | // and "implicit instantiation of definition requested", so we have | |||
18703 | // no direct way to avoid enqueueing the pending instantiation | |||
18704 | // multiple times. | |||
18705 | SemaRef.PendingInstantiations | |||
18706 | .push_back(std::make_pair(Var, PointOfInstantiation)); | |||
18707 | } | |||
18708 | } | |||
18709 | } | |||
18710 | ||||
18711 | // C++2a [basic.def.odr]p4: | |||
18712 | // A variable x whose name appears as a potentially-evaluated expression e | |||
18713 | // is odr-used by e unless | |||
18714 | // -- x is a reference that is usable in constant expressions | |||
18715 | // -- x is a variable of non-reference type that is usable in constant | |||
18716 | // expressions and has no mutable subobjects [FIXME], and e is an | |||
18717 | // element of the set of potential results of an expression of | |||
18718 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | |||
18719 | // conversion is applied | |||
18720 | // -- x is a variable of non-reference type, and e is an element of the set | |||
18721 | // of potential results of a discarded-value expression to which the | |||
18722 | // lvalue-to-rvalue conversion is not applied [FIXME] | |||
18723 | // | |||
18724 | // We check the first part of the second bullet here, and | |||
18725 | // Sema::CheckLValueToRValueConversionOperand deals with the second part. | |||
18726 | // FIXME: To get the third bullet right, we need to delay this even for | |||
18727 | // variables that are not usable in constant expressions. | |||
18728 | ||||
18729 | // If we already know this isn't an odr-use, there's nothing more to do. | |||
18730 | if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | |||
18731 | if (DRE->isNonOdrUse()) | |||
18732 | return; | |||
18733 | if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) | |||
18734 | if (ME->isNonOdrUse()) | |||
18735 | return; | |||
18736 | ||||
18737 | switch (OdrUse) { | |||
18738 | case OdrUseContext::None: | |||
18739 | assert((!E || isa<FunctionParmPackExpr>(E)) &&(static_cast <bool> ((!E || isa<FunctionParmPackExpr >(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "clang/lib/Sema/SemaExpr.cpp", 18740, __extension__ __PRETTY_FUNCTION__ )) | |||
18740 | "missing non-odr-use marking for unevaluated decl ref")(static_cast <bool> ((!E || isa<FunctionParmPackExpr >(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "clang/lib/Sema/SemaExpr.cpp", 18740, __extension__ __PRETTY_FUNCTION__ )); | |||
18741 | break; | |||
18742 | ||||
18743 | case OdrUseContext::FormallyOdrUsed: | |||
18744 | // FIXME: Ignoring formal odr-uses results in incorrect lambda capture | |||
18745 | // behavior. | |||
18746 | break; | |||
18747 | ||||
18748 | case OdrUseContext::Used: | |||
18749 | // If we might later find that this expression isn't actually an odr-use, | |||
18750 | // delay the marking. | |||
18751 | if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) | |||
18752 | SemaRef.MaybeODRUseExprs.insert(E); | |||
18753 | else | |||
18754 | MarkVarDeclODRUsed(Var, Loc, SemaRef); | |||
18755 | break; | |||
18756 | ||||
18757 | case OdrUseContext::Dependent: | |||
18758 | // If this is a dependent context, we don't need to mark variables as | |||
18759 | // odr-used, but we may still need to track them for lambda capture. | |||
18760 | // FIXME: Do we also need to do this inside dependent typeid expressions | |||
18761 | // (which are modeled as unevaluated at this point)? | |||
18762 | const bool RefersToEnclosingScope = | |||
18763 | (SemaRef.CurContext != Var->getDeclContext() && | |||
18764 | Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); | |||
18765 | if (RefersToEnclosingScope) { | |||
18766 | LambdaScopeInfo *const LSI = | |||
18767 | SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); | |||
18768 | if (LSI && (!LSI->CallOperator || | |||
18769 | !LSI->CallOperator->Encloses(Var->getDeclContext()))) { | |||
18770 | // If a variable could potentially be odr-used, defer marking it so | |||
18771 | // until we finish analyzing the full expression for any | |||
18772 | // lvalue-to-rvalue | |||
18773 | // or discarded value conversions that would obviate odr-use. | |||
18774 | // Add it to the list of potential captures that will be analyzed | |||
18775 | // later (ActOnFinishFullExpr) for eventual capture and odr-use marking | |||
18776 | // unless the variable is a reference that was initialized by a constant | |||
18777 | // expression (this will never need to be captured or odr-used). | |||
18778 | // | |||
18779 | // FIXME: We can simplify this a lot after implementing P0588R1. | |||
18780 | assert(E && "Capture variable should be used in an expression.")(static_cast <bool> (E && "Capture variable should be used in an expression." ) ? void (0) : __assert_fail ("E && \"Capture variable should be used in an expression.\"" , "clang/lib/Sema/SemaExpr.cpp", 18780, __extension__ __PRETTY_FUNCTION__ )); | |||
18781 | if (!Var->getType()->isReferenceType() || | |||
18782 | !Var->isUsableInConstantExpressions(SemaRef.Context)) | |||
18783 | LSI->addPotentialCapture(E->IgnoreParens()); | |||
18784 | } | |||
18785 | } | |||
18786 | break; | |||
18787 | } | |||
18788 | } | |||
18789 | ||||
18790 | /// Mark a variable referenced, and check whether it is odr-used | |||
18791 | /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be | |||
18792 | /// used directly for normal expressions referring to VarDecl. | |||
18793 | void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { | |||
18794 | DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); | |||
18795 | } | |||
18796 | ||||
18797 | static void | |||
18798 | MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, | |||
18799 | bool MightBeOdrUse, | |||
18800 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { | |||
18801 | if (SemaRef.isInOpenMPDeclareTargetContext()) | |||
18802 | SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); | |||
18803 | ||||
18804 | if (VarDecl *Var = dyn_cast<VarDecl>(D)) { | |||
18805 | DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); | |||
18806 | return; | |||
18807 | } | |||
18808 | ||||
18809 | SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); | |||
18810 | ||||
18811 | // If this is a call to a method via a cast, also mark the method in the | |||
18812 | // derived class used in case codegen can devirtualize the call. | |||
18813 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | |||
18814 | if (!ME) | |||
18815 | return; | |||
18816 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); | |||
18817 | if (!MD) | |||
18818 | return; | |||
18819 | // Only attempt to devirtualize if this is truly a virtual call. | |||
18820 | bool IsVirtualCall = MD->isVirtual() && | |||
18821 | ME->performsVirtualDispatch(SemaRef.getLangOpts()); | |||
18822 | if (!IsVirtualCall) | |||
18823 | return; | |||
18824 | ||||
18825 | // If it's possible to devirtualize the call, mark the called function | |||
18826 | // referenced. | |||
18827 | CXXMethodDecl *DM = MD->getDevirtualizedMethod( | |||
18828 | ME->getBase(), SemaRef.getLangOpts().AppleKext); | |||
18829 | if (DM) | |||
18830 | SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); | |||
18831 | } | |||
18832 | ||||
18833 | /// Perform reference-marking and odr-use handling for a DeclRefExpr. | |||
18834 | /// | |||
18835 | /// Note, this may change the dependence of the DeclRefExpr, and so needs to be | |||
18836 | /// handled with care if the DeclRefExpr is not newly-created. | |||
18837 | void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { | |||
18838 | // TODO: update this with DR# once a defect report is filed. | |||
18839 | // C++11 defect. The address of a pure member should not be an ODR use, even | |||
18840 | // if it's a qualified reference. | |||
18841 | bool OdrUse = true; | |||
18842 | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) | |||
18843 | if (Method->isVirtual() && | |||
18844 | !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) | |||
18845 | OdrUse = false; | |||
18846 | ||||
18847 | if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) | |||
18848 | if (!isUnevaluatedContext() && !isConstantEvaluated() && | |||
18849 | FD->isConsteval() && !RebuildingImmediateInvocation) | |||
18850 | ExprEvalContexts.back().ReferenceToConsteval.insert(E); | |||
18851 | MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, | |||
18852 | RefsMinusAssignments); | |||
18853 | } | |||
18854 | ||||
18855 | /// Perform reference-marking and odr-use handling for a MemberExpr. | |||
18856 | void Sema::MarkMemberReferenced(MemberExpr *E) { | |||
18857 | // C++11 [basic.def.odr]p2: | |||
18858 | // A non-overloaded function whose name appears as a potentially-evaluated | |||
18859 | // expression or a member of a set of candidate functions, if selected by | |||
18860 | // overload resolution when referred to from a potentially-evaluated | |||
18861 | // expression, is odr-used, unless it is a pure virtual function and its | |||
18862 | // name is not explicitly qualified. | |||
18863 | bool MightBeOdrUse = true; | |||
18864 | if (E->performsVirtualDispatch(getLangOpts())) { | |||
18865 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) | |||
18866 | if (Method->isPure()) | |||
18867 | MightBeOdrUse = false; | |||
18868 | } | |||
18869 | SourceLocation Loc = | |||
18870 | E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); | |||
18871 | MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, | |||
18872 | RefsMinusAssignments); | |||
18873 | } | |||
18874 | ||||
18875 | /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. | |||
18876 | void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { | |||
18877 | for (VarDecl *VD : *E) | |||
18878 | MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, | |||
18879 | RefsMinusAssignments); | |||
18880 | } | |||
18881 | ||||
18882 | /// Perform marking for a reference to an arbitrary declaration. It | |||
18883 | /// marks the declaration referenced, and performs odr-use checking for | |||
18884 | /// functions and variables. This method should not be used when building a | |||
18885 | /// normal expression which refers to a variable. | |||
18886 | void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, | |||
18887 | bool MightBeOdrUse) { | |||
18888 | if (MightBeOdrUse) { | |||
18889 | if (auto *VD = dyn_cast<VarDecl>(D)) { | |||
18890 | MarkVariableReferenced(Loc, VD); | |||
18891 | return; | |||
18892 | } | |||
18893 | } | |||
18894 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { | |||
18895 | MarkFunctionReferenced(Loc, FD, MightBeOdrUse); | |||
18896 | return; | |||
18897 | } | |||
18898 | D->setReferenced(); | |||
18899 | } | |||
18900 | ||||
18901 | namespace { | |||
18902 | // Mark all of the declarations used by a type as referenced. | |||
18903 | // FIXME: Not fully implemented yet! We need to have a better understanding | |||
18904 | // of when we're entering a context we should not recurse into. | |||
18905 | // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to | |||
18906 | // TreeTransforms rebuilding the type in a new context. Rather than | |||
18907 | // duplicating the TreeTransform logic, we should consider reusing it here. | |||
18908 | // Currently that causes problems when rebuilding LambdaExprs. | |||
18909 | class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { | |||
18910 | Sema &S; | |||
18911 | SourceLocation Loc; | |||
18912 | ||||
18913 | public: | |||
18914 | typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; | |||
18915 | ||||
18916 | MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } | |||
18917 | ||||
18918 | bool TraverseTemplateArgument(const TemplateArgument &Arg); | |||
18919 | }; | |||
18920 | } | |||
18921 | ||||
18922 | bool MarkReferencedDecls::TraverseTemplateArgument( | |||
18923 | const TemplateArgument &Arg) { | |||
18924 | { | |||
18925 | // A non-type template argument is a constant-evaluated context. | |||
18926 | EnterExpressionEvaluationContext Evaluated( | |||
18927 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); | |||
18928 | if (Arg.getKind() == TemplateArgument::Declaration) { | |||
18929 | if (Decl *D = Arg.getAsDecl()) | |||
18930 | S.MarkAnyDeclReferenced(Loc, D, true); | |||
18931 | } else if (Arg.getKind() == TemplateArgument::Expression) { | |||
18932 | S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); | |||
18933 | } | |||
18934 | } | |||
18935 | ||||
18936 | return Inherited::TraverseTemplateArgument(Arg); | |||
18937 | } | |||
18938 | ||||
18939 | void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { | |||
18940 | MarkReferencedDecls Marker(*this, Loc); | |||
18941 | Marker.TraverseType(T); | |||
18942 | } | |||
18943 | ||||
18944 | namespace { | |||
18945 | /// Helper class that marks all of the declarations referenced by | |||
18946 | /// potentially-evaluated subexpressions as "referenced". | |||
18947 | class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { | |||
18948 | public: | |||
18949 | typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; | |||
18950 | bool SkipLocalVariables; | |||
18951 | ArrayRef<const Expr *> StopAt; | |||
18952 | ||||
18953 | EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, | |||
18954 | ArrayRef<const Expr *> StopAt) | |||
18955 | : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} | |||
18956 | ||||
18957 | void visitUsedDecl(SourceLocation Loc, Decl *D) { | |||
18958 | S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); | |||
18959 | } | |||
18960 | ||||
18961 | void Visit(Expr *E) { | |||
18962 | if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end()) | |||
18963 | return; | |||
18964 | Inherited::Visit(E); | |||
18965 | } | |||
18966 | ||||
18967 | void VisitDeclRefExpr(DeclRefExpr *E) { | |||
18968 | // If we were asked not to visit local variables, don't. | |||
18969 | if (SkipLocalVariables) { | |||
18970 | if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) | |||
18971 | if (VD->hasLocalStorage()) | |||
18972 | return; | |||
18973 | } | |||
18974 | ||||
18975 | // FIXME: This can trigger the instantiation of the initializer of a | |||
18976 | // variable, which can cause the expression to become value-dependent | |||
18977 | // or error-dependent. Do we need to propagate the new dependence bits? | |||
18978 | S.MarkDeclRefReferenced(E); | |||
18979 | } | |||
18980 | ||||
18981 | void VisitMemberExpr(MemberExpr *E) { | |||
18982 | S.MarkMemberReferenced(E); | |||
18983 | Visit(E->getBase()); | |||
18984 | } | |||
18985 | }; | |||
18986 | } // namespace | |||
18987 | ||||
18988 | /// Mark any declarations that appear within this expression or any | |||
18989 | /// potentially-evaluated subexpressions as "referenced". | |||
18990 | /// | |||
18991 | /// \param SkipLocalVariables If true, don't mark local variables as | |||
18992 | /// 'referenced'. | |||
18993 | /// \param StopAt Subexpressions that we shouldn't recurse into. | |||
18994 | void Sema::MarkDeclarationsReferencedInExpr(Expr *E, | |||
18995 | bool SkipLocalVariables, | |||
18996 | ArrayRef<const Expr*> StopAt) { | |||
18997 | EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); | |||
18998 | } | |||
18999 | ||||
19000 | /// Emit a diagnostic when statements are reachable. | |||
19001 | /// FIXME: check for reachability even in expressions for which we don't build a | |||
19002 | /// CFG (eg, in the initializer of a global or in a constant expression). | |||
19003 | /// For example, | |||
19004 | /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } | |||
19005 | bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, | |||
19006 | const PartialDiagnostic &PD) { | |||
19007 | if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { | |||
19008 | if (!FunctionScopes.empty()) | |||
19009 | FunctionScopes.back()->PossiblyUnreachableDiags.push_back( | |||
19010 | sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); | |||
19011 | return true; | |||
19012 | } | |||
19013 | ||||
19014 | // The initializer of a constexpr variable or of the first declaration of a | |||
19015 | // static data member is not syntactically a constant evaluated constant, | |||
19016 | // but nonetheless is always required to be a constant expression, so we | |||
19017 | // can skip diagnosing. | |||
19018 | // FIXME: Using the mangling context here is a hack. | |||
19019 | if (auto *VD = dyn_cast_or_null<VarDecl>( | |||
19020 | ExprEvalContexts.back().ManglingContextDecl)) { | |||
19021 | if (VD->isConstexpr() || | |||
19022 | (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) | |||
19023 | return false; | |||
19024 | // FIXME: For any other kind of variable, we should build a CFG for its | |||
19025 | // initializer and check whether the context in question is reachable. | |||
19026 | } | |||
19027 | ||||
19028 | Diag(Loc, PD); | |||
19029 | return true; | |||
19030 | } | |||
19031 | ||||
19032 | /// Emit a diagnostic that describes an effect on the run-time behavior | |||
19033 | /// of the program being compiled. | |||
19034 | /// | |||
19035 | /// This routine emits the given diagnostic when the code currently being | |||
19036 | /// type-checked is "potentially evaluated", meaning that there is a | |||
19037 | /// possibility that the code will actually be executable. Code in sizeof() | |||
19038 | /// expressions, code used only during overload resolution, etc., are not | |||
19039 | /// potentially evaluated. This routine will suppress such diagnostics or, | |||
19040 | /// in the absolutely nutty case of potentially potentially evaluated | |||
19041 | /// expressions (C++ typeid), queue the diagnostic to potentially emit it | |||
19042 | /// later. | |||
19043 | /// | |||
19044 | /// This routine should be used for all diagnostics that describe the run-time | |||
19045 | /// behavior of a program, such as passing a non-POD value through an ellipsis. | |||
19046 | /// Failure to do so will likely result in spurious diagnostics or failures | |||
19047 | /// during overload resolution or within sizeof/alignof/typeof/typeid. | |||
19048 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, | |||
19049 | const PartialDiagnostic &PD) { | |||
19050 | ||||
19051 | if (ExprEvalContexts.back().isDiscardedStatementContext()) | |||
19052 | return false; | |||
19053 | ||||
19054 | switch (ExprEvalContexts.back().Context) { | |||
19055 | case ExpressionEvaluationContext::Unevaluated: | |||
19056 | case ExpressionEvaluationContext::UnevaluatedList: | |||
19057 | case ExpressionEvaluationContext::UnevaluatedAbstract: | |||
19058 | case ExpressionEvaluationContext::DiscardedStatement: | |||
19059 | // The argument will never be evaluated, so don't complain. | |||
19060 | break; | |||
19061 | ||||
19062 | case ExpressionEvaluationContext::ConstantEvaluated: | |||
19063 | case ExpressionEvaluationContext::ImmediateFunctionContext: | |||
19064 | // Relevant diagnostics should be produced by constant evaluation. | |||
19065 | break; | |||
19066 | ||||
19067 | case ExpressionEvaluationContext::PotentiallyEvaluated: | |||
19068 | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | |||
19069 | return DiagIfReachable(Loc, Stmts, PD); | |||
19070 | } | |||
19071 | ||||
19072 | return false; | |||
19073 | } | |||
19074 | ||||
19075 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, | |||
19076 | const PartialDiagnostic &PD) { | |||
19077 | return DiagRuntimeBehavior( | |||
19078 | Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); | |||
19079 | } | |||
19080 | ||||
19081 | bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, | |||
19082 | CallExpr *CE, FunctionDecl *FD) { | |||
19083 | if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) | |||
19084 | return false; | |||
19085 | ||||
19086 | // If we're inside a decltype's expression, don't check for a valid return | |||
19087 | // type or construct temporaries until we know whether this is the last call. | |||
19088 | if (ExprEvalContexts.back().ExprContext == | |||
19089 | ExpressionEvaluationContextRecord::EK_Decltype) { | |||
19090 | ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); | |||
19091 | return false; | |||
19092 | } | |||
19093 | ||||
19094 | class CallReturnIncompleteDiagnoser : public TypeDiagnoser { | |||
19095 | FunctionDecl *FD; | |||
19096 | CallExpr *CE; | |||
19097 | ||||
19098 | public: | |||
19099 | CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) | |||
19100 | : FD(FD), CE(CE) { } | |||
19101 | ||||
19102 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | |||
19103 | if (!FD) { | |||
19104 | S.Diag(Loc, diag::err_call_incomplete_return) | |||
19105 | << T << CE->getSourceRange(); | |||
19106 | return; | |||
19107 | } | |||
19108 | ||||
19109 | S.Diag(Loc, diag::err_call_function_incomplete_return) | |||
19110 | << CE->getSourceRange() << FD << T; | |||
19111 | S.Diag(FD->getLocation(), diag::note_entity_declared_at) | |||
19112 | << FD->getDeclName(); | |||
19113 | } | |||
19114 | } Diagnoser(FD, CE); | |||
19115 | ||||
19116 | if (RequireCompleteType(Loc, ReturnType, Diagnoser)) | |||
19117 | return true; | |||
19118 | ||||
19119 | return false; | |||
19120 | } | |||
19121 | ||||
19122 | // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses | |||
19123 | // will prevent this condition from triggering, which is what we want. | |||
19124 | void Sema::DiagnoseAssignmentAsCondition(Expr *E) { | |||
19125 | SourceLocation Loc; | |||
19126 | ||||
19127 | unsigned diagnostic = diag::warn_condition_is_assignment; | |||
19128 | bool IsOrAssign = false; | |||
19129 | ||||
19130 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { | |||
19131 | if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) | |||
19132 | return; | |||
19133 | ||||
19134 | IsOrAssign = Op->getOpcode() == BO_OrAssign; | |||
19135 | ||||
19136 | // Greylist some idioms by putting them into a warning subcategory. | |||
19137 | if (ObjCMessageExpr *ME | |||
19138 | = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { | |||
19139 | Selector Sel = ME->getSelector(); | |||
19140 | ||||
19141 | // self = [<foo> init...] | |||
19142 | if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) | |||
19143 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | |||
19144 | ||||
19145 | // <foo> = [<bar> nextObject] | |||
19146 | else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") | |||
19147 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | |||
19148 | } | |||
19149 | ||||
19150 | Loc = Op->getOperatorLoc(); | |||
19151 | } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { | |||
19152 | if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) | |||
19153 | return; | |||
19154 | ||||
19155 | IsOrAssign = Op->getOperator() == OO_PipeEqual; | |||
19156 | Loc = Op->getOperatorLoc(); | |||
19157 | } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) | |||
19158 | return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); | |||
19159 | else { | |||
19160 | // Not an assignment. | |||
19161 | return; | |||
19162 | } | |||
19163 | ||||
19164 | Diag(Loc, diagnostic) << E->getSourceRange(); | |||
19165 | ||||
19166 | SourceLocation Open = E->getBeginLoc(); | |||
19167 | SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); | |||
19168 | Diag(Loc, diag::note_condition_assign_silence) | |||
19169 | << FixItHint::CreateInsertion(Open, "(") | |||
19170 | << FixItHint::CreateInsertion(Close, ")"); | |||
19171 | ||||
19172 | if (IsOrAssign) | |||
19173 | Diag(Loc, diag::note_condition_or_assign_to_comparison) | |||
19174 | << FixItHint::CreateReplacement(Loc, "!="); | |||
19175 | else | |||
19176 | Diag(Loc, diag::note_condition_assign_to_comparison) | |||
19177 | << FixItHint::CreateReplacement(Loc, "=="); | |||
19178 | } | |||
19179 | ||||
19180 | /// Redundant parentheses over an equality comparison can indicate | |||
19181 | /// that the user intended an assignment used as condition. | |||
19182 | void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { | |||
19183 | // Don't warn if the parens came from a macro. | |||
19184 | SourceLocation parenLoc = ParenE->getBeginLoc(); | |||
19185 | if (parenLoc.isInvalid() || parenLoc.isMacroID()) | |||
19186 | return; | |||
19187 | // Don't warn for dependent expressions. | |||
19188 | if (ParenE->isTypeDependent()) | |||
19189 | return; | |||
19190 | ||||
19191 | Expr *E = ParenE->IgnoreParens(); | |||
19192 | ||||
19193 | if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) | |||
19194 | if (opE->getOpcode() == BO_EQ && | |||
19195 | opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) | |||
19196 | == Expr::MLV_Valid) { | |||
19197 | SourceLocation Loc = opE->getOperatorLoc(); | |||
19198 | ||||
19199 | Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); | |||
19200 | SourceRange ParenERange = ParenE->getSourceRange(); | |||
19201 | Diag(Loc, diag::note_equality_comparison_silence) | |||
19202 | << FixItHint::CreateRemoval(ParenERange.getBegin()) | |||
19203 | << FixItHint::CreateRemoval(ParenERange.getEnd()); | |||
19204 | Diag(Loc, diag::note_equality_comparison_to_assign) | |||
19205 | << FixItHint::CreateReplacement(Loc, "="); | |||
19206 | } | |||
19207 | } | |||
19208 | ||||
19209 | ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, | |||
19210 | bool IsConstexpr) { | |||
19211 | DiagnoseAssignmentAsCondition(E); | |||
19212 | if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) | |||
19213 | DiagnoseEqualityWithExtraParens(parenE); | |||
19214 | ||||
19215 | ExprResult result = CheckPlaceholderExpr(E); | |||
19216 | if (result.isInvalid()) return ExprError(); | |||
19217 | E = result.get(); | |||
19218 | ||||
19219 | if (!E->isTypeDependent()) { | |||
19220 | if (getLangOpts().CPlusPlus) | |||
19221 | return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 | |||
19222 | ||||
19223 | ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); | |||
19224 | if (ERes.isInvalid()) | |||
19225 | return ExprError(); | |||
19226 | E = ERes.get(); | |||
19227 | ||||
19228 | QualType T = E->getType(); | |||
19229 | if (!T->isScalarType()) { // C99 6.8.4.1p1 | |||
19230 | Diag(Loc, diag::err_typecheck_statement_requires_scalar) | |||
19231 | << T << E->getSourceRange(); | |||
19232 | return ExprError(); | |||
19233 | } | |||
19234 | CheckBoolLikeConversion(E, Loc); | |||
19235 | } | |||
19236 | ||||
19237 | return E; | |||
19238 | } | |||
19239 | ||||
19240 | Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, | |||
19241 | Expr *SubExpr, ConditionKind CK, | |||
19242 | bool MissingOK) { | |||
19243 | // MissingOK indicates whether having no condition expression is valid | |||
19244 | // (for loop) or invalid (e.g. while loop). | |||
19245 | if (!SubExpr) | |||
19246 | return MissingOK ? ConditionResult() : ConditionError(); | |||
19247 | ||||
19248 | ExprResult Cond; | |||
19249 | switch (CK) { | |||
19250 | case ConditionKind::Boolean: | |||
19251 | Cond = CheckBooleanCondition(Loc, SubExpr); | |||
19252 | break; | |||
19253 | ||||
19254 | case ConditionKind::ConstexprIf: | |||
19255 | Cond = CheckBooleanCondition(Loc, SubExpr, true); | |||
19256 | break; | |||
19257 | ||||
19258 | case ConditionKind::Switch: | |||
19259 | Cond = CheckSwitchCondition(Loc, SubExpr); | |||
19260 | break; | |||
19261 | } | |||
19262 | if (Cond.isInvalid()) { | |||
19263 | Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), | |||
19264 | {SubExpr}, PreferredConditionType(CK)); | |||
19265 | if (!Cond.get()) | |||
19266 | return ConditionError(); | |||
19267 | } | |||
19268 | // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. | |||
19269 | FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); | |||
19270 | if (!FullExpr.get()) | |||
19271 | return ConditionError(); | |||
19272 | ||||
19273 | return ConditionResult(*this, nullptr, FullExpr, | |||
19274 | CK == ConditionKind::ConstexprIf); | |||
19275 | } | |||
19276 | ||||
19277 | namespace { | |||
19278 | /// A visitor for rebuilding a call to an __unknown_any expression | |||
19279 | /// to have an appropriate type. | |||
19280 | struct RebuildUnknownAnyFunction | |||
19281 | : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { | |||
19282 | ||||
19283 | Sema &S; | |||
19284 | ||||
19285 | RebuildUnknownAnyFunction(Sema &S) : S(S) {} | |||
19286 | ||||
19287 | ExprResult VisitStmt(Stmt *S) { | |||
19288 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp" , 19288); | |||
19289 | } | |||
19290 | ||||
19291 | ExprResult VisitExpr(Expr *E) { | |||
19292 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) | |||
19293 | << E->getSourceRange(); | |||
19294 | return ExprError(); | |||
19295 | } | |||
19296 | ||||
19297 | /// Rebuild an expression which simply semantically wraps another | |||
19298 | /// expression which it shares the type and value kind of. | |||
19299 | template <class T> ExprResult rebuildSugarExpr(T *E) { | |||
19300 | ExprResult SubResult = Visit(E->getSubExpr()); | |||
19301 | if (SubResult.isInvalid()) return ExprError(); | |||
19302 | ||||
19303 | Expr *SubExpr = SubResult.get(); | |||
19304 | E->setSubExpr(SubExpr); | |||
19305 | E->setType(SubExpr->getType()); | |||
19306 | E->setValueKind(SubExpr->getValueKind()); | |||
19307 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 19307, __extension__ __PRETTY_FUNCTION__ )); | |||
19308 | return E; | |||
19309 | } | |||
19310 | ||||
19311 | ExprResult VisitParenExpr(ParenExpr *E) { | |||
19312 | return rebuildSugarExpr(E); | |||
19313 | } | |||
19314 | ||||
19315 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | |||
19316 | return rebuildSugarExpr(E); | |||
19317 | } | |||
19318 | ||||
19319 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | |||
19320 | ExprResult SubResult = Visit(E->getSubExpr()); | |||
19321 | if (SubResult.isInvalid()) return ExprError(); | |||
19322 | ||||
19323 | Expr *SubExpr = SubResult.get(); | |||
19324 | E->setSubExpr(SubExpr); | |||
19325 | E->setType(S.Context.getPointerType(SubExpr->getType())); | |||
19326 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 19326, __extension__ __PRETTY_FUNCTION__)); | |||
19327 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 19327, __extension__ __PRETTY_FUNCTION__ )); | |||
19328 | return E; | |||
19329 | } | |||
19330 | ||||
19331 | ExprResult resolveDecl(Expr *E, ValueDecl *VD) { | |||
19332 | if (!isa<FunctionDecl>(VD)) return VisitExpr(E); | |||
19333 | ||||
19334 | E->setType(VD->getType()); | |||
19335 | ||||
19336 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 19336, __extension__ __PRETTY_FUNCTION__)); | |||
19337 | if (S.getLangOpts().CPlusPlus && | |||
19338 | !(isa<CXXMethodDecl>(VD) && | |||
19339 | cast<CXXMethodDecl>(VD)->isInstance())) | |||
19340 | E->setValueKind(VK_LValue); | |||
19341 | ||||
19342 | return E; | |||
19343 | } | |||
19344 | ||||
19345 | ExprResult VisitMemberExpr(MemberExpr *E) { | |||
19346 | return resolveDecl(E, E->getMemberDecl()); | |||
19347 | } | |||
19348 | ||||
19349 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | |||
19350 | return resolveDecl(E, E->getDecl()); | |||
19351 | } | |||
19352 | }; | |||
19353 | } | |||
19354 | ||||
19355 | /// Given a function expression of unknown-any type, try to rebuild it | |||
19356 | /// to have a function type. | |||
19357 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { | |||
19358 | ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); | |||
19359 | if (Result.isInvalid()) return ExprError(); | |||
19360 | return S.DefaultFunctionArrayConversion(Result.get()); | |||
19361 | } | |||
19362 | ||||
19363 | namespace { | |||
19364 | /// A visitor for rebuilding an expression of type __unknown_anytype | |||
19365 | /// into one which resolves the type directly on the referring | |||
19366 | /// expression. Strict preservation of the original source | |||
19367 | /// structure is not a goal. | |||
19368 | struct RebuildUnknownAnyExpr | |||
19369 | : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { | |||
19370 | ||||
19371 | Sema &S; | |||
19372 | ||||
19373 | /// The current destination type. | |||
19374 | QualType DestType; | |||
19375 | ||||
19376 | RebuildUnknownAnyExpr(Sema &S, QualType CastType) | |||
19377 | : S(S), DestType(CastType) {} | |||
19378 | ||||
19379 | ExprResult VisitStmt(Stmt *S) { | |||
19380 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp" , 19380); | |||
19381 | } | |||
19382 | ||||
19383 | ExprResult VisitExpr(Expr *E) { | |||
19384 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | |||
19385 | << E->getSourceRange(); | |||
19386 | return ExprError(); | |||
19387 | } | |||
19388 | ||||
19389 | ExprResult VisitCallExpr(CallExpr *E); | |||
19390 | ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); | |||
19391 | ||||
19392 | /// Rebuild an expression which simply semantically wraps another | |||
19393 | /// expression which it shares the type and value kind of. | |||
19394 | template <class T> ExprResult rebuildSugarExpr(T *E) { | |||
19395 | ExprResult SubResult = Visit(E->getSubExpr()); | |||
19396 | if (SubResult.isInvalid()) return ExprError(); | |||
19397 | Expr *SubExpr = SubResult.get(); | |||
19398 | E->setSubExpr(SubExpr); | |||
19399 | E->setType(SubExpr->getType()); | |||
19400 | E->setValueKind(SubExpr->getValueKind()); | |||
19401 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 19401, __extension__ __PRETTY_FUNCTION__ )); | |||
19402 | return E; | |||
19403 | } | |||
19404 | ||||
19405 | ExprResult VisitParenExpr(ParenExpr *E) { | |||
19406 | return rebuildSugarExpr(E); | |||
19407 | } | |||
19408 | ||||
19409 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | |||
19410 | return rebuildSugarExpr(E); | |||
19411 | } | |||
19412 | ||||
19413 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | |||
19414 | const PointerType *Ptr = DestType->getAs<PointerType>(); | |||
19415 | if (!Ptr) { | |||
19416 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) | |||
19417 | << E->getSourceRange(); | |||
19418 | return ExprError(); | |||
19419 | } | |||
19420 | ||||
19421 | if (isa<CallExpr>(E->getSubExpr())) { | |||
19422 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) | |||
19423 | << E->getSourceRange(); | |||
19424 | return ExprError(); | |||
19425 | } | |||
19426 | ||||
19427 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 19427, __extension__ __PRETTY_FUNCTION__)); | |||
19428 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 19428, __extension__ __PRETTY_FUNCTION__ )); | |||
19429 | E->setType(DestType); | |||
19430 | ||||
19431 | // Build the sub-expression as if it were an object of the pointee type. | |||
19432 | DestType = Ptr->getPointeeType(); | |||
19433 | ExprResult SubResult = Visit(E->getSubExpr()); | |||
19434 | if (SubResult.isInvalid()) return ExprError(); | |||
19435 | E->setSubExpr(SubResult.get()); | |||
19436 | return E; | |||
19437 | } | |||
19438 | ||||
19439 | ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); | |||
19440 | ||||
19441 | ExprResult resolveDecl(Expr *E, ValueDecl *VD); | |||
19442 | ||||
19443 | ExprResult VisitMemberExpr(MemberExpr *E) { | |||
19444 | return resolveDecl(E, E->getMemberDecl()); | |||
19445 | } | |||
19446 | ||||
19447 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | |||
19448 | return resolveDecl(E, E->getDecl()); | |||
19449 | } | |||
19450 | }; | |||
19451 | } | |||
19452 | ||||
19453 | /// Rebuilds a call expression which yielded __unknown_anytype. | |||
19454 | ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { | |||
19455 | Expr *CalleeExpr = E->getCallee(); | |||
19456 | ||||
19457 | enum FnKind { | |||
19458 | FK_MemberFunction, | |||
19459 | FK_FunctionPointer, | |||
19460 | FK_BlockPointer | |||
19461 | }; | |||
19462 | ||||
19463 | FnKind Kind; | |||
19464 | QualType CalleeType = CalleeExpr->getType(); | |||
19465 | if (CalleeType == S.Context.BoundMemberTy) { | |||
19466 | assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))(static_cast <bool> (isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)) ? void (0) : __assert_fail ("isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)" , "clang/lib/Sema/SemaExpr.cpp", 19466, __extension__ __PRETTY_FUNCTION__ )); | |||
19467 | Kind = FK_MemberFunction; | |||
19468 | CalleeType = Expr::findBoundMemberType(CalleeExpr); | |||
19469 | } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { | |||
19470 | CalleeType = Ptr->getPointeeType(); | |||
19471 | Kind = FK_FunctionPointer; | |||
19472 | } else { | |||
19473 | CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); | |||
19474 | Kind = FK_BlockPointer; | |||
19475 | } | |||
19476 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); | |||
19477 | ||||
19478 | // Verify that this is a legal result type of a function. | |||
19479 | if (DestType->isArrayType() || DestType->isFunctionType()) { | |||
19480 | unsigned diagID = diag::err_func_returning_array_function; | |||
19481 | if (Kind == FK_BlockPointer) | |||
19482 | diagID = diag::err_block_returning_array_function; | |||
19483 | ||||
19484 | S.Diag(E->getExprLoc(), diagID) | |||
19485 | << DestType->isFunctionType() << DestType; | |||
19486 | return ExprError(); | |||
19487 | } | |||
19488 | ||||
19489 | // Otherwise, go ahead and set DestType as the call's result. | |||
19490 | E->setType(DestType.getNonLValueExprType(S.Context)); | |||
19491 | E->setValueKind(Expr::getValueKindForType(DestType)); | |||
19492 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 19492, __extension__ __PRETTY_FUNCTION__ )); | |||
19493 | ||||
19494 | // Rebuild the function type, replacing the result type with DestType. | |||
19495 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); | |||
19496 | if (Proto) { | |||
19497 | // __unknown_anytype(...) is a special case used by the debugger when | |||
19498 | // it has no idea what a function's signature is. | |||
19499 | // | |||
19500 | // We want to build this call essentially under the K&R | |||
19501 | // unprototyped rules, but making a FunctionNoProtoType in C++ | |||
19502 | // would foul up all sorts of assumptions. However, we cannot | |||
19503 | // simply pass all arguments as variadic arguments, nor can we | |||
19504 | // portably just call the function under a non-variadic type; see | |||
19505 | // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. | |||
19506 | // However, it turns out that in practice it is generally safe to | |||
19507 | // call a function declared as "A foo(B,C,D);" under the prototype | |||
19508 | // "A foo(B,C,D,...);". The only known exception is with the | |||
19509 | // Windows ABI, where any variadic function is implicitly cdecl | |||
19510 | // regardless of its normal CC. Therefore we change the parameter | |||
19511 | // types to match the types of the arguments. | |||
19512 | // | |||
19513 | // This is a hack, but it is far superior to moving the | |||
19514 | // corresponding target-specific code from IR-gen to Sema/AST. | |||
19515 | ||||
19516 | ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); | |||
19517 | SmallVector<QualType, 8> ArgTypes; | |||
19518 | if (ParamTypes.empty() && Proto->isVariadic()) { // the special case | |||
19519 | ArgTypes.reserve(E->getNumArgs()); | |||
19520 | for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { | |||
19521 | ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); | |||
19522 | } | |||
19523 | ParamTypes = ArgTypes; | |||
19524 | } | |||
19525 | DestType = S.Context.getFunctionType(DestType, ParamTypes, | |||
19526 | Proto->getExtProtoInfo()); | |||
19527 | } else { | |||
19528 | DestType = S.Context.getFunctionNoProtoType(DestType, | |||
19529 | FnType->getExtInfo()); | |||
19530 | } | |||
19531 | ||||
19532 | // Rebuild the appropriate pointer-to-function type. | |||
19533 | switch (Kind) { | |||
19534 | case FK_MemberFunction: | |||
19535 | // Nothing to do. | |||
19536 | break; | |||
19537 | ||||
19538 | case FK_FunctionPointer: | |||
19539 | DestType = S.Context.getPointerType(DestType); | |||
19540 | break; | |||
19541 | ||||
19542 | case FK_BlockPointer: | |||
19543 | DestType = S.Context.getBlockPointerType(DestType); | |||
19544 | break; | |||
19545 | } | |||
19546 | ||||
19547 | // Finally, we can recurse. | |||
19548 | ExprResult CalleeResult = Visit(CalleeExpr); | |||
19549 | if (!CalleeResult.isUsable()) return ExprError(); | |||
19550 | E->setCallee(CalleeResult.get()); | |||
19551 | ||||
19552 | // Bind a temporary if necessary. | |||
19553 | return S.MaybeBindToTemporary(E); | |||
19554 | } | |||
19555 | ||||
19556 | ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { | |||
19557 | // Verify that this is a legal result type of a call. | |||
19558 | if (DestType->isArrayType() || DestType->isFunctionType()) { | |||
19559 | S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) | |||
19560 | << DestType->isFunctionType() << DestType; | |||
19561 | return ExprError(); | |||
19562 | } | |||
19563 | ||||
19564 | // Rewrite the method result type if available. | |||
19565 | if (ObjCMethodDecl *Method = E->getMethodDecl()) { | |||
19566 | assert(Method->getReturnType() == S.Context.UnknownAnyTy)(static_cast <bool> (Method->getReturnType() == S.Context .UnknownAnyTy) ? void (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy" , "clang/lib/Sema/SemaExpr.cpp", 19566, __extension__ __PRETTY_FUNCTION__ )); | |||
19567 | Method->setReturnType(DestType); | |||
19568 | } | |||
19569 | ||||
19570 | // Change the type of the message. | |||
19571 | E->setType(DestType.getNonReferenceType()); | |||
19572 | E->setValueKind(Expr::getValueKindForType(DestType)); | |||
19573 | ||||
19574 | return S.MaybeBindToTemporary(E); | |||
19575 | } | |||
19576 | ||||
19577 | ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { | |||
19578 | // The only case we should ever see here is a function-to-pointer decay. | |||
19579 | if (E->getCastKind() == CK_FunctionToPointerDecay) { | |||
19580 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 19580, __extension__ __PRETTY_FUNCTION__)); | |||
19581 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 19581, __extension__ __PRETTY_FUNCTION__ )); | |||
19582 | ||||
19583 | E->setType(DestType); | |||
19584 | ||||
19585 | // Rebuild the sub-expression as the pointee (function) type. | |||
19586 | DestType = DestType->castAs<PointerType>()->getPointeeType(); | |||
19587 | ||||
19588 | ExprResult Result = Visit(E->getSubExpr()); | |||
19589 | if (!Result.isUsable()) return ExprError(); | |||
19590 | ||||
19591 | E->setSubExpr(Result.get()); | |||
19592 | return E; | |||
19593 | } else if (E->getCastKind() == CK_LValueToRValue) { | |||
19594 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 19594, __extension__ __PRETTY_FUNCTION__)); | |||
19595 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 19595, __extension__ __PRETTY_FUNCTION__ )); | |||
19596 | ||||
19597 | assert(isa<BlockPointerType>(E->getType()))(static_cast <bool> (isa<BlockPointerType>(E-> getType())) ? void (0) : __assert_fail ("isa<BlockPointerType>(E->getType())" , "clang/lib/Sema/SemaExpr.cpp", 19597, __extension__ __PRETTY_FUNCTION__ )); | |||
19598 | ||||
19599 | E->setType(DestType); | |||
19600 | ||||
19601 | // The sub-expression has to be a lvalue reference, so rebuild it as such. | |||
19602 | DestType = S.Context.getLValueReferenceType(DestType); | |||
19603 | ||||
19604 | ExprResult Result = Visit(E->getSubExpr()); | |||
19605 | if (!Result.isUsable()) return ExprError(); | |||
19606 | ||||
19607 | E->setSubExpr(Result.get()); | |||
19608 | return E; | |||
19609 | } else { | |||
19610 | llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "clang/lib/Sema/SemaExpr.cpp" , 19610); | |||
19611 | } | |||
19612 | } | |||
19613 | ||||
19614 | ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { | |||
19615 | ExprValueKind ValueKind = VK_LValue; | |||
19616 | QualType Type = DestType; | |||
19617 | ||||
19618 | // We know how to make this work for certain kinds of decls: | |||
19619 | ||||
19620 | // - functions | |||
19621 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { | |||
19622 | if (const PointerType *Ptr = Type->getAs<PointerType>()) { | |||
19623 | DestType = Ptr->getPointeeType(); | |||
19624 | ExprResult Result = resolveDecl(E, VD); | |||
19625 | if (Result.isInvalid()) return ExprError(); | |||
19626 | return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, | |||
19627 | VK_PRValue); | |||
19628 | } | |||
19629 | ||||
19630 | if (!Type->isFunctionType()) { | |||
19631 | S.Diag(E->getExprLoc(), diag::err_unknown_any_function) | |||
19632 | << VD << E->getSourceRange(); | |||
19633 | return ExprError(); | |||
19634 | } | |||
19635 | if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { | |||
19636 | // We must match the FunctionDecl's type to the hack introduced in | |||
19637 | // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown | |||
19638 | // type. See the lengthy commentary in that routine. | |||
19639 | QualType FDT = FD->getType(); | |||
19640 | const FunctionType *FnType = FDT->castAs<FunctionType>(); | |||
19641 | const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); | |||
19642 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | |||
19643 | if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { | |||
19644 | SourceLocation Loc = FD->getLocation(); | |||
19645 | FunctionDecl *NewFD = FunctionDecl::Create( | |||
19646 | S.Context, FD->getDeclContext(), Loc, Loc, | |||
19647 | FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), | |||
19648 | SC_None, S.getCurFPFeatures().isFPConstrained(), | |||
19649 | false /*isInlineSpecified*/, FD->hasPrototype(), | |||
19650 | /*ConstexprKind*/ ConstexprSpecKind::Unspecified); | |||
19651 | ||||
19652 | if (FD->getQualifier()) | |||
19653 | NewFD->setQualifierInfo(FD->getQualifierLoc()); | |||
19654 | ||||
19655 | SmallVector<ParmVarDecl*, 16> Params; | |||
19656 | for (const auto &AI : FT->param_types()) { | |||
19657 | ParmVarDecl *Param = | |||
19658 | S.BuildParmVarDeclForTypedef(FD, Loc, AI); | |||
19659 | Param->setScopeInfo(0, Params.size()); | |||
19660 | Params.push_back(Param); | |||
19661 | } | |||
19662 | NewFD->setParams(Params); | |||
19663 | DRE->setDecl(NewFD); | |||
19664 | VD = DRE->getDecl(); | |||
19665 | } | |||
19666 | } | |||
19667 | ||||
19668 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) | |||
19669 | if (MD->isInstance()) { | |||
19670 | ValueKind = VK_PRValue; | |||
19671 | Type = S.Context.BoundMemberTy; | |||
19672 | } | |||
19673 | ||||
19674 | // Function references aren't l-values in C. | |||
19675 | if (!S.getLangOpts().CPlusPlus) | |||
19676 | ValueKind = VK_PRValue; | |||
19677 | ||||
19678 | // - variables | |||
19679 | } else if (isa<VarDecl>(VD)) { | |||
19680 | if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { | |||
19681 | Type = RefTy->getPointeeType(); | |||
19682 | } else if (Type->isFunctionType()) { | |||
19683 | S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) | |||
19684 | << VD << E->getSourceRange(); | |||
19685 | return ExprError(); | |||
19686 | } | |||
19687 | ||||
19688 | // - nothing else | |||
19689 | } else { | |||
19690 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) | |||
19691 | << VD << E->getSourceRange(); | |||
19692 | return ExprError(); | |||
19693 | } | |||
19694 | ||||
19695 | // Modifying the declaration like this is friendly to IR-gen but | |||
19696 | // also really dangerous. | |||
19697 | VD->setType(DestType); | |||
19698 | E->setType(Type); | |||
19699 | E->setValueKind(ValueKind); | |||
19700 | return E; | |||
19701 | } | |||
19702 | ||||
19703 | /// Check a cast of an unknown-any type. We intentionally only | |||
19704 | /// trigger this for C-style casts. | |||
19705 | ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, | |||
19706 | Expr *CastExpr, CastKind &CastKind, | |||
19707 | ExprValueKind &VK, CXXCastPath &Path) { | |||
19708 | // The type we're casting to must be either void or complete. | |||
19709 | if (!CastType->isVoidType() && | |||
19710 | RequireCompleteType(TypeRange.getBegin(), CastType, | |||
19711 | diag::err_typecheck_cast_to_incomplete)) | |||
19712 | return ExprError(); | |||
19713 | ||||
19714 | // Rewrite the casted expression from scratch. | |||
19715 | ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); | |||
19716 | if (!result.isUsable()) return ExprError(); | |||
19717 | ||||
19718 | CastExpr = result.get(); | |||
19719 | VK = CastExpr->getValueKind(); | |||
19720 | CastKind = CK_NoOp; | |||
19721 | ||||
19722 | return CastExpr; | |||
19723 | } | |||
19724 | ||||
19725 | ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { | |||
19726 | return RebuildUnknownAnyExpr(*this, ToType).Visit(E); | |||
19727 | } | |||
19728 | ||||
19729 | ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, | |||
19730 | Expr *arg, QualType ¶mType) { | |||
19731 | // If the syntactic form of the argument is not an explicit cast of | |||
19732 | // any sort, just do default argument promotion. | |||
19733 | ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); | |||
19734 | if (!castArg) { | |||
19735 | ExprResult result = DefaultArgumentPromotion(arg); | |||
19736 | if (result.isInvalid()) return ExprError(); | |||
19737 | paramType = result.get()->getType(); | |||
19738 | return result; | |||
19739 | } | |||
19740 | ||||
19741 | // Otherwise, use the type that was written in the explicit cast. | |||
19742 | assert(!arg->hasPlaceholderType())(static_cast <bool> (!arg->hasPlaceholderType()) ? void (0) : __assert_fail ("!arg->hasPlaceholderType()", "clang/lib/Sema/SemaExpr.cpp" , 19742, __extension__ __PRETTY_FUNCTION__)); | |||
19743 | paramType = castArg->getTypeAsWritten(); | |||
19744 | ||||
19745 | // Copy-initialize a parameter of that type. | |||
19746 | InitializedEntity entity = | |||
19747 | InitializedEntity::InitializeParameter(Context, paramType, | |||
19748 | /*consumed*/ false); | |||
19749 | return PerformCopyInitialization(entity, callLoc, arg); | |||
19750 | } | |||
19751 | ||||
19752 | static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { | |||
19753 | Expr *orig = E; | |||
19754 | unsigned diagID = diag::err_uncasted_use_of_unknown_any; | |||
19755 | while (true) { | |||
19756 | E = E->IgnoreParenImpCasts(); | |||
19757 | if (CallExpr *call = dyn_cast<CallExpr>(E)) { | |||
19758 | E = call->getCallee(); | |||
19759 | diagID = diag::err_uncasted_call_of_unknown_any; | |||
19760 | } else { | |||
19761 | break; | |||
19762 | } | |||
19763 | } | |||
19764 | ||||
19765 | SourceLocation loc; | |||
19766 | NamedDecl *d; | |||
19767 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { | |||
19768 | loc = ref->getLocation(); | |||
19769 | d = ref->getDecl(); | |||
19770 | } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { | |||
19771 | loc = mem->getMemberLoc(); | |||
19772 | d = mem->getMemberDecl(); | |||
19773 | } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { | |||
19774 | diagID = diag::err_uncasted_call_of_unknown_any; | |||
19775 | loc = msg->getSelectorStartLoc(); | |||
19776 | d = msg->getMethodDecl(); | |||
19777 | if (!d) { | |||
19778 | S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) | |||
19779 | << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() | |||
19780 | << orig->getSourceRange(); | |||
19781 | return ExprError(); | |||
19782 | } | |||
19783 | } else { | |||
19784 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | |||
19785 | << E->getSourceRange(); | |||
19786 | return ExprError(); | |||
19787 | } | |||
19788 | ||||
19789 | S.Diag(loc, diagID) << d << orig->getSourceRange(); | |||
19790 | ||||
19791 | // Never recoverable. | |||
19792 | return ExprError(); | |||
19793 | } | |||
19794 | ||||
19795 | /// Check for operands with placeholder types and complain if found. | |||
19796 | /// Returns ExprError() if there was an error and no recovery was possible. | |||
19797 | ExprResult Sema::CheckPlaceholderExpr(Expr *E) { | |||
19798 | if (!Context.isDependenceAllowed()) { | |||
19799 | // C cannot handle TypoExpr nodes on either side of a binop because it | |||
19800 | // doesn't handle dependent types properly, so make sure any TypoExprs have | |||
19801 | // been dealt with before checking the operands. | |||
19802 | ExprResult Result = CorrectDelayedTyposInExpr(E); | |||
19803 | if (!Result.isUsable()) return ExprError(); | |||
19804 | E = Result.get(); | |||
19805 | } | |||
19806 | ||||
19807 | const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); | |||
19808 | if (!placeholderType) return E; | |||
19809 | ||||
19810 | switch (placeholderType->getKind()) { | |||
19811 | ||||
19812 | // Overloaded expressions. | |||
19813 | case BuiltinType::Overload: { | |||
19814 | // Try to resolve a single function template specialization. | |||
19815 | // This is obligatory. | |||
19816 | ExprResult Result = E; | |||
19817 | if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) | |||
19818 | return Result; | |||
19819 | ||||
19820 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization | |||
19821 | // leaves Result unchanged on failure. | |||
19822 | Result = E; | |||
19823 | if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) | |||
19824 | return Result; | |||
19825 | ||||
19826 | // If that failed, try to recover with a call. | |||
19827 | tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), | |||
19828 | /*complain*/ true); | |||
19829 | return Result; | |||
19830 | } | |||
19831 | ||||
19832 | // Bound member functions. | |||
19833 | case BuiltinType::BoundMember: { | |||
19834 | ExprResult result = E; | |||
19835 | const Expr *BME = E->IgnoreParens(); | |||
19836 | PartialDiagnostic PD = PDiag(diag::err_bound_member_function); | |||
19837 | // Try to give a nicer diagnostic if it is a bound member that we recognize. | |||
19838 | if (isa<CXXPseudoDestructorExpr>(BME)) { | |||
19839 | PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; | |||
19840 | } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { | |||
19841 | if (ME->getMemberNameInfo().getName().getNameKind() == | |||
19842 | DeclarationName::CXXDestructorName) | |||
19843 | PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; | |||
19844 | } | |||
19845 | tryToRecoverWithCall(result, PD, | |||
19846 | /*complain*/ true); | |||
19847 | return result; | |||
19848 | } | |||
19849 | ||||
19850 | // ARC unbridged casts. | |||
19851 | case BuiltinType::ARCUnbridgedCast: { | |||
19852 | Expr *realCast = stripARCUnbridgedCast(E); | |||
19853 | diagnoseARCUnbridgedCast(realCast); | |||
19854 | return realCast; | |||
19855 | } | |||
19856 | ||||
19857 | // Expressions of unknown type. | |||
19858 | case BuiltinType::UnknownAny: | |||
19859 | return diagnoseUnknownAnyExpr(*this, E); | |||
19860 | ||||
19861 | // Pseudo-objects. | |||
19862 | case BuiltinType::PseudoObject: | |||
19863 | return checkPseudoObjectRValue(E); | |||
19864 | ||||
19865 | case BuiltinType::BuiltinFn: { | |||
19866 | // Accept __noop without parens by implicitly converting it to a call expr. | |||
19867 | auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); | |||
19868 | if (DRE) { | |||
19869 | auto *FD = cast<FunctionDecl>(DRE->getDecl()); | |||
19870 | if (FD->getBuiltinID() == Builtin::BI__noop) { | |||
19871 | E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), | |||
19872 | CK_BuiltinFnToFnPtr) | |||
19873 | .get(); | |||
19874 | return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, | |||
19875 | VK_PRValue, SourceLocation(), | |||
19876 | FPOptionsOverride()); | |||
19877 | } | |||
19878 | } | |||
19879 | ||||
19880 | Diag(E->getBeginLoc(), diag::err_builtin_fn_use); | |||
19881 | return ExprError(); | |||
19882 | } | |||
19883 | ||||
19884 | case BuiltinType::IncompleteMatrixIdx: | |||
19885 | Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) | |||
19886 | ->getRowIdx() | |||
19887 | ->getBeginLoc(), | |||
19888 | diag::err_matrix_incomplete_index); | |||
19889 | return ExprError(); | |||
19890 | ||||
19891 | // Expressions of unknown type. | |||
19892 | case BuiltinType::OMPArraySection: | |||
19893 | Diag(E->getBeginLoc(), diag::err_omp_array_section_use); | |||
19894 | return ExprError(); | |||
19895 | ||||
19896 | // Expressions of unknown type. | |||
19897 | case BuiltinType::OMPArrayShaping: | |||
19898 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); | |||
19899 | ||||
19900 | case BuiltinType::OMPIterator: | |||
19901 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); | |||
19902 | ||||
19903 | // Everything else should be impossible. | |||
19904 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | |||
19905 | case BuiltinType::Id: | |||
19906 | #include "clang/Basic/OpenCLImageTypes.def" | |||
19907 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | |||
19908 | case BuiltinType::Id: | |||
19909 | #include "clang/Basic/OpenCLExtensionTypes.def" | |||
19910 | #define SVE_TYPE(Name, Id, SingletonId) \ | |||
19911 | case BuiltinType::Id: | |||
19912 | #include "clang/Basic/AArch64SVEACLETypes.def" | |||
19913 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | |||
19914 | case BuiltinType::Id: | |||
19915 | #include "clang/Basic/PPCTypes.def" | |||
19916 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | |||
19917 | #include "clang/Basic/RISCVVTypes.def" | |||
19918 | #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: | |||
19919 | #define PLACEHOLDER_TYPE(Id, SingletonId) | |||
19920 | #include "clang/AST/BuiltinTypes.def" | |||
19921 | break; | |||
19922 | } | |||
19923 | ||||
19924 | llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!" , "clang/lib/Sema/SemaExpr.cpp", 19924); | |||
19925 | } | |||
19926 | ||||
19927 | bool Sema::CheckCaseExpression(Expr *E) { | |||
19928 | if (E->isTypeDependent()) | |||
19929 | return true; | |||
19930 | if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) | |||
19931 | return E->getType()->isIntegralOrEnumerationType(); | |||
19932 | return false; | |||
19933 | } | |||
19934 | ||||
19935 | /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. | |||
19936 | ExprResult | |||
19937 | Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { | |||
19938 | assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(static_cast <bool> ((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!" ) ? void (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "clang/lib/Sema/SemaExpr.cpp", 19939, __extension__ __PRETTY_FUNCTION__ )) | |||
19939 | "Unknown Objective-C Boolean value!")(static_cast <bool> ((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!" ) ? void (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "clang/lib/Sema/SemaExpr.cpp", 19939, __extension__ __PRETTY_FUNCTION__ )); | |||
19940 | QualType BoolT = Context.ObjCBuiltinBoolTy; | |||
19941 | if (!Context.getBOOLDecl()) { | |||
19942 | LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, | |||
19943 | Sema::LookupOrdinaryName); | |||
19944 | if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { | |||
19945 | NamedDecl *ND = Result.getFoundDecl(); | |||
19946 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) | |||
19947 | Context.setBOOLDecl(TD); | |||
19948 | } | |||
19949 | } | |||
19950 | if (Context.getBOOLDecl()) | |||
19951 | BoolT = Context.getBOOLType(); | |||
19952 | return new (Context) | |||
19953 | ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); | |||
19954 | } | |||
19955 | ||||
19956 | ExprResult Sema::ActOnObjCAvailabilityCheckExpr( | |||
19957 | llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, | |||
19958 | SourceLocation RParen) { | |||
19959 | auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { | |||
19960 | auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { | |||
19961 | return Spec.getPlatform() == Platform; | |||
19962 | }); | |||
19963 | // Transcribe the "ios" availability check to "maccatalyst" when compiling | |||
19964 | // for "maccatalyst" if "maccatalyst" is not specified. | |||
19965 | if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { | |||
19966 | Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { | |||
19967 | return Spec.getPlatform() == "ios"; | |||
19968 | }); | |||
19969 | } | |||
19970 | if (Spec == AvailSpecs.end()) | |||
19971 | return None; | |||
19972 | return Spec->getVersion(); | |||
19973 | }; | |||
19974 | ||||
19975 | VersionTuple Version; | |||
19976 | if (auto MaybeVersion = | |||
19977 | FindSpecVersion(Context.getTargetInfo().getPlatformName())) | |||
19978 | Version = *MaybeVersion; | |||
19979 | ||||
19980 | // The use of `@available` in the enclosing context should be analyzed to | |||
19981 | // warn when it's used inappropriately (i.e. not if(@available)). | |||
19982 | if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) | |||
19983 | Context->HasPotentialAvailabilityViolations = true; | |||
19984 | ||||
19985 | return new (Context) | |||
19986 | ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); | |||
19987 | } | |||
19988 | ||||
19989 | ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, | |||
19990 | ArrayRef<Expr *> SubExprs, QualType T) { | |||
19991 | if (!Context.getLangOpts().RecoveryAST) | |||
19992 | return ExprError(); | |||
19993 | ||||
19994 | if (isSFINAEContext()) | |||
19995 | return ExprError(); | |||
19996 | ||||
19997 | if (T.isNull() || T->isUndeducedType() || | |||
19998 | !Context.getLangOpts().RecoveryASTType) | |||
19999 | // We don't know the concrete type, fallback to dependent type. | |||
20000 | T = Context.DependentTy; | |||
20001 | ||||
20002 | return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); | |||
20003 | } |