File: | tools/clang/lib/Sema/SemaExpr.cpp |
Warning: | line 204, column 25 Potential leak of memory pointed to by field 'DiagStorage' |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// | |||
2 | // | |||
3 | // The LLVM Compiler Infrastructure | |||
4 | // | |||
5 | // This file is distributed under the University of Illinois Open Source | |||
6 | // License. See LICENSE.TXT for details. | |||
7 | // | |||
8 | //===----------------------------------------------------------------------===// | |||
9 | // | |||
10 | // This file implements semantic analysis for expressions. | |||
11 | // | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #include "TreeTransform.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/RecursiveASTVisitor.h" | |||
28 | #include "clang/AST/TypeLoc.h" | |||
29 | #include "clang/Basic/PartialDiagnostic.h" | |||
30 | #include "clang/Basic/SourceManager.h" | |||
31 | #include "clang/Basic/TargetInfo.h" | |||
32 | #include "clang/Lex/LiteralSupport.h" | |||
33 | #include "clang/Lex/Preprocessor.h" | |||
34 | #include "clang/Sema/AnalysisBasedWarnings.h" | |||
35 | #include "clang/Sema/DeclSpec.h" | |||
36 | #include "clang/Sema/DelayedDiagnostic.h" | |||
37 | #include "clang/Sema/Designator.h" | |||
38 | #include "clang/Sema/Initialization.h" | |||
39 | #include "clang/Sema/Lookup.h" | |||
40 | #include "clang/Sema/ParsedTemplate.h" | |||
41 | #include "clang/Sema/Scope.h" | |||
42 | #include "clang/Sema/ScopeInfo.h" | |||
43 | #include "clang/Sema/SemaFixItUtils.h" | |||
44 | #include "clang/Sema/SemaInternal.h" | |||
45 | #include "clang/Sema/Template.h" | |||
46 | #include "llvm/Support/ConvertUTF.h" | |||
47 | using namespace clang; | |||
48 | using namespace sema; | |||
49 | ||||
50 | /// \brief Determine whether the use of this declaration is valid, without | |||
51 | /// emitting diagnostics. | |||
52 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { | |||
53 | // See if this is an auto-typed variable whose initializer we are parsing. | |||
54 | if (ParsingInitForAutoVars.count(D)) | |||
55 | return false; | |||
56 | ||||
57 | // See if this is a deleted function. | |||
58 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
59 | if (FD->isDeleted()) | |||
60 | return false; | |||
61 | ||||
62 | // If the function has a deduced return type, and we can't deduce it, | |||
63 | // then we can't use it either. | |||
64 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | |||
65 | DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) | |||
66 | return false; | |||
67 | } | |||
68 | ||||
69 | // See if this function is unavailable. | |||
70 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && | |||
71 | cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) | |||
72 | return false; | |||
73 | ||||
74 | return true; | |||
75 | } | |||
76 | ||||
77 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { | |||
78 | // Warn if this is used but marked unused. | |||
79 | if (const auto *A = D->getAttr<UnusedAttr>()) { | |||
80 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) | |||
81 | // should diagnose them. | |||
82 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && | |||
83 | A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { | |||
84 | const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); | |||
85 | if (DC && !DC->hasAttr<UnusedAttr>()) | |||
86 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); | |||
87 | } | |||
88 | } | |||
89 | } | |||
90 | ||||
91 | /// \brief Emit a note explaining that this function is deleted. | |||
92 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { | |||
93 | assert(Decl->isDeleted())(static_cast <bool> (Decl->isDeleted()) ? void (0) : __assert_fail ("Decl->isDeleted()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 93, __extension__ __PRETTY_FUNCTION__)); | |||
94 | ||||
95 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); | |||
96 | ||||
97 | if (Method && Method->isDeleted() && Method->isDefaulted()) { | |||
98 | // If the method was explicitly defaulted, point at that declaration. | |||
99 | if (!Method->isImplicit()) | |||
100 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); | |||
101 | ||||
102 | // Try to diagnose why this special member function was implicitly | |||
103 | // deleted. This might fail, if that reason no longer applies. | |||
104 | CXXSpecialMember CSM = getSpecialMember(Method); | |||
105 | if (CSM != CXXInvalid) | |||
106 | ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); | |||
107 | ||||
108 | return; | |||
109 | } | |||
110 | ||||
111 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); | |||
112 | if (Ctor && Ctor->isInheritingConstructor()) | |||
113 | return NoteDeletedInheritingConstructor(Ctor); | |||
114 | ||||
115 | Diag(Decl->getLocation(), diag::note_availability_specified_here) | |||
116 | << Decl << true; | |||
117 | } | |||
118 | ||||
119 | /// \brief Determine whether a FunctionDecl was ever declared with an | |||
120 | /// explicit storage class. | |||
121 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { | |||
122 | for (auto I : D->redecls()) { | |||
123 | if (I->getStorageClass() != SC_None) | |||
124 | return true; | |||
125 | } | |||
126 | return false; | |||
127 | } | |||
128 | ||||
129 | /// \brief Check whether we're in an extern inline function and referring to a | |||
130 | /// variable or function with internal linkage (C11 6.7.4p3). | |||
131 | /// | |||
132 | /// This is only a warning because we used to silently accept this code, but | |||
133 | /// in many cases it will not behave correctly. This is not enabled in C++ mode | |||
134 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) | |||
135 | /// and so while there may still be user mistakes, most of the time we can't | |||
136 | /// prove that there are errors. | |||
137 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, | |||
138 | const NamedDecl *D, | |||
139 | SourceLocation Loc) { | |||
140 | // This is disabled under C++; there are too many ways for this to fire in | |||
141 | // contexts where the warning is a false positive, or where it is technically | |||
142 | // correct but benign. | |||
143 | if (S.getLangOpts().CPlusPlus) | |||
144 | return; | |||
145 | ||||
146 | // Check if this is an inlined function or method. | |||
147 | FunctionDecl *Current = S.getCurFunctionDecl(); | |||
148 | if (!Current) | |||
149 | return; | |||
150 | if (!Current->isInlined()) | |||
151 | return; | |||
152 | if (!Current->isExternallyVisible()) | |||
153 | return; | |||
154 | ||||
155 | // Check if the decl has internal linkage. | |||
156 | if (D->getFormalLinkage() != InternalLinkage) | |||
157 | return; | |||
158 | ||||
159 | // Downgrade from ExtWarn to Extension if | |||
160 | // (1) the supposedly external inline function is in the main file, | |||
161 | // and probably won't be included anywhere else. | |||
162 | // (2) the thing we're referencing is a pure function. | |||
163 | // (3) the thing we're referencing is another inline function. | |||
164 | // This last can give us false negatives, but it's better than warning on | |||
165 | // wrappers for simple C library functions. | |||
166 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); | |||
167 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); | |||
168 | if (!DowngradeWarning && UsedFn) | |||
169 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); | |||
170 | ||||
171 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet | |||
172 | : diag::ext_internal_in_extern_inline) | |||
173 | << /*IsVar=*/!UsedFn << D; | |||
174 | ||||
175 | S.MaybeSuggestAddingStaticToDecl(Current); | |||
176 | ||||
177 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) | |||
178 | << D; | |||
179 | } | |||
180 | ||||
181 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { | |||
182 | const FunctionDecl *First = Cur->getFirstDecl(); | |||
183 | ||||
184 | // Suggest "static" on the function, if possible. | |||
185 | if (!hasAnyExplicitStorageClass(First)) { | |||
186 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); | |||
187 | Diag(DeclBegin, diag::note_convert_inline_to_static) | |||
188 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); | |||
189 | } | |||
190 | } | |||
191 | ||||
192 | /// \brief Determine whether the use of this declaration is valid, and | |||
193 | /// emit any corresponding diagnostics. | |||
194 | /// | |||
195 | /// This routine diagnoses various problems with referencing | |||
196 | /// declarations that can occur when using a declaration. For example, | |||
197 | /// it might warn if a deprecated or unavailable declaration is being | |||
198 | /// used, or produce an error (and return true) if a C++0x deleted | |||
199 | /// function is being used. | |||
200 | /// | |||
201 | /// \returns true if there was an error (this declaration cannot be | |||
202 | /// referenced), false otherwise. | |||
203 | /// | |||
204 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | |||
205 | const ObjCInterfaceDecl *UnknownObjCClass, | |||
206 | bool ObjCPropertyAccess, | |||
207 | bool AvoidPartialAvailabilityChecks) { | |||
208 | SourceLocation Loc = Locs.front(); | |||
209 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { | |||
210 | // If there were any diagnostics suppressed by template argument deduction, | |||
211 | // emit them now. | |||
212 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); | |||
213 | if (Pos != SuppressedDiagnostics.end()) { | |||
214 | for (const PartialDiagnosticAt &Suppressed : Pos->second) | |||
215 | Diag(Suppressed.first, Suppressed.second); | |||
216 | ||||
217 | // Clear out the list of suppressed diagnostics, so that we don't emit | |||
218 | // them again for this specialization. However, we don't obsolete this | |||
219 | // entry from the table, because we want to avoid ever emitting these | |||
220 | // diagnostics again. | |||
221 | Pos->second.clear(); | |||
222 | } | |||
223 | ||||
224 | // C++ [basic.start.main]p3: | |||
225 | // The function 'main' shall not be used within a program. | |||
226 | if (cast<FunctionDecl>(D)->isMain()) | |||
227 | Diag(Loc, diag::ext_main_used); | |||
228 | } | |||
229 | ||||
230 | // See if this is an auto-typed variable whose initializer we are parsing. | |||
231 | if (ParsingInitForAutoVars.count(D)) { | |||
232 | if (isa<BindingDecl>(D)) { | |||
233 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) | |||
234 | << D->getDeclName(); | |||
235 | } else { | |||
236 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) | |||
237 | << D->getDeclName() << cast<VarDecl>(D)->getType(); | |||
238 | } | |||
239 | return true; | |||
240 | } | |||
241 | ||||
242 | // See if this is a deleted function. | |||
243 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
244 | if (FD->isDeleted()) { | |||
245 | auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); | |||
246 | if (Ctor && Ctor->isInheritingConstructor()) | |||
247 | Diag(Loc, diag::err_deleted_inherited_ctor_use) | |||
248 | << Ctor->getParent() | |||
249 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); | |||
250 | else | |||
251 | Diag(Loc, diag::err_deleted_function_use); | |||
252 | NoteDeletedFunction(FD); | |||
253 | return true; | |||
254 | } | |||
255 | ||||
256 | // If the function has a deduced return type, and we can't deduce it, | |||
257 | // then we can't use it either. | |||
258 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | |||
259 | DeduceReturnType(FD, Loc)) | |||
260 | return true; | |||
261 | ||||
262 | if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) | |||
263 | return true; | |||
264 | } | |||
265 | ||||
266 | auto getReferencedObjCProp = [](const NamedDecl *D) -> | |||
267 | const ObjCPropertyDecl * { | |||
268 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) | |||
269 | return MD->findPropertyDecl(); | |||
270 | return nullptr; | |||
271 | }; | |||
272 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { | |||
273 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) | |||
274 | return true; | |||
275 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { | |||
276 | return true; | |||
277 | } | |||
278 | ||||
279 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions | |||
280 | // Only the variables omp_in and omp_out are allowed in the combiner. | |||
281 | // Only the variables omp_priv and omp_orig are allowed in the | |||
282 | // initializer-clause. | |||
283 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); | |||
284 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && | |||
285 | isa<VarDecl>(D)) { | |||
286 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) | |||
287 | << getCurFunction()->HasOMPDeclareReductionCombiner; | |||
288 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | |||
289 | return true; | |||
290 | } | |||
291 | ||||
292 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, | |||
293 | AvoidPartialAvailabilityChecks); | |||
294 | ||||
295 | DiagnoseUnusedOfDecl(*this, D, Loc); | |||
296 | ||||
297 | diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); | |||
298 | ||||
299 | return false; | |||
300 | } | |||
301 | ||||
302 | /// \brief Retrieve the message suffix that should be added to a | |||
303 | /// diagnostic complaining about the given function being deleted or | |||
304 | /// unavailable. | |||
305 | std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { | |||
306 | std::string Message; | |||
307 | if (FD->getAvailability(&Message)) | |||
308 | return ": " + Message; | |||
309 | ||||
310 | return std::string(); | |||
311 | } | |||
312 | ||||
313 | /// DiagnoseSentinelCalls - This routine checks whether a call or | |||
314 | /// message-send is to a declaration with the sentinel attribute, and | |||
315 | /// if so, it checks that the requirements of the sentinel are | |||
316 | /// satisfied. | |||
317 | void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, | |||
318 | ArrayRef<Expr *> Args) { | |||
319 | const SentinelAttr *attr = D->getAttr<SentinelAttr>(); | |||
320 | if (!attr) | |||
321 | return; | |||
322 | ||||
323 | // The number of formal parameters of the declaration. | |||
324 | unsigned numFormalParams; | |||
325 | ||||
326 | // The kind of declaration. This is also an index into a %select in | |||
327 | // the diagnostic. | |||
328 | enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; | |||
329 | ||||
330 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { | |||
331 | numFormalParams = MD->param_size(); | |||
332 | calleeType = CT_Method; | |||
333 | } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
334 | numFormalParams = FD->param_size(); | |||
335 | calleeType = CT_Function; | |||
336 | } else if (isa<VarDecl>(D)) { | |||
337 | QualType type = cast<ValueDecl>(D)->getType(); | |||
338 | const FunctionType *fn = nullptr; | |||
339 | if (const PointerType *ptr = type->getAs<PointerType>()) { | |||
340 | fn = ptr->getPointeeType()->getAs<FunctionType>(); | |||
341 | if (!fn) return; | |||
342 | calleeType = CT_Function; | |||
343 | } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { | |||
344 | fn = ptr->getPointeeType()->castAs<FunctionType>(); | |||
345 | calleeType = CT_Block; | |||
346 | } else { | |||
347 | return; | |||
348 | } | |||
349 | ||||
350 | if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { | |||
351 | numFormalParams = proto->getNumParams(); | |||
352 | } else { | |||
353 | numFormalParams = 0; | |||
354 | } | |||
355 | } else { | |||
356 | return; | |||
357 | } | |||
358 | ||||
359 | // "nullPos" is the number of formal parameters at the end which | |||
360 | // effectively count as part of the variadic arguments. This is | |||
361 | // useful if you would prefer to not have *any* formal parameters, | |||
362 | // but the language forces you to have at least one. | |||
363 | unsigned nullPos = attr->getNullPos(); | |||
364 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 364, __extension__ __PRETTY_FUNCTION__)); | |||
365 | numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); | |||
366 | ||||
367 | // The number of arguments which should follow the sentinel. | |||
368 | unsigned numArgsAfterSentinel = attr->getSentinel(); | |||
369 | ||||
370 | // If there aren't enough arguments for all the formal parameters, | |||
371 | // the sentinel, and the args after the sentinel, complain. | |||
372 | if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { | |||
373 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); | |||
374 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | |||
375 | return; | |||
376 | } | |||
377 | ||||
378 | // Otherwise, find the sentinel expression. | |||
379 | Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; | |||
380 | if (!sentinelExpr) return; | |||
381 | if (sentinelExpr->isValueDependent()) return; | |||
382 | if (Context.isSentinelNullExpr(sentinelExpr)) return; | |||
383 | ||||
384 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', | |||
385 | // or 'NULL' if those are actually defined in the context. Only use | |||
386 | // 'nil' for ObjC methods, where it's much more likely that the | |||
387 | // variadic arguments form a list of object pointers. | |||
388 | SourceLocation MissingNilLoc | |||
389 | = getLocForEndOfToken(sentinelExpr->getLocEnd()); | |||
390 | std::string NullValue; | |||
391 | if (calleeType == CT_Method && PP.isMacroDefined("nil")) | |||
392 | NullValue = "nil"; | |||
393 | else if (getLangOpts().CPlusPlus11) | |||
394 | NullValue = "nullptr"; | |||
395 | else if (PP.isMacroDefined("NULL")) | |||
396 | NullValue = "NULL"; | |||
397 | else | |||
398 | NullValue = "(void*) 0"; | |||
399 | ||||
400 | if (MissingNilLoc.isInvalid()) | |||
401 | Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); | |||
402 | else | |||
403 | Diag(MissingNilLoc, diag::warn_missing_sentinel) | |||
404 | << int(calleeType) | |||
405 | << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); | |||
406 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | |||
407 | } | |||
408 | ||||
409 | SourceRange Sema::getExprRange(Expr *E) const { | |||
410 | return E ? E->getSourceRange() : SourceRange(); | |||
411 | } | |||
412 | ||||
413 | //===----------------------------------------------------------------------===// | |||
414 | // Standard Promotions and Conversions | |||
415 | //===----------------------------------------------------------------------===// | |||
416 | ||||
417 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). | |||
418 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { | |||
419 | // Handle any placeholder expressions which made it here. | |||
420 | if (E->getType()->isPlaceholderType()) { | |||
421 | ExprResult result = CheckPlaceholderExpr(E); | |||
422 | if (result.isInvalid()) return ExprError(); | |||
423 | E = result.get(); | |||
424 | } | |||
425 | ||||
426 | QualType Ty = E->getType(); | |||
427 | assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultFunctionArrayConversion - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 427, __extension__ __PRETTY_FUNCTION__)); | |||
428 | ||||
429 | if (Ty->isFunctionType()) { | |||
430 | if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) | |||
431 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | |||
432 | if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) | |||
433 | return ExprError(); | |||
434 | ||||
435 | E = ImpCastExprToType(E, Context.getPointerType(Ty), | |||
436 | CK_FunctionToPointerDecay).get(); | |||
437 | } else if (Ty->isArrayType()) { | |||
438 | // In C90 mode, arrays only promote to pointers if the array expression is | |||
439 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has | |||
440 | // type 'array of type' is converted to an expression that has type 'pointer | |||
441 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression | |||
442 | // that has type 'array of type' ...". The relevant change is "an lvalue" | |||
443 | // (C90) to "an expression" (C99). | |||
444 | // | |||
445 | // C++ 4.2p1: | |||
446 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of | |||
447 | // T" can be converted to an rvalue of type "pointer to T". | |||
448 | // | |||
449 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) | |||
450 | E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), | |||
451 | CK_ArrayToPointerDecay).get(); | |||
452 | } | |||
453 | return E; | |||
454 | } | |||
455 | ||||
456 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { | |||
457 | // Check to see if we are dereferencing a null pointer. If so, | |||
458 | // and if not volatile-qualified, this is undefined behavior that the | |||
459 | // optimizer will delete, so warn about it. People sometimes try to use this | |||
460 | // to get a deterministic trap and are surprised by clang's behavior. This | |||
461 | // only handles the pattern "*null", which is a very syntactic check. | |||
462 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) | |||
463 | if (UO->getOpcode() == UO_Deref && | |||
464 | UO->getSubExpr()->IgnoreParenCasts()-> | |||
465 | isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && | |||
466 | !UO->getType().isVolatileQualified()) { | |||
467 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | |||
468 | S.PDiag(diag::warn_indirection_through_null) | |||
469 | << UO->getSubExpr()->getSourceRange()); | |||
470 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | |||
471 | S.PDiag(diag::note_indirection_through_null)); | |||
472 | } | |||
473 | } | |||
474 | ||||
475 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, | |||
476 | SourceLocation AssignLoc, | |||
477 | const Expr* RHS) { | |||
478 | const ObjCIvarDecl *IV = OIRE->getDecl(); | |||
479 | if (!IV) | |||
480 | return; | |||
481 | ||||
482 | DeclarationName MemberName = IV->getDeclName(); | |||
483 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); | |||
484 | if (!Member || !Member->isStr("isa")) | |||
485 | return; | |||
486 | ||||
487 | const Expr *Base = OIRE->getBase(); | |||
488 | QualType BaseType = Base->getType(); | |||
489 | if (OIRE->isArrow()) | |||
490 | BaseType = BaseType->getPointeeType(); | |||
491 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) | |||
492 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { | |||
493 | ObjCInterfaceDecl *ClassDeclared = nullptr; | |||
494 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); | |||
495 | if (!ClassDeclared->getSuperClass() | |||
496 | && (*ClassDeclared->ivar_begin()) == IV) { | |||
497 | if (RHS) { | |||
498 | NamedDecl *ObjectSetClass = | |||
499 | S.LookupSingleName(S.TUScope, | |||
500 | &S.Context.Idents.get("object_setClass"), | |||
501 | SourceLocation(), S.LookupOrdinaryName); | |||
502 | if (ObjectSetClass) { | |||
503 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); | |||
504 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << | |||
505 | FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << | |||
506 | FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), | |||
507 | AssignLoc), ",") << | |||
508 | FixItHint::CreateInsertion(RHSLocEnd, ")"); | |||
509 | } | |||
510 | else | |||
511 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); | |||
512 | } else { | |||
513 | NamedDecl *ObjectGetClass = | |||
514 | S.LookupSingleName(S.TUScope, | |||
515 | &S.Context.Idents.get("object_getClass"), | |||
516 | SourceLocation(), S.LookupOrdinaryName); | |||
517 | if (ObjectGetClass) | |||
518 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << | |||
519 | FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << | |||
520 | FixItHint::CreateReplacement( | |||
521 | SourceRange(OIRE->getOpLoc(), | |||
522 | OIRE->getLocEnd()), ")"); | |||
523 | else | |||
524 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); | |||
525 | } | |||
526 | S.Diag(IV->getLocation(), diag::note_ivar_decl); | |||
527 | } | |||
528 | } | |||
529 | } | |||
530 | ||||
531 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { | |||
532 | // Handle any placeholder expressions which made it here. | |||
533 | if (E->getType()->isPlaceholderType()) { | |||
534 | ExprResult result = CheckPlaceholderExpr(E); | |||
535 | if (result.isInvalid()) return ExprError(); | |||
536 | E = result.get(); | |||
537 | } | |||
538 | ||||
539 | // C++ [conv.lval]p1: | |||
540 | // A glvalue of a non-function, non-array type T can be | |||
541 | // converted to a prvalue. | |||
542 | if (!E->isGLValue()) return E; | |||
543 | ||||
544 | QualType T = E->getType(); | |||
545 | 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?\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 545, __extension__ __PRETTY_FUNCTION__)); | |||
546 | ||||
547 | // We don't want to throw lvalue-to-rvalue casts on top of | |||
548 | // expressions of certain types in C++. | |||
549 | if (getLangOpts().CPlusPlus && | |||
550 | (E->getType() == Context.OverloadTy || | |||
551 | T->isDependentType() || | |||
552 | T->isRecordType())) | |||
553 | return E; | |||
554 | ||||
555 | // The C standard is actually really unclear on this point, and | |||
556 | // DR106 tells us what the result should be but not why. It's | |||
557 | // generally best to say that void types just doesn't undergo | |||
558 | // lvalue-to-rvalue at all. Note that expressions of unqualified | |||
559 | // 'void' type are never l-values, but qualified void can be. | |||
560 | if (T->isVoidType()) | |||
561 | return E; | |||
562 | ||||
563 | // OpenCL usually rejects direct accesses to values of 'half' type. | |||
564 | if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && | |||
565 | T->isHalfType()) { | |||
566 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) | |||
567 | << 0 << T; | |||
568 | return ExprError(); | |||
569 | } | |||
570 | ||||
571 | CheckForNullPointerDereference(*this, E); | |||
572 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { | |||
573 | NamedDecl *ObjectGetClass = LookupSingleName(TUScope, | |||
574 | &Context.Idents.get("object_getClass"), | |||
575 | SourceLocation(), LookupOrdinaryName); | |||
576 | if (ObjectGetClass) | |||
577 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) << | |||
578 | FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << | |||
579 | FixItHint::CreateReplacement( | |||
580 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); | |||
581 | else | |||
582 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); | |||
583 | } | |||
584 | else if (const ObjCIvarRefExpr *OIRE = | |||
585 | dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) | |||
586 | DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); | |||
587 | ||||
588 | // C++ [conv.lval]p1: | |||
589 | // [...] If T is a non-class type, the type of the prvalue is the | |||
590 | // cv-unqualified version of T. Otherwise, the type of the | |||
591 | // rvalue is T. | |||
592 | // | |||
593 | // C99 6.3.2.1p2: | |||
594 | // If the lvalue has qualified type, the value has the unqualified | |||
595 | // version of the type of the lvalue; otherwise, the value has the | |||
596 | // type of the lvalue. | |||
597 | if (T.hasQualifiers()) | |||
598 | T = T.getUnqualifiedType(); | |||
599 | ||||
600 | // Under the MS ABI, lock down the inheritance model now. | |||
601 | if (T->isMemberPointerType() && | |||
602 | Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
603 | (void)isCompleteType(E->getExprLoc(), T); | |||
604 | ||||
605 | UpdateMarkingForLValueToRValue(E); | |||
606 | ||||
607 | // Loading a __weak object implicitly retains the value, so we need a cleanup to | |||
608 | // balance that. | |||
609 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | |||
610 | Cleanup.setExprNeedsCleanups(true); | |||
611 | ||||
612 | ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, | |||
613 | nullptr, VK_RValue); | |||
614 | ||||
615 | // C11 6.3.2.1p2: | |||
616 | // ... if the lvalue has atomic type, the value has the non-atomic version | |||
617 | // of the type of the lvalue ... | |||
618 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { | |||
619 | T = Atomic->getValueType().getUnqualifiedType(); | |||
620 | Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), | |||
621 | nullptr, VK_RValue); | |||
622 | } | |||
623 | ||||
624 | return Res; | |||
625 | } | |||
626 | ||||
627 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { | |||
628 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); | |||
629 | if (Res.isInvalid()) | |||
630 | return ExprError(); | |||
631 | Res = DefaultLvalueConversion(Res.get()); | |||
632 | if (Res.isInvalid()) | |||
633 | return ExprError(); | |||
634 | return Res; | |||
635 | } | |||
636 | ||||
637 | /// CallExprUnaryConversions - a special case of an unary conversion | |||
638 | /// performed on a function designator of a call expression. | |||
639 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { | |||
640 | QualType Ty = E->getType(); | |||
641 | ExprResult Res = E; | |||
642 | // Only do implicit cast for a function type, but not for a pointer | |||
643 | // to function type. | |||
644 | if (Ty->isFunctionType()) { | |||
645 | Res = ImpCastExprToType(E, Context.getPointerType(Ty), | |||
646 | CK_FunctionToPointerDecay).get(); | |||
647 | if (Res.isInvalid()) | |||
648 | return ExprError(); | |||
649 | } | |||
650 | Res = DefaultLvalueConversion(Res.get()); | |||
651 | if (Res.isInvalid()) | |||
652 | return ExprError(); | |||
653 | return Res.get(); | |||
654 | } | |||
655 | ||||
656 | /// UsualUnaryConversions - Performs various conversions that are common to most | |||
657 | /// operators (C99 6.3). The conversions of array and function types are | |||
658 | /// sometimes suppressed. For example, the array->pointer conversion doesn't | |||
659 | /// apply if the array is an argument to the sizeof or address (&) operators. | |||
660 | /// In these instances, this routine should *not* be called. | |||
661 | ExprResult Sema::UsualUnaryConversions(Expr *E) { | |||
662 | // First, convert to an r-value. | |||
663 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | |||
664 | if (Res.isInvalid()) | |||
665 | return ExprError(); | |||
666 | E = Res.get(); | |||
667 | ||||
668 | QualType Ty = E->getType(); | |||
669 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type")(static_cast <bool> (!Ty.isNull() && "UsualUnaryConversions - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 669, __extension__ __PRETTY_FUNCTION__)); | |||
670 | ||||
671 | // Half FP have to be promoted to float unless it is natively supported | |||
672 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) | |||
673 | return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); | |||
674 | ||||
675 | // Try to perform integral promotions if the object has a theoretically | |||
676 | // promotable type. | |||
677 | if (Ty->isIntegralOrUnscopedEnumerationType()) { | |||
678 | // C99 6.3.1.1p2: | |||
679 | // | |||
680 | // The following may be used in an expression wherever an int or | |||
681 | // unsigned int may be used: | |||
682 | // - an object or expression with an integer type whose integer | |||
683 | // conversion rank is less than or equal to the rank of int | |||
684 | // and unsigned int. | |||
685 | // - A bit-field of type _Bool, int, signed int, or unsigned int. | |||
686 | // | |||
687 | // If an int can represent all values of the original type, the | |||
688 | // value is converted to an int; otherwise, it is converted to an | |||
689 | // unsigned int. These are called the integer promotions. All | |||
690 | // other types are unchanged by the integer promotions. | |||
691 | ||||
692 | QualType PTy = Context.isPromotableBitField(E); | |||
693 | if (!PTy.isNull()) { | |||
694 | E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); | |||
695 | return E; | |||
696 | } | |||
697 | if (Ty->isPromotableIntegerType()) { | |||
698 | QualType PT = Context.getPromotedIntegerType(Ty); | |||
699 | E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); | |||
700 | return E; | |||
701 | } | |||
702 | } | |||
703 | return E; | |||
704 | } | |||
705 | ||||
706 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that | |||
707 | /// do not have a prototype. Arguments that have type float or __fp16 | |||
708 | /// are promoted to double. All other argument types are converted by | |||
709 | /// UsualUnaryConversions(). | |||
710 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { | |||
711 | QualType Ty = E->getType(); | |||
712 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultArgumentPromotion - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 712, __extension__ __PRETTY_FUNCTION__)); | |||
713 | ||||
714 | ExprResult Res = UsualUnaryConversions(E); | |||
715 | if (Res.isInvalid()) | |||
716 | return ExprError(); | |||
717 | E = Res.get(); | |||
718 | ||||
719 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) | |||
720 | // promote to double. | |||
721 | // Note that default argument promotion applies only to float (and | |||
722 | // half/fp16); it does not apply to _Float16. | |||
723 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | |||
724 | if (BTy && (BTy->getKind() == BuiltinType::Half || | |||
725 | BTy->getKind() == BuiltinType::Float)) { | |||
726 | if (getLangOpts().OpenCL && | |||
727 | !getOpenCLOptions().isEnabled("cl_khr_fp64")) { | |||
728 | if (BTy->getKind() == BuiltinType::Half) { | |||
729 | E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); | |||
730 | } | |||
731 | } else { | |||
732 | E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); | |||
733 | } | |||
734 | } | |||
735 | ||||
736 | // C++ performs lvalue-to-rvalue conversion as a default argument | |||
737 | // promotion, even on class types, but note: | |||
738 | // C++11 [conv.lval]p2: | |||
739 | // When an lvalue-to-rvalue conversion occurs in an unevaluated | |||
740 | // operand or a subexpression thereof the value contained in the | |||
741 | // referenced object is not accessed. Otherwise, if the glvalue | |||
742 | // has a class type, the conversion copy-initializes a temporary | |||
743 | // of type T from the glvalue and the result of the conversion | |||
744 | // is a prvalue for the temporary. | |||
745 | // FIXME: add some way to gate this entire thing for correctness in | |||
746 | // potentially potentially evaluated contexts. | |||
747 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { | |||
748 | ExprResult Temp = PerformCopyInitialization( | |||
749 | InitializedEntity::InitializeTemporary(E->getType()), | |||
750 | E->getExprLoc(), E); | |||
751 | if (Temp.isInvalid()) | |||
752 | return ExprError(); | |||
753 | E = Temp.get(); | |||
754 | } | |||
755 | ||||
756 | return E; | |||
757 | } | |||
758 | ||||
759 | /// Determine the degree of POD-ness for an expression. | |||
760 | /// Incomplete types are considered POD, since this check can be performed | |||
761 | /// when we're in an unevaluated context. | |||
762 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { | |||
763 | if (Ty->isIncompleteType()) { | |||
764 | // C++11 [expr.call]p7: | |||
765 | // After these conversions, if the argument does not have arithmetic, | |||
766 | // enumeration, pointer, pointer to member, or class type, the program | |||
767 | // is ill-formed. | |||
768 | // | |||
769 | // Since we've already performed array-to-pointer and function-to-pointer | |||
770 | // decay, the only such type in C++ is cv void. This also handles | |||
771 | // initializer lists as variadic arguments. | |||
772 | if (Ty->isVoidType()) | |||
773 | return VAK_Invalid; | |||
774 | ||||
775 | if (Ty->isObjCObjectType()) | |||
776 | return VAK_Invalid; | |||
777 | return VAK_Valid; | |||
778 | } | |||
779 | ||||
780 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
781 | return VAK_Invalid; | |||
782 | ||||
783 | if (Ty.isCXX98PODType(Context)) | |||
784 | return VAK_Valid; | |||
785 | ||||
786 | // C++11 [expr.call]p7: | |||
787 | // Passing a potentially-evaluated argument of class type (Clause 9) | |||
788 | // having a non-trivial copy constructor, a non-trivial move constructor, | |||
789 | // or a non-trivial destructor, with no corresponding parameter, | |||
790 | // is conditionally-supported with implementation-defined semantics. | |||
791 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) | |||
792 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) | |||
793 | if (!Record->hasNonTrivialCopyConstructor() && | |||
794 | !Record->hasNonTrivialMoveConstructor() && | |||
795 | !Record->hasNonTrivialDestructor()) | |||
796 | return VAK_ValidInCXX11; | |||
797 | ||||
798 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) | |||
799 | return VAK_Valid; | |||
800 | ||||
801 | if (Ty->isObjCObjectType()) | |||
802 | return VAK_Invalid; | |||
803 | ||||
804 | if (getLangOpts().MSVCCompat) | |||
805 | return VAK_MSVCUndefined; | |||
806 | ||||
807 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're | |||
808 | // permitted to reject them. We should consider doing so. | |||
809 | return VAK_Undefined; | |||
810 | } | |||
811 | ||||
812 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { | |||
813 | // Don't allow one to pass an Objective-C interface to a vararg. | |||
814 | const QualType &Ty = E->getType(); | |||
815 | VarArgKind VAK = isValidVarArgType(Ty); | |||
816 | ||||
817 | // Complain about passing non-POD types through varargs. | |||
818 | switch (VAK) { | |||
819 | case VAK_ValidInCXX11: | |||
820 | DiagRuntimeBehavior( | |||
821 | E->getLocStart(), nullptr, | |||
822 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) | |||
823 | << Ty << CT); | |||
824 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
825 | case VAK_Valid: | |||
826 | if (Ty->isRecordType()) { | |||
827 | // This is unlikely to be what the user intended. If the class has a | |||
828 | // 'c_str' member function, the user probably meant to call that. | |||
829 | DiagRuntimeBehavior(E->getLocStart(), nullptr, | |||
830 | PDiag(diag::warn_pass_class_arg_to_vararg) | |||
831 | << Ty << CT << hasCStrMethod(E) << ".c_str()"); | |||
832 | } | |||
833 | break; | |||
834 | ||||
835 | case VAK_Undefined: | |||
836 | case VAK_MSVCUndefined: | |||
837 | DiagRuntimeBehavior( | |||
838 | E->getLocStart(), nullptr, | |||
839 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) | |||
840 | << getLangOpts().CPlusPlus11 << Ty << CT); | |||
841 | break; | |||
842 | ||||
843 | case VAK_Invalid: | |||
844 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
845 | Diag(E->getLocStart(), | |||
846 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT; | |||
847 | else if (Ty->isObjCObjectType()) | |||
848 | DiagRuntimeBehavior( | |||
849 | E->getLocStart(), nullptr, | |||
850 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) | |||
851 | << Ty << CT); | |||
852 | else | |||
853 | Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) | |||
854 | << isa<InitListExpr>(E) << Ty << CT; | |||
855 | break; | |||
856 | } | |||
857 | } | |||
858 | ||||
859 | /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but | |||
860 | /// will create a trap if the resulting type is not a POD type. | |||
861 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, | |||
862 | FunctionDecl *FDecl) { | |||
863 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { | |||
864 | // Strip the unbridged-cast placeholder expression off, if applicable. | |||
865 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && | |||
866 | (CT == VariadicMethod || | |||
867 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { | |||
868 | E = stripARCUnbridgedCast(E); | |||
869 | ||||
870 | // Otherwise, do normal placeholder checking. | |||
871 | } else { | |||
872 | ExprResult ExprRes = CheckPlaceholderExpr(E); | |||
873 | if (ExprRes.isInvalid()) | |||
874 | return ExprError(); | |||
875 | E = ExprRes.get(); | |||
876 | } | |||
877 | } | |||
878 | ||||
879 | ExprResult ExprRes = DefaultArgumentPromotion(E); | |||
880 | if (ExprRes.isInvalid()) | |||
881 | return ExprError(); | |||
882 | E = ExprRes.get(); | |||
883 | ||||
884 | // Diagnostics regarding non-POD argument types are | |||
885 | // emitted along with format string checking in Sema::CheckFunctionCall(). | |||
886 | if (isValidVarArgType(E->getType()) == VAK_Undefined) { | |||
887 | // Turn this into a trap. | |||
888 | CXXScopeSpec SS; | |||
889 | SourceLocation TemplateKWLoc; | |||
890 | UnqualifiedId Name; | |||
891 | Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), | |||
892 | E->getLocStart()); | |||
893 | ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, | |||
894 | Name, true, false); | |||
895 | if (TrapFn.isInvalid()) | |||
896 | return ExprError(); | |||
897 | ||||
898 | ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), | |||
899 | E->getLocStart(), None, | |||
900 | E->getLocEnd()); | |||
901 | if (Call.isInvalid()) | |||
902 | return ExprError(); | |||
903 | ||||
904 | ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, | |||
905 | Call.get(), E); | |||
906 | if (Comma.isInvalid()) | |||
907 | return ExprError(); | |||
908 | return Comma.get(); | |||
909 | } | |||
910 | ||||
911 | if (!getLangOpts().CPlusPlus && | |||
912 | RequireCompleteType(E->getExprLoc(), E->getType(), | |||
913 | diag::err_call_incomplete_argument)) | |||
914 | return ExprError(); | |||
915 | ||||
916 | return E; | |||
917 | } | |||
918 | ||||
919 | /// \brief Converts an integer to complex float type. Helper function of | |||
920 | /// UsualArithmeticConversions() | |||
921 | /// | |||
922 | /// \return false if the integer expression is an integer type and is | |||
923 | /// successfully converted to the complex type. | |||
924 | static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, | |||
925 | ExprResult &ComplexExpr, | |||
926 | QualType IntTy, | |||
927 | QualType ComplexTy, | |||
928 | bool SkipCast) { | |||
929 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; | |||
930 | if (SkipCast) return false; | |||
931 | if (IntTy->isIntegerType()) { | |||
932 | QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); | |||
933 | IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); | |||
934 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | |||
935 | CK_FloatingRealToComplex); | |||
936 | } else { | |||
937 | assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ? void (0) : __assert_fail ("IntTy->isComplexIntegerType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 937, __extension__ __PRETTY_FUNCTION__)); | |||
938 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | |||
939 | CK_IntegralComplexToFloatingComplex); | |||
940 | } | |||
941 | return false; | |||
942 | } | |||
943 | ||||
944 | /// \brief Handle arithmetic conversion with complex types. Helper function of | |||
945 | /// UsualArithmeticConversions() | |||
946 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, | |||
947 | ExprResult &RHS, QualType LHSType, | |||
948 | QualType RHSType, | |||
949 | bool IsCompAssign) { | |||
950 | // if we have an integer operand, the result is the complex type. | |||
951 | if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, | |||
952 | /*skipCast*/false)) | |||
953 | return LHSType; | |||
954 | if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, | |||
955 | /*skipCast*/IsCompAssign)) | |||
956 | return RHSType; | |||
957 | ||||
958 | // This handles complex/complex, complex/float, or float/complex. | |||
959 | // When both operands are complex, the shorter operand is converted to the | |||
960 | // type of the longer, and that is the type of the result. This corresponds | |||
961 | // to what is done when combining two real floating-point operands. | |||
962 | // The fun begins when size promotion occur across type domains. | |||
963 | // From H&S 6.3.4: When one operand is complex and the other is a real | |||
964 | // floating-point type, the less precise type is converted, within it's | |||
965 | // real or complex domain, to the precision of the other type. For example, | |||
966 | // when combining a "long double" with a "double _Complex", the | |||
967 | // "double _Complex" is promoted to "long double _Complex". | |||
968 | ||||
969 | // Compute the rank of the two types, regardless of whether they are complex. | |||
970 | int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | |||
971 | ||||
972 | auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); | |||
973 | auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); | |||
974 | QualType LHSElementType = | |||
975 | LHSComplexType ? LHSComplexType->getElementType() : LHSType; | |||
976 | QualType RHSElementType = | |||
977 | RHSComplexType ? RHSComplexType->getElementType() : RHSType; | |||
978 | ||||
979 | QualType ResultType = S.Context.getComplexType(LHSElementType); | |||
980 | if (Order < 0) { | |||
981 | // Promote the precision of the LHS if not an assignment. | |||
982 | ResultType = S.Context.getComplexType(RHSElementType); | |||
983 | if (!IsCompAssign) { | |||
984 | if (LHSComplexType) | |||
985 | LHS = | |||
986 | S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); | |||
987 | else | |||
988 | LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); | |||
989 | } | |||
990 | } else if (Order > 0) { | |||
991 | // Promote the precision of the RHS. | |||
992 | if (RHSComplexType) | |||
993 | RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); | |||
994 | else | |||
995 | RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); | |||
996 | } | |||
997 | return ResultType; | |||
998 | } | |||
999 | ||||
1000 | /// \brief Handle arithmetic conversion from integer to float. Helper function | |||
1001 | /// of UsualArithmeticConversions() | |||
1002 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, | |||
1003 | ExprResult &IntExpr, | |||
1004 | QualType FloatTy, QualType IntTy, | |||
1005 | bool ConvertFloat, bool ConvertInt) { | |||
1006 | if (IntTy->isIntegerType()) { | |||
1007 | if (ConvertInt) | |||
1008 | // Convert intExpr to the lhs floating point type. | |||
1009 | IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, | |||
1010 | CK_IntegralToFloating); | |||
1011 | return FloatTy; | |||
1012 | } | |||
1013 | ||||
1014 | // Convert both sides to the appropriate complex float. | |||
1015 | assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ? void (0) : __assert_fail ("IntTy->isComplexIntegerType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1015, __extension__ __PRETTY_FUNCTION__)); | |||
1016 | QualType result = S.Context.getComplexType(FloatTy); | |||
1017 | ||||
1018 | // _Complex int -> _Complex float | |||
1019 | if (ConvertInt) | |||
1020 | IntExpr = S.ImpCastExprToType(IntExpr.get(), result, | |||
1021 | CK_IntegralComplexToFloatingComplex); | |||
1022 | ||||
1023 | // float -> _Complex float | |||
1024 | if (ConvertFloat) | |||
1025 | FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, | |||
1026 | CK_FloatingRealToComplex); | |||
1027 | ||||
1028 | return result; | |||
1029 | } | |||
1030 | ||||
1031 | /// \brief Handle arithmethic conversion with floating point types. Helper | |||
1032 | /// function of UsualArithmeticConversions() | |||
1033 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, | |||
1034 | ExprResult &RHS, QualType LHSType, | |||
1035 | QualType RHSType, bool IsCompAssign) { | |||
1036 | bool LHSFloat = LHSType->isRealFloatingType(); | |||
1037 | bool RHSFloat = RHSType->isRealFloatingType(); | |||
1038 | ||||
1039 | // If we have two real floating types, convert the smaller operand | |||
1040 | // to the bigger result. | |||
1041 | if (LHSFloat && RHSFloat) { | |||
1042 | int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | |||
1043 | if (order > 0) { | |||
1044 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); | |||
1045 | return LHSType; | |||
1046 | } | |||
1047 | ||||
1048 | assert(order < 0 && "illegal float comparison")(static_cast <bool> (order < 0 && "illegal float comparison" ) ? void (0) : __assert_fail ("order < 0 && \"illegal float comparison\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1048, __extension__ __PRETTY_FUNCTION__)); | |||
1049 | if (!IsCompAssign) | |||
1050 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); | |||
1051 | return RHSType; | |||
1052 | } | |||
1053 | ||||
1054 | if (LHSFloat) { | |||
1055 | // Half FP has to be promoted to float unless it is natively supported | |||
1056 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) | |||
1057 | LHSType = S.Context.FloatTy; | |||
1058 | ||||
1059 | return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, | |||
1060 | /*convertFloat=*/!IsCompAssign, | |||
1061 | /*convertInt=*/ true); | |||
1062 | } | |||
1063 | assert(RHSFloat)(static_cast <bool> (RHSFloat) ? void (0) : __assert_fail ("RHSFloat", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1063, __extension__ __PRETTY_FUNCTION__)); | |||
1064 | return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, | |||
1065 | /*convertInt=*/ true, | |||
1066 | /*convertFloat=*/!IsCompAssign); | |||
1067 | } | |||
1068 | ||||
1069 | /// \brief Diagnose attempts to convert between __float128 and long double if | |||
1070 | /// there is no support for such conversion. Helper function of | |||
1071 | /// UsualArithmeticConversions(). | |||
1072 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, | |||
1073 | QualType RHSType) { | |||
1074 | /* No issue converting if at least one of the types is not a floating point | |||
1075 | type or the two types have the same rank. | |||
1076 | */ | |||
1077 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || | |||
1078 | S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) | |||
1079 | return false; | |||
1080 | ||||
1081 | assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&(static_cast <bool> (LHSType->isFloatingType() && RHSType->isFloatingType() && "The remaining types must be floating point types." ) ? void (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1082, __extension__ __PRETTY_FUNCTION__)) | |||
1082 | "The remaining types must be floating point types.")(static_cast <bool> (LHSType->isFloatingType() && RHSType->isFloatingType() && "The remaining types must be floating point types." ) ? void (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1082, __extension__ __PRETTY_FUNCTION__)); | |||
1083 | ||||
1084 | auto *LHSComplex = LHSType->getAs<ComplexType>(); | |||
1085 | auto *RHSComplex = RHSType->getAs<ComplexType>(); | |||
1086 | ||||
1087 | QualType LHSElemType = LHSComplex ? | |||
1088 | LHSComplex->getElementType() : LHSType; | |||
1089 | QualType RHSElemType = RHSComplex ? | |||
1090 | RHSComplex->getElementType() : RHSType; | |||
1091 | ||||
1092 | // No issue if the two types have the same representation | |||
1093 | if (&S.Context.getFloatTypeSemantics(LHSElemType) == | |||
1094 | &S.Context.getFloatTypeSemantics(RHSElemType)) | |||
1095 | return false; | |||
1096 | ||||
1097 | bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && | |||
1098 | RHSElemType == S.Context.LongDoubleTy); | |||
1099 | Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && | |||
1100 | RHSElemType == S.Context.Float128Ty); | |||
1101 | ||||
1102 | // We've handled the situation where __float128 and long double have the same | |||
1103 | // representation. We allow all conversions for all possible long double types | |||
1104 | // except PPC's double double. | |||
1105 | return Float128AndLongDouble && | |||
1106 | (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == | |||
1107 | &llvm::APFloat::PPCDoubleDouble()); | |||
1108 | } | |||
1109 | ||||
1110 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); | |||
1111 | ||||
1112 | namespace { | |||
1113 | /// These helper callbacks are placed in an anonymous namespace to | |||
1114 | /// permit their use as function template parameters. | |||
1115 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { | |||
1116 | return S.ImpCastExprToType(op, toType, CK_IntegralCast); | |||
1117 | } | |||
1118 | ||||
1119 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { | |||
1120 | return S.ImpCastExprToType(op, S.Context.getComplexType(toType), | |||
1121 | CK_IntegralComplexCast); | |||
1122 | } | |||
1123 | } | |||
1124 | ||||
1125 | /// \brief Handle integer arithmetic conversions. Helper function of | |||
1126 | /// UsualArithmeticConversions() | |||
1127 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> | |||
1128 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, | |||
1129 | ExprResult &RHS, QualType LHSType, | |||
1130 | QualType RHSType, bool IsCompAssign) { | |||
1131 | // The rules for this case are in C99 6.3.1.8 | |||
1132 | int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); | |||
1133 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); | |||
1134 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); | |||
1135 | if (LHSSigned == RHSSigned) { | |||
1136 | // Same signedness; use the higher-ranked type | |||
1137 | if (order >= 0) { | |||
1138 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | |||
1139 | return LHSType; | |||
1140 | } else if (!IsCompAssign) | |||
1141 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | |||
1142 | return RHSType; | |||
1143 | } else if (order != (LHSSigned ? 1 : -1)) { | |||
1144 | // The unsigned type has greater than or equal rank to the | |||
1145 | // signed type, so use the unsigned type | |||
1146 | if (RHSSigned) { | |||
1147 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | |||
1148 | return LHSType; | |||
1149 | } else if (!IsCompAssign) | |||
1150 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | |||
1151 | return RHSType; | |||
1152 | } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { | |||
1153 | // The two types are different widths; if we are here, that | |||
1154 | // means the signed type is larger than the unsigned type, so | |||
1155 | // use the signed type. | |||
1156 | if (LHSSigned) { | |||
1157 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | |||
1158 | return LHSType; | |||
1159 | } else if (!IsCompAssign) | |||
1160 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | |||
1161 | return RHSType; | |||
1162 | } else { | |||
1163 | // The signed type is higher-ranked than the unsigned type, | |||
1164 | // but isn't actually any bigger (like unsigned int and long | |||
1165 | // on most 32-bit systems). Use the unsigned type corresponding | |||
1166 | // to the signed type. | |||
1167 | QualType result = | |||
1168 | S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); | |||
1169 | RHS = (*doRHSCast)(S, RHS.get(), result); | |||
1170 | if (!IsCompAssign) | |||
1171 | LHS = (*doLHSCast)(S, LHS.get(), result); | |||
1172 | return result; | |||
1173 | } | |||
1174 | } | |||
1175 | ||||
1176 | /// \brief Handle conversions with GCC complex int extension. Helper function | |||
1177 | /// of UsualArithmeticConversions() | |||
1178 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, | |||
1179 | ExprResult &RHS, QualType LHSType, | |||
1180 | QualType RHSType, | |||
1181 | bool IsCompAssign) { | |||
1182 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); | |||
1183 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); | |||
1184 | ||||
1185 | if (LHSComplexInt && RHSComplexInt) { | |||
1186 | QualType LHSEltType = LHSComplexInt->getElementType(); | |||
1187 | QualType RHSEltType = RHSComplexInt->getElementType(); | |||
1188 | QualType ScalarType = | |||
1189 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> | |||
1190 | (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); | |||
1191 | ||||
1192 | return S.Context.getComplexType(ScalarType); | |||
1193 | } | |||
1194 | ||||
1195 | if (LHSComplexInt) { | |||
1196 | QualType LHSEltType = LHSComplexInt->getElementType(); | |||
1197 | QualType ScalarType = | |||
1198 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> | |||
1199 | (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); | |||
1200 | QualType ComplexType = S.Context.getComplexType(ScalarType); | |||
1201 | RHS = S.ImpCastExprToType(RHS.get(), ComplexType, | |||
1202 | CK_IntegralRealToComplex); | |||
1203 | ||||
1204 | return ComplexType; | |||
1205 | } | |||
1206 | ||||
1207 | assert(RHSComplexInt)(static_cast <bool> (RHSComplexInt) ? void (0) : __assert_fail ("RHSComplexInt", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1207, __extension__ __PRETTY_FUNCTION__)); | |||
1208 | ||||
1209 | QualType RHSEltType = RHSComplexInt->getElementType(); | |||
1210 | QualType ScalarType = | |||
1211 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> | |||
1212 | (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); | |||
1213 | QualType ComplexType = S.Context.getComplexType(ScalarType); | |||
1214 | ||||
1215 | if (!IsCompAssign) | |||
1216 | LHS = S.ImpCastExprToType(LHS.get(), ComplexType, | |||
1217 | CK_IntegralRealToComplex); | |||
1218 | return ComplexType; | |||
1219 | } | |||
1220 | ||||
1221 | /// UsualArithmeticConversions - Performs various conversions that are common to | |||
1222 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this | |||
1223 | /// routine returns the first non-arithmetic type found. The client is | |||
1224 | /// responsible for emitting appropriate error diagnostics. | |||
1225 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, | |||
1226 | bool IsCompAssign) { | |||
1227 | if (!IsCompAssign) { | |||
1228 | LHS = UsualUnaryConversions(LHS.get()); | |||
1229 | if (LHS.isInvalid()) | |||
1230 | return QualType(); | |||
1231 | } | |||
1232 | ||||
1233 | RHS = UsualUnaryConversions(RHS.get()); | |||
1234 | if (RHS.isInvalid()) | |||
1235 | return QualType(); | |||
1236 | ||||
1237 | // For conversion purposes, we ignore any qualifiers. | |||
1238 | // For example, "const float" and "float" are equivalent. | |||
1239 | QualType LHSType = | |||
1240 | Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | |||
1241 | QualType RHSType = | |||
1242 | Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | |||
1243 | ||||
1244 | // For conversion purposes, we ignore any atomic qualifier on the LHS. | |||
1245 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) | |||
1246 | LHSType = AtomicLHS->getValueType(); | |||
1247 | ||||
1248 | // If both types are identical, no conversion is needed. | |||
1249 | if (LHSType == RHSType) | |||
1250 | return LHSType; | |||
1251 | ||||
1252 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. | |||
1253 | // The caller can deal with this (e.g. pointer + int). | |||
1254 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) | |||
1255 | return QualType(); | |||
1256 | ||||
1257 | // Apply unary and bitfield promotions to the LHS's type. | |||
1258 | QualType LHSUnpromotedType = LHSType; | |||
1259 | if (LHSType->isPromotableIntegerType()) | |||
1260 | LHSType = Context.getPromotedIntegerType(LHSType); | |||
1261 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); | |||
1262 | if (!LHSBitfieldPromoteTy.isNull()) | |||
1263 | LHSType = LHSBitfieldPromoteTy; | |||
1264 | if (LHSType != LHSUnpromotedType && !IsCompAssign) | |||
1265 | LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); | |||
1266 | ||||
1267 | // If both types are identical, no conversion is needed. | |||
1268 | if (LHSType == RHSType) | |||
1269 | return LHSType; | |||
1270 | ||||
1271 | // At this point, we have two different arithmetic types. | |||
1272 | ||||
1273 | // Diagnose attempts to convert between __float128 and long double where | |||
1274 | // such conversions currently can't be handled. | |||
1275 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | |||
1276 | return QualType(); | |||
1277 | ||||
1278 | // Handle complex types first (C99 6.3.1.8p1). | |||
1279 | if (LHSType->isComplexType() || RHSType->isComplexType()) | |||
1280 | return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, | |||
1281 | IsCompAssign); | |||
1282 | ||||
1283 | // Now handle "real" floating types (i.e. float, double, long double). | |||
1284 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | |||
1285 | return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, | |||
1286 | IsCompAssign); | |||
1287 | ||||
1288 | // Handle GCC complex int extension. | |||
1289 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) | |||
1290 | return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, | |||
1291 | IsCompAssign); | |||
1292 | ||||
1293 | // Finally, we have two differing integer types. | |||
1294 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | |||
1295 | (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); | |||
1296 | } | |||
1297 | ||||
1298 | ||||
1299 | //===----------------------------------------------------------------------===// | |||
1300 | // Semantic Analysis for various Expression Types | |||
1301 | //===----------------------------------------------------------------------===// | |||
1302 | ||||
1303 | ||||
1304 | ExprResult | |||
1305 | Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, | |||
1306 | SourceLocation DefaultLoc, | |||
1307 | SourceLocation RParenLoc, | |||
1308 | Expr *ControllingExpr, | |||
1309 | ArrayRef<ParsedType> ArgTypes, | |||
1310 | ArrayRef<Expr *> ArgExprs) { | |||
1311 | unsigned NumAssocs = ArgTypes.size(); | |||
1312 | assert(NumAssocs == ArgExprs.size())(static_cast <bool> (NumAssocs == ArgExprs.size()) ? void (0) : __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1312, __extension__ __PRETTY_FUNCTION__)); | |||
1313 | ||||
1314 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; | |||
1315 | for (unsigned i = 0; i < NumAssocs; ++i) { | |||
1316 | if (ArgTypes[i]) | |||
1317 | (void) GetTypeFromParser(ArgTypes[i], &Types[i]); | |||
1318 | else | |||
1319 | Types[i] = nullptr; | |||
1320 | } | |||
1321 | ||||
1322 | ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, | |||
1323 | ControllingExpr, | |||
1324 | llvm::makeArrayRef(Types, NumAssocs), | |||
1325 | ArgExprs); | |||
1326 | delete [] Types; | |||
1327 | return ER; | |||
1328 | } | |||
1329 | ||||
1330 | ExprResult | |||
1331 | Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, | |||
1332 | SourceLocation DefaultLoc, | |||
1333 | SourceLocation RParenLoc, | |||
1334 | Expr *ControllingExpr, | |||
1335 | ArrayRef<TypeSourceInfo *> Types, | |||
1336 | ArrayRef<Expr *> Exprs) { | |||
1337 | unsigned NumAssocs = Types.size(); | |||
1338 | assert(NumAssocs == Exprs.size())(static_cast <bool> (NumAssocs == Exprs.size()) ? void ( 0) : __assert_fail ("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1338, __extension__ __PRETTY_FUNCTION__)); | |||
1339 | ||||
1340 | // Decay and strip qualifiers for the controlling expression type, and handle | |||
1341 | // placeholder type replacement. See committee discussion from WG14 DR423. | |||
1342 | { | |||
1343 | EnterExpressionEvaluationContext Unevaluated( | |||
1344 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
1345 | ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); | |||
1346 | if (R.isInvalid()) | |||
1347 | return ExprError(); | |||
1348 | ControllingExpr = R.get(); | |||
1349 | } | |||
1350 | ||||
1351 | // The controlling expression is an unevaluated operand, so side effects are | |||
1352 | // likely unintended. | |||
1353 | if (!inTemplateInstantiation() && | |||
1354 | ControllingExpr->HasSideEffects(Context, false)) | |||
1355 | Diag(ControllingExpr->getExprLoc(), | |||
1356 | diag::warn_side_effects_unevaluated_context); | |||
1357 | ||||
1358 | bool TypeErrorFound = false, | |||
1359 | IsResultDependent = ControllingExpr->isTypeDependent(), | |||
1360 | ContainsUnexpandedParameterPack | |||
1361 | = ControllingExpr->containsUnexpandedParameterPack(); | |||
1362 | ||||
1363 | for (unsigned i = 0; i < NumAssocs; ++i) { | |||
1364 | if (Exprs[i]->containsUnexpandedParameterPack()) | |||
1365 | ContainsUnexpandedParameterPack = true; | |||
1366 | ||||
1367 | if (Types[i]) { | |||
1368 | if (Types[i]->getType()->containsUnexpandedParameterPack()) | |||
1369 | ContainsUnexpandedParameterPack = true; | |||
1370 | ||||
1371 | if (Types[i]->getType()->isDependentType()) { | |||
1372 | IsResultDependent = true; | |||
1373 | } else { | |||
1374 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a | |||
1375 | // complete object type other than a variably modified type." | |||
1376 | unsigned D = 0; | |||
1377 | if (Types[i]->getType()->isIncompleteType()) | |||
1378 | D = diag::err_assoc_type_incomplete; | |||
1379 | else if (!Types[i]->getType()->isObjectType()) | |||
1380 | D = diag::err_assoc_type_nonobject; | |||
1381 | else if (Types[i]->getType()->isVariablyModifiedType()) | |||
1382 | D = diag::err_assoc_type_variably_modified; | |||
1383 | ||||
1384 | if (D != 0) { | |||
1385 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) | |||
1386 | << Types[i]->getTypeLoc().getSourceRange() | |||
1387 | << Types[i]->getType(); | |||
1388 | TypeErrorFound = true; | |||
1389 | } | |||
1390 | ||||
1391 | // C11 6.5.1.1p2 "No two generic associations in the same generic | |||
1392 | // selection shall specify compatible types." | |||
1393 | for (unsigned j = i+1; j < NumAssocs; ++j) | |||
1394 | if (Types[j] && !Types[j]->getType()->isDependentType() && | |||
1395 | Context.typesAreCompatible(Types[i]->getType(), | |||
1396 | Types[j]->getType())) { | |||
1397 | Diag(Types[j]->getTypeLoc().getBeginLoc(), | |||
1398 | diag::err_assoc_compatible_types) | |||
1399 | << Types[j]->getTypeLoc().getSourceRange() | |||
1400 | << Types[j]->getType() | |||
1401 | << Types[i]->getType(); | |||
1402 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | |||
1403 | diag::note_compat_assoc) | |||
1404 | << Types[i]->getTypeLoc().getSourceRange() | |||
1405 | << Types[i]->getType(); | |||
1406 | TypeErrorFound = true; | |||
1407 | } | |||
1408 | } | |||
1409 | } | |||
1410 | } | |||
1411 | if (TypeErrorFound) | |||
1412 | return ExprError(); | |||
1413 | ||||
1414 | // If we determined that the generic selection is result-dependent, don't | |||
1415 | // try to compute the result expression. | |||
1416 | if (IsResultDependent) | |||
1417 | return new (Context) GenericSelectionExpr( | |||
1418 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, | |||
1419 | ContainsUnexpandedParameterPack); | |||
1420 | ||||
1421 | SmallVector<unsigned, 1> CompatIndices; | |||
1422 | unsigned DefaultIndex = -1U; | |||
1423 | for (unsigned i = 0; i < NumAssocs; ++i) { | |||
1424 | if (!Types[i]) | |||
1425 | DefaultIndex = i; | |||
1426 | else if (Context.typesAreCompatible(ControllingExpr->getType(), | |||
1427 | Types[i]->getType())) | |||
1428 | CompatIndices.push_back(i); | |||
1429 | } | |||
1430 | ||||
1431 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have | |||
1432 | // type compatible with at most one of the types named in its generic | |||
1433 | // association list." | |||
1434 | if (CompatIndices.size() > 1) { | |||
1435 | // We strip parens here because the controlling expression is typically | |||
1436 | // parenthesized in macro definitions. | |||
1437 | ControllingExpr = ControllingExpr->IgnoreParens(); | |||
1438 | Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) | |||
1439 | << ControllingExpr->getSourceRange() << ControllingExpr->getType() | |||
1440 | << (unsigned) CompatIndices.size(); | |||
1441 | for (unsigned I : CompatIndices) { | |||
1442 | Diag(Types[I]->getTypeLoc().getBeginLoc(), | |||
1443 | diag::note_compat_assoc) | |||
1444 | << Types[I]->getTypeLoc().getSourceRange() | |||
1445 | << Types[I]->getType(); | |||
1446 | } | |||
1447 | return ExprError(); | |||
1448 | } | |||
1449 | ||||
1450 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, | |||
1451 | // its controlling expression shall have type compatible with exactly one of | |||
1452 | // the types named in its generic association list." | |||
1453 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { | |||
1454 | // We strip parens here because the controlling expression is typically | |||
1455 | // parenthesized in macro definitions. | |||
1456 | ControllingExpr = ControllingExpr->IgnoreParens(); | |||
1457 | Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) | |||
1458 | << ControllingExpr->getSourceRange() << ControllingExpr->getType(); | |||
1459 | return ExprError(); | |||
1460 | } | |||
1461 | ||||
1462 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a | |||
1463 | // type name that is compatible with the type of the controlling expression, | |||
1464 | // then the result expression of the generic selection is the expression | |||
1465 | // in that generic association. Otherwise, the result expression of the | |||
1466 | // generic selection is the expression in the default generic association." | |||
1467 | unsigned ResultIndex = | |||
1468 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; | |||
1469 | ||||
1470 | return new (Context) GenericSelectionExpr( | |||
1471 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, | |||
1472 | ContainsUnexpandedParameterPack, ResultIndex); | |||
1473 | } | |||
1474 | ||||
1475 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the | |||
1476 | /// location of the token and the offset of the ud-suffix within it. | |||
1477 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, | |||
1478 | unsigned Offset) { | |||
1479 | return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), | |||
1480 | S.getLangOpts()); | |||
1481 | } | |||
1482 | ||||
1483 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up | |||
1484 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. | |||
1485 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, | |||
1486 | IdentifierInfo *UDSuffix, | |||
1487 | SourceLocation UDSuffixLoc, | |||
1488 | ArrayRef<Expr*> Args, | |||
1489 | SourceLocation LitEndLoc) { | |||
1490 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1490, __extension__ __PRETTY_FUNCTION__)); | |||
1491 | ||||
1492 | QualType ArgTy[2]; | |||
1493 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { | |||
1494 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); | |||
1495 | if (ArgTy[ArgIdx]->isArrayType()) | |||
1496 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); | |||
1497 | } | |||
1498 | ||||
1499 | DeclarationName OpName = | |||
1500 | S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | |||
1501 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | |||
1502 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | |||
1503 | ||||
1504 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); | |||
1505 | if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), | |||
1506 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | |||
1507 | /*AllowStringTemplate*/ false, | |||
1508 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) | |||
1509 | return ExprError(); | |||
1510 | ||||
1511 | return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); | |||
1512 | } | |||
1513 | ||||
1514 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string | |||
1515 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string | |||
1516 | /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from | |||
1517 | /// multiple tokens. However, the common case is that StringToks points to one | |||
1518 | /// string. | |||
1519 | /// | |||
1520 | ExprResult | |||
1521 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { | |||
1522 | 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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1522, __extension__ __PRETTY_FUNCTION__)); | |||
1523 | ||||
1524 | StringLiteralParser Literal(StringToks, PP); | |||
1525 | if (Literal.hadError) | |||
1526 | return ExprError(); | |||
1527 | ||||
1528 | SmallVector<SourceLocation, 4> StringTokLocs; | |||
1529 | for (const Token &Tok : StringToks) | |||
1530 | StringTokLocs.push_back(Tok.getLocation()); | |||
1531 | ||||
1532 | QualType CharTy = Context.CharTy; | |||
1533 | StringLiteral::StringKind Kind = StringLiteral::Ascii; | |||
1534 | if (Literal.isWide()) { | |||
1535 | CharTy = Context.getWideCharType(); | |||
1536 | Kind = StringLiteral::Wide; | |||
1537 | } else if (Literal.isUTF8()) { | |||
1538 | Kind = StringLiteral::UTF8; | |||
1539 | } else if (Literal.isUTF16()) { | |||
1540 | CharTy = Context.Char16Ty; | |||
1541 | Kind = StringLiteral::UTF16; | |||
1542 | } else if (Literal.isUTF32()) { | |||
1543 | CharTy = Context.Char32Ty; | |||
1544 | Kind = StringLiteral::UTF32; | |||
1545 | } else if (Literal.isPascal()) { | |||
1546 | CharTy = Context.UnsignedCharTy; | |||
1547 | } | |||
1548 | ||||
1549 | QualType CharTyConst = CharTy; | |||
1550 | // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). | |||
1551 | if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) | |||
1552 | CharTyConst.addConst(); | |||
1553 | ||||
1554 | // Get an array type for the string, according to C99 6.4.5. This includes | |||
1555 | // the nul terminator character as well as the string length for pascal | |||
1556 | // strings. | |||
1557 | QualType StrTy = Context.getConstantArrayType(CharTyConst, | |||
1558 | llvm::APInt(32, Literal.GetNumStringChars()+1), | |||
1559 | ArrayType::Normal, 0); | |||
1560 | ||||
1561 | // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. | |||
1562 | if (getLangOpts().OpenCL) { | |||
1563 | StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); | |||
1564 | } | |||
1565 | ||||
1566 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! | |||
1567 | StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), | |||
1568 | Kind, Literal.Pascal, StrTy, | |||
1569 | &StringTokLocs[0], | |||
1570 | StringTokLocs.size()); | |||
1571 | if (Literal.getUDSuffix().empty()) | |||
1572 | return Lit; | |||
1573 | ||||
1574 | // We're building a user-defined literal. | |||
1575 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | |||
1576 | SourceLocation UDSuffixLoc = | |||
1577 | getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], | |||
1578 | Literal.getUDSuffixOffset()); | |||
1579 | ||||
1580 | // Make sure we're allowed user-defined literals here. | |||
1581 | if (!UDLScope) | |||
1582 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); | |||
1583 | ||||
1584 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form | |||
1585 | // operator "" X (str, len) | |||
1586 | QualType SizeType = Context.getSizeType(); | |||
1587 | ||||
1588 | DeclarationName OpName = | |||
1589 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | |||
1590 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | |||
1591 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | |||
1592 | ||||
1593 | QualType ArgTy[] = { | |||
1594 | Context.getArrayDecayedType(StrTy), SizeType | |||
1595 | }; | |||
1596 | ||||
1597 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | |||
1598 | switch (LookupLiteralOperator(UDLScope, R, ArgTy, | |||
1599 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | |||
1600 | /*AllowStringTemplate*/ true, | |||
1601 | /*DiagnoseMissing*/ true)) { | |||
1602 | ||||
1603 | case LOLR_Cooked: { | |||
1604 | llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); | |||
1605 | IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, | |||
1606 | StringTokLocs[0]); | |||
1607 | Expr *Args[] = { Lit, LenArg }; | |||
1608 | ||||
1609 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); | |||
1610 | } | |||
1611 | ||||
1612 | case LOLR_StringTemplate: { | |||
1613 | TemplateArgumentListInfo ExplicitArgs; | |||
1614 | ||||
1615 | unsigned CharBits = Context.getIntWidth(CharTy); | |||
1616 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); | |||
1617 | llvm::APSInt Value(CharBits, CharIsUnsigned); | |||
1618 | ||||
1619 | TemplateArgument TypeArg(CharTy); | |||
1620 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); | |||
1621 | ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); | |||
1622 | ||||
1623 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { | |||
1624 | Value = Lit->getCodeUnit(I); | |||
1625 | TemplateArgument Arg(Context, Value, CharTy); | |||
1626 | TemplateArgumentLocInfo ArgInfo; | |||
1627 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | |||
1628 | } | |||
1629 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | |||
1630 | &ExplicitArgs); | |||
1631 | } | |||
1632 | case LOLR_Raw: | |||
1633 | case LOLR_Template: | |||
1634 | case LOLR_ErrorNoDiagnostic: | |||
1635 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1635); | |||
1636 | case LOLR_Error: | |||
1637 | return ExprError(); | |||
1638 | } | |||
1639 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1639); | |||
1640 | } | |||
1641 | ||||
1642 | ExprResult | |||
1643 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | |||
1644 | SourceLocation Loc, | |||
1645 | const CXXScopeSpec *SS) { | |||
1646 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); | |||
1647 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); | |||
1648 | } | |||
1649 | ||||
1650 | /// BuildDeclRefExpr - Build an expression that references a | |||
1651 | /// declaration that does not require a closure capture. | |||
1652 | ExprResult | |||
1653 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | |||
1654 | const DeclarationNameInfo &NameInfo, | |||
1655 | const CXXScopeSpec *SS, NamedDecl *FoundD, | |||
1656 | const TemplateArgumentListInfo *TemplateArgs) { | |||
1657 | bool RefersToCapturedVariable = | |||
1658 | isa<VarDecl>(D) && | |||
1659 | NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); | |||
1660 | ||||
1661 | DeclRefExpr *E; | |||
1662 | if (isa<VarTemplateSpecializationDecl>(D)) { | |||
1663 | VarTemplateSpecializationDecl *VarSpec = | |||
1664 | cast<VarTemplateSpecializationDecl>(D); | |||
1665 | ||||
1666 | E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) | |||
1667 | : NestedNameSpecifierLoc(), | |||
1668 | VarSpec->getTemplateKeywordLoc(), D, | |||
1669 | RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, | |||
1670 | FoundD, TemplateArgs); | |||
1671 | } else { | |||
1672 | assert(!TemplateArgs && "No template arguments for non-variable"(static_cast <bool> (!TemplateArgs && "No template arguments for non-variable" " template specialization references") ? void (0) : __assert_fail ("!TemplateArgs && \"No template arguments for non-variable\" \" template specialization references\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1673, __extension__ __PRETTY_FUNCTION__)) | |||
1673 | " template specialization references")(static_cast <bool> (!TemplateArgs && "No template arguments for non-variable" " template specialization references") ? void (0) : __assert_fail ("!TemplateArgs && \"No template arguments for non-variable\" \" template specialization references\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1673, __extension__ __PRETTY_FUNCTION__)); | |||
1674 | E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) | |||
1675 | : NestedNameSpecifierLoc(), | |||
1676 | SourceLocation(), D, RefersToCapturedVariable, | |||
1677 | NameInfo, Ty, VK, FoundD); | |||
1678 | } | |||
1679 | ||||
1680 | MarkDeclRefReferenced(E); | |||
1681 | ||||
1682 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && | |||
1683 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && | |||
1684 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) | |||
1685 | getCurFunction()->recordUseOfWeak(E); | |||
1686 | ||||
1687 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | |||
1688 | if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) | |||
1689 | FD = IFD->getAnonField(); | |||
1690 | if (FD) { | |||
1691 | UnusedPrivateFields.remove(FD); | |||
1692 | // Just in case we're building an illegal pointer-to-member. | |||
1693 | if (FD->isBitField()) | |||
1694 | E->setObjectKind(OK_BitField); | |||
1695 | } | |||
1696 | ||||
1697 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier | |||
1698 | // designates a bit-field. | |||
1699 | if (auto *BD = dyn_cast<BindingDecl>(D)) | |||
1700 | if (auto *BE = BD->getBinding()) | |||
1701 | E->setObjectKind(BE->getObjectKind()); | |||
1702 | ||||
1703 | return E; | |||
1704 | } | |||
1705 | ||||
1706 | /// Decomposes the given name into a DeclarationNameInfo, its location, and | |||
1707 | /// possibly a list of template arguments. | |||
1708 | /// | |||
1709 | /// If this produces template arguments, it is permitted to call | |||
1710 | /// DecomposeTemplateName. | |||
1711 | /// | |||
1712 | /// This actually loses a lot of source location information for | |||
1713 | /// non-standard name kinds; we should consider preserving that in | |||
1714 | /// some way. | |||
1715 | void | |||
1716 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, | |||
1717 | TemplateArgumentListInfo &Buffer, | |||
1718 | DeclarationNameInfo &NameInfo, | |||
1719 | const TemplateArgumentListInfo *&TemplateArgs) { | |||
1720 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { | |||
1721 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); | |||
1722 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); | |||
1723 | ||||
1724 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), | |||
1725 | Id.TemplateId->NumArgs); | |||
1726 | translateTemplateArguments(TemplateArgsPtr, Buffer); | |||
1727 | ||||
1728 | TemplateName TName = Id.TemplateId->Template.get(); | |||
1729 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; | |||
1730 | NameInfo = Context.getNameForTemplate(TName, TNameLoc); | |||
1731 | TemplateArgs = &Buffer; | |||
1732 | } else { | |||
1733 | NameInfo = GetNameFromUnqualifiedId(Id); | |||
1734 | TemplateArgs = nullptr; | |||
1735 | } | |||
1736 | } | |||
1737 | ||||
1738 | static void emitEmptyLookupTypoDiagnostic( | |||
1739 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, | |||
1740 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, | |||
1741 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { | |||
1742 | DeclContext *Ctx = | |||
1743 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); | |||
1744 | if (!TC) { | |||
1745 | // Emit a special diagnostic for failed member lookups. | |||
1746 | // FIXME: computing the declaration context might fail here (?) | |||
1747 | if (Ctx) | |||
1748 | SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx | |||
1749 | << SS.getRange(); | |||
1750 | else | |||
1751 | SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; | |||
1752 | return; | |||
1753 | } | |||
1754 | ||||
1755 | std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); | |||
1756 | bool DroppedSpecifier = | |||
1757 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; | |||
1758 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() | |||
1759 | ? diag::note_implicit_param_decl | |||
1760 | : diag::note_previous_decl; | |||
1761 | if (!Ctx) | |||
1762 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, | |||
1763 | SemaRef.PDiag(NoteID)); | |||
1764 | else | |||
1765 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) | |||
1766 | << Typo << Ctx << DroppedSpecifier | |||
1767 | << SS.getRange(), | |||
1768 | SemaRef.PDiag(NoteID)); | |||
1769 | } | |||
1770 | ||||
1771 | /// Diagnose an empty lookup. | |||
1772 | /// | |||
1773 | /// \return false if new lookup candidates were found | |||
1774 | bool | |||
1775 | Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, | |||
1776 | std::unique_ptr<CorrectionCandidateCallback> CCC, | |||
1777 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
1778 | ArrayRef<Expr *> Args, TypoExpr **Out) { | |||
1779 | DeclarationName Name = R.getLookupName(); | |||
1780 | ||||
1781 | unsigned diagnostic = diag::err_undeclared_var_use; | |||
1782 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; | |||
1783 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || | |||
1784 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || | |||
1785 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | |||
1786 | diagnostic = diag::err_undeclared_use; | |||
1787 | diagnostic_suggest = diag::err_undeclared_use_suggest; | |||
1788 | } | |||
1789 | ||||
1790 | // If the original lookup was an unqualified lookup, fake an | |||
1791 | // unqualified lookup. This is useful when (for example) the | |||
1792 | // original lookup would not have found something because it was a | |||
1793 | // dependent name. | |||
1794 | DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; | |||
1795 | while (DC) { | |||
1796 | if (isa<CXXRecordDecl>(DC)) { | |||
1797 | LookupQualifiedName(R, DC); | |||
1798 | ||||
1799 | if (!R.empty()) { | |||
1800 | // Don't give errors about ambiguities in this lookup. | |||
1801 | R.suppressDiagnostics(); | |||
1802 | ||||
1803 | // During a default argument instantiation the CurContext points | |||
1804 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a | |||
1805 | // function parameter list, hence add an explicit check. | |||
1806 | bool isDefaultArgument = | |||
1807 | !CodeSynthesisContexts.empty() && | |||
1808 | CodeSynthesisContexts.back().Kind == | |||
1809 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; | |||
1810 | CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); | |||
1811 | bool isInstance = CurMethod && | |||
1812 | CurMethod->isInstance() && | |||
1813 | DC == CurMethod->getParent() && !isDefaultArgument; | |||
1814 | ||||
1815 | // Give a code modification hint to insert 'this->'. | |||
1816 | // TODO: fixit for inserting 'Base<T>::' in the other cases. | |||
1817 | // Actually quite difficult! | |||
1818 | if (getLangOpts().MSVCCompat) | |||
1819 | diagnostic = diag::ext_found_via_dependent_bases_lookup; | |||
1820 | if (isInstance) { | |||
1821 | Diag(R.getNameLoc(), diagnostic) << Name | |||
1822 | << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); | |||
1823 | CheckCXXThisCapture(R.getNameLoc()); | |||
1824 | } else { | |||
1825 | Diag(R.getNameLoc(), diagnostic) << Name; | |||
1826 | } | |||
1827 | ||||
1828 | // Do we really want to note all of these? | |||
1829 | for (NamedDecl *D : R) | |||
1830 | Diag(D->getLocation(), diag::note_dependent_var_use); | |||
1831 | ||||
1832 | // Return true if we are inside a default argument instantiation | |||
1833 | // and the found name refers to an instance member function, otherwise | |||
1834 | // the function calling DiagnoseEmptyLookup will try to create an | |||
1835 | // implicit member call and this is wrong for default argument. | |||
1836 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { | |||
1837 | Diag(R.getNameLoc(), diag::err_member_call_without_object); | |||
1838 | return true; | |||
1839 | } | |||
1840 | ||||
1841 | // Tell the callee to try to recover. | |||
1842 | return false; | |||
1843 | } | |||
1844 | ||||
1845 | R.clear(); | |||
1846 | } | |||
1847 | ||||
1848 | // In Microsoft mode, if we are performing lookup from within a friend | |||
1849 | // function definition declared at class scope then we must set | |||
1850 | // DC to the lexical parent to be able to search into the parent | |||
1851 | // class. | |||
1852 | if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && | |||
1853 | cast<FunctionDecl>(DC)->getFriendObjectKind() && | |||
1854 | DC->getLexicalParent()->isRecord()) | |||
1855 | DC = DC->getLexicalParent(); | |||
1856 | else | |||
1857 | DC = DC->getParent(); | |||
1858 | } | |||
1859 | ||||
1860 | // We didn't find anything, so try to correct for a typo. | |||
1861 | TypoCorrection Corrected; | |||
1862 | if (S && Out) { | |||
1863 | SourceLocation TypoLoc = R.getNameLoc(); | |||
1864 | 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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1865, __extension__ __PRETTY_FUNCTION__)) | |||
1865 | "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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 1865, __extension__ __PRETTY_FUNCTION__)); | |||
1866 | *Out = CorrectTypoDelayed( | |||
1867 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), | |||
1868 | [=](const TypoCorrection &TC) { | |||
1869 | emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, | |||
| ||||
1870 | diagnostic, diagnostic_suggest); | |||
1871 | }, | |||
1872 | nullptr, CTK_ErrorRecovery); | |||
1873 | if (*Out) | |||
1874 | return true; | |||
1875 | } else if (S && (Corrected = | |||
1876 | CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, | |||
1877 | &SS, std::move(CCC), CTK_ErrorRecovery))) { | |||
1878 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | |||
1879 | bool DroppedSpecifier = | |||
1880 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; | |||
1881 | R.setLookupName(Corrected.getCorrection()); | |||
1882 | ||||
1883 | bool AcceptableWithRecovery = false; | |||
1884 | bool AcceptableWithoutRecovery = false; | |||
1885 | NamedDecl *ND = Corrected.getFoundDecl(); | |||
1886 | if (ND) { | |||
1887 | if (Corrected.isOverloaded()) { | |||
1888 | OverloadCandidateSet OCS(R.getNameLoc(), | |||
1889 | OverloadCandidateSet::CSK_Normal); | |||
1890 | OverloadCandidateSet::iterator Best; | |||
1891 | for (NamedDecl *CD : Corrected) { | |||
1892 | if (FunctionTemplateDecl *FTD = | |||
1893 | dyn_cast<FunctionTemplateDecl>(CD)) | |||
1894 | AddTemplateOverloadCandidate( | |||
1895 | FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, | |||
1896 | Args, OCS); | |||
1897 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | |||
1898 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) | |||
1899 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), | |||
1900 | Args, OCS); | |||
1901 | } | |||
1902 | switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { | |||
1903 | case OR_Success: | |||
1904 | ND = Best->FoundDecl; | |||
1905 | Corrected.setCorrectionDecl(ND); | |||
1906 | break; | |||
1907 | default: | |||
1908 | // FIXME: Arbitrarily pick the first declaration for the note. | |||
1909 | Corrected.setCorrectionDecl(ND); | |||
1910 | break; | |||
1911 | } | |||
1912 | } | |||
1913 | R.addDecl(ND); | |||
1914 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { | |||
1915 | CXXRecordDecl *Record = nullptr; | |||
1916 | if (Corrected.getCorrectionSpecifier()) { | |||
1917 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); | |||
1918 | Record = Ty->getAsCXXRecordDecl(); | |||
1919 | } | |||
1920 | if (!Record) | |||
1921 | Record = cast<CXXRecordDecl>( | |||
1922 | ND->getDeclContext()->getRedeclContext()); | |||
1923 | R.setNamingClass(Record); | |||
1924 | } | |||
1925 | ||||
1926 | auto *UnderlyingND = ND->getUnderlyingDecl(); | |||
1927 | AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || | |||
1928 | isa<FunctionTemplateDecl>(UnderlyingND); | |||
1929 | // FIXME: If we ended up with a typo for a type name or | |||
1930 | // Objective-C class name, we're in trouble because the parser | |||
1931 | // is in the wrong place to recover. Suggest the typo | |||
1932 | // correction, but don't make it a fix-it since we're not going | |||
1933 | // to recover well anyway. | |||
1934 | AcceptableWithoutRecovery = | |||
1935 | isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); | |||
1936 | } else { | |||
1937 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it | |||
1938 | // because we aren't able to recover. | |||
1939 | AcceptableWithoutRecovery = true; | |||
1940 | } | |||
1941 | ||||
1942 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { | |||
1943 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() | |||
1944 | ? diag::note_implicit_param_decl | |||
1945 | : diag::note_previous_decl; | |||
1946 | if (SS.isEmpty()) | |||
1947 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, | |||
1948 | PDiag(NoteID), AcceptableWithRecovery); | |||
1949 | else | |||
1950 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | |||
1951 | << Name << computeDeclContext(SS, false) | |||
1952 | << DroppedSpecifier << SS.getRange(), | |||
1953 | PDiag(NoteID), AcceptableWithRecovery); | |||
1954 | ||||
1955 | // Tell the callee whether to try to recover. | |||
1956 | return !AcceptableWithRecovery; | |||
1957 | } | |||
1958 | } | |||
1959 | R.clear(); | |||
1960 | ||||
1961 | // Emit a special diagnostic for failed member lookups. | |||
1962 | // FIXME: computing the declaration context might fail here (?) | |||
1963 | if (!SS.isEmpty()) { | |||
1964 | Diag(R.getNameLoc(), diag::err_no_member) | |||
1965 | << Name << computeDeclContext(SS, false) | |||
1966 | << SS.getRange(); | |||
1967 | return true; | |||
1968 | } | |||
1969 | ||||
1970 | // Give up, we can't recover. | |||
1971 | Diag(R.getNameLoc(), diagnostic) << Name; | |||
1972 | return true; | |||
1973 | } | |||
1974 | ||||
1975 | /// In Microsoft mode, if we are inside a template class whose parent class has | |||
1976 | /// dependent base classes, and we can't resolve an unqualified identifier, then | |||
1977 | /// assume the identifier is a member of a dependent base class. We can only | |||
1978 | /// recover successfully in static methods, instance methods, and other contexts | |||
1979 | /// where 'this' is available. This doesn't precisely match MSVC's | |||
1980 | /// instantiation model, but it's close enough. | |||
1981 | static Expr * | |||
1982 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, | |||
1983 | DeclarationNameInfo &NameInfo, | |||
1984 | SourceLocation TemplateKWLoc, | |||
1985 | const TemplateArgumentListInfo *TemplateArgs) { | |||
1986 | // Only try to recover from lookup into dependent bases in static methods or | |||
1987 | // contexts where 'this' is available. | |||
1988 | QualType ThisType = S.getCurrentThisType(); | |||
1989 | const CXXRecordDecl *RD = nullptr; | |||
1990 | if (!ThisType.isNull()) | |||
1991 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); | |||
1992 | else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) | |||
1993 | RD = MD->getParent(); | |||
1994 | if (!RD || !RD->hasAnyDependentBases()) | |||
1995 | return nullptr; | |||
1996 | ||||
1997 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' | |||
1998 | // is available, suggest inserting 'this->' as a fixit. | |||
1999 | SourceLocation Loc = NameInfo.getLoc(); | |||
2000 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); | |||
2001 | DB << NameInfo.getName() << RD; | |||
2002 | ||||
2003 | if (!ThisType.isNull()) { | |||
2004 | DB << FixItHint::CreateInsertion(Loc, "this->"); | |||
2005 | return CXXDependentScopeMemberExpr::Create( | |||
2006 | Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, | |||
2007 | /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, | |||
2008 | /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); | |||
2009 | } | |||
2010 | ||||
2011 | // Synthesize a fake NNS that points to the derived class. This will | |||
2012 | // perform name lookup during template instantiation. | |||
2013 | CXXScopeSpec SS; | |||
2014 | auto *NNS = | |||
2015 | NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); | |||
2016 | SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); | |||
2017 | return DependentScopeDeclRefExpr::Create( | |||
2018 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, | |||
2019 | TemplateArgs); | |||
2020 | } | |||
2021 | ||||
2022 | ExprResult | |||
2023 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, | |||
2024 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, | |||
2025 | bool HasTrailingLParen, bool IsAddressOfOperand, | |||
2026 | std::unique_ptr<CorrectionCandidateCallback> CCC, | |||
2027 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { | |||
2028 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2029, __extension__ __PRETTY_FUNCTION__)) | |||
2029 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2029, __extension__ __PRETTY_FUNCTION__)); | |||
2030 | if (SS.isInvalid()) | |||
2031 | return ExprError(); | |||
2032 | ||||
2033 | TemplateArgumentListInfo TemplateArgsBuffer; | |||
2034 | ||||
2035 | // Decompose the UnqualifiedId into the following data. | |||
2036 | DeclarationNameInfo NameInfo; | |||
2037 | const TemplateArgumentListInfo *TemplateArgs; | |||
2038 | DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); | |||
2039 | ||||
2040 | DeclarationName Name = NameInfo.getName(); | |||
2041 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | |||
2042 | SourceLocation NameLoc = NameInfo.getLoc(); | |||
2043 | ||||
2044 | if (II && II->isEditorPlaceholder()) { | |||
2045 | // FIXME: When typed placeholders are supported we can create a typed | |||
2046 | // placeholder expression node. | |||
2047 | return ExprError(); | |||
2048 | } | |||
2049 | ||||
2050 | // C++ [temp.dep.expr]p3: | |||
2051 | // An id-expression is type-dependent if it contains: | |||
2052 | // -- an identifier that was declared with a dependent type, | |||
2053 | // (note: handled after lookup) | |||
2054 | // -- a template-id that is dependent, | |||
2055 | // (note: handled in BuildTemplateIdExpr) | |||
2056 | // -- a conversion-function-id that specifies a dependent type, | |||
2057 | // -- a nested-name-specifier that contains a class-name that | |||
2058 | // names a dependent type. | |||
2059 | // Determine whether this is a member of an unknown specialization; | |||
2060 | // we need to handle these differently. | |||
2061 | bool DependentID = false; | |||
2062 | if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && | |||
2063 | Name.getCXXNameType()->isDependentType()) { | |||
2064 | DependentID = true; | |||
2065 | } else if (SS.isSet()) { | |||
2066 | if (DeclContext *DC = computeDeclContext(SS, false)) { | |||
2067 | if (RequireCompleteDeclContext(SS, DC)) | |||
2068 | return ExprError(); | |||
2069 | } else { | |||
2070 | DependentID = true; | |||
2071 | } | |||
2072 | } | |||
2073 | ||||
2074 | if (DependentID) | |||
2075 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | |||
2076 | IsAddressOfOperand, TemplateArgs); | |||
2077 | ||||
2078 | // Perform the required lookup. | |||
2079 | LookupResult R(*this, NameInfo, | |||
2080 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) | |||
2081 | ? LookupObjCImplicitSelfParam | |||
2082 | : LookupOrdinaryName); | |||
2083 | if (TemplateArgs) { | |||
2084 | // Lookup the template name again to correctly establish the context in | |||
2085 | // which it was found. This is really unfortunate as we already did the | |||
2086 | // lookup to determine that it was a template name in the first place. If | |||
2087 | // this becomes a performance hit, we can work harder to preserve those | |||
2088 | // results until we get here but it's likely not worth it. | |||
2089 | bool MemberOfUnknownSpecialization; | |||
2090 | LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, | |||
2091 | MemberOfUnknownSpecialization); | |||
2092 | ||||
2093 | if (MemberOfUnknownSpecialization || | |||
2094 | (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) | |||
2095 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | |||
2096 | IsAddressOfOperand, TemplateArgs); | |||
2097 | } else { | |||
2098 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); | |||
2099 | LookupParsedName(R, S, &SS, !IvarLookupFollowUp); | |||
2100 | ||||
2101 | // If the result might be in a dependent base class, this is a dependent | |||
2102 | // id-expression. | |||
2103 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | |||
2104 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | |||
2105 | IsAddressOfOperand, TemplateArgs); | |||
2106 | ||||
2107 | // If this reference is in an Objective-C method, then we need to do | |||
2108 | // some special Objective-C lookup, too. | |||
2109 | if (IvarLookupFollowUp) { | |||
2110 | ExprResult E(LookupInObjCMethod(R, S, II, true)); | |||
2111 | if (E.isInvalid()) | |||
2112 | return ExprError(); | |||
2113 | ||||
2114 | if (Expr *Ex = E.getAs<Expr>()) | |||
2115 | return Ex; | |||
2116 | } | |||
2117 | } | |||
2118 | ||||
2119 | if (R.isAmbiguous()) | |||
2120 | return ExprError(); | |||
2121 | ||||
2122 | // This could be an implicitly declared function reference (legal in C90, | |||
2123 | // extension in C99, forbidden in C++). | |||
2124 | if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { | |||
2125 | NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); | |||
2126 | if (D) R.addDecl(D); | |||
2127 | } | |||
2128 | ||||
2129 | // Determine whether this name might be a candidate for | |||
2130 | // argument-dependent lookup. | |||
2131 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); | |||
2132 | ||||
2133 | if (R.empty() && !ADL) { | |||
2134 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { | |||
2135 | if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, | |||
2136 | TemplateKWLoc, TemplateArgs)) | |||
2137 | return E; | |||
2138 | } | |||
2139 | ||||
2140 | // Don't diagnose an empty lookup for inline assembly. | |||
2141 | if (IsInlineAsmIdentifier) | |||
2142 | return ExprError(); | |||
2143 | ||||
2144 | // If this name wasn't predeclared and if this is not a function | |||
2145 | // call, diagnose the problem. | |||
2146 | TypoExpr *TE = nullptr; | |||
2147 | auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( | |||
2148 | II, SS.isValid() ? SS.getScopeRep() : nullptr); | |||
2149 | DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; | |||
2150 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2151, __extension__ __PRETTY_FUNCTION__)) | |||
2151 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2151, __extension__ __PRETTY_FUNCTION__)); | |||
2152 | if (CCC) { | |||
2153 | // Make sure the callback knows what the typo being diagnosed is. | |||
2154 | CCC->setTypoName(II); | |||
2155 | if (SS.isValid()) | |||
2156 | CCC->setTypoNNS(SS.getScopeRep()); | |||
2157 | } | |||
2158 | if (DiagnoseEmptyLookup(S, SS, R, | |||
2159 | CCC ? std::move(CCC) : std::move(DefaultValidator), | |||
2160 | nullptr, None, &TE)) { | |||
2161 | if (TE && KeywordReplacement) { | |||
2162 | auto &State = getTypoExprState(TE); | |||
2163 | auto BestTC = State.Consumer->getNextCorrection(); | |||
2164 | if (BestTC.isKeyword()) { | |||
2165 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); | |||
2166 | if (State.DiagHandler) | |||
2167 | State.DiagHandler(BestTC); | |||
2168 | KeywordReplacement->startToken(); | |||
2169 | KeywordReplacement->setKind(II->getTokenID()); | |||
2170 | KeywordReplacement->setIdentifierInfo(II); | |||
2171 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); | |||
2172 | // Clean up the state associated with the TypoExpr, since it has | |||
2173 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). | |||
2174 | clearDelayedTypo(TE); | |||
2175 | // Signal that a correction to a keyword was performed by returning a | |||
2176 | // valid-but-null ExprResult. | |||
2177 | return (Expr*)nullptr; | |||
2178 | } | |||
2179 | State.Consumer->resetCorrectionStream(); | |||
2180 | } | |||
2181 | return TE ? TE : ExprError(); | |||
2182 | } | |||
2183 | ||||
2184 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2185, __extension__ __PRETTY_FUNCTION__)) | |||
2185 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2185, __extension__ __PRETTY_FUNCTION__)); | |||
2186 | ||||
2187 | // If we found an Objective-C instance variable, let | |||
2188 | // LookupInObjCMethod build the appropriate expression to | |||
2189 | // reference the ivar. | |||
2190 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { | |||
2191 | R.clear(); | |||
2192 | ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); | |||
2193 | // In a hopelessly buggy code, Objective-C instance variable | |||
2194 | // lookup fails and no expression will be built to reference it. | |||
2195 | if (!E.isInvalid() && !E.get()) | |||
2196 | return ExprError(); | |||
2197 | return E; | |||
2198 | } | |||
2199 | } | |||
2200 | ||||
2201 | // This is guaranteed from this point on. | |||
2202 | assert(!R.empty() || ADL)(static_cast <bool> (!R.empty() || ADL) ? void (0) : __assert_fail ("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2202, __extension__ __PRETTY_FUNCTION__)); | |||
2203 | ||||
2204 | // Check whether this might be a C++ implicit instance member access. | |||
2205 | // C++ [class.mfct.non-static]p3: | |||
2206 | // When an id-expression that is not part of a class member access | |||
2207 | // syntax and not used to form a pointer to member is used in the | |||
2208 | // body of a non-static member function of class X, if name lookup | |||
2209 | // resolves the name in the id-expression to a non-static non-type | |||
2210 | // member of some class C, the id-expression is transformed into a | |||
2211 | // class member access expression using (*this) as the | |||
2212 | // postfix-expression to the left of the . operator. | |||
2213 | // | |||
2214 | // But we don't actually need to do this for '&' operands if R | |||
2215 | // resolved to a function or overloaded function set, because the | |||
2216 | // expression is ill-formed if it actually works out to be a | |||
2217 | // non-static member function: | |||
2218 | // | |||
2219 | // C++ [expr.ref]p4: | |||
2220 | // Otherwise, if E1.E2 refers to a non-static member function. . . | |||
2221 | // [t]he expression can be used only as the left-hand operand of a | |||
2222 | // member function call. | |||
2223 | // | |||
2224 | // There are other safeguards against such uses, but it's important | |||
2225 | // to get this right here so that we don't end up making a | |||
2226 | // spuriously dependent expression if we're inside a dependent | |||
2227 | // instance method. | |||
2228 | if (!R.empty() && (*R.begin())->isCXXClassMember()) { | |||
2229 | bool MightBeImplicitMember; | |||
2230 | if (!IsAddressOfOperand) | |||
2231 | MightBeImplicitMember = true; | |||
2232 | else if (!SS.isEmpty()) | |||
2233 | MightBeImplicitMember = false; | |||
2234 | else if (R.isOverloadedResult()) | |||
2235 | MightBeImplicitMember = false; | |||
2236 | else if (R.isUnresolvableResult()) | |||
2237 | MightBeImplicitMember = true; | |||
2238 | else | |||
2239 | MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || | |||
2240 | isa<IndirectFieldDecl>(R.getFoundDecl()) || | |||
2241 | isa<MSPropertyDecl>(R.getFoundDecl()); | |||
2242 | ||||
2243 | if (MightBeImplicitMember) | |||
2244 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, | |||
2245 | R, TemplateArgs, S); | |||
2246 | } | |||
2247 | ||||
2248 | if (TemplateArgs || TemplateKWLoc.isValid()) { | |||
2249 | ||||
2250 | // In C++1y, if this is a variable template id, then check it | |||
2251 | // in BuildTemplateIdExpr(). | |||
2252 | // The single lookup result must be a variable template declaration. | |||
2253 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && | |||
2254 | Id.TemplateId->Kind == TNK_Var_template) { | |||
2255 | 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.\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2256, __extension__ __PRETTY_FUNCTION__)) | |||
2256 | "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.\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2256, __extension__ __PRETTY_FUNCTION__)); | |||
2257 | } | |||
2258 | ||||
2259 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); | |||
2260 | } | |||
2261 | ||||
2262 | return BuildDeclarationNameExpr(SS, R, ADL); | |||
2263 | } | |||
2264 | ||||
2265 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified | |||
2266 | /// declaration name, generally during template instantiation. | |||
2267 | /// There's a large number of things which don't need to be done along | |||
2268 | /// this path. | |||
2269 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( | |||
2270 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, | |||
2271 | bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { | |||
2272 | DeclContext *DC = computeDeclContext(SS, false); | |||
2273 | if (!DC) | |||
2274 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | |||
2275 | NameInfo, /*TemplateArgs=*/nullptr); | |||
2276 | ||||
2277 | if (RequireCompleteDeclContext(SS, DC)) | |||
2278 | return ExprError(); | |||
2279 | ||||
2280 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | |||
2281 | LookupQualifiedName(R, DC); | |||
2282 | ||||
2283 | if (R.isAmbiguous()) | |||
2284 | return ExprError(); | |||
2285 | ||||
2286 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | |||
2287 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | |||
2288 | NameInfo, /*TemplateArgs=*/nullptr); | |||
2289 | ||||
2290 | if (R.empty()) { | |||
2291 | Diag(NameInfo.getLoc(), diag::err_no_member) | |||
2292 | << NameInfo.getName() << DC << SS.getRange(); | |||
2293 | return ExprError(); | |||
2294 | } | |||
2295 | ||||
2296 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { | |||
2297 | // Diagnose a missing typename if this resolved unambiguously to a type in | |||
2298 | // a dependent context. If we can recover with a type, downgrade this to | |||
2299 | // a warning in Microsoft compatibility mode. | |||
2300 | unsigned DiagID = diag::err_typename_missing; | |||
2301 | if (RecoveryTSI && getLangOpts().MSVCCompat) | |||
2302 | DiagID = diag::ext_typename_missing; | |||
2303 | SourceLocation Loc = SS.getBeginLoc(); | |||
2304 | auto D = Diag(Loc, DiagID); | |||
2305 | D << SS.getScopeRep() << NameInfo.getName().getAsString() | |||
2306 | << SourceRange(Loc, NameInfo.getEndLoc()); | |||
2307 | ||||
2308 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE | |||
2309 | // context. | |||
2310 | if (!RecoveryTSI) | |||
2311 | return ExprError(); | |||
2312 | ||||
2313 | // Only issue the fixit if we're prepared to recover. | |||
2314 | D << FixItHint::CreateInsertion(Loc, "typename "); | |||
2315 | ||||
2316 | // Recover by pretending this was an elaborated type. | |||
2317 | QualType Ty = Context.getTypeDeclType(TD); | |||
2318 | TypeLocBuilder TLB; | |||
2319 | TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); | |||
2320 | ||||
2321 | QualType ET = getElaboratedType(ETK_None, SS, Ty); | |||
2322 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); | |||
2323 | QTL.setElaboratedKeywordLoc(SourceLocation()); | |||
2324 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
2325 | ||||
2326 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); | |||
2327 | ||||
2328 | return ExprEmpty(); | |||
2329 | } | |||
2330 | ||||
2331 | // Defend against this resolving to an implicit member access. We usually | |||
2332 | // won't get here if this might be a legitimate a class member (we end up in | |||
2333 | // BuildMemberReferenceExpr instead), but this can be valid if we're forming | |||
2334 | // a pointer-to-member or in an unevaluated context in C++11. | |||
2335 | if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) | |||
2336 | return BuildPossibleImplicitMemberExpr(SS, | |||
2337 | /*TemplateKWLoc=*/SourceLocation(), | |||
2338 | R, /*TemplateArgs=*/nullptr, S); | |||
2339 | ||||
2340 | return BuildDeclarationNameExpr(SS, R, /* ADL */ false); | |||
2341 | } | |||
2342 | ||||
2343 | /// LookupInObjCMethod - The parser has read a name in, and Sema has | |||
2344 | /// detected that we're currently inside an ObjC method. Perform some | |||
2345 | /// additional lookup. | |||
2346 | /// | |||
2347 | /// Ideally, most of this would be done by lookup, but there's | |||
2348 | /// actually quite a lot of extra work involved. | |||
2349 | /// | |||
2350 | /// Returns a null sentinel to indicate trivial success. | |||
2351 | ExprResult | |||
2352 | Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, | |||
2353 | IdentifierInfo *II, bool AllowBuiltinCreation) { | |||
2354 | SourceLocation Loc = Lookup.getNameLoc(); | |||
2355 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | |||
2356 | ||||
2357 | // Check for error condition which is already reported. | |||
2358 | if (!CurMethod) | |||
2359 | return ExprError(); | |||
2360 | ||||
2361 | // There are two cases to handle here. 1) scoped lookup could have failed, | |||
2362 | // in which case we should look for an ivar. 2) scoped lookup could have | |||
2363 | // found a decl, but that decl is outside the current instance method (i.e. | |||
2364 | // a global variable). In these two cases, we do a lookup for an ivar with | |||
2365 | // this name, if the lookup sucedes, we replace it our current decl. | |||
2366 | ||||
2367 | // If we're in a class method, we don't normally want to look for | |||
2368 | // ivars. But if we don't find anything else, and there's an | |||
2369 | // ivar, that's an error. | |||
2370 | bool IsClassMethod = CurMethod->isClassMethod(); | |||
2371 | ||||
2372 | bool LookForIvars; | |||
2373 | if (Lookup.empty()) | |||
2374 | LookForIvars = true; | |||
2375 | else if (IsClassMethod) | |||
2376 | LookForIvars = false; | |||
2377 | else | |||
2378 | LookForIvars = (Lookup.isSingleResult() && | |||
2379 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); | |||
2380 | ObjCInterfaceDecl *IFace = nullptr; | |||
2381 | if (LookForIvars) { | |||
2382 | IFace = CurMethod->getClassInterface(); | |||
2383 | ObjCInterfaceDecl *ClassDeclared; | |||
2384 | ObjCIvarDecl *IV = nullptr; | |||
2385 | if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { | |||
2386 | // Diagnose using an ivar in a class method. | |||
2387 | if (IsClassMethod) | |||
2388 | return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) | |||
2389 | << IV->getDeclName()); | |||
2390 | ||||
2391 | // If we're referencing an invalid decl, just return this as a silent | |||
2392 | // error node. The error diagnostic was already emitted on the decl. | |||
2393 | if (IV->isInvalidDecl()) | |||
2394 | return ExprError(); | |||
2395 | ||||
2396 | // Check if referencing a field with __attribute__((deprecated)). | |||
2397 | if (DiagnoseUseOfDecl(IV, Loc)) | |||
2398 | return ExprError(); | |||
2399 | ||||
2400 | // Diagnose the use of an ivar outside of the declaring class. | |||
2401 | if (IV->getAccessControl() == ObjCIvarDecl::Private && | |||
2402 | !declaresSameEntity(ClassDeclared, IFace) && | |||
2403 | !getLangOpts().DebuggerSupport) | |||
2404 | Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); | |||
2405 | ||||
2406 | // FIXME: This should use a new expr for a direct reference, don't | |||
2407 | // turn this into Self->ivar, just return a BareIVarExpr or something. | |||
2408 | IdentifierInfo &II = Context.Idents.get("self"); | |||
2409 | UnqualifiedId SelfName; | |||
2410 | SelfName.setIdentifier(&II, SourceLocation()); | |||
2411 | SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); | |||
2412 | CXXScopeSpec SelfScopeSpec; | |||
2413 | SourceLocation TemplateKWLoc; | |||
2414 | ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, | |||
2415 | SelfName, false, false); | |||
2416 | if (SelfExpr.isInvalid()) | |||
2417 | return ExprError(); | |||
2418 | ||||
2419 | SelfExpr = DefaultLvalueConversion(SelfExpr.get()); | |||
2420 | if (SelfExpr.isInvalid()) | |||
2421 | return ExprError(); | |||
2422 | ||||
2423 | MarkAnyDeclReferenced(Loc, IV, true); | |||
2424 | ||||
2425 | ObjCMethodFamily MF = CurMethod->getMethodFamily(); | |||
2426 | if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && | |||
2427 | !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) | |||
2428 | Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); | |||
2429 | ||||
2430 | ObjCIvarRefExpr *Result = new (Context) | |||
2431 | ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, | |||
2432 | IV->getLocation(), SelfExpr.get(), true, true); | |||
2433 | ||||
2434 | if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { | |||
2435 | if (!isUnevaluatedContext() && | |||
2436 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | |||
2437 | getCurFunction()->recordUseOfWeak(Result); | |||
2438 | } | |||
2439 | if (getLangOpts().ObjCAutoRefCount) { | |||
2440 | if (CurContext->isClosure()) | |||
2441 | Diag(Loc, diag::warn_implicitly_retains_self) | |||
2442 | << FixItHint::CreateInsertion(Loc, "self->"); | |||
2443 | } | |||
2444 | ||||
2445 | return Result; | |||
2446 | } | |||
2447 | } else if (CurMethod->isInstanceMethod()) { | |||
2448 | // We should warn if a local variable hides an ivar. | |||
2449 | if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { | |||
2450 | ObjCInterfaceDecl *ClassDeclared; | |||
2451 | if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { | |||
2452 | if (IV->getAccessControl() != ObjCIvarDecl::Private || | |||
2453 | declaresSameEntity(IFace, ClassDeclared)) | |||
2454 | Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); | |||
2455 | } | |||
2456 | } | |||
2457 | } else if (Lookup.isSingleResult() && | |||
2458 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { | |||
2459 | // If accessing a stand-alone ivar in a class method, this is an error. | |||
2460 | if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) | |||
2461 | return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) | |||
2462 | << IV->getDeclName()); | |||
2463 | } | |||
2464 | ||||
2465 | if (Lookup.empty() && II && AllowBuiltinCreation) { | |||
2466 | // FIXME. Consolidate this with similar code in LookupName. | |||
2467 | if (unsigned BuiltinID = II->getBuiltinID()) { | |||
2468 | if (!(getLangOpts().CPlusPlus && | |||
2469 | Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { | |||
2470 | NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, | |||
2471 | S, Lookup.isForRedeclaration(), | |||
2472 | Lookup.getNameLoc()); | |||
2473 | if (D) Lookup.addDecl(D); | |||
2474 | } | |||
2475 | } | |||
2476 | } | |||
2477 | // Sentinel value saying that we didn't do anything special. | |||
2478 | return ExprResult((Expr *)nullptr); | |||
2479 | } | |||
2480 | ||||
2481 | /// \brief Cast a base object to a member's actual type. | |||
2482 | /// | |||
2483 | /// Logically this happens in three phases: | |||
2484 | /// | |||
2485 | /// * First we cast from the base type to the naming class. | |||
2486 | /// The naming class is the class into which we were looking | |||
2487 | /// when we found the member; it's the qualifier type if a | |||
2488 | /// qualifier was provided, and otherwise it's the base type. | |||
2489 | /// | |||
2490 | /// * Next we cast from the naming class to the declaring class. | |||
2491 | /// If the member we found was brought into a class's scope by | |||
2492 | /// a using declaration, this is that class; otherwise it's | |||
2493 | /// the class declaring the member. | |||
2494 | /// | |||
2495 | /// * Finally we cast from the declaring class to the "true" | |||
2496 | /// declaring class of the member. This conversion does not | |||
2497 | /// obey access control. | |||
2498 | ExprResult | |||
2499 | Sema::PerformObjectMemberConversion(Expr *From, | |||
2500 | NestedNameSpecifier *Qualifier, | |||
2501 | NamedDecl *FoundDecl, | |||
2502 | NamedDecl *Member) { | |||
2503 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); | |||
2504 | if (!RD) | |||
2505 | return From; | |||
2506 | ||||
2507 | QualType DestRecordType; | |||
2508 | QualType DestType; | |||
2509 | QualType FromRecordType; | |||
2510 | QualType FromType = From->getType(); | |||
2511 | bool PointerConversions = false; | |||
2512 | if (isa<FieldDecl>(Member)) { | |||
2513 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); | |||
2514 | ||||
2515 | if (FromType->getAs<PointerType>()) { | |||
2516 | DestType = Context.getPointerType(DestRecordType); | |||
2517 | FromRecordType = FromType->getPointeeType(); | |||
2518 | PointerConversions = true; | |||
2519 | } else { | |||
2520 | DestType = DestRecordType; | |||
2521 | FromRecordType = FromType; | |||
2522 | } | |||
2523 | } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { | |||
2524 | if (Method->isStatic()) | |||
2525 | return From; | |||
2526 | ||||
2527 | DestType = Method->getThisType(Context); | |||
2528 | DestRecordType = DestType->getPointeeType(); | |||
2529 | ||||
2530 | if (FromType->getAs<PointerType>()) { | |||
2531 | FromRecordType = FromType->getPointeeType(); | |||
2532 | PointerConversions = true; | |||
2533 | } else { | |||
2534 | FromRecordType = FromType; | |||
2535 | DestType = DestRecordType; | |||
2536 | } | |||
2537 | } else { | |||
2538 | // No conversion necessary. | |||
2539 | return From; | |||
2540 | } | |||
2541 | ||||
2542 | if (DestType->isDependentType() || FromType->isDependentType()) | |||
2543 | return From; | |||
2544 | ||||
2545 | // If the unqualified types are the same, no conversion is necessary. | |||
2546 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | |||
2547 | return From; | |||
2548 | ||||
2549 | SourceRange FromRange = From->getSourceRange(); | |||
2550 | SourceLocation FromLoc = FromRange.getBegin(); | |||
2551 | ||||
2552 | ExprValueKind VK = From->getValueKind(); | |||
2553 | ||||
2554 | // C++ [class.member.lookup]p8: | |||
2555 | // [...] Ambiguities can often be resolved by qualifying a name with its | |||
2556 | // class name. | |||
2557 | // | |||
2558 | // If the member was a qualified name and the qualified referred to a | |||
2559 | // specific base subobject type, we'll cast to that intermediate type | |||
2560 | // first and then to the object in which the member is declared. That allows | |||
2561 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: | |||
2562 | // | |||
2563 | // class Base { public: int x; }; | |||
2564 | // class Derived1 : public Base { }; | |||
2565 | // class Derived2 : public Base { }; | |||
2566 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; | |||
2567 | // | |||
2568 | // void VeryDerived::f() { | |||
2569 | // x = 17; // error: ambiguous base subobjects | |||
2570 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 | |||
2571 | // } | |||
2572 | if (Qualifier && Qualifier->getAsType()) { | |||
2573 | QualType QType = QualType(Qualifier->getAsType(), 0); | |||
2574 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2574, __extension__ __PRETTY_FUNCTION__)); | |||
2575 | ||||
2576 | QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); | |||
2577 | ||||
2578 | // In C++98, the qualifier type doesn't actually have to be a base | |||
2579 | // type of the object type, in which case we just ignore it. | |||
2580 | // Otherwise build the appropriate casts. | |||
2581 | if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { | |||
2582 | CXXCastPath BasePath; | |||
2583 | if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, | |||
2584 | FromLoc, FromRange, &BasePath)) | |||
2585 | return ExprError(); | |||
2586 | ||||
2587 | if (PointerConversions) | |||
2588 | QType = Context.getPointerType(QType); | |||
2589 | From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, | |||
2590 | VK, &BasePath).get(); | |||
2591 | ||||
2592 | FromType = QType; | |||
2593 | FromRecordType = QRecordType; | |||
2594 | ||||
2595 | // If the qualifier type was the same as the destination type, | |||
2596 | // we're done. | |||
2597 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | |||
2598 | return From; | |||
2599 | } | |||
2600 | } | |||
2601 | ||||
2602 | bool IgnoreAccess = false; | |||
2603 | ||||
2604 | // If we actually found the member through a using declaration, cast | |||
2605 | // down to the using declaration's type. | |||
2606 | // | |||
2607 | // Pointer equality is fine here because only one declaration of a | |||
2608 | // class ever has member declarations. | |||
2609 | if (FoundDecl->getDeclContext() != Member->getDeclContext()) { | |||
2610 | assert(isa<UsingShadowDecl>(FoundDecl))(static_cast <bool> (isa<UsingShadowDecl>(FoundDecl )) ? void (0) : __assert_fail ("isa<UsingShadowDecl>(FoundDecl)" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2610, __extension__ __PRETTY_FUNCTION__)); | |||
2611 | QualType URecordType = Context.getTypeDeclType( | |||
2612 | cast<CXXRecordDecl>(FoundDecl->getDeclContext())); | |||
2613 | ||||
2614 | // We only need to do this if the naming-class to declaring-class | |||
2615 | // conversion is non-trivial. | |||
2616 | if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { | |||
2617 | assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType))(static_cast <bool> (IsDerivedFrom(FromLoc, FromRecordType , URecordType)) ? void (0) : __assert_fail ("IsDerivedFrom(FromLoc, FromRecordType, URecordType)" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2617, __extension__ __PRETTY_FUNCTION__)); | |||
2618 | CXXCastPath BasePath; | |||
2619 | if (CheckDerivedToBaseConversion(FromRecordType, URecordType, | |||
2620 | FromLoc, FromRange, &BasePath)) | |||
2621 | return ExprError(); | |||
2622 | ||||
2623 | QualType UType = URecordType; | |||
2624 | if (PointerConversions) | |||
2625 | UType = Context.getPointerType(UType); | |||
2626 | From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, | |||
2627 | VK, &BasePath).get(); | |||
2628 | FromType = UType; | |||
2629 | FromRecordType = URecordType; | |||
2630 | } | |||
2631 | ||||
2632 | // We don't do access control for the conversion from the | |||
2633 | // declaring class to the true declaring class. | |||
2634 | IgnoreAccess = true; | |||
2635 | } | |||
2636 | ||||
2637 | CXXCastPath BasePath; | |||
2638 | if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, | |||
2639 | FromLoc, FromRange, &BasePath, | |||
2640 | IgnoreAccess)) | |||
2641 | return ExprError(); | |||
2642 | ||||
2643 | return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, | |||
2644 | VK, &BasePath); | |||
2645 | } | |||
2646 | ||||
2647 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, | |||
2648 | const LookupResult &R, | |||
2649 | bool HasTrailingLParen) { | |||
2650 | // Only when used directly as the postfix-expression of a call. | |||
2651 | if (!HasTrailingLParen) | |||
2652 | return false; | |||
2653 | ||||
2654 | // Never if a scope specifier was provided. | |||
2655 | if (SS.isSet()) | |||
2656 | return false; | |||
2657 | ||||
2658 | // Only in C++ or ObjC++. | |||
2659 | if (!getLangOpts().CPlusPlus) | |||
2660 | return false; | |||
2661 | ||||
2662 | // Turn off ADL when we find certain kinds of declarations during | |||
2663 | // normal lookup: | |||
2664 | for (NamedDecl *D : R) { | |||
2665 | // C++0x [basic.lookup.argdep]p3: | |||
2666 | // -- a declaration of a class member | |||
2667 | // Since using decls preserve this property, we check this on the | |||
2668 | // original decl. | |||
2669 | if (D->isCXXClassMember()) | |||
2670 | return false; | |||
2671 | ||||
2672 | // C++0x [basic.lookup.argdep]p3: | |||
2673 | // -- a block-scope function declaration that is not a | |||
2674 | // using-declaration | |||
2675 | // NOTE: we also trigger this for function templates (in fact, we | |||
2676 | // don't check the decl type at all, since all other decl types | |||
2677 | // turn off ADL anyway). | |||
2678 | if (isa<UsingShadowDecl>(D)) | |||
2679 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
2680 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) | |||
2681 | return false; | |||
2682 | ||||
2683 | // C++0x [basic.lookup.argdep]p3: | |||
2684 | // -- a declaration that is neither a function or a function | |||
2685 | // template | |||
2686 | // And also for builtin functions. | |||
2687 | if (isa<FunctionDecl>(D)) { | |||
2688 | FunctionDecl *FDecl = cast<FunctionDecl>(D); | |||
2689 | ||||
2690 | // But also builtin functions. | |||
2691 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) | |||
2692 | return false; | |||
2693 | } else if (!isa<FunctionTemplateDecl>(D)) | |||
2694 | return false; | |||
2695 | } | |||
2696 | ||||
2697 | return true; | |||
2698 | } | |||
2699 | ||||
2700 | ||||
2701 | /// Diagnoses obvious problems with the use of the given declaration | |||
2702 | /// as an expression. This is only actually called for lookups that | |||
2703 | /// were not overloaded, and it doesn't promise that the declaration | |||
2704 | /// will in fact be used. | |||
2705 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { | |||
2706 | if (D->isInvalidDecl()) | |||
2707 | return true; | |||
2708 | ||||
2709 | if (isa<TypedefNameDecl>(D)) { | |||
2710 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); | |||
2711 | return true; | |||
2712 | } | |||
2713 | ||||
2714 | if (isa<ObjCInterfaceDecl>(D)) { | |||
2715 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); | |||
2716 | return true; | |||
2717 | } | |||
2718 | ||||
2719 | if (isa<NamespaceDecl>(D)) { | |||
2720 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); | |||
2721 | return true; | |||
2722 | } | |||
2723 | ||||
2724 | return false; | |||
2725 | } | |||
2726 | ||||
2727 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, | |||
2728 | LookupResult &R, bool NeedsADL, | |||
2729 | bool AcceptInvalidDecl) { | |||
2730 | // If this is a single, fully-resolved result and we don't need ADL, | |||
2731 | // just build an ordinary singleton decl ref. | |||
2732 | if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) | |||
2733 | return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), | |||
2734 | R.getRepresentativeDecl(), nullptr, | |||
2735 | AcceptInvalidDecl); | |||
2736 | ||||
2737 | // We only need to check the declaration if there's exactly one | |||
2738 | // result, because in the overloaded case the results can only be | |||
2739 | // functions and function templates. | |||
2740 | if (R.isSingleResult() && | |||
2741 | CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) | |||
2742 | return ExprError(); | |||
2743 | ||||
2744 | // Otherwise, just build an unresolved lookup expression. Suppress | |||
2745 | // any lookup-related diagnostics; we'll hash these out later, when | |||
2746 | // we've picked a target. | |||
2747 | R.suppressDiagnostics(); | |||
2748 | ||||
2749 | UnresolvedLookupExpr *ULE | |||
2750 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), | |||
2751 | SS.getWithLocInContext(Context), | |||
2752 | R.getLookupNameInfo(), | |||
2753 | NeedsADL, R.isOverloadedResult(), | |||
2754 | R.begin(), R.end()); | |||
2755 | ||||
2756 | return ULE; | |||
2757 | } | |||
2758 | ||||
2759 | static void | |||
2760 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | |||
2761 | ValueDecl *var, DeclContext *DC); | |||
2762 | ||||
2763 | /// \brief Complete semantic analysis for a reference to the given declaration. | |||
2764 | ExprResult Sema::BuildDeclarationNameExpr( | |||
2765 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, | |||
2766 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, | |||
2767 | bool AcceptInvalidDecl) { | |||
2768 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2768, __extension__ __PRETTY_FUNCTION__)); | |||
2769 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2770, __extension__ __PRETTY_FUNCTION__)) | |||
2770 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2770, __extension__ __PRETTY_FUNCTION__)); | |||
2771 | ||||
2772 | SourceLocation Loc = NameInfo.getLoc(); | |||
2773 | if (CheckDeclInExpr(*this, Loc, D)) | |||
2774 | return ExprError(); | |||
2775 | ||||
2776 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { | |||
2777 | // Specifically diagnose references to class templates that are missing | |||
2778 | // a template argument list. | |||
2779 | Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) | |||
2780 | << Template << SS.getRange(); | |||
2781 | Diag(Template->getLocation(), diag::note_template_decl_here); | |||
2782 | return ExprError(); | |||
2783 | } | |||
2784 | ||||
2785 | // Make sure that we're referring to a value. | |||
2786 | ValueDecl *VD = dyn_cast<ValueDecl>(D); | |||
2787 | if (!VD) { | |||
2788 | Diag(Loc, diag::err_ref_non_value) | |||
2789 | << D << SS.getRange(); | |||
2790 | Diag(D->getLocation(), diag::note_declared_at); | |||
2791 | return ExprError(); | |||
2792 | } | |||
2793 | ||||
2794 | // Check whether this declaration can be used. Note that we suppress | |||
2795 | // this check when we're going to perform argument-dependent lookup | |||
2796 | // on this function name, because this might not be the function | |||
2797 | // that overload resolution actually selects. | |||
2798 | if (DiagnoseUseOfDecl(VD, Loc)) | |||
2799 | return ExprError(); | |||
2800 | ||||
2801 | // Only create DeclRefExpr's for valid Decl's. | |||
2802 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) | |||
2803 | return ExprError(); | |||
2804 | ||||
2805 | // Handle members of anonymous structs and unions. If we got here, | |||
2806 | // and the reference is to a class member indirect field, then this | |||
2807 | // must be the subject of a pointer-to-member expression. | |||
2808 | if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) | |||
2809 | if (!indirectField->isCXXClassMember()) | |||
2810 | return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), | |||
2811 | indirectField); | |||
2812 | ||||
2813 | { | |||
2814 | QualType type = VD->getType(); | |||
2815 | if (type.isNull()) | |||
2816 | return ExprError(); | |||
2817 | if (auto *FPT = type->getAs<FunctionProtoType>()) { | |||
2818 | // C++ [except.spec]p17: | |||
2819 | // An exception-specification is considered to be needed when: | |||
2820 | // - in an expression, the function is the unique lookup result or | |||
2821 | // the selected member of a set of overloaded functions. | |||
2822 | ResolveExceptionSpec(Loc, FPT); | |||
2823 | type = VD->getType(); | |||
2824 | } | |||
2825 | ExprValueKind valueKind = VK_RValue; | |||
2826 | ||||
2827 | switch (D->getKind()) { | |||
2828 | // Ignore all the non-ValueDecl kinds. | |||
2829 | #define ABSTRACT_DECL(kind) | |||
2830 | #define VALUE(type, base) | |||
2831 | #define DECL(type, base) \ | |||
2832 | case Decl::type: | |||
2833 | #include "clang/AST/DeclNodes.inc" | |||
2834 | llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2834); | |||
2835 | ||||
2836 | // These shouldn't make it here. | |||
2837 | case Decl::ObjCAtDefsField: | |||
2838 | case Decl::ObjCIvar: | |||
2839 | llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2839); | |||
2840 | ||||
2841 | // Enum constants are always r-values and never references. | |||
2842 | // Unresolved using declarations are dependent. | |||
2843 | case Decl::EnumConstant: | |||
2844 | case Decl::UnresolvedUsingValue: | |||
2845 | case Decl::OMPDeclareReduction: | |||
2846 | valueKind = VK_RValue; | |||
2847 | break; | |||
2848 | ||||
2849 | // Fields and indirect fields that got here must be for | |||
2850 | // pointer-to-member expressions; we just call them l-values for | |||
2851 | // internal consistency, because this subexpression doesn't really | |||
2852 | // exist in the high-level semantics. | |||
2853 | case Decl::Field: | |||
2854 | case Decl::IndirectField: | |||
2855 | assert(getLangOpts().CPlusPlus &&(static_cast <bool> (getLangOpts().CPlusPlus && "building reference to field in C?") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2856, __extension__ __PRETTY_FUNCTION__)) | |||
2856 | "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?\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2856, __extension__ __PRETTY_FUNCTION__)); | |||
2857 | ||||
2858 | // These can't have reference type in well-formed programs, but | |||
2859 | // for internal consistency we do this anyway. | |||
2860 | type = type.getNonReferenceType(); | |||
2861 | valueKind = VK_LValue; | |||
2862 | break; | |||
2863 | ||||
2864 | // Non-type template parameters are either l-values or r-values | |||
2865 | // depending on the type. | |||
2866 | case Decl::NonTypeTemplateParm: { | |||
2867 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { | |||
2868 | type = reftype->getPointeeType(); | |||
2869 | valueKind = VK_LValue; // even if the parameter is an r-value reference | |||
2870 | break; | |||
2871 | } | |||
2872 | ||||
2873 | // For non-references, we need to strip qualifiers just in case | |||
2874 | // the template parameter was declared as 'const int' or whatever. | |||
2875 | valueKind = VK_RValue; | |||
2876 | type = type.getUnqualifiedType(); | |||
2877 | break; | |||
2878 | } | |||
2879 | ||||
2880 | case Decl::Var: | |||
2881 | case Decl::VarTemplateSpecialization: | |||
2882 | case Decl::VarTemplatePartialSpecialization: | |||
2883 | case Decl::Decomposition: | |||
2884 | case Decl::OMPCapturedExpr: | |||
2885 | // In C, "extern void blah;" is valid and is an r-value. | |||
2886 | if (!getLangOpts().CPlusPlus && | |||
2887 | !type.hasQualifiers() && | |||
2888 | type->isVoidType()) { | |||
2889 | valueKind = VK_RValue; | |||
2890 | break; | |||
2891 | } | |||
2892 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
2893 | ||||
2894 | case Decl::ImplicitParam: | |||
2895 | case Decl::ParmVar: { | |||
2896 | // These are always l-values. | |||
2897 | valueKind = VK_LValue; | |||
2898 | type = type.getNonReferenceType(); | |||
2899 | ||||
2900 | // FIXME: Does the addition of const really only apply in | |||
2901 | // potentially-evaluated contexts? Since the variable isn't actually | |||
2902 | // captured in an unevaluated context, it seems that the answer is no. | |||
2903 | if (!isUnevaluatedContext()) { | |||
2904 | QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); | |||
2905 | if (!CapturedType.isNull()) | |||
2906 | type = CapturedType; | |||
2907 | } | |||
2908 | ||||
2909 | break; | |||
2910 | } | |||
2911 | ||||
2912 | case Decl::Binding: { | |||
2913 | // These are always lvalues. | |||
2914 | valueKind = VK_LValue; | |||
2915 | type = type.getNonReferenceType(); | |||
2916 | // FIXME: Support lambda-capture of BindingDecls, once CWG actually | |||
2917 | // decides how that's supposed to work. | |||
2918 | auto *BD = cast<BindingDecl>(VD); | |||
2919 | if (BD->getDeclContext()->isFunctionOrMethod() && | |||
2920 | BD->getDeclContext() != CurContext) | |||
2921 | diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); | |||
2922 | break; | |||
2923 | } | |||
2924 | ||||
2925 | case Decl::Function: { | |||
2926 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { | |||
2927 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { | |||
2928 | type = Context.BuiltinFnTy; | |||
2929 | valueKind = VK_RValue; | |||
2930 | break; | |||
2931 | } | |||
2932 | } | |||
2933 | ||||
2934 | const FunctionType *fty = type->castAs<FunctionType>(); | |||
2935 | ||||
2936 | // If we're referring to a function with an __unknown_anytype | |||
2937 | // result type, make the entire expression __unknown_anytype. | |||
2938 | if (fty->getReturnType() == Context.UnknownAnyTy) { | |||
2939 | type = Context.UnknownAnyTy; | |||
2940 | valueKind = VK_RValue; | |||
2941 | break; | |||
2942 | } | |||
2943 | ||||
2944 | // Functions are l-values in C++. | |||
2945 | if (getLangOpts().CPlusPlus) { | |||
2946 | valueKind = VK_LValue; | |||
2947 | break; | |||
2948 | } | |||
2949 | ||||
2950 | // C99 DR 316 says that, if a function type comes from a | |||
2951 | // function definition (without a prototype), that type is only | |||
2952 | // used for checking compatibility. Therefore, when referencing | |||
2953 | // the function, we pretend that we don't have the full function | |||
2954 | // type. | |||
2955 | if (!cast<FunctionDecl>(VD)->hasPrototype() && | |||
2956 | isa<FunctionProtoType>(fty)) | |||
2957 | type = Context.getFunctionNoProtoType(fty->getReturnType(), | |||
2958 | fty->getExtInfo()); | |||
2959 | ||||
2960 | // Functions are r-values in C. | |||
2961 | valueKind = VK_RValue; | |||
2962 | break; | |||
2963 | } | |||
2964 | ||||
2965 | case Decl::CXXDeductionGuide: | |||
2966 | llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 2966); | |||
2967 | ||||
2968 | case Decl::MSProperty: | |||
2969 | valueKind = VK_LValue; | |||
2970 | break; | |||
2971 | ||||
2972 | case Decl::CXXMethod: | |||
2973 | // If we're referring to a method with an __unknown_anytype | |||
2974 | // result type, make the entire expression __unknown_anytype. | |||
2975 | // This should only be possible with a type written directly. | |||
2976 | if (const FunctionProtoType *proto | |||
2977 | = dyn_cast<FunctionProtoType>(VD->getType())) | |||
2978 | if (proto->getReturnType() == Context.UnknownAnyTy) { | |||
2979 | type = Context.UnknownAnyTy; | |||
2980 | valueKind = VK_RValue; | |||
2981 | break; | |||
2982 | } | |||
2983 | ||||
2984 | // C++ methods are l-values if static, r-values if non-static. | |||
2985 | if (cast<CXXMethodDecl>(VD)->isStatic()) { | |||
2986 | valueKind = VK_LValue; | |||
2987 | break; | |||
2988 | } | |||
2989 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
2990 | ||||
2991 | case Decl::CXXConversion: | |||
2992 | case Decl::CXXDestructor: | |||
2993 | case Decl::CXXConstructor: | |||
2994 | valueKind = VK_RValue; | |||
2995 | break; | |||
2996 | } | |||
2997 | ||||
2998 | return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, | |||
2999 | TemplateArgs); | |||
3000 | } | |||
3001 | } | |||
3002 | ||||
3003 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, | |||
3004 | SmallString<32> &Target) { | |||
3005 | Target.resize(CharByteWidth * (Source.size() + 1)); | |||
3006 | char *ResultPtr = &Target[0]; | |||
3007 | const llvm::UTF8 *ErrorPtr; | |||
3008 | bool success = | |||
3009 | llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); | |||
3010 | (void)success; | |||
3011 | assert(success)(static_cast <bool> (success) ? void (0) : __assert_fail ("success", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3011, __extension__ __PRETTY_FUNCTION__)); | |||
3012 | Target.resize(ResultPtr - &Target[0]); | |||
3013 | } | |||
3014 | ||||
3015 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, | |||
3016 | PredefinedExpr::IdentType IT) { | |||
3017 | // Pick the current block, lambda, captured statement or function. | |||
3018 | Decl *currentDecl = nullptr; | |||
3019 | if (const BlockScopeInfo *BSI = getCurBlock()) | |||
3020 | currentDecl = BSI->TheDecl; | |||
3021 | else if (const LambdaScopeInfo *LSI = getCurLambda()) | |||
3022 | currentDecl = LSI->CallOperator; | |||
3023 | else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) | |||
3024 | currentDecl = CSI->TheCapturedDecl; | |||
3025 | else | |||
3026 | currentDecl = getCurFunctionOrMethodDecl(); | |||
3027 | ||||
3028 | if (!currentDecl) { | |||
3029 | Diag(Loc, diag::ext_predef_outside_function); | |||
3030 | currentDecl = Context.getTranslationUnitDecl(); | |||
3031 | } | |||
3032 | ||||
3033 | QualType ResTy; | |||
3034 | StringLiteral *SL = nullptr; | |||
3035 | if (cast<DeclContext>(currentDecl)->isDependentContext()) | |||
3036 | ResTy = Context.DependentTy; | |||
3037 | else { | |||
3038 | // Pre-defined identifiers are of type char[x], where x is the length of | |||
3039 | // the string. | |||
3040 | auto Str = PredefinedExpr::ComputeName(IT, currentDecl); | |||
3041 | unsigned Length = Str.length(); | |||
3042 | ||||
3043 | llvm::APInt LengthI(32, Length + 1); | |||
3044 | if (IT == PredefinedExpr::LFunction) { | |||
3045 | ResTy = Context.WideCharTy.withConst(); | |||
3046 | SmallString<32> RawChars; | |||
3047 | ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), | |||
3048 | Str, RawChars); | |||
3049 | ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, | |||
3050 | /*IndexTypeQuals*/ 0); | |||
3051 | SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, | |||
3052 | /*Pascal*/ false, ResTy, Loc); | |||
3053 | } else { | |||
3054 | ResTy = Context.CharTy.withConst(); | |||
3055 | ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, | |||
3056 | /*IndexTypeQuals*/ 0); | |||
3057 | SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, | |||
3058 | /*Pascal*/ false, ResTy, Loc); | |||
3059 | } | |||
3060 | } | |||
3061 | ||||
3062 | return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); | |||
3063 | } | |||
3064 | ||||
3065 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { | |||
3066 | PredefinedExpr::IdentType IT; | |||
3067 | ||||
3068 | switch (Kind) { | |||
3069 | default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3069); | |||
3070 | case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] | |||
3071 | case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; | |||
3072 | case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] | |||
3073 | case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] | |||
3074 | case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; | |||
3075 | case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; | |||
3076 | } | |||
3077 | ||||
3078 | return BuildPredefinedExpr(Loc, IT); | |||
3079 | } | |||
3080 | ||||
3081 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { | |||
3082 | SmallString<16> CharBuffer; | |||
3083 | bool Invalid = false; | |||
3084 | StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); | |||
3085 | if (Invalid) | |||
3086 | return ExprError(); | |||
3087 | ||||
3088 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), | |||
3089 | PP, Tok.getKind()); | |||
3090 | if (Literal.hadError()) | |||
3091 | return ExprError(); | |||
3092 | ||||
3093 | QualType Ty; | |||
3094 | if (Literal.isWide()) | |||
3095 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. | |||
3096 | else if (Literal.isUTF16()) | |||
3097 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. | |||
3098 | else if (Literal.isUTF32()) | |||
3099 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. | |||
3100 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) | |||
3101 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. | |||
3102 | else | |||
3103 | Ty = Context.CharTy; // 'x' -> char in C++ | |||
3104 | ||||
3105 | CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; | |||
3106 | if (Literal.isWide()) | |||
3107 | Kind = CharacterLiteral::Wide; | |||
3108 | else if (Literal.isUTF16()) | |||
3109 | Kind = CharacterLiteral::UTF16; | |||
3110 | else if (Literal.isUTF32()) | |||
3111 | Kind = CharacterLiteral::UTF32; | |||
3112 | else if (Literal.isUTF8()) | |||
3113 | Kind = CharacterLiteral::UTF8; | |||
3114 | ||||
3115 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, | |||
3116 | Tok.getLocation()); | |||
3117 | ||||
3118 | if (Literal.getUDSuffix().empty()) | |||
3119 | return Lit; | |||
3120 | ||||
3121 | // We're building a user-defined literal. | |||
3122 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | |||
3123 | SourceLocation UDSuffixLoc = | |||
3124 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | |||
3125 | ||||
3126 | // Make sure we're allowed user-defined literals here. | |||
3127 | if (!UDLScope) | |||
3128 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); | |||
3129 | ||||
3130 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form | |||
3131 | // operator "" X (ch) | |||
3132 | return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, | |||
3133 | Lit, Tok.getLocation()); | |||
3134 | } | |||
3135 | ||||
3136 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { | |||
3137 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | |||
3138 | return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), | |||
3139 | Context.IntTy, Loc); | |||
3140 | } | |||
3141 | ||||
3142 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, | |||
3143 | QualType Ty, SourceLocation Loc) { | |||
3144 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); | |||
3145 | ||||
3146 | using llvm::APFloat; | |||
3147 | APFloat Val(Format); | |||
3148 | ||||
3149 | APFloat::opStatus result = Literal.GetFloatValue(Val); | |||
3150 | ||||
3151 | // Overflow is always an error, but underflow is only an error if | |||
3152 | // we underflowed to zero (APFloat reports denormals as underflow). | |||
3153 | if ((result & APFloat::opOverflow) || | |||
3154 | ((result & APFloat::opUnderflow) && Val.isZero())) { | |||
3155 | unsigned diagnostic; | |||
3156 | SmallString<20> buffer; | |||
3157 | if (result & APFloat::opOverflow) { | |||
3158 | diagnostic = diag::warn_float_overflow; | |||
3159 | APFloat::getLargest(Format).toString(buffer); | |||
3160 | } else { | |||
3161 | diagnostic = diag::warn_float_underflow; | |||
3162 | APFloat::getSmallest(Format).toString(buffer); | |||
3163 | } | |||
3164 | ||||
3165 | S.Diag(Loc, diagnostic) | |||
3166 | << Ty | |||
3167 | << StringRef(buffer.data(), buffer.size()); | |||
3168 | } | |||
3169 | ||||
3170 | bool isExact = (result == APFloat::opOK); | |||
3171 | return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); | |||
3172 | } | |||
3173 | ||||
3174 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { | |||
3175 | assert(E && "Invalid expression")(static_cast <bool> (E && "Invalid expression") ? void (0) : __assert_fail ("E && \"Invalid expression\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3175, __extension__ __PRETTY_FUNCTION__)); | |||
3176 | ||||
3177 | if (E->isValueDependent()) | |||
3178 | return false; | |||
3179 | ||||
3180 | QualType QT = E->getType(); | |||
3181 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { | |||
3182 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; | |||
3183 | return true; | |||
3184 | } | |||
3185 | ||||
3186 | llvm::APSInt ValueAPS; | |||
3187 | ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); | |||
3188 | ||||
3189 | if (R.isInvalid()) | |||
3190 | return true; | |||
3191 | ||||
3192 | bool ValueIsPositive = ValueAPS.isStrictlyPositive(); | |||
3193 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { | |||
3194 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) | |||
3195 | << ValueAPS.toString(10) << ValueIsPositive; | |||
3196 | return true; | |||
3197 | } | |||
3198 | ||||
3199 | return false; | |||
3200 | } | |||
3201 | ||||
3202 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { | |||
3203 | // Fast path for a single digit (which is quite common). A single digit | |||
3204 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. | |||
3205 | if (Tok.getLength() == 1) { | |||
3206 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); | |||
3207 | return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); | |||
3208 | } | |||
3209 | ||||
3210 | SmallString<128> SpellingBuffer; | |||
3211 | // NumericLiteralParser wants to overread by one character. Add padding to | |||
3212 | // the buffer in case the token is copied to the buffer. If getSpelling() | |||
3213 | // returns a StringRef to the memory buffer, it should have a null char at | |||
3214 | // the EOF, so it is also safe. | |||
3215 | SpellingBuffer.resize(Tok.getLength() + 1); | |||
3216 | ||||
3217 | // Get the spelling of the token, which eliminates trigraphs, etc. | |||
3218 | bool Invalid = false; | |||
3219 | StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); | |||
3220 | if (Invalid) | |||
3221 | return ExprError(); | |||
3222 | ||||
3223 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); | |||
3224 | if (Literal.hadError) | |||
3225 | return ExprError(); | |||
3226 | ||||
3227 | if (Literal.hasUDSuffix()) { | |||
3228 | // We're building a user-defined literal. | |||
3229 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | |||
3230 | SourceLocation UDSuffixLoc = | |||
3231 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | |||
3232 | ||||
3233 | // Make sure we're allowed user-defined literals here. | |||
3234 | if (!UDLScope) | |||
3235 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); | |||
3236 | ||||
3237 | QualType CookedTy; | |||
3238 | if (Literal.isFloatingLiteral()) { | |||
3239 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type | |||
3240 | // long double, the literal is treated as a call of the form | |||
3241 | // operator "" X (f L) | |||
3242 | CookedTy = Context.LongDoubleTy; | |||
3243 | } else { | |||
3244 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type | |||
3245 | // unsigned long long, the literal is treated as a call of the form | |||
3246 | // operator "" X (n ULL) | |||
3247 | CookedTy = Context.UnsignedLongLongTy; | |||
3248 | } | |||
3249 | ||||
3250 | DeclarationName OpName = | |||
3251 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | |||
3252 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | |||
3253 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | |||
3254 | ||||
3255 | SourceLocation TokLoc = Tok.getLocation(); | |||
3256 | ||||
3257 | // Perform literal operator lookup to determine if we're building a raw | |||
3258 | // literal or a cooked one. | |||
3259 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | |||
3260 | switch (LookupLiteralOperator(UDLScope, R, CookedTy, | |||
3261 | /*AllowRaw*/ true, /*AllowTemplate*/ true, | |||
3262 | /*AllowStringTemplate*/ false, | |||
3263 | /*DiagnoseMissing*/ !Literal.isImaginary)) { | |||
3264 | case LOLR_ErrorNoDiagnostic: | |||
3265 | // Lookup failure for imaginary constants isn't fatal, there's still the | |||
3266 | // GNU extension producing _Complex types. | |||
3267 | break; | |||
3268 | case LOLR_Error: | |||
3269 | return ExprError(); | |||
3270 | case LOLR_Cooked: { | |||
3271 | Expr *Lit; | |||
3272 | if (Literal.isFloatingLiteral()) { | |||
3273 | Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); | |||
3274 | } else { | |||
3275 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); | |||
3276 | if (Literal.GetIntegerValue(ResultVal)) | |||
3277 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | |||
3278 | << /* Unsigned */ 1; | |||
3279 | Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, | |||
3280 | Tok.getLocation()); | |||
3281 | } | |||
3282 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | |||
3283 | } | |||
3284 | ||||
3285 | case LOLR_Raw: { | |||
3286 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the | |||
3287 | // literal is treated as a call of the form | |||
3288 | // operator "" X ("n") | |||
3289 | unsigned Length = Literal.getUDSuffixOffset(); | |||
3290 | QualType StrTy = Context.getConstantArrayType( | |||
3291 | Context.CharTy.withConst(), llvm::APInt(32, Length + 1), | |||
3292 | ArrayType::Normal, 0); | |||
3293 | Expr *Lit = StringLiteral::Create( | |||
3294 | Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, | |||
3295 | /*Pascal*/false, StrTy, &TokLoc, 1); | |||
3296 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | |||
3297 | } | |||
3298 | ||||
3299 | case LOLR_Template: { | |||
3300 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator | |||
3301 | // template), L is treated as a call fo the form | |||
3302 | // operator "" X <'c1', 'c2', ... 'ck'>() | |||
3303 | // where n is the source character sequence c1 c2 ... ck. | |||
3304 | TemplateArgumentListInfo ExplicitArgs; | |||
3305 | unsigned CharBits = Context.getIntWidth(Context.CharTy); | |||
3306 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); | |||
3307 | llvm::APSInt Value(CharBits, CharIsUnsigned); | |||
3308 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { | |||
3309 | Value = TokSpelling[I]; | |||
3310 | TemplateArgument Arg(Context, Value, Context.CharTy); | |||
3311 | TemplateArgumentLocInfo ArgInfo; | |||
3312 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | |||
3313 | } | |||
3314 | return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, | |||
3315 | &ExplicitArgs); | |||
3316 | } | |||
3317 | case LOLR_StringTemplate: | |||
3318 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3318); | |||
3319 | } | |||
3320 | } | |||
3321 | ||||
3322 | Expr *Res; | |||
3323 | ||||
3324 | if (Literal.isFloatingLiteral()) { | |||
3325 | QualType Ty; | |||
3326 | if (Literal.isHalf){ | |||
3327 | if (getOpenCLOptions().isEnabled("cl_khr_fp16")) | |||
3328 | Ty = Context.HalfTy; | |||
3329 | else { | |||
3330 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); | |||
3331 | return ExprError(); | |||
3332 | } | |||
3333 | } else if (Literal.isFloat) | |||
3334 | Ty = Context.FloatTy; | |||
3335 | else if (Literal.isLong) | |||
3336 | Ty = Context.LongDoubleTy; | |||
3337 | else if (Literal.isFloat16) | |||
3338 | Ty = Context.Float16Ty; | |||
3339 | else if (Literal.isFloat128) | |||
3340 | Ty = Context.Float128Ty; | |||
3341 | else | |||
3342 | Ty = Context.DoubleTy; | |||
3343 | ||||
3344 | Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); | |||
3345 | ||||
3346 | if (Ty == Context.DoubleTy) { | |||
3347 | if (getLangOpts().SinglePrecisionConstants) { | |||
3348 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | |||
3349 | if (BTy->getKind() != BuiltinType::Float) { | |||
3350 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | |||
3351 | } | |||
3352 | } else if (getLangOpts().OpenCL && | |||
3353 | !getOpenCLOptions().isEnabled("cl_khr_fp64")) { | |||
3354 | // Impose single-precision float type when cl_khr_fp64 is not enabled. | |||
3355 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); | |||
3356 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | |||
3357 | } | |||
3358 | } | |||
3359 | } else if (!Literal.isIntegerLiteral()) { | |||
3360 | return ExprError(); | |||
3361 | } else { | |||
3362 | QualType Ty; | |||
3363 | ||||
3364 | // 'long long' is a C99 or C++11 feature. | |||
3365 | if (!getLangOpts().C99 && Literal.isLongLong) { | |||
3366 | if (getLangOpts().CPlusPlus) | |||
3367 | Diag(Tok.getLocation(), | |||
3368 | getLangOpts().CPlusPlus11 ? | |||
3369 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | |||
3370 | else | |||
3371 | Diag(Tok.getLocation(), diag::ext_c99_longlong); | |||
3372 | } | |||
3373 | ||||
3374 | // Get the value in the widest-possible width. | |||
3375 | unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); | |||
3376 | llvm::APInt ResultVal(MaxWidth, 0); | |||
3377 | ||||
3378 | if (Literal.GetIntegerValue(ResultVal)) { | |||
3379 | // If this value didn't fit into uintmax_t, error and force to ull. | |||
3380 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | |||
3381 | << /* Unsigned */ 1; | |||
3382 | Ty = Context.UnsignedLongLongTy; | |||
3383 | 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?\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3384, __extension__ __PRETTY_FUNCTION__)) | |||
3384 | "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?\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3384, __extension__ __PRETTY_FUNCTION__)); | |||
3385 | } else { | |||
3386 | // If this value fits into a ULL, try to figure out what else it fits into | |||
3387 | // according to the rules of C99 6.4.4.1p5. | |||
3388 | ||||
3389 | // Octal, Hexadecimal, and integers with a U suffix are allowed to | |||
3390 | // be an unsigned int. | |||
3391 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; | |||
3392 | ||||
3393 | // Check from smallest to largest, picking the smallest type we can. | |||
3394 | unsigned Width = 0; | |||
3395 | ||||
3396 | // Microsoft specific integer suffixes are explicitly sized. | |||
3397 | if (Literal.MicrosoftInteger) { | |||
3398 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { | |||
3399 | Width = 8; | |||
3400 | Ty = Context.CharTy; | |||
3401 | } else { | |||
3402 | Width = Literal.MicrosoftInteger; | |||
3403 | Ty = Context.getIntTypeForBitwidth(Width, | |||
3404 | /*Signed=*/!Literal.isUnsigned); | |||
3405 | } | |||
3406 | } | |||
3407 | ||||
3408 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { | |||
3409 | // Are int/unsigned possibilities? | |||
3410 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | |||
3411 | ||||
3412 | // Does it fit in a unsigned int? | |||
3413 | if (ResultVal.isIntN(IntSize)) { | |||
3414 | // Does it fit in a signed int? | |||
3415 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) | |||
3416 | Ty = Context.IntTy; | |||
3417 | else if (AllowUnsigned) | |||
3418 | Ty = Context.UnsignedIntTy; | |||
3419 | Width = IntSize; | |||
3420 | } | |||
3421 | } | |||
3422 | ||||
3423 | // Are long/unsigned long possibilities? | |||
3424 | if (Ty.isNull() && !Literal.isLongLong) { | |||
3425 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); | |||
3426 | ||||
3427 | // Does it fit in a unsigned long? | |||
3428 | if (ResultVal.isIntN(LongSize)) { | |||
3429 | // Does it fit in a signed long? | |||
3430 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) | |||
3431 | Ty = Context.LongTy; | |||
3432 | else if (AllowUnsigned) | |||
3433 | Ty = Context.UnsignedLongTy; | |||
3434 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 | |||
3435 | // is compatible. | |||
3436 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { | |||
3437 | const unsigned LongLongSize = | |||
3438 | Context.getTargetInfo().getLongLongWidth(); | |||
3439 | Diag(Tok.getLocation(), | |||
3440 | getLangOpts().CPlusPlus | |||
3441 | ? Literal.isLong | |||
3442 | ? diag::warn_old_implicitly_unsigned_long_cxx | |||
3443 | : /*C++98 UB*/ diag:: | |||
3444 | ext_old_implicitly_unsigned_long_cxx | |||
3445 | : diag::warn_old_implicitly_unsigned_long) | |||
3446 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 | |||
3447 | : /*will be ill-formed*/ 1); | |||
3448 | Ty = Context.UnsignedLongTy; | |||
3449 | } | |||
3450 | Width = LongSize; | |||
3451 | } | |||
3452 | } | |||
3453 | ||||
3454 | // Check long long if needed. | |||
3455 | if (Ty.isNull()) { | |||
3456 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); | |||
3457 | ||||
3458 | // Does it fit in a unsigned long long? | |||
3459 | if (ResultVal.isIntN(LongLongSize)) { | |||
3460 | // Does it fit in a signed long long? | |||
3461 | // To be compatible with MSVC, hex integer literals ending with the | |||
3462 | // LL or i64 suffix are always signed in Microsoft mode. | |||
3463 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || | |||
3464 | (getLangOpts().MSVCCompat && Literal.isLongLong))) | |||
3465 | Ty = Context.LongLongTy; | |||
3466 | else if (AllowUnsigned) | |||
3467 | Ty = Context.UnsignedLongLongTy; | |||
3468 | Width = LongLongSize; | |||
3469 | } | |||
3470 | } | |||
3471 | ||||
3472 | // If we still couldn't decide a type, we probably have something that | |||
3473 | // does not fit in a signed long long, but has no U suffix. | |||
3474 | if (Ty.isNull()) { | |||
3475 | Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); | |||
3476 | Ty = Context.UnsignedLongLongTy; | |||
3477 | Width = Context.getTargetInfo().getLongLongWidth(); | |||
3478 | } | |||
3479 | ||||
3480 | if (ResultVal.getBitWidth() != Width) | |||
3481 | ResultVal = ResultVal.trunc(Width); | |||
3482 | } | |||
3483 | Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); | |||
3484 | } | |||
3485 | ||||
3486 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. | |||
3487 | if (Literal.isImaginary) { | |||
3488 | Res = new (Context) ImaginaryLiteral(Res, | |||
3489 | Context.getComplexType(Res->getType())); | |||
3490 | ||||
3491 | Diag(Tok.getLocation(), diag::ext_imaginary_constant); | |||
3492 | } | |||
3493 | return Res; | |||
3494 | } | |||
3495 | ||||
3496 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { | |||
3497 | assert(E && "ActOnParenExpr() missing expr")(static_cast <bool> (E && "ActOnParenExpr() missing expr" ) ? void (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3497, __extension__ __PRETTY_FUNCTION__)); | |||
3498 | return new (Context) ParenExpr(L, R, E); | |||
3499 | } | |||
3500 | ||||
3501 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, | |||
3502 | SourceLocation Loc, | |||
3503 | SourceRange ArgRange) { | |||
3504 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in | |||
3505 | // scalar or vector data type argument..." | |||
3506 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic | |||
3507 | // type (C99 6.2.5p18) or void. | |||
3508 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { | |||
3509 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) | |||
3510 | << T << ArgRange; | |||
3511 | return true; | |||
3512 | } | |||
3513 | ||||
3514 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3515, __extension__ __PRETTY_FUNCTION__)) | |||
3515 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3515, __extension__ __PRETTY_FUNCTION__)); | |||
3516 | return false; | |||
3517 | } | |||
3518 | ||||
3519 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, | |||
3520 | SourceLocation Loc, | |||
3521 | SourceRange ArgRange, | |||
3522 | UnaryExprOrTypeTrait TraitKind) { | |||
3523 | // Invalid types must be hard errors for SFINAE in C++. | |||
3524 | if (S.LangOpts.CPlusPlus) | |||
3525 | return true; | |||
3526 | ||||
3527 | // C99 6.5.3.4p1: | |||
3528 | if (T->isFunctionType() && | |||
3529 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { | |||
3530 | // sizeof(function)/alignof(function) is allowed as an extension. | |||
3531 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) | |||
3532 | << TraitKind << ArgRange; | |||
3533 | return false; | |||
3534 | } | |||
3535 | ||||
3536 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where | |||
3537 | // this is an error (OpenCL v1.1 s6.3.k) | |||
3538 | if (T->isVoidType()) { | |||
3539 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type | |||
3540 | : diag::ext_sizeof_alignof_void_type; | |||
3541 | S.Diag(Loc, DiagID) << TraitKind << ArgRange; | |||
3542 | return false; | |||
3543 | } | |||
3544 | ||||
3545 | return true; | |||
3546 | } | |||
3547 | ||||
3548 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, | |||
3549 | SourceLocation Loc, | |||
3550 | SourceRange ArgRange, | |||
3551 | UnaryExprOrTypeTrait TraitKind) { | |||
3552 | // Reject sizeof(interface) and sizeof(interface<proto>) if the | |||
3553 | // runtime doesn't allow it. | |||
3554 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { | |||
3555 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) | |||
3556 | << T << (TraitKind == UETT_SizeOf) | |||
3557 | << ArgRange; | |||
3558 | return true; | |||
3559 | } | |||
3560 | ||||
3561 | return false; | |||
3562 | } | |||
3563 | ||||
3564 | /// \brief Check whether E is a pointer from a decayed array type (the decayed | |||
3565 | /// pointer type is equal to T) and emit a warning if it is. | |||
3566 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, | |||
3567 | Expr *E) { | |||
3568 | // Don't warn if the operation changed the type. | |||
3569 | if (T != E->getType()) | |||
3570 | return; | |||
3571 | ||||
3572 | // Now look for array decays. | |||
3573 | ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); | |||
3574 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) | |||
3575 | return; | |||
3576 | ||||
3577 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() | |||
3578 | << ICE->getType() | |||
3579 | << ICE->getSubExpr()->getType(); | |||
3580 | } | |||
3581 | ||||
3582 | /// \brief Check the constraints on expression operands to unary type expression | |||
3583 | /// and type traits. | |||
3584 | /// | |||
3585 | /// Completes any types necessary and validates the constraints on the operand | |||
3586 | /// expression. The logic mostly mirrors the type-based overload, but may modify | |||
3587 | /// the expression as it completes the type for that expression through template | |||
3588 | /// instantiation, etc. | |||
3589 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, | |||
3590 | UnaryExprOrTypeTrait ExprKind) { | |||
3591 | QualType ExprTy = E->getType(); | |||
3592 | assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void (0) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3592, __extension__ __PRETTY_FUNCTION__)); | |||
3593 | ||||
3594 | if (ExprKind == UETT_VecStep) | |||
3595 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), | |||
3596 | E->getSourceRange()); | |||
3597 | ||||
3598 | // Whitelist some types as extensions | |||
3599 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), | |||
3600 | E->getSourceRange(), ExprKind)) | |||
3601 | return false; | |||
3602 | ||||
3603 | // 'alignof' applied to an expression only requires the base element type of | |||
3604 | // the expression to be complete. 'sizeof' requires the expression's type to | |||
3605 | // be complete (and will attempt to complete it if it's an array of unknown | |||
3606 | // bound). | |||
3607 | if (ExprKind == UETT_AlignOf) { | |||
3608 | if (RequireCompleteType(E->getExprLoc(), | |||
3609 | Context.getBaseElementType(E->getType()), | |||
3610 | diag::err_sizeof_alignof_incomplete_type, ExprKind, | |||
3611 | E->getSourceRange())) | |||
3612 | return true; | |||
3613 | } else { | |||
3614 | if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, | |||
3615 | ExprKind, E->getSourceRange())) | |||
3616 | return true; | |||
3617 | } | |||
3618 | ||||
3619 | // Completing the expression's type may have changed it. | |||
3620 | ExprTy = E->getType(); | |||
3621 | assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void (0) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3621, __extension__ __PRETTY_FUNCTION__)); | |||
3622 | ||||
3623 | if (ExprTy->isFunctionType()) { | |||
3624 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) | |||
3625 | << ExprKind << E->getSourceRange(); | |||
3626 | return true; | |||
3627 | } | |||
3628 | ||||
3629 | // The operand for sizeof and alignof is in an unevaluated expression context, | |||
3630 | // so side effects could result in unintended consequences. | |||
3631 | if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && | |||
3632 | !inTemplateInstantiation() && E->HasSideEffects(Context, false)) | |||
3633 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | |||
3634 | ||||
3635 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), | |||
3636 | E->getSourceRange(), ExprKind)) | |||
3637 | return true; | |||
3638 | ||||
3639 | if (ExprKind == UETT_SizeOf) { | |||
3640 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | |||
3641 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { | |||
3642 | QualType OType = PVD->getOriginalType(); | |||
3643 | QualType Type = PVD->getType(); | |||
3644 | if (Type->isPointerType() && OType->isArrayType()) { | |||
3645 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) | |||
3646 | << Type << OType; | |||
3647 | Diag(PVD->getLocation(), diag::note_declared_at); | |||
3648 | } | |||
3649 | } | |||
3650 | } | |||
3651 | ||||
3652 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array | |||
3653 | // decays into a pointer and returns an unintended result. This is most | |||
3654 | // likely a typo for "sizeof(array) op x". | |||
3655 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { | |||
3656 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | |||
3657 | BO->getLHS()); | |||
3658 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | |||
3659 | BO->getRHS()); | |||
3660 | } | |||
3661 | } | |||
3662 | ||||
3663 | return false; | |||
3664 | } | |||
3665 | ||||
3666 | /// \brief Check the constraints on operands to unary expression and type | |||
3667 | /// traits. | |||
3668 | /// | |||
3669 | /// This will complete any types necessary, and validate the various constraints | |||
3670 | /// on those operands. | |||
3671 | /// | |||
3672 | /// The UsualUnaryConversions() function is *not* called by this routine. | |||
3673 | /// C99 6.3.2.1p[2-4] all state: | |||
3674 | /// Except when it is the operand of the sizeof operator ... | |||
3675 | /// | |||
3676 | /// C++ [expr.sizeof]p4 | |||
3677 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer | |||
3678 | /// standard conversions are not applied to the operand of sizeof. | |||
3679 | /// | |||
3680 | /// This policy is followed for all of the unary trait expressions. | |||
3681 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, | |||
3682 | SourceLocation OpLoc, | |||
3683 | SourceRange ExprRange, | |||
3684 | UnaryExprOrTypeTrait ExprKind) { | |||
3685 | if (ExprType->isDependentType()) | |||
3686 | return false; | |||
3687 | ||||
3688 | // C++ [expr.sizeof]p2: | |||
3689 | // When applied to a reference or a reference type, the result | |||
3690 | // is the size of the referenced type. | |||
3691 | // C++11 [expr.alignof]p3: | |||
3692 | // When alignof is applied to a reference type, the result | |||
3693 | // shall be the alignment of the referenced type. | |||
3694 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) | |||
3695 | ExprType = Ref->getPointeeType(); | |||
3696 | ||||
3697 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: | |||
3698 | // When alignof or _Alignof is applied to an array type, the result | |||
3699 | // is the alignment of the element type. | |||
3700 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) | |||
3701 | ExprType = Context.getBaseElementType(ExprType); | |||
3702 | ||||
3703 | if (ExprKind == UETT_VecStep) | |||
3704 | return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); | |||
3705 | ||||
3706 | // Whitelist some types as extensions | |||
3707 | if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, | |||
3708 | ExprKind)) | |||
3709 | return false; | |||
3710 | ||||
3711 | if (RequireCompleteType(OpLoc, ExprType, | |||
3712 | diag::err_sizeof_alignof_incomplete_type, | |||
3713 | ExprKind, ExprRange)) | |||
3714 | return true; | |||
3715 | ||||
3716 | if (ExprType->isFunctionType()) { | |||
3717 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) | |||
3718 | << ExprKind << ExprRange; | |||
3719 | return true; | |||
3720 | } | |||
3721 | ||||
3722 | if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, | |||
3723 | ExprKind)) | |||
3724 | return true; | |||
3725 | ||||
3726 | return false; | |||
3727 | } | |||
3728 | ||||
3729 | static bool CheckAlignOfExpr(Sema &S, Expr *E) { | |||
3730 | E = E->IgnoreParens(); | |||
3731 | ||||
3732 | // Cannot know anything else if the expression is dependent. | |||
3733 | if (E->isTypeDependent()) | |||
3734 | return false; | |||
3735 | ||||
3736 | if (E->getObjectKind() == OK_BitField) { | |||
3737 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) | |||
3738 | << 1 << E->getSourceRange(); | |||
3739 | return true; | |||
3740 | } | |||
3741 | ||||
3742 | ValueDecl *D = nullptr; | |||
3743 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
3744 | D = DRE->getDecl(); | |||
3745 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | |||
3746 | D = ME->getMemberDecl(); | |||
3747 | } | |||
3748 | ||||
3749 | // If it's a field, require the containing struct to have a | |||
3750 | // complete definition so that we can compute the layout. | |||
3751 | // | |||
3752 | // This can happen in C++11 onwards, either by naming the member | |||
3753 | // in a way that is not transformed into a member access expression | |||
3754 | // (in an unevaluated operand, for instance), or by naming the member | |||
3755 | // in a trailing-return-type. | |||
3756 | // | |||
3757 | // For the record, since __alignof__ on expressions is a GCC | |||
3758 | // extension, GCC seems to permit this but always gives the | |||
3759 | // nonsensical answer 0. | |||
3760 | // | |||
3761 | // We don't really need the layout here --- we could instead just | |||
3762 | // directly check for all the appropriate alignment-lowing | |||
3763 | // attributes --- but that would require duplicating a lot of | |||
3764 | // logic that just isn't worth duplicating for such a marginal | |||
3765 | // use-case. | |||
3766 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { | |||
3767 | // Fast path this check, since we at least know the record has a | |||
3768 | // definition if we can find a member of it. | |||
3769 | if (!FD->getParent()->isCompleteDefinition()) { | |||
3770 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) | |||
3771 | << E->getSourceRange(); | |||
3772 | return true; | |||
3773 | } | |||
3774 | ||||
3775 | // Otherwise, if it's a field, and the field doesn't have | |||
3776 | // reference type, then it must have a complete type (or be a | |||
3777 | // flexible array member, which we explicitly want to | |||
3778 | // white-list anyway), which makes the following checks trivial. | |||
3779 | if (!FD->getType()->isReferenceType()) | |||
3780 | return false; | |||
3781 | } | |||
3782 | ||||
3783 | return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); | |||
3784 | } | |||
3785 | ||||
3786 | bool Sema::CheckVecStepExpr(Expr *E) { | |||
3787 | E = E->IgnoreParens(); | |||
3788 | ||||
3789 | // Cannot know anything else if the expression is dependent. | |||
3790 | if (E->isTypeDependent()) | |||
3791 | return false; | |||
3792 | ||||
3793 | return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); | |||
3794 | } | |||
3795 | ||||
3796 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, | |||
3797 | CapturingScopeInfo *CSI) { | |||
3798 | assert(T->isVariablyModifiedType())(static_cast <bool> (T->isVariablyModifiedType()) ? void (0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3798, __extension__ __PRETTY_FUNCTION__)); | |||
3799 | assert(CSI != nullptr)(static_cast <bool> (CSI != nullptr) ? void (0) : __assert_fail ("CSI != nullptr", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3799, __extension__ __PRETTY_FUNCTION__)); | |||
3800 | ||||
3801 | // We're going to walk down into the type and look for VLA expressions. | |||
3802 | do { | |||
3803 | const Type *Ty = T.getTypePtr(); | |||
3804 | switch (Ty->getTypeClass()) { | |||
3805 | #define TYPE(Class, Base) | |||
3806 | #define ABSTRACT_TYPE(Class, Base) | |||
3807 | #define NON_CANONICAL_TYPE(Class, Base) | |||
3808 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: | |||
3809 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) | |||
3810 | #include "clang/AST/TypeNodes.def" | |||
3811 | T = QualType(); | |||
3812 | break; | |||
3813 | // These types are never variably-modified. | |||
3814 | case Type::Builtin: | |||
3815 | case Type::Complex: | |||
3816 | case Type::Vector: | |||
3817 | case Type::ExtVector: | |||
3818 | case Type::Record: | |||
3819 | case Type::Enum: | |||
3820 | case Type::Elaborated: | |||
3821 | case Type::TemplateSpecialization: | |||
3822 | case Type::ObjCObject: | |||
3823 | case Type::ObjCInterface: | |||
3824 | case Type::ObjCObjectPointer: | |||
3825 | case Type::ObjCTypeParam: | |||
3826 | case Type::Pipe: | |||
3827 | llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 3827); | |||
3828 | case Type::Adjusted: | |||
3829 | T = cast<AdjustedType>(Ty)->getOriginalType(); | |||
3830 | break; | |||
3831 | case Type::Decayed: | |||
3832 | T = cast<DecayedType>(Ty)->getPointeeType(); | |||
3833 | break; | |||
3834 | case Type::Pointer: | |||
3835 | T = cast<PointerType>(Ty)->getPointeeType(); | |||
3836 | break; | |||
3837 | case Type::BlockPointer: | |||
3838 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | |||
3839 | break; | |||
3840 | case Type::LValueReference: | |||
3841 | case Type::RValueReference: | |||
3842 | T = cast<ReferenceType>(Ty)->getPointeeType(); | |||
3843 | break; | |||
3844 | case Type::MemberPointer: | |||
3845 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | |||
3846 | break; | |||
3847 | case Type::ConstantArray: | |||
3848 | case Type::IncompleteArray: | |||
3849 | // Losing element qualification here is fine. | |||
3850 | T = cast<ArrayType>(Ty)->getElementType(); | |||
3851 | break; | |||
3852 | case Type::VariableArray: { | |||
3853 | // Losing element qualification here is fine. | |||
3854 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); | |||
3855 | ||||
3856 | // Unknown size indication requires no size computation. | |||
3857 | // Otherwise, evaluate and record it. | |||
3858 | if (auto Size = VAT->getSizeExpr()) { | |||
3859 | if (!CSI->isVLATypeCaptured(VAT)) { | |||
3860 | RecordDecl *CapRecord = nullptr; | |||
3861 | if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { | |||
3862 | CapRecord = LSI->Lambda; | |||
3863 | } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | |||
3864 | CapRecord = CRSI->TheRecordDecl; | |||
3865 | } | |||
3866 | if (CapRecord) { | |||
3867 | auto ExprLoc = Size->getExprLoc(); | |||
3868 | auto SizeType = Context.getSizeType(); | |||
3869 | // Build the non-static data member. | |||
3870 | auto Field = | |||
3871 | FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, | |||
3872 | /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, | |||
3873 | /*BW*/ nullptr, /*Mutable*/ false, | |||
3874 | /*InitStyle*/ ICIS_NoInit); | |||
3875 | Field->setImplicit(true); | |||
3876 | Field->setAccess(AS_private); | |||
3877 | Field->setCapturedVLAType(VAT); | |||
3878 | CapRecord->addDecl(Field); | |||
3879 | ||||
3880 | CSI->addVLATypeCapture(ExprLoc, SizeType); | |||
3881 | } | |||
3882 | } | |||
3883 | } | |||
3884 | T = VAT->getElementType(); | |||
3885 | break; | |||
3886 | } | |||
3887 | case Type::FunctionProto: | |||
3888 | case Type::FunctionNoProto: | |||
3889 | T = cast<FunctionType>(Ty)->getReturnType(); | |||
3890 | break; | |||
3891 | case Type::Paren: | |||
3892 | case Type::TypeOf: | |||
3893 | case Type::UnaryTransform: | |||
3894 | case Type::Attributed: | |||
3895 | case Type::SubstTemplateTypeParm: | |||
3896 | case Type::PackExpansion: | |||
3897 | // Keep walking after single level desugaring. | |||
3898 | T = T.getSingleStepDesugaredType(Context); | |||
3899 | break; | |||
3900 | case Type::Typedef: | |||
3901 | T = cast<TypedefType>(Ty)->desugar(); | |||
3902 | break; | |||
3903 | case Type::Decltype: | |||
3904 | T = cast<DecltypeType>(Ty)->desugar(); | |||
3905 | break; | |||
3906 | case Type::Auto: | |||
3907 | case Type::DeducedTemplateSpecialization: | |||
3908 | T = cast<DeducedType>(Ty)->getDeducedType(); | |||
3909 | break; | |||
3910 | case Type::TypeOfExpr: | |||
3911 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); | |||
3912 | break; | |||
3913 | case Type::Atomic: | |||
3914 | T = cast<AtomicType>(Ty)->getValueType(); | |||
3915 | break; | |||
3916 | } | |||
3917 | } while (!T.isNull() && T->isVariablyModifiedType()); | |||
3918 | } | |||
3919 | ||||
3920 | /// \brief Build a sizeof or alignof expression given a type operand. | |||
3921 | ExprResult | |||
3922 | Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, | |||
3923 | SourceLocation OpLoc, | |||
3924 | UnaryExprOrTypeTrait ExprKind, | |||
3925 | SourceRange R) { | |||
3926 | if (!TInfo) | |||
3927 | return ExprError(); | |||
3928 | ||||
3929 | QualType T = TInfo->getType(); | |||
3930 | ||||
3931 | if (!T->isDependentType() && | |||
3932 | CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) | |||
3933 | return ExprError(); | |||
3934 | ||||
3935 | if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { | |||
3936 | if (auto *TT = T->getAs<TypedefType>()) { | |||
3937 | for (auto I = FunctionScopes.rbegin(), | |||
3938 | E = std::prev(FunctionScopes.rend()); | |||
3939 | I != E; ++I) { | |||
3940 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | |||
3941 | if (CSI == nullptr) | |||
3942 | break; | |||
3943 | DeclContext *DC = nullptr; | |||
3944 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | |||
3945 | DC = LSI->CallOperator; | |||
3946 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | |||
3947 | DC = CRSI->TheCapturedDecl; | |||
3948 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | |||
3949 | DC = BSI->TheDecl; | |||
3950 | if (DC) { | |||
3951 | if (DC->containsDecl(TT->getDecl())) | |||
3952 | break; | |||
3953 | captureVariablyModifiedType(Context, T, CSI); | |||
3954 | } | |||
3955 | } | |||
3956 | } | |||
3957 | } | |||
3958 | ||||
3959 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | |||
3960 | return new (Context) UnaryExprOrTypeTraitExpr( | |||
3961 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); | |||
3962 | } | |||
3963 | ||||
3964 | /// \brief Build a sizeof or alignof expression given an expression | |||
3965 | /// operand. | |||
3966 | ExprResult | |||
3967 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, | |||
3968 | UnaryExprOrTypeTrait ExprKind) { | |||
3969 | ExprResult PE = CheckPlaceholderExpr(E); | |||
3970 | if (PE.isInvalid()) | |||
3971 | return ExprError(); | |||
3972 | ||||
3973 | E = PE.get(); | |||
3974 | ||||
3975 | // Verify that the operand is valid. | |||
3976 | bool isInvalid = false; | |||
3977 | if (E->isTypeDependent()) { | |||
3978 | // Delay type-checking for type-dependent expressions. | |||
3979 | } else if (ExprKind == UETT_AlignOf) { | |||
3980 | isInvalid = CheckAlignOfExpr(*this, E); | |||
3981 | } else if (ExprKind == UETT_VecStep) { | |||
3982 | isInvalid = CheckVecStepExpr(E); | |||
3983 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { | |||
3984 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); | |||
3985 | isInvalid = true; | |||
3986 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. | |||
3987 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; | |||
3988 | isInvalid = true; | |||
3989 | } else { | |||
3990 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); | |||
3991 | } | |||
3992 | ||||
3993 | if (isInvalid) | |||
3994 | return ExprError(); | |||
3995 | ||||
3996 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { | |||
3997 | PE = TransformToPotentiallyEvaluated(E); | |||
3998 | if (PE.isInvalid()) return ExprError(); | |||
3999 | E = PE.get(); | |||
4000 | } | |||
4001 | ||||
4002 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | |||
4003 | return new (Context) UnaryExprOrTypeTraitExpr( | |||
4004 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); | |||
4005 | } | |||
4006 | ||||
4007 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c | |||
4008 | /// expr and the same for @c alignof and @c __alignof | |||
4009 | /// Note that the ArgRange is invalid if isType is false. | |||
4010 | ExprResult | |||
4011 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, | |||
4012 | UnaryExprOrTypeTrait ExprKind, bool IsType, | |||
4013 | void *TyOrEx, SourceRange ArgRange) { | |||
4014 | // If error parsing type, ignore. | |||
4015 | if (!TyOrEx) return ExprError(); | |||
4016 | ||||
4017 | if (IsType) { | |||
4018 | TypeSourceInfo *TInfo; | |||
4019 | (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); | |||
4020 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); | |||
4021 | } | |||
4022 | ||||
4023 | Expr *ArgEx = (Expr *)TyOrEx; | |||
4024 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); | |||
4025 | return Result; | |||
4026 | } | |||
4027 | ||||
4028 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, | |||
4029 | bool IsReal) { | |||
4030 | if (V.get()->isTypeDependent()) | |||
4031 | return S.Context.DependentTy; | |||
4032 | ||||
4033 | // _Real and _Imag are only l-values for normal l-values. | |||
4034 | if (V.get()->getObjectKind() != OK_Ordinary) { | |||
4035 | V = S.DefaultLvalueConversion(V.get()); | |||
4036 | if (V.isInvalid()) | |||
4037 | return QualType(); | |||
4038 | } | |||
4039 | ||||
4040 | // These operators return the element type of a complex type. | |||
4041 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) | |||
4042 | return CT->getElementType(); | |||
4043 | ||||
4044 | // Otherwise they pass through real integer and floating point types here. | |||
4045 | if (V.get()->getType()->isArithmeticType()) | |||
4046 | return V.get()->getType(); | |||
4047 | ||||
4048 | // Test for placeholders. | |||
4049 | ExprResult PR = S.CheckPlaceholderExpr(V.get()); | |||
4050 | if (PR.isInvalid()) return QualType(); | |||
4051 | if (PR.get() != V.get()) { | |||
4052 | V = PR; | |||
4053 | return CheckRealImagOperand(S, V, Loc, IsReal); | |||
4054 | } | |||
4055 | ||||
4056 | // Reject anything else. | |||
4057 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() | |||
4058 | << (IsReal ? "__real" : "__imag"); | |||
4059 | return QualType(); | |||
4060 | } | |||
4061 | ||||
4062 | ||||
4063 | ||||
4064 | ExprResult | |||
4065 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, | |||
4066 | tok::TokenKind Kind, Expr *Input) { | |||
4067 | UnaryOperatorKind Opc; | |||
4068 | switch (Kind) { | |||
4069 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 4069); | |||
4070 | case tok::plusplus: Opc = UO_PostInc; break; | |||
4071 | case tok::minusminus: Opc = UO_PostDec; break; | |||
4072 | } | |||
4073 | ||||
4074 | // Since this might is a postfix expression, get rid of ParenListExprs. | |||
4075 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); | |||
4076 | if (Result.isInvalid()) return ExprError(); | |||
4077 | Input = Result.get(); | |||
4078 | ||||
4079 | return BuildUnaryOp(S, OpLoc, Opc, Input); | |||
4080 | } | |||
4081 | ||||
4082 | /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. | |||
4083 | /// | |||
4084 | /// \return true on error | |||
4085 | static bool checkArithmeticOnObjCPointer(Sema &S, | |||
4086 | SourceLocation opLoc, | |||
4087 | Expr *op) { | |||
4088 | assert(op->getType()->isObjCObjectPointerType())(static_cast <bool> (op->getType()->isObjCObjectPointerType ()) ? void (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 4088, __extension__ __PRETTY_FUNCTION__)); | |||
4089 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && | |||
4090 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) | |||
4091 | return false; | |||
4092 | ||||
4093 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) | |||
4094 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() | |||
4095 | << op->getSourceRange(); | |||
4096 | return true; | |||
4097 | } | |||
4098 | ||||
4099 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { | |||
4100 | auto *BaseNoParens = Base->IgnoreParens(); | |||
4101 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) | |||
4102 | return MSProp->getPropertyDecl()->getType()->isArrayType(); | |||
4103 | return isa<MSPropertySubscriptExpr>(BaseNoParens); | |||
4104 | } | |||
4105 | ||||
4106 | ExprResult | |||
4107 | Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, | |||
4108 | Expr *idx, SourceLocation rbLoc) { | |||
4109 | if (base && !base->getType().isNull() && | |||
4110 | base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) | |||
4111 | return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), | |||
4112 | /*Length=*/nullptr, rbLoc); | |||
4113 | ||||
4114 | // Since this might be a postfix expression, get rid of ParenListExprs. | |||
4115 | if (isa<ParenListExpr>(base)) { | |||
4116 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); | |||
4117 | if (result.isInvalid()) return ExprError(); | |||
4118 | base = result.get(); | |||
4119 | } | |||
4120 | ||||
4121 | // Handle any non-overload placeholder types in the base and index | |||
4122 | // expressions. We can't handle overloads here because the other | |||
4123 | // operand might be an overloadable type, in which case the overload | |||
4124 | // resolution for the operator overload should get the first crack | |||
4125 | // at the overload. | |||
4126 | bool IsMSPropertySubscript = false; | |||
4127 | if (base->getType()->isNonOverloadPlaceholderType()) { | |||
4128 | IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); | |||
4129 | if (!IsMSPropertySubscript) { | |||
4130 | ExprResult result = CheckPlaceholderExpr(base); | |||
4131 | if (result.isInvalid()) | |||
4132 | return ExprError(); | |||
4133 | base = result.get(); | |||
4134 | } | |||
4135 | } | |||
4136 | if (idx->getType()->isNonOverloadPlaceholderType()) { | |||
4137 | ExprResult result = CheckPlaceholderExpr(idx); | |||
4138 | if (result.isInvalid()) return ExprError(); | |||
4139 | idx = result.get(); | |||
4140 | } | |||
4141 | ||||
4142 | // Build an unanalyzed expression if either operand is type-dependent. | |||
4143 | if (getLangOpts().CPlusPlus && | |||
4144 | (base->isTypeDependent() || idx->isTypeDependent())) { | |||
4145 | return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, | |||
4146 | VK_LValue, OK_Ordinary, rbLoc); | |||
4147 | } | |||
4148 | ||||
4149 | // MSDN, property (C++) | |||
4150 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx | |||
4151 | // This attribute can also be used in the declaration of an empty array in a | |||
4152 | // class or structure definition. For example: | |||
4153 | // __declspec(property(get=GetX, put=PutX)) int x[]; | |||
4154 | // The above statement indicates that x[] can be used with one or more array | |||
4155 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), | |||
4156 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); | |||
4157 | if (IsMSPropertySubscript) { | |||
4158 | // Build MS property subscript expression if base is MS property reference | |||
4159 | // or MS property subscript. | |||
4160 | return new (Context) MSPropertySubscriptExpr( | |||
4161 | base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); | |||
4162 | } | |||
4163 | ||||
4164 | // Use C++ overloaded-operator rules if either operand has record | |||
4165 | // type. The spec says to do this if either type is *overloadable*, | |||
4166 | // but enum types can't declare subscript operators or conversion | |||
4167 | // operators, so there's nothing interesting for overload resolution | |||
4168 | // to do if there aren't any record types involved. | |||
4169 | // | |||
4170 | // ObjC pointers have their own subscripting logic that is not tied | |||
4171 | // to overload resolution and so should not take this path. | |||
4172 | if (getLangOpts().CPlusPlus && | |||
4173 | (base->getType()->isRecordType() || | |||
4174 | (!base->getType()->isObjCObjectPointerType() && | |||
4175 | idx->getType()->isRecordType()))) { | |||
4176 | return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); | |||
4177 | } | |||
4178 | ||||
4179 | return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); | |||
4180 | } | |||
4181 | ||||
4182 | ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, | |||
4183 | Expr *LowerBound, | |||
4184 | SourceLocation ColonLoc, Expr *Length, | |||
4185 | SourceLocation RBLoc) { | |||
4186 | if (Base->getType()->isPlaceholderType() && | |||
4187 | !Base->getType()->isSpecificPlaceholderType( | |||
4188 | BuiltinType::OMPArraySection)) { | |||
4189 | ExprResult Result = CheckPlaceholderExpr(Base); | |||
4190 | if (Result.isInvalid()) | |||
4191 | return ExprError(); | |||
4192 | Base = Result.get(); | |||
4193 | } | |||
4194 | if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { | |||
4195 | ExprResult Result = CheckPlaceholderExpr(LowerBound); | |||
4196 | if (Result.isInvalid()) | |||
4197 | return ExprError(); | |||
4198 | Result = DefaultLvalueConversion(Result.get()); | |||
4199 | if (Result.isInvalid()) | |||
4200 | return ExprError(); | |||
4201 | LowerBound = Result.get(); | |||
4202 | } | |||
4203 | if (Length && Length->getType()->isNonOverloadPlaceholderType()) { | |||
4204 | ExprResult Result = CheckPlaceholderExpr(Length); | |||
4205 | if (Result.isInvalid()) | |||
4206 | return ExprError(); | |||
4207 | Result = DefaultLvalueConversion(Result.get()); | |||
4208 | if (Result.isInvalid()) | |||
4209 | return ExprError(); | |||
4210 | Length = Result.get(); | |||
4211 | } | |||
4212 | ||||
4213 | // Build an unanalyzed expression if either operand is type-dependent. | |||
4214 | if (Base->isTypeDependent() || | |||
4215 | (LowerBound && | |||
4216 | (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || | |||
4217 | (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { | |||
4218 | return new (Context) | |||
4219 | OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, | |||
4220 | VK_LValue, OK_Ordinary, ColonLoc, RBLoc); | |||
4221 | } | |||
4222 | ||||
4223 | // Perform default conversions. | |||
4224 | QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); | |||
4225 | QualType ResultTy; | |||
4226 | if (OriginalTy->isAnyPointerType()) { | |||
4227 | ResultTy = OriginalTy->getPointeeType(); | |||
4228 | } else if (OriginalTy->isArrayType()) { | |||
4229 | ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); | |||
4230 | } else { | |||
4231 | return ExprError( | |||
4232 | Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) | |||
4233 | << Base->getSourceRange()); | |||
4234 | } | |||
4235 | // C99 6.5.2.1p1 | |||
4236 | if (LowerBound) { | |||
4237 | auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), | |||
4238 | LowerBound); | |||
4239 | if (Res.isInvalid()) | |||
4240 | return ExprError(Diag(LowerBound->getExprLoc(), | |||
4241 | diag::err_omp_typecheck_section_not_integer) | |||
4242 | << 0 << LowerBound->getSourceRange()); | |||
4243 | LowerBound = Res.get(); | |||
4244 | ||||
4245 | if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
4246 | LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
4247 | Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) | |||
4248 | << 0 << LowerBound->getSourceRange(); | |||
4249 | } | |||
4250 | if (Length) { | |||
4251 | auto Res = | |||
4252 | PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); | |||
4253 | if (Res.isInvalid()) | |||
4254 | return ExprError(Diag(Length->getExprLoc(), | |||
4255 | diag::err_omp_typecheck_section_not_integer) | |||
4256 | << 1 << Length->getSourceRange()); | |||
4257 | Length = Res.get(); | |||
4258 | ||||
4259 | if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
4260 | Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
4261 | Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) | |||
4262 | << 1 << Length->getSourceRange(); | |||
4263 | } | |||
4264 | ||||
4265 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | |||
4266 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | |||
4267 | // type. Note that functions are not objects, and that (in C99 parlance) | |||
4268 | // incomplete types are not object types. | |||
4269 | if (ResultTy->isFunctionType()) { | |||
4270 | Diag(Base->getExprLoc(), diag::err_omp_section_function_type) | |||
4271 | << ResultTy << Base->getSourceRange(); | |||
4272 | return ExprError(); | |||
4273 | } | |||
4274 | ||||
4275 | if (RequireCompleteType(Base->getExprLoc(), ResultTy, | |||
4276 | diag::err_omp_section_incomplete_type, Base)) | |||
4277 | return ExprError(); | |||
4278 | ||||
4279 | if (LowerBound && !OriginalTy->isAnyPointerType()) { | |||
4280 | llvm::APSInt LowerBoundValue; | |||
4281 | if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { | |||
4282 | // OpenMP 4.5, [2.4 Array Sections] | |||
4283 | // The array section must be a subset of the original array. | |||
4284 | if (LowerBoundValue.isNegative()) { | |||
4285 | Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) | |||
4286 | << LowerBound->getSourceRange(); | |||
4287 | return ExprError(); | |||
4288 | } | |||
4289 | } | |||
4290 | } | |||
4291 | ||||
4292 | if (Length) { | |||
4293 | llvm::APSInt LengthValue; | |||
4294 | if (Length->EvaluateAsInt(LengthValue, Context)) { | |||
4295 | // OpenMP 4.5, [2.4 Array Sections] | |||
4296 | // The length must evaluate to non-negative integers. | |||
4297 | if (LengthValue.isNegative()) { | |||
4298 | Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) | |||
4299 | << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) | |||
4300 | << Length->getSourceRange(); | |||
4301 | return ExprError(); | |||
4302 | } | |||
4303 | } | |||
4304 | } else if (ColonLoc.isValid() && | |||
4305 | (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && | |||
4306 | !OriginalTy->isVariableArrayType()))) { | |||
4307 | // OpenMP 4.5, [2.4 Array Sections] | |||
4308 | // When the size of the array dimension is not known, the length must be | |||
4309 | // specified explicitly. | |||
4310 | Diag(ColonLoc, diag::err_omp_section_length_undefined) | |||
4311 | << (!OriginalTy.isNull() && OriginalTy->isArrayType()); | |||
4312 | return ExprError(); | |||
4313 | } | |||
4314 | ||||
4315 | if (!Base->getType()->isSpecificPlaceholderType( | |||
4316 | BuiltinType::OMPArraySection)) { | |||
4317 | ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); | |||
4318 | if (Result.isInvalid()) | |||
4319 | return ExprError(); | |||
4320 | Base = Result.get(); | |||
4321 | } | |||
4322 | return new (Context) | |||
4323 | OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, | |||
4324 | VK_LValue, OK_Ordinary, ColonLoc, RBLoc); | |||
4325 | } | |||
4326 | ||||
4327 | ExprResult | |||
4328 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, | |||
4329 | Expr *Idx, SourceLocation RLoc) { | |||
4330 | Expr *LHSExp = Base; | |||
4331 | Expr *RHSExp = Idx; | |||
4332 | ||||
4333 | ExprValueKind VK = VK_LValue; | |||
4334 | ExprObjectKind OK = OK_Ordinary; | |||
4335 | ||||
4336 | // Per C++ core issue 1213, the result is an xvalue if either operand is | |||
4337 | // a non-lvalue array, and an lvalue otherwise. | |||
4338 | if (getLangOpts().CPlusPlus11 && | |||
4339 | ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || | |||
4340 | (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) | |||
4341 | VK = VK_XValue; | |||
4342 | ||||
4343 | // Perform default conversions. | |||
4344 | if (!LHSExp->getType()->getAs<VectorType>()) { | |||
4345 | ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); | |||
4346 | if (Result.isInvalid()) | |||
4347 | return ExprError(); | |||
4348 | LHSExp = Result.get(); | |||
4349 | } | |||
4350 | ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); | |||
4351 | if (Result.isInvalid()) | |||
4352 | return ExprError(); | |||
4353 | RHSExp = Result.get(); | |||
4354 | ||||
4355 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); | |||
4356 | ||||
4357 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent | |||
4358 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be | |||
4359 | // in the subscript position. As a result, we need to derive the array base | |||
4360 | // and index from the expression types. | |||
4361 | Expr *BaseExpr, *IndexExpr; | |||
4362 | QualType ResultType; | |||
4363 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { | |||
4364 | BaseExpr = LHSExp; | |||
4365 | IndexExpr = RHSExp; | |||
4366 | ResultType = Context.DependentTy; | |||
4367 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { | |||
4368 | BaseExpr = LHSExp; | |||
4369 | IndexExpr = RHSExp; | |||
4370 | ResultType = PTy->getPointeeType(); | |||
4371 | } else if (const ObjCObjectPointerType *PTy = | |||
4372 | LHSTy->getAs<ObjCObjectPointerType>()) { | |||
4373 | BaseExpr = LHSExp; | |||
4374 | IndexExpr = RHSExp; | |||
4375 | ||||
4376 | // Use custom logic if this should be the pseudo-object subscript | |||
4377 | // expression. | |||
4378 | if (!LangOpts.isSubscriptPointerArithmetic()) | |||
4379 | return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, | |||
4380 | nullptr); | |||
4381 | ||||
4382 | ResultType = PTy->getPointeeType(); | |||
4383 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { | |||
4384 | // Handle the uncommon case of "123[Ptr]". | |||
4385 | BaseExpr = RHSExp; | |||
4386 | IndexExpr = LHSExp; | |||
4387 | ResultType = PTy->getPointeeType(); | |||
4388 | } else if (const ObjCObjectPointerType *PTy = | |||
4389 | RHSTy->getAs<ObjCObjectPointerType>()) { | |||
4390 | // Handle the uncommon case of "123[Ptr]". | |||
4391 | BaseExpr = RHSExp; | |||
4392 | IndexExpr = LHSExp; | |||
4393 | ResultType = PTy->getPointeeType(); | |||
4394 | if (!LangOpts.isSubscriptPointerArithmetic()) { | |||
4395 | Diag(LLoc, diag::err_subscript_nonfragile_interface) | |||
4396 | << ResultType << BaseExpr->getSourceRange(); | |||
4397 | return ExprError(); | |||
4398 | } | |||
4399 | } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { | |||
4400 | BaseExpr = LHSExp; // vectors: V[123] | |||
4401 | IndexExpr = RHSExp; | |||
4402 | VK = LHSExp->getValueKind(); | |||
4403 | if (VK != VK_RValue) | |||
4404 | OK = OK_VectorComponent; | |||
4405 | ||||
4406 | ResultType = VTy->getElementType(); | |||
4407 | QualType BaseType = BaseExpr->getType(); | |||
4408 | Qualifiers BaseQuals = BaseType.getQualifiers(); | |||
4409 | Qualifiers MemberQuals = ResultType.getQualifiers(); | |||
4410 | Qualifiers Combined = BaseQuals + MemberQuals; | |||
4411 | if (Combined != MemberQuals) | |||
4412 | ResultType = Context.getQualifiedType(ResultType, Combined); | |||
4413 | } else if (LHSTy->isArrayType()) { | |||
4414 | // If we see an array that wasn't promoted by | |||
4415 | // DefaultFunctionArrayLvalueConversion, it must be an array that | |||
4416 | // wasn't promoted because of the C90 rule that doesn't | |||
4417 | // allow promoting non-lvalue arrays. Warn, then | |||
4418 | // force the promotion here. | |||
4419 | Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << | |||
4420 | LHSExp->getSourceRange(); | |||
4421 | LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), | |||
4422 | CK_ArrayToPointerDecay).get(); | |||
4423 | LHSTy = LHSExp->getType(); | |||
4424 | ||||
4425 | BaseExpr = LHSExp; | |||
4426 | IndexExpr = RHSExp; | |||
4427 | ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); | |||
4428 | } else if (RHSTy->isArrayType()) { | |||
4429 | // Same as previous, except for 123[f().a] case | |||
4430 | Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << | |||
4431 | RHSExp->getSourceRange(); | |||
4432 | RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), | |||
4433 | CK_ArrayToPointerDecay).get(); | |||
4434 | RHSTy = RHSExp->getType(); | |||
4435 | ||||
4436 | BaseExpr = RHSExp; | |||
4437 | IndexExpr = LHSExp; | |||
4438 | ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); | |||
4439 | } else { | |||
4440 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) | |||
4441 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | |||
4442 | } | |||
4443 | // C99 6.5.2.1p1 | |||
4444 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) | |||
4445 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) | |||
4446 | << IndexExpr->getSourceRange()); | |||
4447 | ||||
4448 | if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
4449 | IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
4450 | && !IndexExpr->isTypeDependent()) | |||
4451 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); | |||
4452 | ||||
4453 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | |||
4454 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | |||
4455 | // type. Note that Functions are not objects, and that (in C99 parlance) | |||
4456 | // incomplete types are not object types. | |||
4457 | if (ResultType->isFunctionType()) { | |||
4458 | Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) | |||
4459 | << ResultType << BaseExpr->getSourceRange(); | |||
4460 | return ExprError(); | |||
4461 | } | |||
4462 | ||||
4463 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { | |||
4464 | // GNU extension: subscripting on pointer to void | |||
4465 | Diag(LLoc, diag::ext_gnu_subscript_void_type) | |||
4466 | << BaseExpr->getSourceRange(); | |||
4467 | ||||
4468 | // C forbids expressions of unqualified void type from being l-values. | |||
4469 | // See IsCForbiddenLValueType. | |||
4470 | if (!ResultType.hasQualifiers()) VK = VK_RValue; | |||
4471 | } else if (!ResultType->isDependentType() && | |||
4472 | RequireCompleteType(LLoc, ResultType, | |||
4473 | diag::err_subscript_incomplete_type, BaseExpr)) | |||
4474 | return ExprError(); | |||
4475 | ||||
4476 | assert(VK == VK_RValue || LangOpts.CPlusPlus ||(static_cast <bool> (VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 4477, __extension__ __PRETTY_FUNCTION__)) | |||
4477 | !ResultType.isCForbiddenLValueType())(static_cast <bool> (VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 4477, __extension__ __PRETTY_FUNCTION__)); | |||
4478 | ||||
4479 | return new (Context) | |||
4480 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); | |||
4481 | } | |||
4482 | ||||
4483 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, | |||
4484 | ParmVarDecl *Param) { | |||
4485 | if (Param->hasUnparsedDefaultArg()) { | |||
4486 | Diag(CallLoc, | |||
4487 | diag::err_use_of_default_argument_to_function_declared_later) << | |||
4488 | FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); | |||
4489 | Diag(UnparsedDefaultArgLocs[Param], | |||
4490 | diag::note_default_argument_declared_here); | |||
4491 | return true; | |||
4492 | } | |||
4493 | ||||
4494 | if (Param->hasUninstantiatedDefaultArg()) { | |||
4495 | Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); | |||
4496 | ||||
4497 | EnterExpressionEvaluationContext EvalContext( | |||
4498 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | |||
4499 | ||||
4500 | // Instantiate the expression. | |||
4501 | // | |||
4502 | // FIXME: Pass in a correct Pattern argument, otherwise | |||
4503 | // getTemplateInstantiationArgs uses the lexical context of FD, e.g. | |||
4504 | // | |||
4505 | // template<typename T> | |||
4506 | // struct A { | |||
4507 | // static int FooImpl(); | |||
4508 | // | |||
4509 | // template<typename Tp> | |||
4510 | // // bug: default argument A<T>::FooImpl() is evaluated with 2-level | |||
4511 | // // template argument list [[T], [Tp]], should be [[Tp]]. | |||
4512 | // friend A<Tp> Foo(int a); | |||
4513 | // }; | |||
4514 | // | |||
4515 | // template<typename T> | |||
4516 | // A<T> Foo(int a = A<T>::FooImpl()); | |||
4517 | MultiLevelTemplateArgumentList MutiLevelArgList | |||
4518 | = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); | |||
4519 | ||||
4520 | InstantiatingTemplate Inst(*this, CallLoc, Param, | |||
4521 | MutiLevelArgList.getInnermost()); | |||
4522 | if (Inst.isInvalid()) | |||
4523 | return true; | |||
4524 | if (Inst.isAlreadyInstantiating()) { | |||
4525 | Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; | |||
4526 | Param->setInvalidDecl(); | |||
4527 | return true; | |||
4528 | } | |||
4529 | ||||
4530 | ExprResult Result; | |||
4531 | { | |||
4532 | // C++ [dcl.fct.default]p5: | |||
4533 | // The names in the [default argument] expression are bound, and | |||
4534 | // the semantic constraints are checked, at the point where the | |||
4535 | // default argument expression appears. | |||
4536 | ContextRAII SavedContext(*this, FD); | |||
4537 | LocalInstantiationScope Local(*this); | |||
4538 | Result = SubstInitializer(UninstExpr, MutiLevelArgList, | |||
4539 | /*DirectInit*/false); | |||
4540 | } | |||
4541 | if (Result.isInvalid()) | |||
4542 | return true; | |||
4543 | ||||
4544 | // Check the expression as an initializer for the parameter. | |||
4545 | InitializedEntity Entity | |||
4546 | = InitializedEntity::InitializeParameter(Context, Param); | |||
4547 | InitializationKind Kind | |||
4548 | = InitializationKind::CreateCopy(Param->getLocation(), | |||
4549 | /*FIXME:EqualLoc*/UninstExpr->getLocStart()); | |||
4550 | Expr *ResultE = Result.getAs<Expr>(); | |||
4551 | ||||
4552 | InitializationSequence InitSeq(*this, Entity, Kind, ResultE); | |||
4553 | Result = InitSeq.Perform(*this, Entity, Kind, ResultE); | |||
4554 | if (Result.isInvalid()) | |||
4555 | return true; | |||
4556 | ||||
4557 | Result = ActOnFinishFullExpr(Result.getAs<Expr>(), | |||
4558 | Param->getOuterLocStart()); | |||
4559 | if (Result.isInvalid()) | |||
4560 | return true; | |||
4561 | ||||
4562 | // Remember the instantiated default argument. | |||
4563 | Param->setDefaultArg(Result.getAs<Expr>()); | |||
4564 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
4565 | L->DefaultArgumentInstantiated(Param); | |||
4566 | } | |||
4567 | } | |||
4568 | ||||
4569 | // If the default argument expression is not set yet, we are building it now. | |||
4570 | if (!Param->hasInit()) { | |||
4571 | Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; | |||
4572 | Param->setInvalidDecl(); | |||
4573 | return true; | |||
4574 | } | |||
4575 | ||||
4576 | // If the default expression creates temporaries, we need to | |||
4577 | // push them to the current stack of expression temporaries so they'll | |||
4578 | // be properly destroyed. | |||
4579 | // FIXME: We should really be rebuilding the default argument with new | |||
4580 | // bound temporaries; see the comment in PR5810. | |||
4581 | // We don't need to do that with block decls, though, because | |||
4582 | // blocks in default argument expression can never capture anything. | |||
4583 | if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { | |||
4584 | // Set the "needs cleanups" bit regardless of whether there are | |||
4585 | // any explicit objects. | |||
4586 | Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); | |||
4587 | ||||
4588 | // Append all the objects to the cleanup list. Right now, this | |||
4589 | // should always be a no-op, because blocks in default argument | |||
4590 | // expressions should never be able to capture anything. | |||
4591 | 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?\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 4592, __extension__ __PRETTY_FUNCTION__)) | |||
4592 | "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?\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 4592, __extension__ __PRETTY_FUNCTION__)); | |||
4593 | } | |||
4594 | ||||
4595 | // We already type-checked the argument, so we know it works. | |||
4596 | // Just mark all of the declarations in this potentially-evaluated expression | |||
4597 | // as being "referenced". | |||
4598 | MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), | |||
4599 | /*SkipLocalVariables=*/true); | |||
4600 | return false; | |||
4601 | } | |||
4602 | ||||
4603 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, | |||
4604 | FunctionDecl *FD, ParmVarDecl *Param) { | |||
4605 | if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) | |||
4606 | return ExprError(); | |||
4607 | return CXXDefaultArgExpr::Create(Context, CallLoc, Param); | |||
4608 | } | |||
4609 | ||||
4610 | Sema::VariadicCallType | |||
4611 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, | |||
4612 | Expr *Fn) { | |||
4613 | if (Proto && Proto->isVariadic()) { | |||
4614 | if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) | |||
4615 | return VariadicConstructor; | |||
4616 | else if (Fn && Fn->getType()->isBlockPointerType()) | |||
4617 | return VariadicBlock; | |||
4618 | else if (FDecl) { | |||
4619 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | |||
4620 | if (Method->isInstance()) | |||
4621 | return VariadicMethod; | |||
4622 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) | |||
4623 | return VariadicMethod; | |||
4624 | return VariadicFunction; | |||
4625 | } | |||
4626 | return VariadicDoesNotApply; | |||
4627 | } | |||
4628 | ||||
4629 | namespace { | |||
4630 | class FunctionCallCCC : public FunctionCallFilterCCC { | |||
4631 | public: | |||
4632 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, | |||
4633 | unsigned NumArgs, MemberExpr *ME) | |||
4634 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), | |||
4635 | FunctionName(FuncName) {} | |||
4636 | ||||
4637 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
4638 | if (!candidate.getCorrectionSpecifier() || | |||
4639 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { | |||
4640 | return false; | |||
4641 | } | |||
4642 | ||||
4643 | return FunctionCallFilterCCC::ValidateCandidate(candidate); | |||
4644 | } | |||
4645 | ||||
4646 | private: | |||
4647 | const IdentifierInfo *const FunctionName; | |||
4648 | }; | |||
4649 | } | |||
4650 | ||||
4651 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, | |||
4652 | FunctionDecl *FDecl, | |||
4653 | ArrayRef<Expr *> Args) { | |||
4654 | MemberExpr *ME = dyn_cast<MemberExpr>(Fn); | |||
4655 | DeclarationName FuncName = FDecl->getDeclName(); | |||
4656 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); | |||
4657 | ||||
4658 | if (TypoCorrection Corrected = S.CorrectTypo( | |||
4659 | DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, | |||
4660 | S.getScopeForContext(S.CurContext), nullptr, | |||
4661 | llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), | |||
4662 | Args.size(), ME), | |||
4663 | Sema::CTK_ErrorRecovery)) { | |||
4664 | if (NamedDecl *ND = Corrected.getFoundDecl()) { | |||
4665 | if (Corrected.isOverloaded()) { | |||
4666 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); | |||
4667 | OverloadCandidateSet::iterator Best; | |||
4668 | for (NamedDecl *CD : Corrected) { | |||
4669 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | |||
4670 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, | |||
4671 | OCS); | |||
4672 | } | |||
4673 | switch (OCS.BestViableFunction(S, NameLoc, Best)) { | |||
4674 | case OR_Success: | |||
4675 | ND = Best->FoundDecl; | |||
4676 | Corrected.setCorrectionDecl(ND); | |||
4677 | break; | |||
4678 | default: | |||
4679 | break; | |||
4680 | } | |||
4681 | } | |||
4682 | ND = ND->getUnderlyingDecl(); | |||
4683 | if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) | |||
4684 | return Corrected; | |||
4685 | } | |||
4686 | } | |||
4687 | return TypoCorrection(); | |||
4688 | } | |||
4689 | ||||
4690 | /// ConvertArgumentsForCall - Converts the arguments specified in | |||
4691 | /// Args/NumArgs to the parameter types of the function FDecl with | |||
4692 | /// function prototype Proto. Call is the call expression itself, and | |||
4693 | /// Fn is the function expression. For a C++ member function, this | |||
4694 | /// routine does not attempt to convert the object argument. Returns | |||
4695 | /// true if the call is ill-formed. | |||
4696 | bool | |||
4697 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, | |||
4698 | FunctionDecl *FDecl, | |||
4699 | const FunctionProtoType *Proto, | |||
4700 | ArrayRef<Expr *> Args, | |||
4701 | SourceLocation RParenLoc, | |||
4702 | bool IsExecConfig) { | |||
4703 | // Bail out early if calling a builtin with custom typechecking. | |||
4704 | if (FDecl) | |||
4705 | if (unsigned ID = FDecl->getBuiltinID()) | |||
4706 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) | |||
4707 | return false; | |||
4708 | ||||
4709 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by | |||
4710 | // assignment, to the types of the corresponding parameter, ... | |||
4711 | unsigned NumParams = Proto->getNumParams(); | |||
4712 | bool Invalid = false; | |||
4713 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; | |||
4714 | unsigned FnKind = Fn->getType()->isBlockPointerType() | |||
4715 | ? 1 /* block */ | |||
4716 | : (IsExecConfig ? 3 /* kernel function (exec config) */ | |||
4717 | : 0 /* function */); | |||
4718 | ||||
4719 | // If too few arguments are available (and we don't have default | |||
4720 | // arguments for the remaining parameters), don't make the call. | |||
4721 | if (Args.size() < NumParams) { | |||
4722 | if (Args.size() < MinArgs) { | |||
4723 | TypoCorrection TC; | |||
4724 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | |||
4725 | unsigned diag_id = | |||
4726 | MinArgs == NumParams && !Proto->isVariadic() | |||
4727 | ? diag::err_typecheck_call_too_few_args_suggest | |||
4728 | : diag::err_typecheck_call_too_few_args_at_least_suggest; | |||
4729 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs | |||
4730 | << static_cast<unsigned>(Args.size()) | |||
4731 | << TC.getCorrectionRange()); | |||
4732 | } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) | |||
4733 | Diag(RParenLoc, | |||
4734 | MinArgs == NumParams && !Proto->isVariadic() | |||
4735 | ? diag::err_typecheck_call_too_few_args_one | |||
4736 | : diag::err_typecheck_call_too_few_args_at_least_one) | |||
4737 | << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); | |||
4738 | else | |||
4739 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() | |||
4740 | ? diag::err_typecheck_call_too_few_args | |||
4741 | : diag::err_typecheck_call_too_few_args_at_least) | |||
4742 | << FnKind << MinArgs << static_cast<unsigned>(Args.size()) | |||
4743 | << Fn->getSourceRange(); | |||
4744 | ||||
4745 | // Emit the location of the prototype. | |||
4746 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | |||
4747 | Diag(FDecl->getLocStart(), diag::note_callee_decl) | |||
4748 | << FDecl; | |||
4749 | ||||
4750 | return true; | |||
4751 | } | |||
4752 | Call->setNumArgs(Context, NumParams); | |||
4753 | } | |||
4754 | ||||
4755 | // If too many are passed and not variadic, error on the extras and drop | |||
4756 | // them. | |||
4757 | if (Args.size() > NumParams) { | |||
4758 | if (!Proto->isVariadic()) { | |||
4759 | TypoCorrection TC; | |||
4760 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | |||
4761 | unsigned diag_id = | |||
4762 | MinArgs == NumParams && !Proto->isVariadic() | |||
4763 | ? diag::err_typecheck_call_too_many_args_suggest | |||
4764 | : diag::err_typecheck_call_too_many_args_at_most_suggest; | |||
4765 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams | |||
4766 | << static_cast<unsigned>(Args.size()) | |||
4767 | << TC.getCorrectionRange()); | |||
4768 | } else if (NumParams == 1 && FDecl && | |||
4769 | FDecl->getParamDecl(0)->getDeclName()) | |||
4770 | Diag(Args[NumParams]->getLocStart(), | |||
4771 | MinArgs == NumParams | |||
4772 | ? diag::err_typecheck_call_too_many_args_one | |||
4773 | : diag::err_typecheck_call_too_many_args_at_most_one) | |||
4774 | << FnKind << FDecl->getParamDecl(0) | |||
4775 | << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() | |||
4776 | << SourceRange(Args[NumParams]->getLocStart(), | |||
4777 | Args.back()->getLocEnd()); | |||
4778 | else | |||
4779 | Diag(Args[NumParams]->getLocStart(), | |||
4780 | MinArgs == NumParams | |||
4781 | ? diag::err_typecheck_call_too_many_args | |||
4782 | : diag::err_typecheck_call_too_many_args_at_most) | |||
4783 | << FnKind << NumParams << static_cast<unsigned>(Args.size()) | |||
4784 | << Fn->getSourceRange() | |||
4785 | << SourceRange(Args[NumParams]->getLocStart(), | |||
4786 | Args.back()->getLocEnd()); | |||
4787 | ||||
4788 | // Emit the location of the prototype. | |||
4789 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | |||
4790 | Diag(FDecl->getLocStart(), diag::note_callee_decl) | |||
4791 | << FDecl; | |||
4792 | ||||
4793 | // This deletes the extra arguments. | |||
4794 | Call->setNumArgs(Context, NumParams); | |||
4795 | return true; | |||
4796 | } | |||
4797 | } | |||
4798 | SmallVector<Expr *, 8> AllArgs; | |||
4799 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); | |||
4800 | ||||
4801 | Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, | |||
4802 | Proto, 0, Args, AllArgs, CallType); | |||
4803 | if (Invalid) | |||
4804 | return true; | |||
4805 | unsigned TotalNumArgs = AllArgs.size(); | |||
4806 | for (unsigned i = 0; i < TotalNumArgs; ++i) | |||
4807 | Call->setArg(i, AllArgs[i]); | |||
4808 | ||||
4809 | return false; | |||
4810 | } | |||
4811 | ||||
4812 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, | |||
4813 | const FunctionProtoType *Proto, | |||
4814 | unsigned FirstParam, ArrayRef<Expr *> Args, | |||
4815 | SmallVectorImpl<Expr *> &AllArgs, | |||
4816 | VariadicCallType CallType, bool AllowExplicit, | |||
4817 | bool IsListInitialization) { | |||
4818 | unsigned NumParams = Proto->getNumParams(); | |||
4819 | bool Invalid = false; | |||
4820 | size_t ArgIx = 0; | |||
4821 | // Continue to check argument types (even if we have too few/many args). | |||
4822 | for (unsigned i = FirstParam; i < NumParams; i++) { | |||
4823 | QualType ProtoArgType = Proto->getParamType(i); | |||
4824 | ||||
4825 | Expr *Arg; | |||
4826 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; | |||
4827 | if (ArgIx < Args.size()) { | |||
4828 | Arg = Args[ArgIx++]; | |||
4829 | ||||
4830 | if (RequireCompleteType(Arg->getLocStart(), | |||
4831 | ProtoArgType, | |||
4832 | diag::err_call_incomplete_argument, Arg)) | |||
4833 | return true; | |||
4834 | ||||
4835 | // Strip the unbridged-cast placeholder expression off, if applicable. | |||
4836 | bool CFAudited = false; | |||
4837 | if (Arg->getType() == Context.ARCUnbridgedCastTy && | |||
4838 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | |||
4839 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | |||
4840 | Arg = stripARCUnbridgedCast(Arg); | |||
4841 | else if (getLangOpts().ObjCAutoRefCount && | |||
4842 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | |||
4843 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | |||
4844 | CFAudited = true; | |||
4845 | ||||
4846 | if (Proto->getExtParameterInfo(i).isNoEscape()) | |||
4847 | if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) | |||
4848 | BE->getBlockDecl()->setDoesNotEscape(); | |||
4849 | ||||
4850 | InitializedEntity Entity = | |||
4851 | Param ? InitializedEntity::InitializeParameter(Context, Param, | |||
4852 | ProtoArgType) | |||
4853 | : InitializedEntity::InitializeParameter( | |||
4854 | Context, ProtoArgType, Proto->isParamConsumed(i)); | |||
4855 | ||||
4856 | // Remember that parameter belongs to a CF audited API. | |||
4857 | if (CFAudited) | |||
4858 | Entity.setParameterCFAudited(); | |||
4859 | ||||
4860 | ExprResult ArgE = PerformCopyInitialization( | |||
4861 | Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); | |||
4862 | if (ArgE.isInvalid()) | |||
4863 | return true; | |||
4864 | ||||
4865 | Arg = ArgE.getAs<Expr>(); | |||
4866 | } else { | |||
4867 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 4867, __extension__ __PRETTY_FUNCTION__)); | |||
4868 | ||||
4869 | ExprResult ArgExpr = | |||
4870 | BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); | |||
4871 | if (ArgExpr.isInvalid()) | |||
4872 | return true; | |||
4873 | ||||
4874 | Arg = ArgExpr.getAs<Expr>(); | |||
4875 | } | |||
4876 | ||||
4877 | // Check for array bounds violations for each argument to the call. This | |||
4878 | // check only triggers warnings when the argument isn't a more complex Expr | |||
4879 | // with its own checking, such as a BinaryOperator. | |||
4880 | CheckArrayAccess(Arg); | |||
4881 | ||||
4882 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). | |||
4883 | CheckStaticArrayArgument(CallLoc, Param, Arg); | |||
4884 | ||||
4885 | AllArgs.push_back(Arg); | |||
4886 | } | |||
4887 | ||||
4888 | // If this is a variadic call, handle args passed through "...". | |||
4889 | if (CallType != VariadicDoesNotApply) { | |||
4890 | // Assume that extern "C" functions with variadic arguments that | |||
4891 | // return __unknown_anytype aren't *really* variadic. | |||
4892 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && | |||
4893 | FDecl->isExternC()) { | |||
4894 | for (Expr *A : Args.slice(ArgIx)) { | |||
4895 | QualType paramType; // ignored | |||
4896 | ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); | |||
4897 | Invalid |= arg.isInvalid(); | |||
4898 | AllArgs.push_back(arg.get()); | |||
4899 | } | |||
4900 | ||||
4901 | // Otherwise do argument promotion, (C99 6.5.2.2p7). | |||
4902 | } else { | |||
4903 | for (Expr *A : Args.slice(ArgIx)) { | |||
4904 | ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); | |||
4905 | Invalid |= Arg.isInvalid(); | |||
4906 | AllArgs.push_back(Arg.get()); | |||
4907 | } | |||
4908 | } | |||
4909 | ||||
4910 | // Check for array bounds violations. | |||
4911 | for (Expr *A : Args.slice(ArgIx)) | |||
4912 | CheckArrayAccess(A); | |||
4913 | } | |||
4914 | return Invalid; | |||
4915 | } | |||
4916 | ||||
4917 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { | |||
4918 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); | |||
4919 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) | |||
4920 | TL = DTL.getOriginalLoc(); | |||
4921 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) | |||
4922 | S.Diag(PVD->getLocation(), diag::note_callee_static_array) | |||
4923 | << ATL.getLocalSourceRange(); | |||
4924 | } | |||
4925 | ||||
4926 | /// CheckStaticArrayArgument - If the given argument corresponds to a static | |||
4927 | /// array parameter, check that it is non-null, and that if it is formed by | |||
4928 | /// array-to-pointer decay, the underlying array is sufficiently large. | |||
4929 | /// | |||
4930 | /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the | |||
4931 | /// array type derivation, then for each call to the function, the value of the | |||
4932 | /// corresponding actual argument shall provide access to the first element of | |||
4933 | /// an array with at least as many elements as specified by the size expression. | |||
4934 | void | |||
4935 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, | |||
4936 | ParmVarDecl *Param, | |||
4937 | const Expr *ArgExpr) { | |||
4938 | // Static array parameters are not supported in C++. | |||
4939 | if (!Param || getLangOpts().CPlusPlus) | |||
4940 | return; | |||
4941 | ||||
4942 | QualType OrigTy = Param->getOriginalType(); | |||
4943 | ||||
4944 | const ArrayType *AT = Context.getAsArrayType(OrigTy); | |||
4945 | if (!AT || AT->getSizeModifier() != ArrayType::Static) | |||
4946 | return; | |||
4947 | ||||
4948 | if (ArgExpr->isNullPointerConstant(Context, | |||
4949 | Expr::NPC_NeverValueDependent)) { | |||
4950 | Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); | |||
4951 | DiagnoseCalleeStaticArrayParam(*this, Param); | |||
4952 | return; | |||
4953 | } | |||
4954 | ||||
4955 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); | |||
4956 | if (!CAT) | |||
4957 | return; | |||
4958 | ||||
4959 | const ConstantArrayType *ArgCAT = | |||
4960 | Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); | |||
4961 | if (!ArgCAT) | |||
4962 | return; | |||
4963 | ||||
4964 | if (ArgCAT->getSize().ult(CAT->getSize())) { | |||
4965 | Diag(CallLoc, diag::warn_static_array_too_small) | |||
4966 | << ArgExpr->getSourceRange() | |||
4967 | << (unsigned) ArgCAT->getSize().getZExtValue() | |||
4968 | << (unsigned) CAT->getSize().getZExtValue(); | |||
4969 | DiagnoseCalleeStaticArrayParam(*this, Param); | |||
4970 | } | |||
4971 | } | |||
4972 | ||||
4973 | /// Given a function expression of unknown-any type, try to rebuild it | |||
4974 | /// to have a function type. | |||
4975 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); | |||
4976 | ||||
4977 | /// Is the given type a placeholder that we need to lower out | |||
4978 | /// immediately during argument processing? | |||
4979 | static bool isPlaceholderToRemoveAsArg(QualType type) { | |||
4980 | // Placeholders are never sugared. | |||
4981 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); | |||
4982 | if (!placeholder) return false; | |||
4983 | ||||
4984 | switch (placeholder->getKind()) { | |||
4985 | // Ignore all the non-placeholder types. | |||
4986 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | |||
4987 | case BuiltinType::Id: | |||
4988 | #include "clang/Basic/OpenCLImageTypes.def" | |||
4989 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) | |||
4990 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: | |||
4991 | #include "clang/AST/BuiltinTypes.def" | |||
4992 | return false; | |||
4993 | ||||
4994 | // We cannot lower out overload sets; they might validly be resolved | |||
4995 | // by the call machinery. | |||
4996 | case BuiltinType::Overload: | |||
4997 | return false; | |||
4998 | ||||
4999 | // Unbridged casts in ARC can be handled in some call positions and | |||
5000 | // should be left in place. | |||
5001 | case BuiltinType::ARCUnbridgedCast: | |||
5002 | return false; | |||
5003 | ||||
5004 | // Pseudo-objects should be converted as soon as possible. | |||
5005 | case BuiltinType::PseudoObject: | |||
5006 | return true; | |||
5007 | ||||
5008 | // The debugger mode could theoretically but currently does not try | |||
5009 | // to resolve unknown-typed arguments based on known parameter types. | |||
5010 | case BuiltinType::UnknownAny: | |||
5011 | return true; | |||
5012 | ||||
5013 | // These are always invalid as call arguments and should be reported. | |||
5014 | case BuiltinType::BoundMember: | |||
5015 | case BuiltinType::BuiltinFn: | |||
5016 | case BuiltinType::OMPArraySection: | |||
5017 | return true; | |||
5018 | ||||
5019 | } | |||
5020 | llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5020); | |||
5021 | } | |||
5022 | ||||
5023 | /// Check an argument list for placeholders that we won't try to | |||
5024 | /// handle later. | |||
5025 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { | |||
5026 | // Apply this processing to all the arguments at once instead of | |||
5027 | // dying at the first failure. | |||
5028 | bool hasInvalid = false; | |||
5029 | for (size_t i = 0, e = args.size(); i != e; i++) { | |||
5030 | if (isPlaceholderToRemoveAsArg(args[i]->getType())) { | |||
5031 | ExprResult result = S.CheckPlaceholderExpr(args[i]); | |||
5032 | if (result.isInvalid()) hasInvalid = true; | |||
5033 | else args[i] = result.get(); | |||
5034 | } else if (hasInvalid) { | |||
5035 | (void)S.CorrectDelayedTyposInExpr(args[i]); | |||
5036 | } | |||
5037 | } | |||
5038 | return hasInvalid; | |||
5039 | } | |||
5040 | ||||
5041 | /// If a builtin function has a pointer argument with no explicit address | |||
5042 | /// space, then it should be able to accept a pointer to any address | |||
5043 | /// space as input. In order to do this, we need to replace the | |||
5044 | /// standard builtin declaration with one that uses the same address space | |||
5045 | /// as the call. | |||
5046 | /// | |||
5047 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. | |||
5048 | /// it does not contain any pointer arguments without | |||
5049 | /// an address space qualifer. Otherwise the rewritten | |||
5050 | /// FunctionDecl is returned. | |||
5051 | /// TODO: Handle pointer return types. | |||
5052 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, | |||
5053 | const FunctionDecl *FDecl, | |||
5054 | MultiExprArg ArgExprs) { | |||
5055 | ||||
5056 | QualType DeclType = FDecl->getType(); | |||
5057 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); | |||
5058 | ||||
5059 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || | |||
5060 | !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) | |||
5061 | return nullptr; | |||
5062 | ||||
5063 | bool NeedsNewDecl = false; | |||
5064 | unsigned i = 0; | |||
5065 | SmallVector<QualType, 8> OverloadParams; | |||
5066 | ||||
5067 | for (QualType ParamType : FT->param_types()) { | |||
5068 | ||||
5069 | // Convert array arguments to pointer to simplify type lookup. | |||
5070 | ExprResult ArgRes = | |||
5071 | Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); | |||
5072 | if (ArgRes.isInvalid()) | |||
5073 | return nullptr; | |||
5074 | Expr *Arg = ArgRes.get(); | |||
5075 | QualType ArgType = Arg->getType(); | |||
5076 | if (!ParamType->isPointerType() || | |||
5077 | ParamType.getQualifiers().hasAddressSpace() || | |||
5078 | !ArgType->isPointerType() || | |||
5079 | !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { | |||
5080 | OverloadParams.push_back(ParamType); | |||
5081 | continue; | |||
5082 | } | |||
5083 | ||||
5084 | NeedsNewDecl = true; | |||
5085 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); | |||
5086 | ||||
5087 | QualType PointeeType = ParamType->getPointeeType(); | |||
5088 | PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); | |||
5089 | OverloadParams.push_back(Context.getPointerType(PointeeType)); | |||
5090 | } | |||
5091 | ||||
5092 | if (!NeedsNewDecl) | |||
5093 | return nullptr; | |||
5094 | ||||
5095 | FunctionProtoType::ExtProtoInfo EPI; | |||
5096 | QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), | |||
5097 | OverloadParams, EPI); | |||
5098 | DeclContext *Parent = Context.getTranslationUnitDecl(); | |||
5099 | FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, | |||
5100 | FDecl->getLocation(), | |||
5101 | FDecl->getLocation(), | |||
5102 | FDecl->getIdentifier(), | |||
5103 | OverloadTy, | |||
5104 | /*TInfo=*/nullptr, | |||
5105 | SC_Extern, false, | |||
5106 | /*hasPrototype=*/true); | |||
5107 | SmallVector<ParmVarDecl*, 16> Params; | |||
5108 | FT = cast<FunctionProtoType>(OverloadTy); | |||
5109 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | |||
5110 | QualType ParamType = FT->getParamType(i); | |||
5111 | ParmVarDecl *Parm = | |||
5112 | ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), | |||
5113 | SourceLocation(), nullptr, ParamType, | |||
5114 | /*TInfo=*/nullptr, SC_None, nullptr); | |||
5115 | Parm->setScopeInfo(0, i); | |||
5116 | Params.push_back(Parm); | |||
5117 | } | |||
5118 | OverloadDecl->setParams(Params); | |||
5119 | return OverloadDecl; | |||
5120 | } | |||
5121 | ||||
5122 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, | |||
5123 | FunctionDecl *Callee, | |||
5124 | MultiExprArg ArgExprs) { | |||
5125 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and | |||
5126 | // similar attributes) really don't like it when functions are called with an | |||
5127 | // invalid number of args. | |||
5128 | if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), | |||
5129 | /*PartialOverloading=*/false) && | |||
5130 | !Callee->isVariadic()) | |||
5131 | return; | |||
5132 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) | |||
5133 | return; | |||
5134 | ||||
5135 | if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { | |||
5136 | S.Diag(Fn->getLocStart(), | |||
5137 | isa<CXXMethodDecl>(Callee) | |||
5138 | ? diag::err_ovl_no_viable_member_function_in_call | |||
5139 | : diag::err_ovl_no_viable_function_in_call) | |||
5140 | << Callee << Callee->getSourceRange(); | |||
5141 | S.Diag(Callee->getLocation(), | |||
5142 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | |||
5143 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | |||
5144 | return; | |||
5145 | } | |||
5146 | } | |||
5147 | ||||
5148 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( | |||
5149 | const UnresolvedMemberExpr *const UME, Sema &S) { | |||
5150 | ||||
5151 | const auto GetFunctionLevelDCIfCXXClass = | |||
5152 | [](Sema &S) -> const CXXRecordDecl * { | |||
5153 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); | |||
5154 | if (!DC || !DC->getParent()) | |||
5155 | return nullptr; | |||
5156 | ||||
5157 | // If the call to some member function was made from within a member | |||
5158 | // function body 'M' return return 'M's parent. | |||
5159 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | |||
5160 | return MD->getParent()->getCanonicalDecl(); | |||
5161 | // else the call was made from within a default member initializer of a | |||
5162 | // class, so return the class. | |||
5163 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) | |||
5164 | return RD->getCanonicalDecl(); | |||
5165 | return nullptr; | |||
5166 | }; | |||
5167 | // If our DeclContext is neither a member function nor a class (in the | |||
5168 | // case of a lambda in a default member initializer), we can't have an | |||
5169 | // enclosing 'this'. | |||
5170 | ||||
5171 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); | |||
5172 | if (!CurParentClass) | |||
5173 | return false; | |||
5174 | ||||
5175 | // The naming class for implicit member functions call is the class in which | |||
5176 | // name lookup starts. | |||
5177 | const CXXRecordDecl *const NamingClass = | |||
5178 | UME->getNamingClass()->getCanonicalDecl(); | |||
5179 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5179, __extension__ __PRETTY_FUNCTION__)); | |||
5180 | ||||
5181 | // If the unresolved member functions were found in a 'naming class' that is | |||
5182 | // related (either the same or derived from) to the class that contains the | |||
5183 | // member function that itself contained the implicit member access. | |||
5184 | ||||
5185 | return CurParentClass == NamingClass || | |||
5186 | CurParentClass->isDerivedFrom(NamingClass); | |||
5187 | } | |||
5188 | ||||
5189 | static void | |||
5190 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | |||
5191 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { | |||
5192 | ||||
5193 | if (!UME) | |||
5194 | return; | |||
5195 | ||||
5196 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); | |||
5197 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't | |||
5198 | // already been captured, or if this is an implicit member function call (if | |||
5199 | // it isn't, an attempt to capture 'this' should already have been made). | |||
5200 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || | |||
5201 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) | |||
5202 | return; | |||
5203 | ||||
5204 | // Check if the naming class in which the unresolved members were found is | |||
5205 | // related (same as or is a base of) to the enclosing class. | |||
5206 | ||||
5207 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) | |||
5208 | return; | |||
5209 | ||||
5210 | ||||
5211 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); | |||
5212 | // If the enclosing function is not dependent, then this lambda is | |||
5213 | // capture ready, so if we can capture this, do so. | |||
5214 | if (!EnclosingFunctionCtx->isDependentContext()) { | |||
5215 | // If the current lambda and all enclosing lambdas can capture 'this' - | |||
5216 | // then go ahead and capture 'this' (since our unresolved overload set | |||
5217 | // contains at least one non-static member function). | |||
5218 | if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) | |||
5219 | S.CheckCXXThisCapture(CallLoc); | |||
5220 | } else if (S.CurContext->isDependentContext()) { | |||
5221 | // ... since this is an implicit member reference, that might potentially | |||
5222 | // involve a 'this' capture, mark 'this' for potential capture in | |||
5223 | // enclosing lambdas. | |||
5224 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) | |||
5225 | CurLSI->addPotentialThisCapture(CallLoc); | |||
5226 | } | |||
5227 | } | |||
5228 | ||||
5229 | /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. | |||
5230 | /// This provides the location of the left/right parens and a list of comma | |||
5231 | /// locations. | |||
5232 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | |||
5233 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | |||
5234 | Expr *ExecConfig, bool IsExecConfig) { | |||
5235 | // Since this might be a postfix expression, get rid of ParenListExprs. | |||
5236 | ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); | |||
5237 | if (Result.isInvalid()) return ExprError(); | |||
5238 | Fn = Result.get(); | |||
5239 | ||||
5240 | if (checkArgsForPlaceholders(*this, ArgExprs)) | |||
5241 | return ExprError(); | |||
5242 | ||||
5243 | if (getLangOpts().CPlusPlus) { | |||
5244 | // If this is a pseudo-destructor expression, build the call immediately. | |||
5245 | if (isa<CXXPseudoDestructorExpr>(Fn)) { | |||
5246 | if (!ArgExprs.empty()) { | |||
5247 | // Pseudo-destructor calls should not have any arguments. | |||
5248 | Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) | |||
5249 | << FixItHint::CreateRemoval( | |||
5250 | SourceRange(ArgExprs.front()->getLocStart(), | |||
5251 | ArgExprs.back()->getLocEnd())); | |||
5252 | } | |||
5253 | ||||
5254 | return new (Context) | |||
5255 | CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); | |||
5256 | } | |||
5257 | if (Fn->getType() == Context.PseudoObjectTy) { | |||
5258 | ExprResult result = CheckPlaceholderExpr(Fn); | |||
5259 | if (result.isInvalid()) return ExprError(); | |||
5260 | Fn = result.get(); | |||
5261 | } | |||
5262 | ||||
5263 | // Determine whether this is a dependent call inside a C++ template, | |||
5264 | // in which case we won't do any semantic analysis now. | |||
5265 | bool Dependent = false; | |||
5266 | if (Fn->isTypeDependent()) | |||
5267 | Dependent = true; | |||
5268 | else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) | |||
5269 | Dependent = true; | |||
5270 | ||||
5271 | if (Dependent) { | |||
5272 | if (ExecConfig) { | |||
5273 | return new (Context) CUDAKernelCallExpr( | |||
5274 | Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, | |||
5275 | Context.DependentTy, VK_RValue, RParenLoc); | |||
5276 | } else { | |||
5277 | ||||
5278 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | |||
5279 | *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), | |||
5280 | Fn->getLocStart()); | |||
5281 | ||||
5282 | return new (Context) CallExpr( | |||
5283 | Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); | |||
5284 | } | |||
5285 | } | |||
5286 | ||||
5287 | // Determine whether this is a call to an object (C++ [over.call.object]). | |||
5288 | if (Fn->getType()->isRecordType()) | |||
5289 | return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, | |||
5290 | RParenLoc); | |||
5291 | ||||
5292 | if (Fn->getType() == Context.UnknownAnyTy) { | |||
5293 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | |||
5294 | if (result.isInvalid()) return ExprError(); | |||
5295 | Fn = result.get(); | |||
5296 | } | |||
5297 | ||||
5298 | if (Fn->getType() == Context.BoundMemberTy) { | |||
5299 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | |||
5300 | RParenLoc); | |||
5301 | } | |||
5302 | } | |||
5303 | ||||
5304 | // Check for overloaded calls. This can happen even in C due to extensions. | |||
5305 | if (Fn->getType() == Context.OverloadTy) { | |||
5306 | OverloadExpr::FindResult find = OverloadExpr::find(Fn); | |||
5307 | ||||
5308 | // We aren't supposed to apply this logic if there's an '&' involved. | |||
5309 | if (!find.HasFormOfMemberPointer) { | |||
5310 | if (Expr::hasAnyTypeDependentArguments(ArgExprs)) | |||
5311 | return new (Context) CallExpr( | |||
5312 | Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); | |||
5313 | OverloadExpr *ovl = find.Expression; | |||
5314 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) | |||
5315 | return BuildOverloadedCallExpr( | |||
5316 | Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | |||
5317 | /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); | |||
5318 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | |||
5319 | RParenLoc); | |||
5320 | } | |||
5321 | } | |||
5322 | ||||
5323 | // If we're directly calling a function, get the appropriate declaration. | |||
5324 | if (Fn->getType() == Context.UnknownAnyTy) { | |||
5325 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | |||
5326 | if (result.isInvalid()) return ExprError(); | |||
5327 | Fn = result.get(); | |||
5328 | } | |||
5329 | ||||
5330 | Expr *NakedFn = Fn->IgnoreParens(); | |||
5331 | ||||
5332 | bool CallingNDeclIndirectly = false; | |||
5333 | NamedDecl *NDecl = nullptr; | |||
5334 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { | |||
5335 | if (UnOp->getOpcode() == UO_AddrOf) { | |||
5336 | CallingNDeclIndirectly = true; | |||
5337 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); | |||
5338 | } | |||
5339 | } | |||
5340 | ||||
5341 | if (isa<DeclRefExpr>(NakedFn)) { | |||
5342 | NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); | |||
5343 | ||||
5344 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); | |||
5345 | if (FDecl && FDecl->getBuiltinID()) { | |||
5346 | // Rewrite the function decl for this builtin by replacing parameters | |||
5347 | // with no explicit address space with the address space of the arguments | |||
5348 | // in ArgExprs. | |||
5349 | if ((FDecl = | |||
5350 | rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { | |||
5351 | NDecl = FDecl; | |||
5352 | Fn = DeclRefExpr::Create( | |||
5353 | Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, | |||
5354 | SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); | |||
5355 | } | |||
5356 | } | |||
5357 | } else if (isa<MemberExpr>(NakedFn)) | |||
5358 | NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); | |||
5359 | ||||
5360 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { | |||
5361 | if (CallingNDeclIndirectly && | |||
5362 | !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | |||
5363 | Fn->getLocStart())) | |||
5364 | return ExprError(); | |||
5365 | ||||
5366 | if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) | |||
5367 | return ExprError(); | |||
5368 | ||||
5369 | checkDirectCallValidity(*this, Fn, FD, ArgExprs); | |||
5370 | } | |||
5371 | ||||
5372 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, | |||
5373 | ExecConfig, IsExecConfig); | |||
5374 | } | |||
5375 | ||||
5376 | /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. | |||
5377 | /// | |||
5378 | /// __builtin_astype( value, dst type ) | |||
5379 | /// | |||
5380 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, | |||
5381 | SourceLocation BuiltinLoc, | |||
5382 | SourceLocation RParenLoc) { | |||
5383 | ExprValueKind VK = VK_RValue; | |||
5384 | ExprObjectKind OK = OK_Ordinary; | |||
5385 | QualType DstTy = GetTypeFromParser(ParsedDestTy); | |||
5386 | QualType SrcTy = E->getType(); | |||
5387 | if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) | |||
5388 | return ExprError(Diag(BuiltinLoc, | |||
5389 | diag::err_invalid_astype_of_different_size) | |||
5390 | << DstTy | |||
5391 | << SrcTy | |||
5392 | << E->getSourceRange()); | |||
5393 | return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); | |||
5394 | } | |||
5395 | ||||
5396 | /// ActOnConvertVectorExpr - create a new convert-vector expression from the | |||
5397 | /// provided arguments. | |||
5398 | /// | |||
5399 | /// __builtin_convertvector( value, dst type ) | |||
5400 | /// | |||
5401 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, | |||
5402 | SourceLocation BuiltinLoc, | |||
5403 | SourceLocation RParenLoc) { | |||
5404 | TypeSourceInfo *TInfo; | |||
5405 | GetTypeFromParser(ParsedDestTy, &TInfo); | |||
5406 | return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); | |||
5407 | } | |||
5408 | ||||
5409 | /// BuildResolvedCallExpr - Build a call to a resolved expression, | |||
5410 | /// i.e. an expression not of \p OverloadTy. The expression should | |||
5411 | /// unary-convert to an expression of function-pointer or | |||
5412 | /// block-pointer type. | |||
5413 | /// | |||
5414 | /// \param NDecl the declaration being called, if available | |||
5415 | ExprResult | |||
5416 | Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, | |||
5417 | SourceLocation LParenLoc, | |||
5418 | ArrayRef<Expr *> Args, | |||
5419 | SourceLocation RParenLoc, | |||
5420 | Expr *Config, bool IsExecConfig) { | |||
5421 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); | |||
5422 | unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); | |||
5423 | ||||
5424 | // Functions with 'interrupt' attribute cannot be called directly. | |||
5425 | if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { | |||
5426 | Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); | |||
5427 | return ExprError(); | |||
5428 | } | |||
5429 | ||||
5430 | // Interrupt handlers don't save off the VFP regs automatically on ARM, | |||
5431 | // so there's some risk when calling out to non-interrupt handler functions | |||
5432 | // that the callee might not preserve them. This is easy to diagnose here, | |||
5433 | // but can be very challenging to debug. | |||
5434 | if (auto *Caller = getCurFunctionDecl()) | |||
5435 | if (Caller->hasAttr<ARMInterruptAttr>()) { | |||
5436 | bool VFP = Context.getTargetInfo().hasFeature("vfp"); | |||
5437 | if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) | |||
5438 | Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); | |||
5439 | } | |||
5440 | ||||
5441 | // Promote the function operand. | |||
5442 | // We special-case function promotion here because we only allow promoting | |||
5443 | // builtin functions to function pointers in the callee of a call. | |||
5444 | ExprResult Result; | |||
5445 | if (BuiltinID && | |||
5446 | Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { | |||
5447 | Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), | |||
5448 | CK_BuiltinFnToFnPtr).get(); | |||
5449 | } else { | |||
5450 | Result = CallExprUnaryConversions(Fn); | |||
5451 | } | |||
5452 | if (Result.isInvalid()) | |||
5453 | return ExprError(); | |||
5454 | Fn = Result.get(); | |||
5455 | ||||
5456 | // Make the call expr early, before semantic checks. This guarantees cleanup | |||
5457 | // of arguments and function on error. | |||
5458 | CallExpr *TheCall; | |||
5459 | if (Config) | |||
5460 | TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, | |||
5461 | cast<CallExpr>(Config), Args, | |||
5462 | Context.BoolTy, VK_RValue, | |||
5463 | RParenLoc); | |||
5464 | else | |||
5465 | TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, | |||
5466 | VK_RValue, RParenLoc); | |||
5467 | ||||
5468 | if (!getLangOpts().CPlusPlus) { | |||
5469 | // C cannot always handle TypoExpr nodes in builtin calls and direct | |||
5470 | // function calls as their argument checking don't necessarily handle | |||
5471 | // dependent types properly, so make sure any TypoExprs have been | |||
5472 | // dealt with. | |||
5473 | ExprResult Result = CorrectDelayedTyposInExpr(TheCall); | |||
5474 | if (!Result.isUsable()) return ExprError(); | |||
5475 | TheCall = dyn_cast<CallExpr>(Result.get()); | |||
5476 | if (!TheCall) return Result; | |||
5477 | Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); | |||
5478 | } | |||
5479 | ||||
5480 | // Bail out early if calling a builtin with custom typechecking. | |||
5481 | if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) | |||
5482 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | |||
5483 | ||||
5484 | retry: | |||
5485 | const FunctionType *FuncT; | |||
5486 | if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { | |||
5487 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall | |||
5488 | // have type pointer to function". | |||
5489 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); | |||
5490 | if (!FuncT) | |||
5491 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | |||
5492 | << Fn->getType() << Fn->getSourceRange()); | |||
5493 | } else if (const BlockPointerType *BPT = | |||
5494 | Fn->getType()->getAs<BlockPointerType>()) { | |||
5495 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); | |||
5496 | } else { | |||
5497 | // Handle calls to expressions of unknown-any type. | |||
5498 | if (Fn->getType() == Context.UnknownAnyTy) { | |||
5499 | ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); | |||
5500 | if (rewrite.isInvalid()) return ExprError(); | |||
5501 | Fn = rewrite.get(); | |||
5502 | TheCall->setCallee(Fn); | |||
5503 | goto retry; | |||
5504 | } | |||
5505 | ||||
5506 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | |||
5507 | << Fn->getType() << Fn->getSourceRange()); | |||
5508 | } | |||
5509 | ||||
5510 | if (getLangOpts().CUDA) { | |||
5511 | if (Config) { | |||
5512 | // CUDA: Kernel calls must be to global functions | |||
5513 | if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) | |||
5514 | return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) | |||
5515 | << FDecl << Fn->getSourceRange()); | |||
5516 | ||||
5517 | // CUDA: Kernel function must have 'void' return type | |||
5518 | if (!FuncT->getReturnType()->isVoidType()) | |||
5519 | return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) | |||
5520 | << Fn->getType() << Fn->getSourceRange()); | |||
5521 | } else { | |||
5522 | // CUDA: Calls to global functions must be configured | |||
5523 | if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) | |||
5524 | return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) | |||
5525 | << FDecl << Fn->getSourceRange()); | |||
5526 | } | |||
5527 | } | |||
5528 | ||||
5529 | // Check for a valid return type | |||
5530 | if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, | |||
5531 | FDecl)) | |||
5532 | return ExprError(); | |||
5533 | ||||
5534 | // We know the result type of the call, set it. | |||
5535 | TheCall->setType(FuncT->getCallResultType(Context)); | |||
5536 | TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); | |||
5537 | ||||
5538 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); | |||
5539 | if (Proto) { | |||
5540 | if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, | |||
5541 | IsExecConfig)) | |||
5542 | return ExprError(); | |||
5543 | } else { | |||
5544 | assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")(static_cast <bool> (isa<FunctionNoProtoType>(FuncT ) && "Unknown FunctionType!") ? void (0) : __assert_fail ("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5544, __extension__ __PRETTY_FUNCTION__)); | |||
5545 | ||||
5546 | if (FDecl) { | |||
5547 | // Check if we have too few/too many template arguments, based | |||
5548 | // on our knowledge of the function definition. | |||
5549 | const FunctionDecl *Def = nullptr; | |||
5550 | if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { | |||
5551 | Proto = Def->getType()->getAs<FunctionProtoType>(); | |||
5552 | if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) | |||
5553 | Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) | |||
5554 | << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); | |||
5555 | } | |||
5556 | ||||
5557 | // If the function we're calling isn't a function prototype, but we have | |||
5558 | // a function prototype from a prior declaratiom, use that prototype. | |||
5559 | if (!FDecl->hasPrototype()) | |||
5560 | Proto = FDecl->getType()->getAs<FunctionProtoType>(); | |||
5561 | } | |||
5562 | ||||
5563 | // Promote the arguments (C99 6.5.2.2p6). | |||
5564 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | |||
5565 | Expr *Arg = Args[i]; | |||
5566 | ||||
5567 | if (Proto && i < Proto->getNumParams()) { | |||
5568 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | |||
5569 | Context, Proto->getParamType(i), Proto->isParamConsumed(i)); | |||
5570 | ExprResult ArgE = | |||
5571 | PerformCopyInitialization(Entity, SourceLocation(), Arg); | |||
5572 | if (ArgE.isInvalid()) | |||
5573 | return true; | |||
5574 | ||||
5575 | Arg = ArgE.getAs<Expr>(); | |||
5576 | ||||
5577 | } else { | |||
5578 | ExprResult ArgE = DefaultArgumentPromotion(Arg); | |||
5579 | ||||
5580 | if (ArgE.isInvalid()) | |||
5581 | return true; | |||
5582 | ||||
5583 | Arg = ArgE.getAs<Expr>(); | |||
5584 | } | |||
5585 | ||||
5586 | if (RequireCompleteType(Arg->getLocStart(), | |||
5587 | Arg->getType(), | |||
5588 | diag::err_call_incomplete_argument, Arg)) | |||
5589 | return ExprError(); | |||
5590 | ||||
5591 | TheCall->setArg(i, Arg); | |||
5592 | } | |||
5593 | } | |||
5594 | ||||
5595 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | |||
5596 | if (!Method->isStatic()) | |||
5597 | return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) | |||
5598 | << Fn->getSourceRange()); | |||
5599 | ||||
5600 | // Check for sentinels | |||
5601 | if (NDecl) | |||
5602 | DiagnoseSentinelCalls(NDecl, LParenLoc, Args); | |||
5603 | ||||
5604 | // Do special checking on direct calls to functions. | |||
5605 | if (FDecl) { | |||
5606 | if (CheckFunctionCall(FDecl, TheCall, Proto)) | |||
5607 | return ExprError(); | |||
5608 | ||||
5609 | if (BuiltinID) | |||
5610 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | |||
5611 | } else if (NDecl) { | |||
5612 | if (CheckPointerCall(NDecl, TheCall, Proto)) | |||
5613 | return ExprError(); | |||
5614 | } else { | |||
5615 | if (CheckOtherCall(TheCall, Proto)) | |||
5616 | return ExprError(); | |||
5617 | } | |||
5618 | ||||
5619 | return MaybeBindToTemporary(TheCall); | |||
5620 | } | |||
5621 | ||||
5622 | ExprResult | |||
5623 | Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, | |||
5624 | SourceLocation RParenLoc, Expr *InitExpr) { | |||
5625 | assert(Ty && "ActOnCompoundLiteral(): missing type")(static_cast <bool> (Ty && "ActOnCompoundLiteral(): missing type" ) ? void (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5625, __extension__ __PRETTY_FUNCTION__)); | |||
5626 | assert(InitExpr && "ActOnCompoundLiteral(): missing expression")(static_cast <bool> (InitExpr && "ActOnCompoundLiteral(): missing expression" ) ? void (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5626, __extension__ __PRETTY_FUNCTION__)); | |||
5627 | ||||
5628 | TypeSourceInfo *TInfo; | |||
5629 | QualType literalType = GetTypeFromParser(Ty, &TInfo); | |||
5630 | if (!TInfo) | |||
5631 | TInfo = Context.getTrivialTypeSourceInfo(literalType); | |||
5632 | ||||
5633 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); | |||
5634 | } | |||
5635 | ||||
5636 | ExprResult | |||
5637 | Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, | |||
5638 | SourceLocation RParenLoc, Expr *LiteralExpr) { | |||
5639 | QualType literalType = TInfo->getType(); | |||
5640 | ||||
5641 | if (literalType->isArrayType()) { | |||
5642 | if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), | |||
5643 | diag::err_illegal_decl_array_incomplete_type, | |||
5644 | SourceRange(LParenLoc, | |||
5645 | LiteralExpr->getSourceRange().getEnd()))) | |||
5646 | return ExprError(); | |||
5647 | if (literalType->isVariableArrayType()) | |||
5648 | return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) | |||
5649 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); | |||
5650 | } else if (!literalType->isDependentType() && | |||
5651 | RequireCompleteType(LParenLoc, literalType, | |||
5652 | diag::err_typecheck_decl_incomplete_type, | |||
5653 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | |||
5654 | return ExprError(); | |||
5655 | ||||
5656 | InitializedEntity Entity | |||
5657 | = InitializedEntity::InitializeCompoundLiteralInit(TInfo); | |||
5658 | InitializationKind Kind | |||
5659 | = InitializationKind::CreateCStyleCast(LParenLoc, | |||
5660 | SourceRange(LParenLoc, RParenLoc), | |||
5661 | /*InitList=*/true); | |||
5662 | InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); | |||
5663 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, | |||
5664 | &literalType); | |||
5665 | if (Result.isInvalid()) | |||
5666 | return ExprError(); | |||
5667 | LiteralExpr = Result.get(); | |||
5668 | ||||
5669 | bool isFileScope = !CurContext->isFunctionOrMethod(); | |||
5670 | if (isFileScope && | |||
5671 | !LiteralExpr->isTypeDependent() && | |||
5672 | !LiteralExpr->isValueDependent() && | |||
5673 | !literalType->isDependentType()) { // 6.5.2.5p3 | |||
5674 | if (CheckForConstantInitializer(LiteralExpr, literalType)) | |||
5675 | return ExprError(); | |||
5676 | } | |||
5677 | ||||
5678 | // In C, compound literals are l-values for some reason. | |||
5679 | // For GCC compatibility, in C++, file-scope array compound literals with | |||
5680 | // constant initializers are also l-values, and compound literals are | |||
5681 | // otherwise prvalues. | |||
5682 | // | |||
5683 | // (GCC also treats C++ list-initialized file-scope array prvalues with | |||
5684 | // constant initializers as l-values, but that's non-conforming, so we don't | |||
5685 | // follow it there.) | |||
5686 | // | |||
5687 | // FIXME: It would be better to handle the lvalue cases as materializing and | |||
5688 | // lifetime-extending a temporary object, but our materialized temporaries | |||
5689 | // representation only supports lifetime extension from a variable, not "out | |||
5690 | // of thin air". | |||
5691 | // FIXME: For C++, we might want to instead lifetime-extend only if a pointer | |||
5692 | // is bound to the result of applying array-to-pointer decay to the compound | |||
5693 | // literal. | |||
5694 | // FIXME: GCC supports compound literals of reference type, which should | |||
5695 | // obviously have a value kind derived from the kind of reference involved. | |||
5696 | ExprValueKind VK = | |||
5697 | (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) | |||
5698 | ? VK_RValue | |||
5699 | : VK_LValue; | |||
5700 | ||||
5701 | return MaybeBindToTemporary( | |||
5702 | new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, | |||
5703 | VK, LiteralExpr, isFileScope)); | |||
5704 | } | |||
5705 | ||||
5706 | ExprResult | |||
5707 | Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | |||
5708 | SourceLocation RBraceLoc) { | |||
5709 | // Immediately handle non-overload placeholders. Overloads can be | |||
5710 | // resolved contextually, but everything else here can't. | |||
5711 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | |||
5712 | if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { | |||
5713 | ExprResult result = CheckPlaceholderExpr(InitArgList[I]); | |||
5714 | ||||
5715 | // Ignore failures; dropping the entire initializer list because | |||
5716 | // of one failure would be terrible for indexing/etc. | |||
5717 | if (result.isInvalid()) continue; | |||
5718 | ||||
5719 | InitArgList[I] = result.get(); | |||
5720 | } | |||
5721 | } | |||
5722 | ||||
5723 | // Semantic analysis for initializers is done by ActOnDeclarator() and | |||
5724 | // CheckInitializer() - it requires knowledge of the object being initialized. | |||
5725 | ||||
5726 | InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, | |||
5727 | RBraceLoc); | |||
5728 | E->setType(Context.VoidTy); // FIXME: just a place holder for now. | |||
5729 | return E; | |||
5730 | } | |||
5731 | ||||
5732 | /// Do an explicit extend of the given block pointer if we're in ARC. | |||
5733 | void Sema::maybeExtendBlockObject(ExprResult &E) { | |||
5734 | assert(E.get()->getType()->isBlockPointerType())(static_cast <bool> (E.get()->getType()->isBlockPointerType ()) ? void (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5734, __extension__ __PRETTY_FUNCTION__)); | |||
5735 | assert(E.get()->isRValue())(static_cast <bool> (E.get()->isRValue()) ? void (0) : __assert_fail ("E.get()->isRValue()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5735, __extension__ __PRETTY_FUNCTION__)); | |||
5736 | ||||
5737 | // Only do this in an r-value context. | |||
5738 | if (!getLangOpts().ObjCAutoRefCount) return; | |||
5739 | ||||
5740 | E = ImplicitCastExpr::Create(Context, E.get()->getType(), | |||
5741 | CK_ARCExtendBlockObject, E.get(), | |||
5742 | /*base path*/ nullptr, VK_RValue); | |||
5743 | Cleanup.setExprNeedsCleanups(true); | |||
5744 | } | |||
5745 | ||||
5746 | /// Prepare a conversion of the given expression to an ObjC object | |||
5747 | /// pointer type. | |||
5748 | CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { | |||
5749 | QualType type = E.get()->getType(); | |||
5750 | if (type->isObjCObjectPointerType()) { | |||
5751 | return CK_BitCast; | |||
5752 | } else if (type->isBlockPointerType()) { | |||
5753 | maybeExtendBlockObject(E); | |||
5754 | return CK_BlockPointerToObjCPointerCast; | |||
5755 | } else { | |||
5756 | assert(type->isPointerType())(static_cast <bool> (type->isPointerType()) ? void ( 0) : __assert_fail ("type->isPointerType()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5756, __extension__ __PRETTY_FUNCTION__)); | |||
5757 | return CK_CPointerToObjCPointerCast; | |||
5758 | } | |||
5759 | } | |||
5760 | ||||
5761 | /// Prepares for a scalar cast, performing all the necessary stages | |||
5762 | /// except the final cast and returning the kind required. | |||
5763 | CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { | |||
5764 | // Both Src and Dest are scalar types, i.e. arithmetic or pointer. | |||
5765 | // Also, callers should have filtered out the invalid cases with | |||
5766 | // pointers. Everything else should be possible. | |||
5767 | ||||
5768 | QualType SrcTy = Src.get()->getType(); | |||
5769 | if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) | |||
5770 | return CK_NoOp; | |||
5771 | ||||
5772 | switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { | |||
5773 | case Type::STK_MemberPointer: | |||
5774 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5774); | |||
5775 | ||||
5776 | case Type::STK_CPointer: | |||
5777 | case Type::STK_BlockPointer: | |||
5778 | case Type::STK_ObjCObjectPointer: | |||
5779 | switch (DestTy->getScalarTypeKind()) { | |||
5780 | case Type::STK_CPointer: { | |||
5781 | LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); | |||
5782 | LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); | |||
5783 | if (SrcAS != DestAS) | |||
5784 | return CK_AddressSpaceConversion; | |||
5785 | return CK_BitCast; | |||
5786 | } | |||
5787 | case Type::STK_BlockPointer: | |||
5788 | return (SrcKind == Type::STK_BlockPointer | |||
5789 | ? CK_BitCast : CK_AnyPointerToBlockPointerCast); | |||
5790 | case Type::STK_ObjCObjectPointer: | |||
5791 | if (SrcKind == Type::STK_ObjCObjectPointer) | |||
5792 | return CK_BitCast; | |||
5793 | if (SrcKind == Type::STK_CPointer) | |||
5794 | return CK_CPointerToObjCPointerCast; | |||
5795 | maybeExtendBlockObject(Src); | |||
5796 | return CK_BlockPointerToObjCPointerCast; | |||
5797 | case Type::STK_Bool: | |||
5798 | return CK_PointerToBoolean; | |||
5799 | case Type::STK_Integral: | |||
5800 | return CK_PointerToIntegral; | |||
5801 | case Type::STK_Floating: | |||
5802 | case Type::STK_FloatingComplex: | |||
5803 | case Type::STK_IntegralComplex: | |||
5804 | case Type::STK_MemberPointer: | |||
5805 | llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5805); | |||
5806 | } | |||
5807 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5807); | |||
5808 | ||||
5809 | case Type::STK_Bool: // casting from bool is like casting from an integer | |||
5810 | case Type::STK_Integral: | |||
5811 | switch (DestTy->getScalarTypeKind()) { | |||
5812 | case Type::STK_CPointer: | |||
5813 | case Type::STK_ObjCObjectPointer: | |||
5814 | case Type::STK_BlockPointer: | |||
5815 | if (Src.get()->isNullPointerConstant(Context, | |||
5816 | Expr::NPC_ValueDependentIsNull)) | |||
5817 | return CK_NullToPointer; | |||
5818 | return CK_IntegralToPointer; | |||
5819 | case Type::STK_Bool: | |||
5820 | return CK_IntegralToBoolean; | |||
5821 | case Type::STK_Integral: | |||
5822 | return CK_IntegralCast; | |||
5823 | case Type::STK_Floating: | |||
5824 | return CK_IntegralToFloating; | |||
5825 | case Type::STK_IntegralComplex: | |||
5826 | Src = ImpCastExprToType(Src.get(), | |||
5827 | DestTy->castAs<ComplexType>()->getElementType(), | |||
5828 | CK_IntegralCast); | |||
5829 | return CK_IntegralRealToComplex; | |||
5830 | case Type::STK_FloatingComplex: | |||
5831 | Src = ImpCastExprToType(Src.get(), | |||
5832 | DestTy->castAs<ComplexType>()->getElementType(), | |||
5833 | CK_IntegralToFloating); | |||
5834 | return CK_FloatingRealToComplex; | |||
5835 | case Type::STK_MemberPointer: | |||
5836 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5836); | |||
5837 | } | |||
5838 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5838); | |||
5839 | ||||
5840 | case Type::STK_Floating: | |||
5841 | switch (DestTy->getScalarTypeKind()) { | |||
5842 | case Type::STK_Floating: | |||
5843 | return CK_FloatingCast; | |||
5844 | case Type::STK_Bool: | |||
5845 | return CK_FloatingToBoolean; | |||
5846 | case Type::STK_Integral: | |||
5847 | return CK_FloatingToIntegral; | |||
5848 | case Type::STK_FloatingComplex: | |||
5849 | Src = ImpCastExprToType(Src.get(), | |||
5850 | DestTy->castAs<ComplexType>()->getElementType(), | |||
5851 | CK_FloatingCast); | |||
5852 | return CK_FloatingRealToComplex; | |||
5853 | case Type::STK_IntegralComplex: | |||
5854 | Src = ImpCastExprToType(Src.get(), | |||
5855 | DestTy->castAs<ComplexType>()->getElementType(), | |||
5856 | CK_FloatingToIntegral); | |||
5857 | return CK_IntegralRealToComplex; | |||
5858 | case Type::STK_CPointer: | |||
5859 | case Type::STK_ObjCObjectPointer: | |||
5860 | case Type::STK_BlockPointer: | |||
5861 | llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5861); | |||
5862 | case Type::STK_MemberPointer: | |||
5863 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5863); | |||
5864 | } | |||
5865 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5865); | |||
5866 | ||||
5867 | case Type::STK_FloatingComplex: | |||
5868 | switch (DestTy->getScalarTypeKind()) { | |||
5869 | case Type::STK_FloatingComplex: | |||
5870 | return CK_FloatingComplexCast; | |||
5871 | case Type::STK_IntegralComplex: | |||
5872 | return CK_FloatingComplexToIntegralComplex; | |||
5873 | case Type::STK_Floating: { | |||
5874 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | |||
5875 | if (Context.hasSameType(ET, DestTy)) | |||
5876 | return CK_FloatingComplexToReal; | |||
5877 | Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); | |||
5878 | return CK_FloatingCast; | |||
5879 | } | |||
5880 | case Type::STK_Bool: | |||
5881 | return CK_FloatingComplexToBoolean; | |||
5882 | case Type::STK_Integral: | |||
5883 | Src = ImpCastExprToType(Src.get(), | |||
5884 | SrcTy->castAs<ComplexType>()->getElementType(), | |||
5885 | CK_FloatingComplexToReal); | |||
5886 | return CK_FloatingToIntegral; | |||
5887 | case Type::STK_CPointer: | |||
5888 | case Type::STK_ObjCObjectPointer: | |||
5889 | case Type::STK_BlockPointer: | |||
5890 | llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5890); | |||
5891 | case Type::STK_MemberPointer: | |||
5892 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5892); | |||
5893 | } | |||
5894 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5894); | |||
5895 | ||||
5896 | case Type::STK_IntegralComplex: | |||
5897 | switch (DestTy->getScalarTypeKind()) { | |||
5898 | case Type::STK_FloatingComplex: | |||
5899 | return CK_IntegralComplexToFloatingComplex; | |||
5900 | case Type::STK_IntegralComplex: | |||
5901 | return CK_IntegralComplexCast; | |||
5902 | case Type::STK_Integral: { | |||
5903 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | |||
5904 | if (Context.hasSameType(ET, DestTy)) | |||
5905 | return CK_IntegralComplexToReal; | |||
5906 | Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); | |||
5907 | return CK_IntegralCast; | |||
5908 | } | |||
5909 | case Type::STK_Bool: | |||
5910 | return CK_IntegralComplexToBoolean; | |||
5911 | case Type::STK_Floating: | |||
5912 | Src = ImpCastExprToType(Src.get(), | |||
5913 | SrcTy->castAs<ComplexType>()->getElementType(), | |||
5914 | CK_IntegralComplexToReal); | |||
5915 | return CK_IntegralToFloating; | |||
5916 | case Type::STK_CPointer: | |||
5917 | case Type::STK_ObjCObjectPointer: | |||
5918 | case Type::STK_BlockPointer: | |||
5919 | llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5919); | |||
5920 | case Type::STK_MemberPointer: | |||
5921 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5921); | |||
5922 | } | |||
5923 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5923); | |||
5924 | } | |||
5925 | ||||
5926 | llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5926); | |||
5927 | } | |||
5928 | ||||
5929 | static bool breakDownVectorType(QualType type, uint64_t &len, | |||
5930 | QualType &eltType) { | |||
5931 | // Vectors are simple. | |||
5932 | if (const VectorType *vecType = type->getAs<VectorType>()) { | |||
5933 | len = vecType->getNumElements(); | |||
5934 | eltType = vecType->getElementType(); | |||
5935 | assert(eltType->isScalarType())(static_cast <bool> (eltType->isScalarType()) ? void (0) : __assert_fail ("eltType->isScalarType()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5935, __extension__ __PRETTY_FUNCTION__)); | |||
5936 | return true; | |||
5937 | } | |||
5938 | ||||
5939 | // We allow lax conversion to and from non-vector types, but only if | |||
5940 | // they're real types (i.e. non-complex, non-pointer scalar types). | |||
5941 | if (!type->isRealType()) return false; | |||
5942 | ||||
5943 | len = 1; | |||
5944 | eltType = type; | |||
5945 | return true; | |||
5946 | } | |||
5947 | ||||
5948 | /// Are the two types lax-compatible vector types? That is, given | |||
5949 | /// that one of them is a vector, do they have equal storage sizes, | |||
5950 | /// where the storage size is the number of elements times the element | |||
5951 | /// size? | |||
5952 | /// | |||
5953 | /// This will also return false if either of the types is neither a | |||
5954 | /// vector nor a real type. | |||
5955 | bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { | |||
5956 | assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy ->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5956, __extension__ __PRETTY_FUNCTION__)); | |||
5957 | ||||
5958 | // Disallow lax conversions between scalars and ExtVectors (these | |||
5959 | // conversions are allowed for other vector types because common headers | |||
5960 | // depend on them). Most scalar OP ExtVector cases are handled by the | |||
5961 | // splat path anyway, which does what we want (convert, not bitcast). | |||
5962 | // What this rules out for ExtVectors is crazy things like char4*float. | |||
5963 | if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; | |||
5964 | if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; | |||
5965 | ||||
5966 | uint64_t srcLen, destLen; | |||
5967 | QualType srcEltTy, destEltTy; | |||
5968 | if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; | |||
5969 | if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; | |||
5970 | ||||
5971 | // ASTContext::getTypeSize will return the size rounded up to a | |||
5972 | // power of 2, so instead of using that, we need to use the raw | |||
5973 | // element size multiplied by the element count. | |||
5974 | uint64_t srcEltSize = Context.getTypeSize(srcEltTy); | |||
5975 | uint64_t destEltSize = Context.getTypeSize(destEltTy); | |||
5976 | ||||
5977 | return (srcLen * srcEltSize == destLen * destEltSize); | |||
5978 | } | |||
5979 | ||||
5980 | /// Is this a legal conversion between two types, one of which is | |||
5981 | /// known to be a vector type? | |||
5982 | bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { | |||
5983 | assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy ->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5983, __extension__ __PRETTY_FUNCTION__)); | |||
5984 | ||||
5985 | if (!Context.getLangOpts().LaxVectorConversions) | |||
5986 | return false; | |||
5987 | return areLaxCompatibleVectorTypes(srcTy, destTy); | |||
5988 | } | |||
5989 | ||||
5990 | bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, | |||
5991 | CastKind &Kind) { | |||
5992 | 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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 5992, __extension__ __PRETTY_FUNCTION__)); | |||
5993 | ||||
5994 | if (Ty->isVectorType() || Ty->isIntegralType(Context)) { | |||
5995 | if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) | |||
5996 | return Diag(R.getBegin(), | |||
5997 | Ty->isVectorType() ? | |||
5998 | diag::err_invalid_conversion_between_vectors : | |||
5999 | diag::err_invalid_conversion_between_vector_and_integer) | |||
6000 | << VectorTy << Ty << R; | |||
6001 | } else | |||
6002 | return Diag(R.getBegin(), | |||
6003 | diag::err_invalid_conversion_between_vector_and_scalar) | |||
6004 | << VectorTy << Ty << R; | |||
6005 | ||||
6006 | Kind = CK_BitCast; | |||
6007 | return false; | |||
6008 | } | |||
6009 | ||||
6010 | ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { | |||
6011 | QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); | |||
6012 | ||||
6013 | if (DestElemTy == SplattedExpr->getType()) | |||
6014 | return SplattedExpr; | |||
6015 | ||||
6016 | assert(DestElemTy->isFloatingType() ||(static_cast <bool> (DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 6017, __extension__ __PRETTY_FUNCTION__)) | |||
6017 | DestElemTy->isIntegralOrEnumerationType())(static_cast <bool> (DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 6017, __extension__ __PRETTY_FUNCTION__)); | |||
6018 | ||||
6019 | CastKind CK; | |||
6020 | if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { | |||
6021 | // OpenCL requires that we convert `true` boolean expressions to -1, but | |||
6022 | // only when splatting vectors. | |||
6023 | if (DestElemTy->isFloatingType()) { | |||
6024 | // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast | |||
6025 | // in two steps: boolean to signed integral, then to floating. | |||
6026 | ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, | |||
6027 | CK_BooleanToSignedIntegral); | |||
6028 | SplattedExpr = CastExprRes.get(); | |||
6029 | CK = CK_IntegralToFloating; | |||
6030 | } else { | |||
6031 | CK = CK_BooleanToSignedIntegral; | |||
6032 | } | |||
6033 | } else { | |||
6034 | ExprResult CastExprRes = SplattedExpr; | |||
6035 | CK = PrepareScalarCast(CastExprRes, DestElemTy); | |||
6036 | if (CastExprRes.isInvalid()) | |||
6037 | return ExprError(); | |||
6038 | SplattedExpr = CastExprRes.get(); | |||
6039 | } | |||
6040 | return ImpCastExprToType(SplattedExpr, DestElemTy, CK); | |||
6041 | } | |||
6042 | ||||
6043 | ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, | |||
6044 | Expr *CastExpr, CastKind &Kind) { | |||
6045 | 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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 6045, __extension__ __PRETTY_FUNCTION__)); | |||
6046 | ||||
6047 | QualType SrcTy = CastExpr->getType(); | |||
6048 | ||||
6049 | // If SrcTy is a VectorType, the total size must match to explicitly cast to | |||
6050 | // an ExtVectorType. | |||
6051 | // In OpenCL, casts between vectors of different types are not allowed. | |||
6052 | // (See OpenCL 6.2). | |||
6053 | if (SrcTy->isVectorType()) { | |||
6054 | if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || | |||
6055 | (getLangOpts().OpenCL && | |||
6056 | !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { | |||
6057 | Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) | |||
6058 | << DestTy << SrcTy << R; | |||
6059 | return ExprError(); | |||
6060 | } | |||
6061 | Kind = CK_BitCast; | |||
6062 | return CastExpr; | |||
6063 | } | |||
6064 | ||||
6065 | // All non-pointer scalars can be cast to ExtVector type. The appropriate | |||
6066 | // conversion will take place first from scalar to elt type, and then | |||
6067 | // splat from elt type to vector. | |||
6068 | if (SrcTy->isPointerType()) | |||
6069 | return Diag(R.getBegin(), | |||
6070 | diag::err_invalid_conversion_between_vector_and_scalar) | |||
6071 | << DestTy << SrcTy << R; | |||
6072 | ||||
6073 | Kind = CK_VectorSplat; | |||
6074 | return prepareVectorSplat(DestTy, CastExpr); | |||
6075 | } | |||
6076 | ||||
6077 | ExprResult | |||
6078 | Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, | |||
6079 | Declarator &D, ParsedType &Ty, | |||
6080 | SourceLocation RParenLoc, Expr *CastExpr) { | |||
6081 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 6082, __extension__ __PRETTY_FUNCTION__)) | |||
6082 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 6082, __extension__ __PRETTY_FUNCTION__)); | |||
6083 | ||||
6084 | TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); | |||
6085 | if (D.isInvalidType()) | |||
6086 | return ExprError(); | |||
6087 | ||||
6088 | if (getLangOpts().CPlusPlus) { | |||
6089 | // Check that there are no default arguments (C++ only). | |||
6090 | CheckExtraCXXDefaultArguments(D); | |||
6091 | } else { | |||
6092 | // Make sure any TypoExprs have been dealt with. | |||
6093 | ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); | |||
6094 | if (!Res.isUsable()) | |||
6095 | return ExprError(); | |||
6096 | CastExpr = Res.get(); | |||
6097 | } | |||
6098 | ||||
6099 | checkUnusedDeclAttributes(D); | |||
6100 | ||||
6101 | QualType castType = castTInfo->getType(); | |||
6102 | Ty = CreateParsedType(castType, castTInfo); | |||
6103 | ||||
6104 | bool isVectorLiteral = false; | |||
6105 | ||||
6106 | // Check for an altivec or OpenCL literal, | |||
6107 | // i.e. all the elements are integer constants. | |||
6108 | ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); | |||
6109 | ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); | |||
6110 | if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) | |||
6111 | && castType->isVectorType() && (PE || PLE)) { | |||
6112 | if (PLE && PLE->getNumExprs() == 0) { | |||
6113 | Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); | |||
6114 | return ExprError(); | |||
6115 | } | |||
6116 | if (PE || PLE->getNumExprs() == 1) { | |||
6117 | Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); | |||
6118 | if (!E->getType()->isVectorType()) | |||
6119 | isVectorLiteral = true; | |||
6120 | } | |||
6121 | else | |||
6122 | isVectorLiteral = true; | |||
6123 | } | |||
6124 | ||||
6125 | // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' | |||
6126 | // then handle it as such. | |||
6127 | if (isVectorLiteral) | |||
6128 | return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); | |||
6129 | ||||
6130 | // If the Expr being casted is a ParenListExpr, handle it specially. | |||
6131 | // This is not an AltiVec-style cast, so turn the ParenListExpr into a | |||
6132 | // sequence of BinOp comma operators. | |||
6133 | if (isa<ParenListExpr>(CastExpr)) { | |||
6134 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); | |||
6135 | if (Result.isInvalid()) return ExprError(); | |||
6136 | CastExpr = Result.get(); | |||
6137 | } | |||
6138 | ||||
6139 | if (getLangOpts().CPlusPlus && !castType->isVoidType() && | |||
6140 | !getSourceManager().isInSystemMacro(LParenLoc)) | |||
6141 | Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); | |||
6142 | ||||
6143 | CheckTollFreeBridgeCast(castType, CastExpr); | |||
6144 | ||||
6145 | CheckObjCBridgeRelatedCast(castType, CastExpr); | |||
6146 | ||||
6147 | DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); | |||
6148 | ||||
6149 | return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); | |||
6150 | } | |||
6151 | ||||
6152 | ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, | |||
6153 | SourceLocation RParenLoc, Expr *E, | |||
6154 | TypeSourceInfo *TInfo) { | |||
6155 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 6156, __extension__ __PRETTY_FUNCTION__)) | |||
6156 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 6156, __extension__ __PRETTY_FUNCTION__)); | |||
6157 | ||||
6158 | Expr **exprs; | |||
6159 | unsigned numExprs; | |||
6160 | Expr *subExpr; | |||
6161 | SourceLocation LiteralLParenLoc, LiteralRParenLoc; | |||
6162 | if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { | |||
6163 | LiteralLParenLoc = PE->getLParenLoc(); | |||
6164 | LiteralRParenLoc = PE->getRParenLoc(); | |||
6165 | exprs = PE->getExprs(); | |||
6166 | numExprs = PE->getNumExprs(); | |||
6167 | } else { // isa<ParenExpr> by assertion at function entrance | |||
6168 | LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); | |||
6169 | LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); | |||
6170 | subExpr = cast<ParenExpr>(E)->getSubExpr(); | |||
6171 | exprs = &subExpr; | |||
6172 | numExprs = 1; | |||
6173 | } | |||
6174 | ||||
6175 | QualType Ty = TInfo->getType(); | |||
6176 | assert(Ty->isVectorType() && "Expected vector type")(static_cast <bool> (Ty->isVectorType() && "Expected vector type" ) ? void (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 6176, __extension__ __PRETTY_FUNCTION__)); | |||
6177 | ||||
6178 | SmallVector<Expr *, 8> initExprs; | |||
6179 | const VectorType *VTy = Ty->getAs<VectorType>(); | |||
6180 | unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); | |||
6181 | ||||
6182 | // '(...)' form of vector initialization in AltiVec: the number of | |||
6183 | // initializers must be one or must match the size of the vector. | |||
6184 | // If a single value is specified in the initializer then it will be | |||
6185 | // replicated to all the components of the vector | |||
6186 | if (VTy->getVectorKind() == VectorType::AltiVecVector) { | |||
6187 | // The number of initializers must be one or must match the size of the | |||
6188 | // vector. If a single value is specified in the initializer then it will | |||
6189 | // be replicated to all the components of the vector | |||
6190 | if (numExprs == 1) { | |||
6191 | QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); | |||
6192 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | |||
6193 | if (Literal.isInvalid()) | |||
6194 | return ExprError(); | |||
6195 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | |||
6196 | PrepareScalarCast(Literal, ElemTy)); | |||
6197 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | |||
6198 | } | |||
6199 | else if (numExprs < numElems) { | |||
6200 | Diag(E->getExprLoc(), | |||
6201 | diag::err_incorrect_number_of_vector_initializers); | |||
6202 | return ExprError(); | |||
6203 | } | |||
6204 | else | |||
6205 | initExprs.append(exprs, exprs + numExprs); | |||
6206 | } | |||
6207 | else { | |||
6208 | // For OpenCL, when the number of initializers is a single value, | |||
6209 | // it will be replicated to all components of the vector. | |||
6210 | if (getLangOpts().OpenCL && | |||
6211 | VTy->getVectorKind() == VectorType::GenericVector && | |||
6212 | numExprs == 1) { | |||
6213 | QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); | |||
6214 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | |||
6215 | if (Literal.isInvalid()) | |||
6216 | return ExprError(); | |||
6217 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | |||
6218 | PrepareScalarCast(Literal, ElemTy)); | |||
6219 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | |||
6220 | } | |||
6221 | ||||
6222 | initExprs.append(exprs, exprs + numExprs); | |||
6223 | } | |||
6224 | // FIXME: This means that pretty-printing the final AST will produce curly | |||
6225 | // braces instead of the original commas. | |||
6226 | InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, | |||
6227 | initExprs, LiteralRParenLoc); | |||
6228 | initE->setType(Ty); | |||
6229 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); | |||
6230 | } | |||
6231 | ||||
6232 | /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn | |||
6233 | /// the ParenListExpr into a sequence of comma binary operators. | |||
6234 | ExprResult | |||
6235 | Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { | |||
6236 | ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); | |||
6237 | if (!E) | |||
6238 | return OrigExpr; | |||
6239 | ||||
6240 | ExprResult Result(E->getExpr(0)); | |||
6241 | ||||
6242 | for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) | |||
6243 | Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), | |||
6244 | E->getExpr(i)); | |||
6245 | ||||
6246 | if (Result.isInvalid()) return ExprError(); | |||
6247 | ||||
6248 | return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); | |||
6249 | } | |||
6250 | ||||
6251 | ExprResult Sema::ActOnParenListExpr(SourceLocation L, | |||
6252 | SourceLocation R, | |||
6253 | MultiExprArg Val) { | |||
6254 | Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); | |||
6255 | return expr; | |||
6256 | } | |||
6257 | ||||
6258 | /// \brief Emit a specialized diagnostic when one expression is a null pointer | |||
6259 | /// constant and the other is not a pointer. Returns true if a diagnostic is | |||
6260 | /// emitted. | |||
6261 | bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, | |||
6262 | SourceLocation QuestionLoc) { | |||
6263 | Expr *NullExpr = LHSExpr; | |||
6264 | Expr *NonPointerExpr = RHSExpr; | |||
6265 | Expr::NullPointerConstantKind NullKind = | |||
6266 | NullExpr->isNullPointerConstant(Context, | |||
6267 | Expr::NPC_ValueDependentIsNotNull); | |||
6268 | ||||
6269 | if (NullKind == Expr::NPCK_NotNull) { | |||
6270 | NullExpr = RHSExpr; | |||
6271 | NonPointerExpr = LHSExpr; | |||
6272 | NullKind = | |||
6273 | NullExpr->isNullPointerConstant(Context, | |||
6274 | Expr::NPC_ValueDependentIsNotNull); | |||
6275 | } | |||
6276 | ||||
6277 | if (NullKind == Expr::NPCK_NotNull) | |||
6278 | return false; | |||
6279 | ||||
6280 | if (NullKind == Expr::NPCK_ZeroExpression) | |||
6281 | return false; | |||
6282 | ||||
6283 | if (NullKind == Expr::NPCK_ZeroLiteral) { | |||
6284 | // In this case, check to make sure that we got here from a "NULL" | |||
6285 | // string in the source code. | |||
6286 | NullExpr = NullExpr->IgnoreParenImpCasts(); | |||
6287 | SourceLocation loc = NullExpr->getExprLoc(); | |||
6288 | if (!findMacroSpelling(loc, "NULL")) | |||
6289 | return false; | |||
6290 | } | |||
6291 | ||||
6292 | int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); | |||
6293 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) | |||
6294 | << NonPointerExpr->getType() << DiagType | |||
6295 | << NonPointerExpr->getSourceRange(); | |||
6296 | return true; | |||
6297 | } | |||
6298 | ||||
6299 | /// \brief Return false if the condition expression is valid, true otherwise. | |||
6300 | static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { | |||
6301 | QualType CondTy = Cond->getType(); | |||
6302 | ||||
6303 | // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. | |||
6304 | if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { | |||
6305 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | |||
6306 | << CondTy << Cond->getSourceRange(); | |||
6307 | return true; | |||
6308 | } | |||
6309 | ||||
6310 | // C99 6.5.15p2 | |||
6311 | if (CondTy->isScalarType()) return false; | |||
6312 | ||||
6313 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) | |||
6314 | << CondTy << Cond->getSourceRange(); | |||
6315 | return true; | |||
6316 | } | |||
6317 | ||||
6318 | /// \brief Handle when one or both operands are void type. | |||
6319 | static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, | |||
6320 | ExprResult &RHS) { | |||
6321 | Expr *LHSExpr = LHS.get(); | |||
6322 | Expr *RHSExpr = RHS.get(); | |||
6323 | ||||
6324 | if (!LHSExpr->getType()->isVoidType()) | |||
6325 | S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) | |||
6326 | << RHSExpr->getSourceRange(); | |||
6327 | if (!RHSExpr->getType()->isVoidType()) | |||
6328 | S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) | |||
6329 | << LHSExpr->getSourceRange(); | |||
6330 | LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); | |||
6331 | RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); | |||
6332 | return S.Context.VoidTy; | |||
6333 | } | |||
6334 | ||||
6335 | /// \brief Return false if the NullExpr can be promoted to PointerTy, | |||
6336 | /// true otherwise. | |||
6337 | static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, | |||
6338 | QualType PointerTy) { | |||
6339 | if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || | |||
6340 | !NullExpr.get()->isNullPointerConstant(S.Context, | |||
6341 | Expr::NPC_ValueDependentIsNull)) | |||
6342 | return true; | |||
6343 | ||||
6344 | NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); | |||
6345 | return false; | |||
6346 | } | |||
6347 | ||||
6348 | /// \brief Checks compatibility between two pointers and return the resulting | |||
6349 | /// type. | |||
6350 | static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, | |||
6351 | ExprResult &RHS, | |||
6352 | SourceLocation Loc) { | |||
6353 | QualType LHSTy = LHS.get()->getType(); | |||
6354 | QualType RHSTy = RHS.get()->getType(); | |||
6355 | ||||
6356 | if (S.Context.hasSameType(LHSTy, RHSTy)) { | |||
6357 | // Two identical pointers types are always compatible. | |||
6358 | return LHSTy; | |||
6359 | } | |||
6360 | ||||
6361 | QualType lhptee, rhptee; | |||
6362 | ||||
6363 | // Get the pointee types. | |||
6364 | bool IsBlockPointer = false; | |||
6365 | if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { | |||
6366 | lhptee = LHSBTy->getPointeeType(); | |||
6367 | rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); | |||
6368 | IsBlockPointer = true; | |||
6369 | } else { | |||
6370 | lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | |||
6371 | rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | |||
6372 | } | |||
6373 | ||||
6374 | // C99 6.5.15p6: If both operands are pointers to compatible types or to | |||
6375 | // differently qualified versions of compatible types, the result type is | |||
6376 | // a pointer to an appropriately qualified version of the composite | |||
6377 | // type. | |||
6378 | ||||
6379 | // Only CVR-qualifiers exist in the standard, and the differently-qualified | |||
6380 | // clause doesn't make sense for our extensions. E.g. address space 2 should | |||
6381 | // be incompatible with address space 3: they may live on different devices or | |||
6382 | // anything. | |||
6383 | Qualifiers lhQual = lhptee.getQualifiers(); | |||
6384 | Qualifiers rhQual = rhptee.getQualifiers(); | |||
6385 | ||||
6386 | LangAS ResultAddrSpace = LangAS::Default; | |||
6387 | LangAS LAddrSpace = lhQual.getAddressSpace(); | |||
6388 | LangAS RAddrSpace = rhQual.getAddressSpace(); | |||
6389 | if (S.getLangOpts().OpenCL) { | |||
6390 | // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address | |||
6391 | // spaces is disallowed. | |||
6392 | if (lhQual.isAddressSpaceSupersetOf(rhQual)) | |||
6393 | ResultAddrSpace = LAddrSpace; | |||
6394 | else if (rhQual.isAddressSpaceSupersetOf(lhQual)) | |||
6395 | ResultAddrSpace = RAddrSpace; | |||
6396 | else { | |||
6397 | S.Diag(Loc, | |||
6398 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | |||
6399 | << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() | |||
6400 | << RHS.get()->getSourceRange(); | |||
6401 | return QualType(); | |||
6402 | } | |||
6403 | } | |||
6404 | ||||
6405 | unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); | |||
6406 | auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; | |||
6407 | lhQual.removeCVRQualifiers(); | |||
6408 | rhQual.removeCVRQualifiers(); | |||
6409 | ||||
6410 | // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers | |||
6411 | // (C99 6.7.3) for address spaces. We assume that the check should behave in | |||
6412 | // the same manner as it's defined for CVR qualifiers, so for OpenCL two | |||
6413 | // qual types are compatible iff | |||
6414 | // * corresponded types are compatible | |||
6415 | // * CVR qualifiers are equal | |||
6416 | // * address spaces are equal | |||
6417 | // Thus for conditional operator we merge CVR and address space unqualified | |||
6418 | // pointees and if there is a composite type we return a pointer to it with | |||
6419 | // merged qualifiers. | |||
6420 | if (S.getLangOpts().OpenCL) { | |||
6421 | LHSCastKind = LAddrSpace == ResultAddrSpace | |||
6422 | ? CK_BitCast | |||
6423 | : CK_AddressSpaceConversion; | |||
6424 | RHSCastKind = RAddrSpace == ResultAddrSpace | |||
6425 | ? CK_BitCast | |||
6426 | : CK_AddressSpaceConversion; | |||
6427 | lhQual.removeAddressSpace(); | |||
6428 | rhQual.removeAddressSpace(); | |||
6429 | } | |||
6430 | ||||
6431 | lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); | |||
6432 | rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); | |||
6433 | ||||
6434 | QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); | |||
6435 | ||||
6436 | if (CompositeTy.isNull()) { | |||
6437 | // In this situation, we assume void* type. No especially good | |||
6438 | // reason, but this is what gcc does, and we do have to pick | |||
6439 | // to get a consistent AST. | |||
6440 | QualType incompatTy; | |||
6441 | incompatTy = S.Context.getPointerType( | |||
6442 | S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); | |||
6443 | LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); | |||
6444 | RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); | |||
6445 | // FIXME: For OpenCL the warning emission and cast to void* leaves a room | |||
6446 | // for casts between types with incompatible address space qualifiers. | |||
6447 | // For the following code the compiler produces casts between global and | |||
6448 | // local address spaces of the corresponded innermost pointees: | |||
6449 | // local int *global *a; | |||
6450 | // global int *global *b; | |||
6451 | // a = (0 ? a : b); // see C99 6.5.16.1.p1. | |||
6452 | S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) | |||
6453 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | |||
6454 | << RHS.get()->getSourceRange(); | |||
6455 | return incompatTy; | |||
6456 | } | |||
6457 | ||||
6458 | // The pointer types are compatible. | |||
6459 | // In case of OpenCL ResultTy should have the address space qualifier | |||
6460 | // which is a superset of address spaces of both the 2nd and the 3rd | |||
6461 | // operands of the conditional operator. | |||
6462 | QualType ResultTy = [&, ResultAddrSpace]() { | |||
6463 | if (S.getLangOpts().OpenCL) { | |||
6464 | Qualifiers CompositeQuals = CompositeTy.getQualifiers(); | |||
6465 | CompositeQuals.setAddressSpace(ResultAddrSpace); | |||
6466 | return S.Context | |||
6467 | .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) | |||
6468 | .withCVRQualifiers(MergedCVRQual); | |||
6469 | } | |||
6470 | return CompositeTy.withCVRQualifiers(MergedCVRQual); | |||
6471 | }(); | |||
6472 | if (IsBlockPointer) | |||
6473 | ResultTy = S.Context.getBlockPointerType(ResultTy); | |||
6474 | else | |||
6475 | ResultTy = S.Context.getPointerType(ResultTy); | |||
6476 | ||||
6477 | LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); | |||
6478 | RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); | |||
6479 | return ResultTy; | |||
6480 | } | |||
6481 | ||||
6482 | /// \brief Return the resulting type when the operands are both block pointers. | |||
6483 | static QualType checkConditionalBlockPointerCompatibility(Sema &S, | |||
6484 | ExprResult &LHS, | |||
6485 | ExprResult &RHS, | |||
6486 | SourceLocation Loc) { | |||
6487 | QualType LHSTy = LHS.get()->getType(); | |||
6488 | QualType RHSTy = RHS.get()->getType(); | |||
6489 | ||||
6490 | if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { | |||
6491 | if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { | |||
6492 | QualType destType = S.Context.getPointerType(S.Context.VoidTy); | |||
6493 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | |||
6494 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | |||
6495 | return destType; | |||
6496 | } | |||
6497 | S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) | |||
6498 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | |||
6499 | << RHS.get()->getSourceRange(); | |||
6500 | return QualType(); | |||
6501 | } | |||
6502 | ||||
6503 | // We have 2 block pointer types. | |||
6504 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | |||
6505 | } | |||
6506 | ||||
6507 | /// \brief Return the resulting type when the operands are both pointers. | |||
6508 | static QualType | |||
6509 | checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, | |||
6510 | ExprResult &RHS, | |||
6511 | SourceLocation Loc) { | |||
6512 | // get the pointer types | |||
6513 | QualType LHSTy = LHS.get()->getType(); | |||
6514 | QualType RHSTy = RHS.get()->getType(); | |||
6515 | ||||
6516 | // get the "pointed to" types | |||
6517 | QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); | |||
6518 | QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); | |||
6519 | ||||
6520 | // ignore qualifiers on void (C99 6.5.15p3, clause 6) | |||
6521 | if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { | |||
6522 | // Figure out necessary qualifiers (C99 6.5.15p6) | |||
6523 | QualType destPointee | |||
6524 | = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | |||
6525 | QualType destType = S.Context.getPointerType(destPointee); | |||
6526 | // Add qualifiers if necessary. | |||
6527 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); | |||
6528 | // Promote to void*. | |||
6529 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | |||
6530 | return destType; | |||
6531 | } | |||
6532 | if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { | |||
6533 | QualType destPointee | |||
6534 | = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | |||
6535 | QualType destType = S.Context.getPointerType(destPointee); | |||
6536 | // Add qualifiers if necessary. | |||
6537 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); | |||
6538 | // Promote to void*. | |||
6539 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | |||
6540 | return destType; | |||
6541 | } | |||
6542 | ||||
6543 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | |||
6544 | } | |||
6545 | ||||
6546 | /// \brief Return false if the first expression is not an integer and the second | |||
6547 | /// expression is not a pointer, true otherwise. | |||
6548 | static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, | |||
6549 | Expr* PointerExpr, SourceLocation Loc, | |||
6550 | bool IsIntFirstExpr) { | |||
6551 | if (!PointerExpr->getType()->isPointerType() || | |||
6552 | !Int.get()->getType()->isIntegerType()) | |||
6553 | return false; | |||
6554 | ||||
6555 | Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; | |||
6556 | Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); | |||
6557 | ||||
6558 | S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) | |||
6559 | << Expr1->getType() << Expr2->getType() | |||
6560 | << Expr1->getSourceRange() << Expr2->getSourceRange(); | |||
6561 | Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), | |||
6562 | CK_IntegralToPointer); | |||
6563 | return true; | |||
6564 | } | |||
6565 | ||||
6566 | /// \brief Simple conversion between integer and floating point types. | |||
6567 | /// | |||
6568 | /// Used when handling the OpenCL conditional operator where the | |||
6569 | /// condition is a vector while the other operands are scalar. | |||
6570 | /// | |||
6571 | /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar | |||
6572 | /// types are either integer or floating type. Between the two | |||
6573 | /// operands, the type with the higher rank is defined as the "result | |||
6574 | /// type". The other operand needs to be promoted to the same type. No | |||
6575 | /// other type promotion is allowed. We cannot use | |||
6576 | /// UsualArithmeticConversions() for this purpose, since it always | |||
6577 | /// promotes promotable types. | |||
6578 | static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, | |||
6579 | ExprResult &RHS, | |||
6580 | SourceLocation QuestionLoc) { | |||
6581 | LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
6582 | if (LHS.isInvalid()) | |||
6583 | return QualType(); | |||
6584 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
6585 | if (RHS.isInvalid()) | |||
6586 | return QualType(); | |||
6587 | ||||
6588 | // For conversion purposes, we ignore any qualifiers. | |||
6589 | // For example, "const float" and "float" are equivalent. | |||
6590 | QualType LHSType = | |||
6591 | S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | |||
6592 | QualType RHSType = | |||
6593 | S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | |||
6594 | ||||
6595 | if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { | |||
6596 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | |||
6597 | << LHSType << LHS.get()->getSourceRange(); | |||
6598 | return QualType(); | |||
6599 | } | |||
6600 | ||||
6601 | if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { | |||
6602 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | |||
6603 | << RHSType << RHS.get()->getSourceRange(); | |||
6604 | return QualType(); | |||
6605 | } | |||
6606 | ||||
6607 | // If both types are identical, no conversion is needed. | |||
6608 | if (LHSType == RHSType) | |||
6609 | return LHSType; | |||
6610 | ||||
6611 | // Now handle "real" floating types (i.e. float, double, long double). | |||
6612 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | |||
6613 | return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, | |||
6614 | /*IsCompAssign = */ false); | |||
6615 | ||||
6616 | // Finally, we have two differing integer types. | |||
6617 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | |||
6618 | (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); | |||
6619 | } | |||
6620 | ||||
6621 | /// \brief Convert scalar operands to a vector that matches the | |||
6622 | /// condition in length. | |||
6623 | /// | |||
6624 | /// Used when handling the OpenCL conditional operator where the | |||
6625 | /// condition is a vector while the other operands are scalar. | |||
6626 | /// | |||
6627 | /// We first compute the "result type" for the scalar operands | |||
6628 | /// according to OpenCL v1.1 s6.3.i. Both operands are then converted | |||
6629 | /// into a vector of that type where the length matches the condition | |||
6630 | /// vector type. s6.11.6 requires that the element types of the result | |||
6631 | /// and the condition must have the same number of bits. | |||
6632 | static QualType | |||
6633 | OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, | |||
6634 | QualType CondTy, SourceLocation QuestionLoc) { | |||
6635 | QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); | |||
6636 | if (ResTy.isNull()) return QualType(); | |||
6637 | ||||
6638 | const VectorType *CV = CondTy->getAs<VectorType>(); | |||
6639 | assert(CV)(static_cast <bool> (CV) ? void (0) : __assert_fail ("CV" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 6639, __extension__ __PRETTY_FUNCTION__)); | |||
6640 | ||||
6641 | // Determine the vector result type | |||
6642 | unsigned NumElements = CV->getNumElements(); | |||
6643 | QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); | |||
6644 | ||||
6645 | // Ensure that all types have the same number of bits | |||
6646 | if (S.Context.getTypeSize(CV->getElementType()) | |||
6647 | != S.Context.getTypeSize(ResTy)) { | |||
6648 | // Since VectorTy is created internally, it does not pretty print | |||
6649 | // with an OpenCL name. Instead, we just print a description. | |||
6650 | std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); | |||
6651 | SmallString<64> Str; | |||
6652 | llvm::raw_svector_ostream OS(Str); | |||
6653 | OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; | |||
6654 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | |||
6655 | << CondTy << OS.str(); | |||
6656 | return QualType(); | |||
6657 | } | |||
6658 | ||||
6659 | // Convert operands to the vector result type | |||
6660 | LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); | |||
6661 | RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); | |||
6662 | ||||
6663 | return VectorTy; | |||
6664 | } | |||
6665 | ||||
6666 | /// \brief Return false if this is a valid OpenCL condition vector | |||
6667 | static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, | |||
6668 | SourceLocation QuestionLoc) { | |||
6669 | // OpenCL v1.1 s6.11.6 says the elements of the vector must be of | |||
6670 | // integral type. | |||
6671 | const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); | |||
6672 | assert(CondTy)(static_cast <bool> (CondTy) ? void (0) : __assert_fail ("CondTy", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 6672, __extension__ __PRETTY_FUNCTION__)); | |||
6673 | QualType EleTy = CondTy->getElementType(); | |||
6674 | if (EleTy->isIntegerType()) return false; | |||
6675 | ||||
6676 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | |||
6677 | << Cond->getType() << Cond->getSourceRange(); | |||
6678 | return true; | |||
6679 | } | |||
6680 | ||||
6681 | /// \brief Return false if the vector condition type and the vector | |||
6682 | /// result type are compatible. | |||
6683 | /// | |||
6684 | /// OpenCL v1.1 s6.11.6 requires that both vector types have the same | |||
6685 | /// number of elements, and their element types have the same number | |||
6686 | /// of bits. | |||
6687 | static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, | |||
6688 | SourceLocation QuestionLoc) { | |||
6689 | const VectorType *CV = CondTy->getAs<VectorType>(); | |||
6690 | const VectorType *RV = VecResTy->getAs<VectorType>(); | |||
6691 | assert(CV && RV)(static_cast <bool> (CV && RV) ? void (0) : __assert_fail ("CV && RV", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 6691, __extension__ __PRETTY_FUNCTION__)); | |||
6692 | ||||
6693 | if (CV->getNumElements() != RV->getNumElements()) { | |||
6694 | S.Diag(QuestionLoc, diag::err_conditional_vector_size) | |||
6695 | << CondTy << VecResTy; | |||
6696 | return true; | |||
6697 | } | |||
6698 | ||||
6699 | QualType CVE = CV->getElementType(); | |||
6700 | QualType RVE = RV->getElementType(); | |||
6701 | ||||
6702 | if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { | |||
6703 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | |||
6704 | << CondTy << VecResTy; | |||
6705 | return true; | |||
6706 | } | |||
6707 | ||||
6708 | return false; | |||
6709 | } | |||
6710 | ||||
6711 | /// \brief Return the resulting type for the conditional operator in | |||
6712 | /// OpenCL (aka "ternary selection operator", OpenCL v1.1 | |||
6713 | /// s6.3.i) when the condition is a vector type. | |||
6714 | static QualType | |||
6715 | OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, | |||
6716 | ExprResult &LHS, ExprResult &RHS, | |||
6717 | SourceLocation QuestionLoc) { | |||
6718 | Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); | |||
6719 | if (Cond.isInvalid()) | |||
6720 | return QualType(); | |||
6721 | QualType CondTy = Cond.get()->getType(); | |||
6722 | ||||
6723 | if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) | |||
6724 | return QualType(); | |||
6725 | ||||
6726 | // If either operand is a vector then find the vector type of the | |||
6727 | // result as specified in OpenCL v1.1 s6.3.i. | |||
6728 | if (LHS.get()->getType()->isVectorType() || | |||
6729 | RHS.get()->getType()->isVectorType()) { | |||
6730 | QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, | |||
6731 | /*isCompAssign*/false, | |||
6732 | /*AllowBothBool*/true, | |||
6733 | /*AllowBoolConversions*/false); | |||
6734 | if (VecResTy.isNull()) return QualType(); | |||
6735 | // The result type must match the condition type as specified in | |||
6736 | // OpenCL v1.1 s6.11.6. | |||
6737 | if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) | |||
6738 | return QualType(); | |||
6739 | return VecResTy; | |||
6740 | } | |||
6741 | ||||
6742 | // Both operands are scalar. | |||
6743 | return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); | |||
6744 | } | |||
6745 | ||||
6746 | /// \brief Return true if the Expr is block type | |||
6747 | static bool checkBlockType(Sema &S, const Expr *E) { | |||
6748 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | |||
6749 | QualType Ty = CE->getCallee()->getType(); | |||
6750 | if (Ty->isBlockPointerType()) { | |||
6751 | S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); | |||
6752 | return true; | |||
6753 | } | |||
6754 | } | |||
6755 | return false; | |||
6756 | } | |||
6757 | ||||
6758 | /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. | |||
6759 | /// In that case, LHS = cond. | |||
6760 | /// C99 6.5.15 | |||
6761 | QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, | |||
6762 | ExprResult &RHS, ExprValueKind &VK, | |||
6763 | ExprObjectKind &OK, | |||
6764 | SourceLocation QuestionLoc) { | |||
6765 | ||||
6766 | ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); | |||
6767 | if (!LHSResult.isUsable()) return QualType(); | |||
6768 | LHS = LHSResult; | |||
6769 | ||||
6770 | ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); | |||
6771 | if (!RHSResult.isUsable()) return QualType(); | |||
6772 | RHS = RHSResult; | |||
6773 | ||||
6774 | // C++ is sufficiently different to merit its own checker. | |||
6775 | if (getLangOpts().CPlusPlus) | |||
6776 | return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); | |||
6777 | ||||
6778 | VK = VK_RValue; | |||
6779 | OK = OK_Ordinary; | |||
6780 | ||||
6781 | // The OpenCL operator with a vector condition is sufficiently | |||
6782 | // different to merit its own checker. | |||
6783 | if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) | |||
6784 | return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); | |||
6785 | ||||
6786 | // First, check the condition. | |||
6787 | Cond = UsualUnaryConversions(Cond.get()); | |||
6788 | if (Cond.isInvalid()) | |||
6789 | return QualType(); | |||
6790 | if (checkCondition(*this, Cond.get(), QuestionLoc)) | |||
6791 | return QualType(); | |||
6792 | ||||
6793 | // Now check the two expressions. | |||
6794 | if (LHS.get()->getType()->isVectorType() || | |||
6795 | RHS.get()->getType()->isVectorType()) | |||
6796 | return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, | |||
6797 | /*AllowBothBool*/true, | |||
6798 | /*AllowBoolConversions*/false); | |||
6799 | ||||
6800 | QualType ResTy = UsualArithmeticConversions(LHS, RHS); | |||
6801 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
6802 | return QualType(); | |||
6803 | ||||
6804 | QualType LHSTy = LHS.get()->getType(); | |||
6805 | QualType RHSTy = RHS.get()->getType(); | |||
6806 | ||||
6807 | // Diagnose attempts to convert between __float128 and long double where | |||
6808 | // such conversions currently can't be handled. | |||
6809 | if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { | |||
6810 | Diag(QuestionLoc, | |||
6811 | diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy | |||
6812 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6813 | return QualType(); | |||
6814 | } | |||
6815 | ||||
6816 | // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary | |||
6817 | // selection operator (?:). | |||
6818 | if (getLangOpts().OpenCL && | |||
6819 | (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { | |||
6820 | return QualType(); | |||
6821 | } | |||
6822 | ||||
6823 | // If both operands have arithmetic type, do the usual arithmetic conversions | |||
6824 | // to find a common type: C99 6.5.15p3,5. | |||
6825 | if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { | |||
6826 | LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); | |||
6827 | RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); | |||
6828 | ||||
6829 | return ResTy; | |||
6830 | } | |||
6831 | ||||
6832 | // If both operands are the same structure or union type, the result is that | |||
6833 | // type. | |||
6834 | if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 | |||
6835 | if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) | |||
6836 | if (LHSRT->getDecl() == RHSRT->getDecl()) | |||
6837 | // "If both the operands have structure or union type, the result has | |||
6838 | // that type." This implies that CV qualifiers are dropped. | |||
6839 | return LHSTy.getUnqualifiedType(); | |||
6840 | // FIXME: Type of conditional expression must be complete in C mode. | |||
6841 | } | |||
6842 | ||||
6843 | // C99 6.5.15p5: "If both operands have void type, the result has void type." | |||
6844 | // The following || allows only one side to be void (a GCC-ism). | |||
6845 | if (LHSTy->isVoidType() || RHSTy->isVoidType()) { | |||
6846 | return checkConditionalVoidType(*this, LHS, RHS); | |||
6847 | } | |||
6848 | ||||
6849 | // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has | |||
6850 | // the type of the other operand." | |||
6851 | if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; | |||
6852 | if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; | |||
6853 | ||||
6854 | // All objective-c pointer type analysis is done here. | |||
6855 | QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, | |||
6856 | QuestionLoc); | |||
6857 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
6858 | return QualType(); | |||
6859 | if (!compositeType.isNull()) | |||
6860 | return compositeType; | |||
6861 | ||||
6862 | ||||
6863 | // Handle block pointer types. | |||
6864 | if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) | |||
6865 | return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, | |||
6866 | QuestionLoc); | |||
6867 | ||||
6868 | // Check constraints for C object pointers types (C99 6.5.15p3,6). | |||
6869 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) | |||
6870 | return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, | |||
6871 | QuestionLoc); | |||
6872 | ||||
6873 | // GCC compatibility: soften pointer/integer mismatch. Note that | |||
6874 | // null pointers have been filtered out by this point. | |||
6875 | if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, | |||
6876 | /*isIntFirstExpr=*/true)) | |||
6877 | return RHSTy; | |||
6878 | if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, | |||
6879 | /*isIntFirstExpr=*/false)) | |||
6880 | return LHSTy; | |||
6881 | ||||
6882 | // Emit a better diagnostic if one of the expressions is a null pointer | |||
6883 | // constant and the other is not a pointer type. In this case, the user most | |||
6884 | // likely forgot to take the address of the other expression. | |||
6885 | if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | |||
6886 | return QualType(); | |||
6887 | ||||
6888 | // Otherwise, the operands are not compatible. | |||
6889 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | |||
6890 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | |||
6891 | << RHS.get()->getSourceRange(); | |||
6892 | return QualType(); | |||
6893 | } | |||
6894 | ||||
6895 | /// FindCompositeObjCPointerType - Helper method to find composite type of | |||
6896 | /// two objective-c pointer types of the two input expressions. | |||
6897 | QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, | |||
6898 | SourceLocation QuestionLoc) { | |||
6899 | QualType LHSTy = LHS.get()->getType(); | |||
6900 | QualType RHSTy = RHS.get()->getType(); | |||
6901 | ||||
6902 | // Handle things like Class and struct objc_class*. Here we case the result | |||
6903 | // to the pseudo-builtin, because that will be implicitly cast back to the | |||
6904 | // redefinition type if an attempt is made to access its fields. | |||
6905 | if (LHSTy->isObjCClassType() && | |||
6906 | (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { | |||
6907 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | |||
6908 | return LHSTy; | |||
6909 | } | |||
6910 | if (RHSTy->isObjCClassType() && | |||
6911 | (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { | |||
6912 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | |||
6913 | return RHSTy; | |||
6914 | } | |||
6915 | // And the same for struct objc_object* / id | |||
6916 | if (LHSTy->isObjCIdType() && | |||
6917 | (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { | |||
6918 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | |||
6919 | return LHSTy; | |||
6920 | } | |||
6921 | if (RHSTy->isObjCIdType() && | |||
6922 | (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { | |||
6923 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | |||
6924 | return RHSTy; | |||
6925 | } | |||
6926 | // And the same for struct objc_selector* / SEL | |||
6927 | if (Context.isObjCSelType(LHSTy) && | |||
6928 | (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { | |||
6929 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); | |||
6930 | return LHSTy; | |||
6931 | } | |||
6932 | if (Context.isObjCSelType(RHSTy) && | |||
6933 | (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { | |||
6934 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); | |||
6935 | return RHSTy; | |||
6936 | } | |||
6937 | // Check constraints for Objective-C object pointers types. | |||
6938 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { | |||
6939 | ||||
6940 | if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { | |||
6941 | // Two identical object pointer types are always compatible. | |||
6942 | return LHSTy; | |||
6943 | } | |||
6944 | const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); | |||
6945 | const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); | |||
6946 | QualType compositeType = LHSTy; | |||
6947 | ||||
6948 | // If both operands are interfaces and either operand can be | |||
6949 | // assigned to the other, use that type as the composite | |||
6950 | // type. This allows | |||
6951 | // xxx ? (A*) a : (B*) b | |||
6952 | // where B is a subclass of A. | |||
6953 | // | |||
6954 | // Additionally, as for assignment, if either type is 'id' | |||
6955 | // allow silent coercion. Finally, if the types are | |||
6956 | // incompatible then make sure to use 'id' as the composite | |||
6957 | // type so the result is acceptable for sending messages to. | |||
6958 | ||||
6959 | // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. | |||
6960 | // It could return the composite type. | |||
6961 | if (!(compositeType = | |||
6962 | Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { | |||
6963 | // Nothing more to do. | |||
6964 | } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { | |||
6965 | compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; | |||
6966 | } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { | |||
6967 | compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; | |||
6968 | } else if ((LHSTy->isObjCQualifiedIdType() || | |||
6969 | RHSTy->isObjCQualifiedIdType()) && | |||
6970 | Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { | |||
6971 | // Need to handle "id<xx>" explicitly. | |||
6972 | // GCC allows qualified id and any Objective-C type to devolve to | |||
6973 | // id. Currently localizing to here until clear this should be | |||
6974 | // part of ObjCQualifiedIdTypesAreCompatible. | |||
6975 | compositeType = Context.getObjCIdType(); | |||
6976 | } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { | |||
6977 | compositeType = Context.getObjCIdType(); | |||
6978 | } else { | |||
6979 | Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) | |||
6980 | << LHSTy << RHSTy | |||
6981 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6982 | QualType incompatTy = Context.getObjCIdType(); | |||
6983 | LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); | |||
6984 | RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); | |||
6985 | return incompatTy; | |||
6986 | } | |||
6987 | // The object pointer types are compatible. | |||
6988 | LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); | |||
6989 | RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); | |||
6990 | return compositeType; | |||
6991 | } | |||
6992 | // Check Objective-C object pointer types and 'void *' | |||
6993 | if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { | |||
6994 | if (getLangOpts().ObjCAutoRefCount) { | |||
6995 | // ARC forbids the implicit conversion of object pointers to 'void *', | |||
6996 | // so these types are not compatible. | |||
6997 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | |||
6998 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6999 | LHS = RHS = true; | |||
7000 | return QualType(); | |||
7001 | } | |||
7002 | QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); | |||
7003 | QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); | |||
7004 | QualType destPointee | |||
7005 | = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | |||
7006 | QualType destType = Context.getPointerType(destPointee); | |||
7007 | // Add qualifiers if necessary. | |||
7008 | LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); | |||
7009 | // Promote to void*. | |||
7010 | RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); | |||
7011 | return destType; | |||
7012 | } | |||
7013 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { | |||
7014 | if (getLangOpts().ObjCAutoRefCount) { | |||
7015 | // ARC forbids the implicit conversion of object pointers to 'void *', | |||
7016 | // so these types are not compatible. | |||
7017 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | |||
7018 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
7019 | LHS = RHS = true; | |||
7020 | return QualType(); | |||
7021 | } | |||
7022 | QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); | |||
7023 | QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); | |||
7024 | QualType destPointee | |||
7025 | = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | |||
7026 | QualType destType = Context.getPointerType(destPointee); | |||
7027 | // Add qualifiers if necessary. | |||
7028 | RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); | |||
7029 | // Promote to void*. | |||
7030 | LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); | |||
7031 | return destType; | |||
7032 | } | |||
7033 | return QualType(); | |||
7034 | } | |||
7035 | ||||
7036 | /// SuggestParentheses - Emit a note with a fixit hint that wraps | |||
7037 | /// ParenRange in parentheses. | |||
7038 | static void SuggestParentheses(Sema &Self, SourceLocation Loc, | |||
7039 | const PartialDiagnostic &Note, | |||
7040 | SourceRange ParenRange) { | |||
7041 | SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); | |||
7042 | if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && | |||
7043 | EndLoc.isValid()) { | |||
7044 | Self.Diag(Loc, Note) | |||
7045 | << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") | |||
7046 | << FixItHint::CreateInsertion(EndLoc, ")"); | |||
7047 | } else { | |||
7048 | // We can't display the parentheses, so just show the bare note. | |||
7049 | Self.Diag(Loc, Note) << ParenRange; | |||
7050 | } | |||
7051 | } | |||
7052 | ||||
7053 | static bool IsArithmeticOp(BinaryOperatorKind Opc) { | |||
7054 | return BinaryOperator::isAdditiveOp(Opc) || | |||
7055 | BinaryOperator::isMultiplicativeOp(Opc) || | |||
7056 | BinaryOperator::isShiftOp(Opc); | |||
7057 | } | |||
7058 | ||||
7059 | /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary | |||
7060 | /// expression, either using a built-in or overloaded operator, | |||
7061 | /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side | |||
7062 | /// expression. | |||
7063 | static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, | |||
7064 | Expr **RHSExprs) { | |||
7065 | // Don't strip parenthesis: we should not warn if E is in parenthesis. | |||
7066 | E = E->IgnoreImpCasts(); | |||
7067 | E = E->IgnoreConversionOperator(); | |||
7068 | E = E->IgnoreImpCasts(); | |||
7069 | ||||
7070 | // Built-in binary operator. | |||
7071 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { | |||
7072 | if (IsArithmeticOp(OP->getOpcode())) { | |||
7073 | *Opcode = OP->getOpcode(); | |||
7074 | *RHSExprs = OP->getRHS(); | |||
7075 | return true; | |||
7076 | } | |||
7077 | } | |||
7078 | ||||
7079 | // Overloaded operator. | |||
7080 | if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { | |||
7081 | if (Call->getNumArgs() != 2) | |||
7082 | return false; | |||
7083 | ||||
7084 | // Make sure this is really a binary operator that is safe to pass into | |||
7085 | // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. | |||
7086 | OverloadedOperatorKind OO = Call->getOperator(); | |||
7087 | if (OO < OO_Plus || OO > OO_Arrow || | |||
7088 | OO == OO_PlusPlus || OO == OO_MinusMinus) | |||
7089 | return false; | |||
7090 | ||||
7091 | BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); | |||
7092 | if (IsArithmeticOp(OpKind)) { | |||
7093 | *Opcode = OpKind; | |||
7094 | *RHSExprs = Call->getArg(1); | |||
7095 | return true; | |||
7096 | } | |||
7097 | } | |||
7098 | ||||
7099 | return false; | |||
7100 | } | |||
7101 | ||||
7102 | /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type | |||
7103 | /// or is a logical expression such as (x==y) which has int type, but is | |||
7104 | /// commonly interpreted as boolean. | |||
7105 | static bool ExprLooksBoolean(Expr *E) { | |||
7106 | E = E->IgnoreParenImpCasts(); | |||
7107 | ||||
7108 | if (E->getType()->isBooleanType()) | |||
7109 | return true; | |||
7110 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) | |||
7111 | return OP->isComparisonOp() || OP->isLogicalOp(); | |||
7112 | if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) | |||
7113 | return OP->getOpcode() == UO_LNot; | |||
7114 | if (E->getType()->isPointerType()) | |||
7115 | return true; | |||
7116 | ||||
7117 | return false; | |||
7118 | } | |||
7119 | ||||
7120 | /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator | |||
7121 | /// and binary operator are mixed in a way that suggests the programmer assumed | |||
7122 | /// the conditional operator has higher precedence, for example: | |||
7123 | /// "int x = a + someBinaryCondition ? 1 : 2". | |||
7124 | static void DiagnoseConditionalPrecedence(Sema &Self, | |||
7125 | SourceLocation OpLoc, | |||
7126 | Expr *Condition, | |||
7127 | Expr *LHSExpr, | |||
7128 | Expr *RHSExpr) { | |||
7129 | BinaryOperatorKind CondOpcode; | |||
7130 | Expr *CondRHS; | |||
7131 | ||||
7132 | if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) | |||
7133 | return; | |||
7134 | if (!ExprLooksBoolean(CondRHS)) | |||
7135 | return; | |||
7136 | ||||
7137 | // The condition is an arithmetic binary expression, with a right- | |||
7138 | // hand side that looks boolean, so warn. | |||
7139 | ||||
7140 | Self.Diag(OpLoc, diag::warn_precedence_conditional) | |||
7141 | << Condition->getSourceRange() | |||
7142 | << BinaryOperator::getOpcodeStr(CondOpcode); | |||
7143 | ||||
7144 | SuggestParentheses(Self, OpLoc, | |||
7145 | Self.PDiag(diag::note_precedence_silence) | |||
7146 | << BinaryOperator::getOpcodeStr(CondOpcode), | |||
7147 | SourceRange(Condition->getLocStart(), Condition->getLocEnd())); | |||
7148 | ||||
7149 | SuggestParentheses(Self, OpLoc, | |||
7150 | Self.PDiag(diag::note_precedence_conditional_first), | |||
7151 | SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); | |||
7152 | } | |||
7153 | ||||
7154 | /// Compute the nullability of a conditional expression. | |||
7155 | static QualType computeConditionalNullability(QualType ResTy, bool IsBin, | |||
7156 | QualType LHSTy, QualType RHSTy, | |||
7157 | ASTContext &Ctx) { | |||
7158 | if (!ResTy->isAnyPointerType()) | |||
7159 | return ResTy; | |||
7160 | ||||
7161 | auto GetNullability = [&Ctx](QualType Ty) { | |||
7162 | Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); | |||
7163 | if (Kind) | |||
7164 | return *Kind; | |||
7165 | return NullabilityKind::Unspecified; | |||
7166 | }; | |||
7167 | ||||
7168 | auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); | |||
7169 | NullabilityKind MergedKind; | |||
7170 | ||||
7171 | // Compute nullability of a binary conditional expression. | |||
7172 | if (IsBin) { | |||
7173 | if (LHSKind == NullabilityKind::NonNull) | |||
7174 | MergedKind = NullabilityKind::NonNull; | |||
7175 | else | |||
7176 | MergedKind = RHSKind; | |||
7177 | // Compute nullability of a normal conditional expression. | |||
7178 | } else { | |||
7179 | if (LHSKind == NullabilityKind::Nullable || | |||
7180 | RHSKind == NullabilityKind::Nullable) | |||
7181 | MergedKind = NullabilityKind::Nullable; | |||
7182 | else if (LHSKind == NullabilityKind::NonNull) | |||
7183 | MergedKind = RHSKind; | |||
7184 | else if (RHSKind == NullabilityKind::NonNull) | |||
7185 | MergedKind = LHSKind; | |||
7186 | else | |||
7187 | MergedKind = NullabilityKind::Unspecified; | |||
7188 | } | |||
7189 | ||||
7190 | // Return if ResTy already has the correct nullability. | |||
7191 | if (GetNullability(ResTy) == MergedKind) | |||
7192 | return ResTy; | |||
7193 | ||||
7194 | // Strip all nullability from ResTy. | |||
7195 | while (ResTy->getNullability(Ctx)) | |||
7196 | ResTy = ResTy.getSingleStepDesugaredType(Ctx); | |||
7197 | ||||
7198 | // Create a new AttributedType with the new nullability kind. | |||
7199 | auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); | |||
7200 | return Ctx.getAttributedType(NewAttr, ResTy, ResTy); | |||
7201 | } | |||
7202 | ||||
7203 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null | |||
7204 | /// in the case of a the GNU conditional expr extension. | |||
7205 | ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, | |||
7206 | SourceLocation ColonLoc, | |||
7207 | Expr *CondExpr, Expr *LHSExpr, | |||
7208 | Expr *RHSExpr) { | |||
7209 | if (!getLangOpts().CPlusPlus) { | |||
7210 | // C cannot handle TypoExpr nodes in the condition because it | |||
7211 | // doesn't handle dependent types properly, so make sure any TypoExprs have | |||
7212 | // been dealt with before checking the operands. | |||
7213 | ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); | |||
7214 | ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); | |||
7215 | ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); | |||
7216 | ||||
7217 | if (!CondResult.isUsable()) | |||
7218 | return ExprError(); | |||
7219 | ||||
7220 | if (LHSExpr) { | |||
7221 | if (!LHSResult.isUsable()) | |||
7222 | return ExprError(); | |||
7223 | } | |||
7224 | ||||
7225 | if (!RHSResult.isUsable()) | |||
7226 | return ExprError(); | |||
7227 | ||||
7228 | CondExpr = CondResult.get(); | |||
7229 | LHSExpr = LHSResult.get(); | |||
7230 | RHSExpr = RHSResult.get(); | |||
7231 | } | |||
7232 | ||||
7233 | // If this is the gnu "x ?: y" extension, analyze the types as though the LHS | |||
7234 | // was the condition. | |||
7235 | OpaqueValueExpr *opaqueValue = nullptr; | |||
7236 | Expr *commonExpr = nullptr; | |||
7237 | if (!LHSExpr) { | |||
7238 | commonExpr = CondExpr; | |||
7239 | // Lower out placeholder types first. This is important so that we don't | |||
7240 | // try to capture a placeholder. This happens in few cases in C++; such | |||
7241 | // as Objective-C++'s dictionary subscripting syntax. | |||
7242 | if (commonExpr->hasPlaceholderType()) { | |||
7243 | ExprResult result = CheckPlaceholderExpr(commonExpr); | |||
7244 | if (!result.isUsable()) return ExprError(); | |||
7245 | commonExpr = result.get(); | |||
7246 | } | |||
7247 | // We usually want to apply unary conversions *before* saving, except | |||
7248 | // in the special case of a C++ l-value conditional. | |||
7249 | if (!(getLangOpts().CPlusPlus | |||
7250 | && !commonExpr->isTypeDependent() | |||
7251 | && commonExpr->getValueKind() == RHSExpr->getValueKind() | |||
7252 | && commonExpr->isGLValue() | |||
7253 | && commonExpr->isOrdinaryOrBitFieldObject() | |||
7254 | && RHSExpr->isOrdinaryOrBitFieldObject() | |||
7255 | && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { | |||
7256 | ExprResult commonRes = UsualUnaryConversions(commonExpr); | |||
7257 | if (commonRes.isInvalid()) | |||
7258 | return ExprError(); | |||
7259 | commonExpr = commonRes.get(); | |||
7260 | } | |||
7261 | ||||
7262 | // If the common expression is a class or array prvalue, materialize it | |||
7263 | // so that we can safely refer to it multiple times. | |||
7264 | if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || | |||
7265 | commonExpr->getType()->isArrayType())) { | |||
7266 | ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); | |||
7267 | if (MatExpr.isInvalid()) | |||
7268 | return ExprError(); | |||
7269 | commonExpr = MatExpr.get(); | |||
7270 | } | |||
7271 | ||||
7272 | opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), | |||
7273 | commonExpr->getType(), | |||
7274 | commonExpr->getValueKind(), | |||
7275 | commonExpr->getObjectKind(), | |||
7276 | commonExpr); | |||
7277 | LHSExpr = CondExpr = opaqueValue; | |||
7278 | } | |||
7279 | ||||
7280 | QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); | |||
7281 | ExprValueKind VK = VK_RValue; | |||
7282 | ExprObjectKind OK = OK_Ordinary; | |||
7283 | ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; | |||
7284 | QualType result = CheckConditionalOperands(Cond, LHS, RHS, | |||
7285 | VK, OK, QuestionLoc); | |||
7286 | if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || | |||
7287 | RHS.isInvalid()) | |||
7288 | return ExprError(); | |||
7289 | ||||
7290 | DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), | |||
7291 | RHS.get()); | |||
7292 | ||||
7293 | CheckBoolLikeConversion(Cond.get(), QuestionLoc); | |||
7294 | ||||
7295 | result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, | |||
7296 | Context); | |||
7297 | ||||
7298 | if (!commonExpr) | |||
7299 | return new (Context) | |||
7300 | ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, | |||
7301 | RHS.get(), result, VK, OK); | |||
7302 | ||||
7303 | return new (Context) BinaryConditionalOperator( | |||
7304 | commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, | |||
7305 | ColonLoc, result, VK, OK); | |||
7306 | } | |||
7307 | ||||
7308 | // checkPointerTypesForAssignment - This is a very tricky routine (despite | |||
7309 | // being closely modeled after the C99 spec:-). The odd characteristic of this | |||
7310 | // routine is it effectively iqnores the qualifiers on the top level pointee. | |||
7311 | // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. | |||
7312 | // FIXME: add a couple examples in this comment. | |||
7313 | static Sema::AssignConvertType | |||
7314 | checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { | |||
7315 | assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 7315, __extension__ __PRETTY_FUNCTION__)); | |||
7316 | assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 7316, __extension__ __PRETTY_FUNCTION__)); | |||
7317 | ||||
7318 | // get the "pointed to" type (ignoring qualifiers at the top level) | |||
7319 | const Type *lhptee, *rhptee; | |||
7320 | Qualifiers lhq, rhq; | |||
7321 | std::tie(lhptee, lhq) = | |||
7322 | cast<PointerType>(LHSType)->getPointeeType().split().asPair(); | |||
7323 | std::tie(rhptee, rhq) = | |||
7324 | cast<PointerType>(RHSType)->getPointeeType().split().asPair(); | |||
7325 | ||||
7326 | Sema::AssignConvertType ConvTy = Sema::Compatible; | |||
7327 | ||||
7328 | // C99 6.5.16.1p1: This following citation is common to constraints | |||
7329 | // 3 & 4 (below). ...and the type *pointed to* by the left has all the | |||
7330 | // qualifiers of the type *pointed to* by the right; | |||
7331 | ||||
7332 | // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. | |||
7333 | if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && | |||
7334 | lhq.compatiblyIncludesObjCLifetime(rhq)) { | |||
7335 | // Ignore lifetime for further calculation. | |||
7336 | lhq.removeObjCLifetime(); | |||
7337 | rhq.removeObjCLifetime(); | |||
7338 | } | |||
7339 | ||||
7340 | if (!lhq.compatiblyIncludes(rhq)) { | |||
7341 | // Treat address-space mismatches as fatal. TODO: address subspaces | |||
7342 | if (!lhq.isAddressSpaceSupersetOf(rhq)) | |||
7343 | ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; | |||
7344 | ||||
7345 | // It's okay to add or remove GC or lifetime qualifiers when converting to | |||
7346 | // and from void*. | |||
7347 | else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() | |||
7348 | .compatiblyIncludes( | |||
7349 | rhq.withoutObjCGCAttr().withoutObjCLifetime()) | |||
7350 | && (lhptee->isVoidType() || rhptee->isVoidType())) | |||
7351 | ; // keep old | |||
7352 | ||||
7353 | // Treat lifetime mismatches as fatal. | |||
7354 | else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) | |||
7355 | ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; | |||
7356 | ||||
7357 | // For GCC/MS compatibility, other qualifier mismatches are treated | |||
7358 | // as still compatible in C. | |||
7359 | else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | |||
7360 | } | |||
7361 | ||||
7362 | // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or | |||
7363 | // incomplete type and the other is a pointer to a qualified or unqualified | |||
7364 | // version of void... | |||
7365 | if (lhptee->isVoidType()) { | |||
7366 | if (rhptee->isIncompleteOrObjectType()) | |||
7367 | return ConvTy; | |||
7368 | ||||
7369 | // As an extension, we allow cast to/from void* to function pointer. | |||
7370 | assert(rhptee->isFunctionType())(static_cast <bool> (rhptee->isFunctionType()) ? void (0) : __assert_fail ("rhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 7370, __extension__ __PRETTY_FUNCTION__)); | |||
7371 | return Sema::FunctionVoidPointer; | |||
7372 | } | |||
7373 | ||||
7374 | if (rhptee->isVoidType()) { | |||
7375 | if (lhptee->isIncompleteOrObjectType()) | |||
7376 | return ConvTy; | |||
7377 | ||||
7378 | // As an extension, we allow cast to/from void* to function pointer. | |||
7379 | assert(lhptee->isFunctionType())(static_cast <bool> (lhptee->isFunctionType()) ? void (0) : __assert_fail ("lhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 7379, __extension__ __PRETTY_FUNCTION__)); | |||
7380 | return Sema::FunctionVoidPointer; | |||
7381 | } | |||
7382 | ||||
7383 | // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or | |||
7384 | // unqualified versions of compatible types, ... | |||
7385 | QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); | |||
7386 | if (!S.Context.typesAreCompatible(ltrans, rtrans)) { | |||
7387 | // Check if the pointee types are compatible ignoring the sign. | |||
7388 | // We explicitly check for char so that we catch "char" vs | |||
7389 | // "unsigned char" on systems where "char" is unsigned. | |||
7390 | if (lhptee->isCharType()) | |||
7391 | ltrans = S.Context.UnsignedCharTy; | |||
7392 | else if (lhptee->hasSignedIntegerRepresentation()) | |||
7393 | ltrans = S.Context.getCorrespondingUnsignedType(ltrans); | |||
7394 | ||||
7395 | if (rhptee->isCharType()) | |||
7396 | rtrans = S.Context.UnsignedCharTy; | |||
7397 | else if (rhptee->hasSignedIntegerRepresentation()) | |||
7398 | rtrans = S.Context.getCorrespondingUnsignedType(rtrans); | |||
7399 | ||||
7400 | if (ltrans == rtrans) { | |||
7401 | // Types are compatible ignoring the sign. Qualifier incompatibility | |||
7402 | // takes priority over sign incompatibility because the sign | |||
7403 | // warning can be disabled. | |||
7404 | if (ConvTy != Sema::Compatible) | |||
7405 | return ConvTy; | |||
7406 | ||||
7407 | return Sema::IncompatiblePointerSign; | |||
7408 | } | |||
7409 | ||||
7410 | // If we are a multi-level pointer, it's possible that our issue is simply | |||
7411 | // one of qualification - e.g. char ** -> const char ** is not allowed. If | |||
7412 | // the eventual target type is the same and the pointers have the same | |||
7413 | // level of indirection, this must be the issue. | |||
7414 | if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { | |||
7415 | do { | |||
7416 | lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); | |||
7417 | rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); | |||
7418 | } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); | |||
7419 | ||||
7420 | if (lhptee == rhptee) | |||
7421 | return Sema::IncompatibleNestedPointerQualifiers; | |||
7422 | } | |||
7423 | ||||
7424 | // General pointer incompatibility takes priority over qualifiers. | |||
7425 | return Sema::IncompatiblePointer; | |||
7426 | } | |||
7427 | if (!S.getLangOpts().CPlusPlus && | |||
7428 | S.IsFunctionConversion(ltrans, rtrans, ltrans)) | |||
7429 | return Sema::IncompatiblePointer; | |||
7430 | return ConvTy; | |||
7431 | } | |||
7432 | ||||
7433 | /// checkBlockPointerTypesForAssignment - This routine determines whether two | |||
7434 | /// block pointer types are compatible or whether a block and normal pointer | |||
7435 | /// are compatible. It is more restrict than comparing two function pointer | |||
7436 | // types. | |||
7437 | static Sema::AssignConvertType | |||
7438 | checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, | |||
7439 | QualType RHSType) { | |||
7440 | assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 7440, __extension__ __PRETTY_FUNCTION__)); | |||
7441 | assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 7441, __extension__ __PRETTY_FUNCTION__)); | |||
7442 | ||||
7443 | QualType lhptee, rhptee; | |||
7444 | ||||
7445 | // get the "pointed to" type (ignoring qualifiers at the top level) | |||
7446 | lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); | |||
7447 | rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); | |||
7448 | ||||
7449 | // In C++, the types have to match exactly. | |||
7450 | if (S.getLangOpts().CPlusPlus) | |||
7451 | return Sema::IncompatibleBlockPointer; | |||
7452 | ||||
7453 | Sema::AssignConvertType ConvTy = Sema::Compatible; | |||
7454 | ||||
7455 | // For blocks we enforce that qualifiers are identical. | |||
7456 | Qualifiers LQuals = lhptee.getLocalQualifiers(); | |||
7457 | Qualifiers RQuals = rhptee.getLocalQualifiers(); | |||
7458 | if (S.getLangOpts().OpenCL) { | |||
7459 | LQuals.removeAddressSpace(); | |||
7460 | RQuals.removeAddressSpace(); | |||
7461 | } | |||
7462 | if (LQuals != RQuals) | |||
7463 | ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | |||
7464 | ||||
7465 | // FIXME: OpenCL doesn't define the exact compile time semantics for a block | |||
7466 | // assignment. | |||
7467 | // The current behavior is similar to C++ lambdas. A block might be | |||
7468 | // assigned to a variable iff its return type and parameters are compatible | |||
7469 | // (C99 6.2.7) with the corresponding return type and parameters of the LHS of | |||
7470 | // an assignment. Presumably it should behave in way that a function pointer | |||
7471 | // assignment does in C, so for each parameter and return type: | |||
7472 | // * CVR and address space of LHS should be a superset of CVR and address | |||
7473 | // space of RHS. | |||
7474 | // * unqualified types should be compatible. | |||
7475 | if (S.getLangOpts().OpenCL) { | |||
7476 | if (!S.Context.typesAreBlockPointerCompatible( | |||
7477 | S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), | |||
7478 | S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) | |||
7479 | return Sema::IncompatibleBlockPointer; | |||
7480 | } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) | |||
7481 | return Sema::IncompatibleBlockPointer; | |||
7482 | ||||
7483 | return ConvTy; | |||
7484 | } | |||
7485 | ||||
7486 | /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types | |||
7487 | /// for assignment compatibility. | |||
7488 | static Sema::AssignConvertType | |||
7489 | checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, | |||
7490 | QualType RHSType) { | |||
7491 | 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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 7491, __extension__ __PRETTY_FUNCTION__)); | |||
7492 | 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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 7492, __extension__ __PRETTY_FUNCTION__)); | |||
7493 | ||||
7494 | if (LHSType->isObjCBuiltinType()) { | |||
7495 | // Class is not compatible with ObjC object pointers. | |||
7496 | if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && | |||
7497 | !RHSType->isObjCQualifiedClassType()) | |||
7498 | return Sema::IncompatiblePointer; | |||
7499 | return Sema::Compatible; | |||
7500 | } | |||
7501 | if (RHSType->isObjCBuiltinType()) { | |||
7502 | if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && | |||
7503 | !LHSType->isObjCQualifiedClassType()) | |||
7504 | return Sema::IncompatiblePointer; | |||
7505 | return Sema::Compatible; | |||
7506 | } | |||
7507 | QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); | |||
7508 | QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); | |||
7509 | ||||
7510 | if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && | |||
7511 | // make an exception for id<P> | |||
7512 | !LHSType->isObjCQualifiedIdType()) | |||
7513 | return Sema::CompatiblePointerDiscardsQualifiers; | |||
7514 | ||||
7515 | if (S.Context.typesAreCompatible(LHSType, RHSType)) | |||
7516 | return Sema::Compatible; | |||
7517 | if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) | |||
7518 | return Sema::IncompatibleObjCQualifiedId; | |||
7519 | return Sema::IncompatiblePointer; | |||
7520 | } | |||
7521 | ||||
7522 | Sema::AssignConvertType | |||
7523 | Sema::CheckAssignmentConstraints(SourceLocation Loc, | |||
7524 | QualType LHSType, QualType RHSType) { | |||
7525 | // Fake up an opaque expression. We don't actually care about what | |||
7526 | // cast operations are required, so if CheckAssignmentConstraints | |||
7527 | // adds casts to this they'll be wasted, but fortunately that doesn't | |||
7528 | // usually happen on valid code. | |||
7529 | OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); | |||
7530 | ExprResult RHSPtr = &RHSExpr; | |||
7531 | CastKind K; | |||
7532 | ||||
7533 | return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); | |||
7534 | } | |||
7535 | ||||
7536 | /// This helper function returns true if QT is a vector type that has element | |||
7537 | /// type ElementType. | |||
7538 | static bool isVector(QualType QT, QualType ElementType) { | |||
7539 | if (const VectorType *VT = QT->getAs<VectorType>()) | |||
7540 | return VT->getElementType() == ElementType; | |||
7541 | return false; | |||
7542 | } | |||
7543 | ||||
7544 | /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently | |||
7545 | /// has code to accommodate several GCC extensions when type checking | |||
7546 | /// pointers. Here are some objectionable examples that GCC considers warnings: | |||
7547 | /// | |||
7548 | /// int a, *pint; | |||
7549 | /// short *pshort; | |||
7550 | /// struct foo *pfoo; | |||
7551 | /// | |||
7552 | /// pint = pshort; // warning: assignment from incompatible pointer type | |||
7553 | /// a = pint; // warning: assignment makes integer from pointer without a cast | |||
7554 | /// pint = a; // warning: assignment makes pointer from integer without a cast | |||
7555 | /// pint = pfoo; // warning: assignment from incompatible pointer type | |||
7556 | /// | |||
7557 | /// As a result, the code for dealing with pointers is more complex than the | |||
7558 | /// C99 spec dictates. | |||
7559 | /// | |||
7560 | /// Sets 'Kind' for any result kind except Incompatible. | |||
7561 | Sema::AssignConvertType | |||
7562 | Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, | |||
7563 | CastKind &Kind, bool ConvertRHS) { | |||
7564 | QualType RHSType = RHS.get()->getType(); | |||
7565 | QualType OrigLHSType = LHSType; | |||
7566 | ||||
7567 | // Get canonical types. We're not formatting these types, just comparing | |||
7568 | // them. | |||
7569 | LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); | |||
7570 | RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); | |||
7571 | ||||
7572 | // Common case: no conversion required. | |||
7573 | if (LHSType == RHSType) { | |||
7574 | Kind = CK_NoOp; | |||
7575 | return Compatible; | |||
7576 | } | |||
7577 | ||||
7578 | // If we have an atomic type, try a non-atomic assignment, then just add an | |||
7579 | // atomic qualification step. | |||
7580 | if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { | |||
7581 | Sema::AssignConvertType result = | |||
7582 | CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); | |||
7583 | if (result != Compatible) | |||
7584 | return result; | |||
7585 | if (Kind != CK_NoOp && ConvertRHS) | |||
7586 | RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); | |||
7587 | Kind = CK_NonAtomicToAtomic; | |||
7588 | return Compatible; | |||
7589 | } | |||
7590 | ||||
7591 | // If the left-hand side is a reference type, then we are in a | |||
7592 | // (rare!) case where we've allowed the use of references in C, | |||
7593 | // e.g., as a parameter type in a built-in function. In this case, | |||
7594 | // just make sure that the type referenced is compatible with the | |||
7595 | // right-hand side type. The caller is responsible for adjusting | |||
7596 | // LHSType so that the resulting expression does not have reference | |||
7597 | // type. | |||
7598 | if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { | |||
7599 | if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { | |||
7600 | Kind = CK_LValueBitCast; | |||
7601 | return Compatible; | |||
7602 | } | |||
7603 | return Incompatible; | |||
7604 | } | |||
7605 | ||||
7606 | // Allow scalar to ExtVector assignments, and assignments of an ExtVector type | |||
7607 | // to the same ExtVector type. | |||
7608 | if (LHSType->isExtVectorType()) { | |||
7609 | if (RHSType->isExtVectorType()) | |||
7610 | return Incompatible; | |||
7611 | if (RHSType->isArithmeticType()) { | |||
7612 | // CK_VectorSplat does T -> vector T, so first cast to the element type. | |||
7613 | if (ConvertRHS) | |||
7614 | RHS = prepareVectorSplat(LHSType, RHS.get()); | |||
7615 | Kind = CK_VectorSplat; | |||
7616 | return Compatible; | |||
7617 | } | |||
7618 | } | |||
7619 | ||||
7620 | // Conversions to or from vector type. | |||
7621 | if (LHSType->isVectorType() || RHSType->isVectorType()) { | |||
7622 | if (LHSType->isVectorType() && RHSType->isVectorType()) { | |||
7623 | // Allow assignments of an AltiVec vector type to an equivalent GCC | |||
7624 | // vector type and vice versa | |||
7625 | if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { | |||
7626 | Kind = CK_BitCast; | |||
7627 | return Compatible; | |||
7628 | } | |||
7629 | ||||
7630 | // If we are allowing lax vector conversions, and LHS and RHS are both | |||
7631 | // vectors, the total size only needs to be the same. This is a bitcast; | |||
7632 | // no bits are changed but the result type is different. | |||
7633 | if (isLaxVectorConversion(RHSType, LHSType)) { | |||
7634 | Kind = CK_BitCast; | |||
7635 | return IncompatibleVectors; | |||
7636 | } | |||
7637 | } | |||
7638 | ||||
7639 | // When the RHS comes from another lax conversion (e.g. binops between | |||
7640 | // scalars and vectors) the result is canonicalized as a vector. When the | |||
7641 | // LHS is also a vector, the lax is allowed by the condition above. Handle | |||
7642 | // the case where LHS is a scalar. | |||
7643 | if (LHSType->isScalarType()) { | |||
7644 | const VectorType *VecType = RHSType->getAs<VectorType>(); | |||
7645 | if (VecType && VecType->getNumElements() == 1 && | |||
7646 | isLaxVectorConversion(RHSType, LHSType)) { | |||
7647 | ExprResult *VecExpr = &RHS; | |||
7648 | *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); | |||
7649 | Kind = CK_BitCast; | |||
7650 | return Compatible; | |||
7651 | } | |||
7652 | } | |||
7653 | ||||
7654 | return Incompatible; | |||
7655 | } | |||
7656 | ||||
7657 | // Diagnose attempts to convert between __float128 and long double where | |||
7658 | // such conversions currently can't be handled. | |||
7659 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | |||
7660 | return Incompatible; | |||
7661 | ||||
7662 | // Disallow assigning a _Complex to a real type in C++ mode since it simply | |||
7663 | // discards the imaginary part. | |||
7664 | if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && | |||
7665 | !LHSType->getAs<ComplexType>()) | |||
7666 | return Incompatible; | |||
7667 | ||||
7668 | // Arithmetic conversions. | |||
7669 | if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && | |||
7670 | !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { | |||
7671 | if (ConvertRHS) | |||
7672 | Kind = PrepareScalarCast(RHS, LHSType); | |||
7673 | return Compatible; | |||
7674 | } | |||
7675 | ||||
7676 | // Conversions to normal pointers. | |||
7677 | if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { | |||
7678 | // U* -> T* | |||
7679 | if (isa<PointerType>(RHSType)) { | |||
7680 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | |||
7681 | LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); | |||
7682 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | |||
7683 | return checkPointerTypesForAssignment(*this, LHSType, RHSType); | |||
7684 | } | |||
7685 | ||||
7686 | // int -> T* | |||
7687 | if (RHSType->isIntegerType()) { | |||
7688 | Kind = CK_IntegralToPointer; // FIXME: null? | |||
7689 | return IntToPointer; | |||
7690 | } | |||
7691 | ||||
7692 | // C pointers are not compatible with ObjC object pointers, | |||
7693 | // with two exceptions: | |||
7694 | if (isa<ObjCObjectPointerType>(RHSType)) { | |||
7695 | // - conversions to void* | |||
7696 | if (LHSPointer->getPointeeType()->isVoidType()) { | |||
7697 | Kind = CK_BitCast; | |||
7698 | return Compatible; | |||
7699 | } | |||
7700 | ||||
7701 | // - conversions from 'Class' to the redefinition type | |||
7702 | if (RHSType->isObjCClassType() && | |||
7703 | Context.hasSameType(LHSType, | |||
7704 | Context.getObjCClassRedefinitionType())) { | |||
7705 | Kind = CK_BitCast; | |||
7706 | return Compatible; | |||
7707 | } | |||
7708 | ||||
7709 | Kind = CK_BitCast; | |||
7710 | return IncompatiblePointer; | |||
7711 | } | |||
7712 | ||||
7713 | // U^ -> void* | |||
7714 | if (RHSType->getAs<BlockPointerType>()) { | |||
7715 | if (LHSPointer->getPointeeType()->isVoidType()) { | |||
7716 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | |||
7717 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | |||
7718 | ->getPointeeType() | |||
7719 | .getAddressSpace(); | |||
7720 | Kind = | |||
7721 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | |||
7722 | return Compatible; | |||
7723 | } | |||
7724 | } | |||
7725 | ||||
7726 | return Incompatible; | |||
7727 | } | |||
7728 | ||||
7729 | // Conversions to block pointers. | |||
7730 | if (isa<BlockPointerType>(LHSType)) { | |||
7731 | // U^ -> T^ | |||
7732 | if (RHSType->isBlockPointerType()) { | |||
7733 | LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() | |||
7734 | ->getPointeeType() | |||
7735 | .getAddressSpace(); | |||
7736 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | |||
7737 | ->getPointeeType() | |||
7738 | .getAddressSpace(); | |||
7739 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | |||
7740 | return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); | |||
7741 | } | |||
7742 | ||||
7743 | // int or null -> T^ | |||
7744 | if (RHSType->isIntegerType()) { | |||
7745 | Kind = CK_IntegralToPointer; // FIXME: null | |||
7746 | return IntToBlockPointer; | |||
7747 | } | |||
7748 | ||||
7749 | // id -> T^ | |||
7750 | if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { | |||
7751 | Kind = CK_AnyPointerToBlockPointerCast; | |||
7752 | return Compatible; | |||
7753 | } | |||
7754 | ||||
7755 | // void* -> T^ | |||
7756 | if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) | |||
7757 | if (RHSPT->getPointeeType()->isVoidType()) { | |||
7758 | Kind = CK_AnyPointerToBlockPointerCast; | |||
7759 | return Compatible; | |||
7760 | } | |||
7761 | ||||
7762 | return Incompatible; | |||
7763 | } | |||
7764 | ||||
7765 | // Conversions to Objective-C pointers. | |||
7766 | if (isa<ObjCObjectPointerType>(LHSType)) { | |||
7767 | // A* -> B* | |||
7768 | if (RHSType->isObjCObjectPointerType()) { | |||
7769 | Kind = CK_BitCast; | |||
7770 | Sema::AssignConvertType result = | |||
7771 | checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); | |||
7772 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
7773 | result == Compatible && | |||
7774 | !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) | |||
7775 | result = IncompatibleObjCWeakRef; | |||
7776 | return result; | |||
7777 | } | |||
7778 | ||||
7779 | // int or null -> A* | |||
7780 | if (RHSType->isIntegerType()) { | |||
7781 | Kind = CK_IntegralToPointer; // FIXME: null | |||
7782 | return IntToPointer; | |||
7783 | } | |||
7784 | ||||
7785 | // In general, C pointers are not compatible with ObjC object pointers, | |||
7786 | // with two exceptions: | |||
7787 | if (isa<PointerType>(RHSType)) { | |||
7788 | Kind = CK_CPointerToObjCPointerCast; | |||
7789 | ||||
7790 | // - conversions from 'void*' | |||
7791 | if (RHSType->isVoidPointerType()) { | |||
7792 | return Compatible; | |||
7793 | } | |||
7794 | ||||
7795 | // - conversions to 'Class' from its redefinition type | |||
7796 | if (LHSType->isObjCClassType() && | |||
7797 | Context.hasSameType(RHSType, | |||
7798 | Context.getObjCClassRedefinitionType())) { | |||
7799 | return Compatible; | |||
7800 | } | |||
7801 | ||||
7802 | return IncompatiblePointer; | |||
7803 | } | |||
7804 | ||||
7805 | // Only under strict condition T^ is compatible with an Objective-C pointer. | |||
7806 | if (RHSType->isBlockPointerType() && | |||
7807 | LHSType->isBlockCompatibleObjCPointerType(Context)) { | |||
7808 | if (ConvertRHS) | |||
7809 | maybeExtendBlockObject(RHS); | |||
7810 | Kind = CK_BlockPointerToObjCPointerCast; | |||
7811 | return Compatible; | |||
7812 | } | |||
7813 | ||||
7814 | return Incompatible; | |||
7815 | } | |||
7816 | ||||
7817 | // Conversions from pointers that are not covered by the above. | |||
7818 | if (isa<PointerType>(RHSType)) { | |||
7819 | // T* -> _Bool | |||
7820 | if (LHSType == Context.BoolTy) { | |||
7821 | Kind = CK_PointerToBoolean; | |||
7822 | return Compatible; | |||
7823 | } | |||
7824 | ||||
7825 | // T* -> int | |||
7826 | if (LHSType->isIntegerType()) { | |||
7827 | Kind = CK_PointerToIntegral; | |||
7828 | return PointerToInt; | |||
7829 | } | |||
7830 | ||||
7831 | return Incompatible; | |||
7832 | } | |||
7833 | ||||
7834 | // Conversions from Objective-C pointers that are not covered by the above. | |||
7835 | if (isa<ObjCObjectPointerType>(RHSType)) { | |||
7836 | // T* -> _Bool | |||
7837 | if (LHSType == Context.BoolTy) { | |||
7838 | Kind = CK_PointerToBoolean; | |||
7839 | return Compatible; | |||
7840 | } | |||
7841 | ||||
7842 | // T* -> int | |||
7843 | if (LHSType->isIntegerType()) { | |||
7844 | Kind = CK_PointerToIntegral; | |||
7845 | return PointerToInt; | |||
7846 | } | |||
7847 | ||||
7848 | return Incompatible; | |||
7849 | } | |||
7850 | ||||
7851 | // struct A -> struct B | |||
7852 | if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { | |||
7853 | if (Context.typesAreCompatible(LHSType, RHSType)) { | |||
7854 | Kind = CK_NoOp; | |||
7855 | return Compatible; | |||
7856 | } | |||
7857 | } | |||
7858 | ||||
7859 | if (LHSType->isSamplerT() && RHSType->isIntegerType()) { | |||
7860 | Kind = CK_IntToOCLSampler; | |||
7861 | return Compatible; | |||
7862 | } | |||
7863 | ||||
7864 | return Incompatible; | |||
7865 | } | |||
7866 | ||||
7867 | /// \brief Constructs a transparent union from an expression that is | |||
7868 | /// used to initialize the transparent union. | |||
7869 | static void ConstructTransparentUnion(Sema &S, ASTContext &C, | |||
7870 | ExprResult &EResult, QualType UnionType, | |||
7871 | FieldDecl *Field) { | |||
7872 | // Build an initializer list that designates the appropriate member | |||
7873 | // of the transparent union. | |||
7874 | Expr *E = EResult.get(); | |||
7875 | InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), | |||
7876 | E, SourceLocation()); | |||
7877 | Initializer->setType(UnionType); | |||
7878 | Initializer->setInitializedFieldInUnion(Field); | |||
7879 | ||||
7880 | // Build a compound literal constructing a value of the transparent | |||
7881 | // union type from this initializer list. | |||
7882 | TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); | |||
7883 | EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, | |||
7884 | VK_RValue, Initializer, false); | |||
7885 | } | |||
7886 | ||||
7887 | Sema::AssignConvertType | |||
7888 | Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, | |||
7889 | ExprResult &RHS) { | |||
7890 | QualType RHSType = RHS.get()->getType(); | |||
7891 | ||||
7892 | // If the ArgType is a Union type, we want to handle a potential | |||
7893 | // transparent_union GCC extension. | |||
7894 | const RecordType *UT = ArgType->getAsUnionType(); | |||
7895 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) | |||
7896 | return Incompatible; | |||
7897 | ||||
7898 | // The field to initialize within the transparent union. | |||
7899 | RecordDecl *UD = UT->getDecl(); | |||
7900 | FieldDecl *InitField = nullptr; | |||
7901 | // It's compatible if the expression matches any of the fields. | |||
7902 | for (auto *it : UD->fields()) { | |||
7903 | if (it->getType()->isPointerType()) { | |||
7904 | // If the transparent union contains a pointer type, we allow: | |||
7905 | // 1) void pointer | |||
7906 | // 2) null pointer constant | |||
7907 | if (RHSType->isPointerType()) | |||
7908 | if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { | |||
7909 | RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); | |||
7910 | InitField = it; | |||
7911 | break; | |||
7912 | } | |||
7913 | ||||
7914 | if (RHS.get()->isNullPointerConstant(Context, | |||
7915 | Expr::NPC_ValueDependentIsNull)) { | |||
7916 | RHS = ImpCastExprToType(RHS.get(), it->getType(), | |||
7917 | CK_NullToPointer); | |||
7918 | InitField = it; | |||
7919 | break; | |||
7920 | } | |||
7921 | } | |||
7922 | ||||
7923 | CastKind Kind; | |||
7924 | if (CheckAssignmentConstraints(it->getType(), RHS, Kind) | |||
7925 | == Compatible) { | |||
7926 | RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); | |||
7927 | InitField = it; | |||
7928 | break; | |||
7929 | } | |||
7930 | } | |||
7931 | ||||
7932 | if (!InitField) | |||
7933 | return Incompatible; | |||
7934 | ||||
7935 | ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); | |||
7936 | return Compatible; | |||
7937 | } | |||
7938 | ||||
7939 | Sema::AssignConvertType | |||
7940 | Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, | |||
7941 | bool Diagnose, | |||
7942 | bool DiagnoseCFAudited, | |||
7943 | bool ConvertRHS) { | |||
7944 | // We need to be able to tell the caller whether we diagnosed a problem, if | |||
7945 | // they ask us to issue diagnostics. | |||
7946 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 7946, __extension__ __PRETTY_FUNCTION__)); | |||
7947 | ||||
7948 | // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, | |||
7949 | // we can't avoid *all* modifications at the moment, so we need some somewhere | |||
7950 | // to put the updated value. | |||
7951 | ExprResult LocalRHS = CallerRHS; | |||
7952 | ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; | |||
7953 | ||||
7954 | if (getLangOpts().CPlusPlus) { | |||
7955 | if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { | |||
7956 | // C++ 5.17p3: If the left operand is not of class type, the | |||
7957 | // expression is implicitly converted (C++ 4) to the | |||
7958 | // cv-unqualified type of the left operand. | |||
7959 | QualType RHSType = RHS.get()->getType(); | |||
7960 | if (Diagnose) { | |||
7961 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | |||
7962 | AA_Assigning); | |||
7963 | } else { | |||
7964 | ImplicitConversionSequence ICS = | |||
7965 | TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | |||
7966 | /*SuppressUserConversions=*/false, | |||
7967 | /*AllowExplicit=*/false, | |||
7968 | /*InOverloadResolution=*/false, | |||
7969 | /*CStyle=*/false, | |||
7970 | /*AllowObjCWritebackConversion=*/false); | |||
7971 | if (ICS.isFailure()) | |||
7972 | return Incompatible; | |||
7973 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | |||
7974 | ICS, AA_Assigning); | |||
7975 | } | |||
7976 | if (RHS.isInvalid()) | |||
7977 | return Incompatible; | |||
7978 | Sema::AssignConvertType result = Compatible; | |||
7979 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
7980 | !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) | |||
7981 | result = IncompatibleObjCWeakRef; | |||
7982 | return result; | |||
7983 | } | |||
7984 | ||||
7985 | // FIXME: Currently, we fall through and treat C++ classes like C | |||
7986 | // structures. | |||
7987 | // FIXME: We also fall through for atomics; not sure what should | |||
7988 | // happen there, though. | |||
7989 | } else if (RHS.get()->getType() == Context.OverloadTy) { | |||
7990 | // As a set of extensions to C, we support overloading on functions. These | |||
7991 | // functions need to be resolved here. | |||
7992 | DeclAccessPair DAP; | |||
7993 | if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( | |||
7994 | RHS.get(), LHSType, /*Complain=*/false, DAP)) | |||
7995 | RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); | |||
7996 | else | |||
7997 | return Incompatible; | |||
7998 | } | |||
7999 | ||||
8000 | // C99 6.5.16.1p1: the left operand is a pointer and the right is | |||
8001 | // a null pointer constant. | |||
8002 | if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || | |||
8003 | LHSType->isBlockPointerType()) && | |||
8004 | RHS.get()->isNullPointerConstant(Context, | |||
8005 | Expr::NPC_ValueDependentIsNull)) { | |||
8006 | if (Diagnose || ConvertRHS) { | |||
8007 | CastKind Kind; | |||
8008 | CXXCastPath Path; | |||
8009 | CheckPointerConversion(RHS.get(), LHSType, Kind, Path, | |||
8010 | /*IgnoreBaseAccess=*/false, Diagnose); | |||
8011 | if (ConvertRHS) | |||
8012 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); | |||
8013 | } | |||
8014 | return Compatible; | |||
8015 | } | |||
8016 | ||||
8017 | // This check seems unnatural, however it is necessary to ensure the proper | |||
8018 | // conversion of functions/arrays. If the conversion were done for all | |||
8019 | // DeclExpr's (created by ActOnIdExpression), it would mess up the unary | |||
8020 | // expressions that suppress this implicit conversion (&, sizeof). | |||
8021 | // | |||
8022 | // Suppress this for references: C++ 8.5.3p5. | |||
8023 | if (!LHSType->isReferenceType()) { | |||
8024 | // FIXME: We potentially allocate here even if ConvertRHS is false. | |||
8025 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); | |||
8026 | if (RHS.isInvalid()) | |||
8027 | return Incompatible; | |||
8028 | } | |||
8029 | ||||
8030 | Expr *PRE = RHS.get()->IgnoreParenCasts(); | |||
8031 | if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { | |||
8032 | ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); | |||
8033 | if (PDecl && !PDecl->hasDefinition()) { | |||
8034 | Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl; | |||
8035 | Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; | |||
8036 | } | |||
8037 | } | |||
8038 | ||||
8039 | CastKind Kind; | |||
8040 | Sema::AssignConvertType result = | |||
8041 | CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); | |||
8042 | ||||
8043 | // C99 6.5.16.1p2: The value of the right operand is converted to the | |||
8044 | // type of the assignment expression. | |||
8045 | // CheckAssignmentConstraints allows the left-hand side to be a reference, | |||
8046 | // so that we can use references in built-in functions even in C. | |||
8047 | // The getNonReferenceType() call makes sure that the resulting expression | |||
8048 | // does not have reference type. | |||
8049 | if (result != Incompatible && RHS.get()->getType() != LHSType) { | |||
8050 | QualType Ty = LHSType.getNonLValueExprType(Context); | |||
8051 | Expr *E = RHS.get(); | |||
8052 | ||||
8053 | // Check for various Objective-C errors. If we are not reporting | |||
8054 | // diagnostics and just checking for errors, e.g., during overload | |||
8055 | // resolution, return Incompatible to indicate the failure. | |||
8056 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
8057 | CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, | |||
8058 | Diagnose, DiagnoseCFAudited) != ACR_okay) { | |||
8059 | if (!Diagnose) | |||
8060 | return Incompatible; | |||
8061 | } | |||
8062 | if (getLangOpts().ObjC1 && | |||
8063 | (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, | |||
8064 | E->getType(), E, Diagnose) || | |||
8065 | ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { | |||
8066 | if (!Diagnose) | |||
8067 | return Incompatible; | |||
8068 | // Replace the expression with a corrected version and continue so we | |||
8069 | // can find further errors. | |||
8070 | RHS = E; | |||
8071 | return Compatible; | |||
8072 | } | |||
8073 | ||||
8074 | if (ConvertRHS) | |||
8075 | RHS = ImpCastExprToType(E, Ty, Kind); | |||
8076 | } | |||
8077 | return result; | |||
8078 | } | |||
8079 | ||||
8080 | QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, | |||
8081 | ExprResult &RHS) { | |||
8082 | Diag(Loc, diag::err_typecheck_invalid_operands) | |||
8083 | << LHS.get()->getType() << RHS.get()->getType() | |||
8084 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
8085 | return QualType(); | |||
8086 | } | |||
8087 | ||||
8088 | // Diagnose cases where a scalar was implicitly converted to a vector and | |||
8089 | // diagnose the underlying types. Otherwise, diagnose the error | |||
8090 | // as invalid vector logical operands for non-C++ cases. | |||
8091 | QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, | |||
8092 | ExprResult &RHS) { | |||
8093 | QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); | |||
8094 | QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); | |||
8095 | ||||
8096 | bool LHSNatVec = LHSType->isVectorType(); | |||
8097 | bool RHSNatVec = RHSType->isVectorType(); | |||
8098 | ||||
8099 | if (!(LHSNatVec && RHSNatVec)) { | |||
8100 | Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); | |||
8101 | Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); | |||
8102 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | |||
8103 | << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() | |||
8104 | << Vector->getSourceRange(); | |||
8105 | return QualType(); | |||
8106 | } | |||
8107 | ||||
8108 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | |||
8109 | << 1 << LHSType << RHSType << LHS.get()->getSourceRange() | |||
8110 | << RHS.get()->getSourceRange(); | |||
8111 | ||||
8112 | return QualType(); | |||
8113 | } | |||
8114 | ||||
8115 | /// Try to convert a value of non-vector type to a vector type by converting | |||
8116 | /// the type to the element type of the vector and then performing a splat. | |||
8117 | /// If the language is OpenCL, we only use conversions that promote scalar | |||
8118 | /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except | |||
8119 | /// for float->int. | |||
8120 | /// | |||
8121 | /// OpenCL V2.0 6.2.6.p2: | |||
8122 | /// An error shall occur if any scalar operand type has greater rank | |||
8123 | /// than the type of the vector element. | |||
8124 | /// | |||
8125 | /// \param scalar - if non-null, actually perform the conversions | |||
8126 | /// \return true if the operation fails (but without diagnosing the failure) | |||
8127 | static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, | |||
8128 | QualType scalarTy, | |||
8129 | QualType vectorEltTy, | |||
8130 | QualType vectorTy, | |||
8131 | unsigned &DiagID) { | |||
8132 | // The conversion to apply to the scalar before splatting it, | |||
8133 | // if necessary. | |||
8134 | CastKind scalarCast = CK_NoOp; | |||
8135 | ||||
8136 | if (vectorEltTy->isIntegralType(S.Context)) { | |||
8137 | if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || | |||
8138 | (scalarTy->isIntegerType() && | |||
8139 | S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { | |||
8140 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | |||
8141 | return true; | |||
8142 | } | |||
8143 | if (!scalarTy->isIntegralType(S.Context)) | |||
8144 | return true; | |||
8145 | scalarCast = CK_IntegralCast; | |||
8146 | } else if (vectorEltTy->isRealFloatingType()) { | |||
8147 | if (scalarTy->isRealFloatingType()) { | |||
8148 | if (S.getLangOpts().OpenCL && | |||
8149 | S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { | |||
8150 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | |||
8151 | return true; | |||
8152 | } | |||
8153 | scalarCast = CK_FloatingCast; | |||
8154 | } | |||
8155 | else if (scalarTy->isIntegralType(S.Context)) | |||
8156 | scalarCast = CK_IntegralToFloating; | |||
8157 | else | |||
8158 | return true; | |||
8159 | } else { | |||
8160 | return true; | |||
8161 | } | |||
8162 | ||||
8163 | // Adjust scalar if desired. | |||
8164 | if (scalar) { | |||
8165 | if (scalarCast != CK_NoOp) | |||
8166 | *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); | |||
8167 | *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); | |||
8168 | } | |||
8169 | return false; | |||
8170 | } | |||
8171 | ||||
8172 | /// Convert vector E to a vector with the same number of elements but different | |||
8173 | /// element type. | |||
8174 | static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { | |||
8175 | const auto *VecTy = E->getType()->getAs<VectorType>(); | |||
8176 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 8176, __extension__ __PRETTY_FUNCTION__)); | |||
8177 | QualType NewVecTy = S.Context.getVectorType(ElementType, | |||
8178 | VecTy->getNumElements(), | |||
8179 | VecTy->getVectorKind()); | |||
8180 | ||||
8181 | // Look through the implicit cast. Return the subexpression if its type is | |||
8182 | // NewVecTy. | |||
8183 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | |||
8184 | if (ICE->getSubExpr()->getType() == NewVecTy) | |||
8185 | return ICE->getSubExpr(); | |||
8186 | ||||
8187 | auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; | |||
8188 | return S.ImpCastExprToType(E, NewVecTy, Cast); | |||
8189 | } | |||
8190 | ||||
8191 | /// Test if a (constant) integer Int can be casted to another integer type | |||
8192 | /// IntTy without losing precision. | |||
8193 | static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, | |||
8194 | QualType OtherIntTy) { | |||
8195 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | |||
8196 | ||||
8197 | // Reject cases where the value of the Int is unknown as that would | |||
8198 | // possibly cause truncation, but accept cases where the scalar can be | |||
8199 | // demoted without loss of precision. | |||
8200 | llvm::APSInt Result; | |||
8201 | bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); | |||
8202 | int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); | |||
8203 | bool IntSigned = IntTy->hasSignedIntegerRepresentation(); | |||
8204 | bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); | |||
8205 | ||||
8206 | if (CstInt) { | |||
8207 | // If the scalar is constant and is of a higher order and has more active | |||
8208 | // bits that the vector element type, reject it. | |||
8209 | unsigned NumBits = IntSigned | |||
8210 | ? (Result.isNegative() ? Result.getMinSignedBits() | |||
8211 | : Result.getActiveBits()) | |||
8212 | : Result.getActiveBits(); | |||
8213 | if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) | |||
8214 | return true; | |||
8215 | ||||
8216 | // If the signedness of the scalar type and the vector element type | |||
8217 | // differs and the number of bits is greater than that of the vector | |||
8218 | // element reject it. | |||
8219 | return (IntSigned != OtherIntSigned && | |||
8220 | NumBits > S.Context.getIntWidth(OtherIntTy)); | |||
8221 | } | |||
8222 | ||||
8223 | // Reject cases where the value of the scalar is not constant and it's | |||
8224 | // order is greater than that of the vector element type. | |||
8225 | return (Order < 0); | |||
8226 | } | |||
8227 | ||||
8228 | /// Test if a (constant) integer Int can be casted to floating point type | |||
8229 | /// FloatTy without losing precision. | |||
8230 | static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, | |||
8231 | QualType FloatTy) { | |||
8232 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | |||
8233 | ||||
8234 | // Determine if the integer constant can be expressed as a floating point | |||
8235 | // number of the appropriate type. | |||
8236 | llvm::APSInt Result; | |||
8237 | bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); | |||
8238 | uint64_t Bits = 0; | |||
8239 | if (CstInt) { | |||
8240 | // Reject constants that would be truncated if they were converted to | |||
8241 | // the floating point type. Test by simple to/from conversion. | |||
8242 | // FIXME: Ideally the conversion to an APFloat and from an APFloat | |||
8243 | // could be avoided if there was a convertFromAPInt method | |||
8244 | // which could signal back if implicit truncation occurred. | |||
8245 | llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); | |||
8246 | Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), | |||
8247 | llvm::APFloat::rmTowardZero); | |||
8248 | llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), | |||
8249 | !IntTy->hasSignedIntegerRepresentation()); | |||
8250 | bool Ignored = false; | |||
8251 | Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, | |||
8252 | &Ignored); | |||
8253 | if (Result != ConvertBack) | |||
8254 | return true; | |||
8255 | } else { | |||
8256 | // Reject types that cannot be fully encoded into the mantissa of | |||
8257 | // the float. | |||
8258 | Bits = S.Context.getTypeSize(IntTy); | |||
8259 | unsigned FloatPrec = llvm::APFloat::semanticsPrecision( | |||
8260 | S.Context.getFloatTypeSemantics(FloatTy)); | |||
8261 | if (Bits > FloatPrec) | |||
8262 | return true; | |||
8263 | } | |||
8264 | ||||
8265 | return false; | |||
8266 | } | |||
8267 | ||||
8268 | /// Attempt to convert and splat Scalar into a vector whose types matches | |||
8269 | /// Vector following GCC conversion rules. The rule is that implicit | |||
8270 | /// conversion can occur when Scalar can be casted to match Vector's element | |||
8271 | /// type without causing truncation of Scalar. | |||
8272 | static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, | |||
8273 | ExprResult *Vector) { | |||
8274 | QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); | |||
8275 | QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); | |||
8276 | const VectorType *VT = VectorTy->getAs<VectorType>(); | |||
8277 | ||||
8278 | 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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 8279, __extension__ __PRETTY_FUNCTION__)) | |||
8279 | "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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 8279, __extension__ __PRETTY_FUNCTION__)); | |||
8280 | ||||
8281 | QualType VectorEltTy = VT->getElementType(); | |||
8282 | ||||
8283 | // Reject cases where the vector element type or the scalar element type are | |||
8284 | // not integral or floating point types. | |||
8285 | if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) | |||
8286 | return true; | |||
8287 | ||||
8288 | // The conversion to apply to the scalar before splatting it, | |||
8289 | // if necessary. | |||
8290 | CastKind ScalarCast = CK_NoOp; | |||
8291 | ||||
8292 | // Accept cases where the vector elements are integers and the scalar is | |||
8293 | // an integer. | |||
8294 | // FIXME: Notionally if the scalar was a floating point value with a precise | |||
8295 | // integral representation, we could cast it to an appropriate integer | |||
8296 | // type and then perform the rest of the checks here. GCC will perform | |||
8297 | // this conversion in some cases as determined by the input language. | |||
8298 | // We should accept it on a language independent basis. | |||
8299 | if (VectorEltTy->isIntegralType(S.Context) && | |||
8300 | ScalarTy->isIntegralType(S.Context) && | |||
8301 | S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { | |||
8302 | ||||
8303 | if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) | |||
8304 | return true; | |||
8305 | ||||
8306 | ScalarCast = CK_IntegralCast; | |||
8307 | } else if (VectorEltTy->isRealFloatingType()) { | |||
8308 | if (ScalarTy->isRealFloatingType()) { | |||
8309 | ||||
8310 | // Reject cases where the scalar type is not a constant and has a higher | |||
8311 | // Order than the vector element type. | |||
8312 | llvm::APFloat Result(0.0); | |||
8313 | bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); | |||
8314 | int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); | |||
8315 | if (!CstScalar && Order < 0) | |||
8316 | return true; | |||
8317 | ||||
8318 | // If the scalar cannot be safely casted to the vector element type, | |||
8319 | // reject it. | |||
8320 | if (CstScalar) { | |||
8321 | bool Truncated = false; | |||
8322 | Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), | |||
8323 | llvm::APFloat::rmNearestTiesToEven, &Truncated); | |||
8324 | if (Truncated) | |||
8325 | return true; | |||
8326 | } | |||
8327 | ||||
8328 | ScalarCast = CK_FloatingCast; | |||
8329 | } else if (ScalarTy->isIntegralType(S.Context)) { | |||
8330 | if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) | |||
8331 | return true; | |||
8332 | ||||
8333 | ScalarCast = CK_IntegralToFloating; | |||
8334 | } else | |||
8335 | return true; | |||
8336 | } | |||
8337 | ||||
8338 | // Adjust scalar if desired. | |||
8339 | if (Scalar) { | |||
8340 | if (ScalarCast != CK_NoOp) | |||
8341 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); | |||
8342 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); | |||
8343 | } | |||
8344 | return false; | |||
8345 | } | |||
8346 | ||||
8347 | QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, | |||
8348 | SourceLocation Loc, bool IsCompAssign, | |||
8349 | bool AllowBothBool, | |||
8350 | bool AllowBoolConversions) { | |||
8351 | if (!IsCompAssign) { | |||
8352 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
8353 | if (LHS.isInvalid()) | |||
8354 | return QualType(); | |||
8355 | } | |||
8356 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
8357 | if (RHS.isInvalid()) | |||
8358 | return QualType(); | |||
8359 | ||||
8360 | // For conversion purposes, we ignore any qualifiers. | |||
8361 | // For example, "const float" and "float" are equivalent. | |||
8362 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | |||
8363 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | |||
8364 | ||||
8365 | const VectorType *LHSVecType = LHSType->getAs<VectorType>(); | |||
8366 | const VectorType *RHSVecType = RHSType->getAs<VectorType>(); | |||
8367 | assert(LHSVecType || RHSVecType)(static_cast <bool> (LHSVecType || RHSVecType) ? void ( 0) : __assert_fail ("LHSVecType || RHSVecType", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 8367, __extension__ __PRETTY_FUNCTION__)); | |||
8368 | ||||
8369 | // AltiVec-style "vector bool op vector bool" combinations are allowed | |||
8370 | // for some operators but not others. | |||
8371 | if (!AllowBothBool && | |||
8372 | LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && | |||
8373 | RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) | |||
8374 | return InvalidOperands(Loc, LHS, RHS); | |||
8375 | ||||
8376 | // If the vector types are identical, return. | |||
8377 | if (Context.hasSameType(LHSType, RHSType)) | |||
8378 | return LHSType; | |||
8379 | ||||
8380 | // If we have compatible AltiVec and GCC vector types, use the AltiVec type. | |||
8381 | if (LHSVecType && RHSVecType && | |||
8382 | Context.areCompatibleVectorTypes(LHSType, RHSType)) { | |||
8383 | if (isa<ExtVectorType>(LHSVecType)) { | |||
8384 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
8385 | return LHSType; | |||
8386 | } | |||
8387 | ||||
8388 | if (!IsCompAssign) | |||
8389 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | |||
8390 | return RHSType; | |||
8391 | } | |||
8392 | ||||
8393 | // AllowBoolConversions says that bool and non-bool AltiVec vectors | |||
8394 | // can be mixed, with the result being the non-bool type. The non-bool | |||
8395 | // operand must have integer element type. | |||
8396 | if (AllowBoolConversions && LHSVecType && RHSVecType && | |||
8397 | LHSVecType->getNumElements() == RHSVecType->getNumElements() && | |||
8398 | (Context.getTypeSize(LHSVecType->getElementType()) == | |||
8399 | Context.getTypeSize(RHSVecType->getElementType()))) { | |||
8400 | if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && | |||
8401 | LHSVecType->getElementType()->isIntegerType() && | |||
8402 | RHSVecType->getVectorKind() == VectorType::AltiVecBool) { | |||
8403 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
8404 | return LHSType; | |||
8405 | } | |||
8406 | if (!IsCompAssign && | |||
8407 | LHSVecType->getVectorKind() == VectorType::AltiVecBool && | |||
8408 | RHSVecType->getVectorKind() == VectorType::AltiVecVector && | |||
8409 | RHSVecType->getElementType()->isIntegerType()) { | |||
8410 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | |||
8411 | return RHSType; | |||
8412 | } | |||
8413 | } | |||
8414 | ||||
8415 | // If there's a vector type and a scalar, try to convert the scalar to | |||
8416 | // the vector element type and splat. | |||
8417 | unsigned DiagID = diag::err_typecheck_vector_not_convertable; | |||
8418 | if (!RHSVecType) { | |||
8419 | if (isa<ExtVectorType>(LHSVecType)) { | |||
8420 | if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, | |||
8421 | LHSVecType->getElementType(), LHSType, | |||
8422 | DiagID)) | |||
8423 | return LHSType; | |||
8424 | } else { | |||
8425 | if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) | |||
8426 | return LHSType; | |||
8427 | } | |||
8428 | } | |||
8429 | if (!LHSVecType) { | |||
8430 | if (isa<ExtVectorType>(RHSVecType)) { | |||
8431 | if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), | |||
8432 | LHSType, RHSVecType->getElementType(), | |||
8433 | RHSType, DiagID)) | |||
8434 | return RHSType; | |||
8435 | } else { | |||
8436 | if (LHS.get()->getValueKind() == VK_LValue || | |||
8437 | !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) | |||
8438 | return RHSType; | |||
8439 | } | |||
8440 | } | |||
8441 | ||||
8442 | // FIXME: The code below also handles conversion between vectors and | |||
8443 | // non-scalars, we should break this down into fine grained specific checks | |||
8444 | // and emit proper diagnostics. | |||
8445 | QualType VecType = LHSVecType ? LHSType : RHSType; | |||
8446 | const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; | |||
8447 | QualType OtherType = LHSVecType ? RHSType : LHSType; | |||
8448 | ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; | |||
8449 | if (isLaxVectorConversion(OtherType, VecType)) { | |||
8450 | // If we're allowing lax vector conversions, only the total (data) size | |||
8451 | // needs to be the same. For non compound assignment, if one of the types is | |||
8452 | // scalar, the result is always the vector type. | |||
8453 | if (!IsCompAssign) { | |||
8454 | *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); | |||
8455 | return VecType; | |||
8456 | // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding | |||
8457 | // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' | |||
8458 | // type. Note that this is already done by non-compound assignments in | |||
8459 | // CheckAssignmentConstraints. If it's a scalar type, only bitcast for | |||
8460 | // <1 x T> -> T. The result is also a vector type. | |||
8461 | } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || | |||
8462 | (OtherType->isScalarType() && VT->getNumElements() == 1)) { | |||
8463 | ExprResult *RHSExpr = &RHS; | |||
8464 | *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); | |||
8465 | return VecType; | |||
8466 | } | |||
8467 | } | |||
8468 | ||||
8469 | // Okay, the expression is invalid. | |||
8470 | ||||
8471 | // If there's a non-vector, non-real operand, diagnose that. | |||
8472 | if ((!RHSVecType && !RHSType->isRealType()) || | |||
8473 | (!LHSVecType && !LHSType->isRealType())) { | |||
8474 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) | |||
8475 | << LHSType << RHSType | |||
8476 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
8477 | return QualType(); | |||
8478 | } | |||
8479 | ||||
8480 | // OpenCL V1.1 6.2.6.p1: | |||
8481 | // If the operands are of more than one vector type, then an error shall | |||
8482 | // occur. Implicit conversions between vector types are not permitted, per | |||
8483 | // section 6.2.1. | |||
8484 | if (getLangOpts().OpenCL && | |||
8485 | RHSVecType && isa<ExtVectorType>(RHSVecType) && | |||
8486 | LHSVecType && isa<ExtVectorType>(LHSVecType)) { | |||
8487 | Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType | |||
8488 | << RHSType; | |||
8489 | return QualType(); | |||
8490 | } | |||
8491 | ||||
8492 | ||||
8493 | // If there is a vector type that is not a ExtVector and a scalar, we reach | |||
8494 | // this point if scalar could not be converted to the vector's element type | |||
8495 | // without truncation. | |||
8496 | if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || | |||
8497 | (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { | |||
8498 | QualType Scalar = LHSVecType ? RHSType : LHSType; | |||
8499 | QualType Vector = LHSVecType ? LHSType : RHSType; | |||
8500 | unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; | |||
8501 | Diag(Loc, | |||
8502 | diag::err_typecheck_vector_not_convertable_implict_truncation) | |||
8503 | << ScalarOrVector << Scalar << Vector; | |||
8504 | ||||
8505 | return QualType(); | |||
8506 | } | |||
8507 | ||||
8508 | // Otherwise, use the generic diagnostic. | |||
8509 | Diag(Loc, DiagID) | |||
8510 | << LHSType << RHSType | |||
8511 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
8512 | return QualType(); | |||
8513 | } | |||
8514 | ||||
8515 | // checkArithmeticNull - Detect when a NULL constant is used improperly in an | |||
8516 | // expression. These are mainly cases where the null pointer is used as an | |||
8517 | // integer instead of a pointer. | |||
8518 | static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, | |||
8519 | SourceLocation Loc, bool IsCompare) { | |||
8520 | // The canonical way to check for a GNU null is with isNullPointerConstant, | |||
8521 | // but we use a bit of a hack here for speed; this is a relatively | |||
8522 | // hot path, and isNullPointerConstant is slow. | |||
8523 | bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); | |||
8524 | bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); | |||
8525 | ||||
8526 | QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); | |||
8527 | ||||
8528 | // Avoid analyzing cases where the result will either be invalid (and | |||
8529 | // diagnosed as such) or entirely valid and not something to warn about. | |||
8530 | if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || | |||
8531 | NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) | |||
8532 | return; | |||
8533 | ||||
8534 | // Comparison operations would not make sense with a null pointer no matter | |||
8535 | // what the other expression is. | |||
8536 | if (!IsCompare) { | |||
8537 | S.Diag(Loc, diag::warn_null_in_arithmetic_operation) | |||
8538 | << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) | |||
8539 | << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); | |||
8540 | return; | |||
8541 | } | |||
8542 | ||||
8543 | // The rest of the operations only make sense with a null pointer | |||
8544 | // if the other expression is a pointer. | |||
8545 | if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || | |||
8546 | NonNullType->canDecayToPointerType()) | |||
8547 | return; | |||
8548 | ||||
8549 | S.Diag(Loc, diag::warn_null_in_comparison_operation) | |||
8550 | << LHSNull /* LHS is NULL */ << NonNullType | |||
8551 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
8552 | } | |||
8553 | ||||
8554 | static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, | |||
8555 | ExprResult &RHS, | |||
8556 | SourceLocation Loc, bool IsDiv) { | |||
8557 | // Check for division/remainder by zero. | |||
8558 | llvm::APSInt RHSValue; | |||
8559 | if (!RHS.get()->isValueDependent() && | |||
8560 | RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) | |||
8561 | S.DiagRuntimeBehavior(Loc, RHS.get(), | |||
8562 | S.PDiag(diag::warn_remainder_division_by_zero) | |||
8563 | << IsDiv << RHS.get()->getSourceRange()); | |||
8564 | } | |||
8565 | ||||
8566 | QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, | |||
8567 | SourceLocation Loc, | |||
8568 | bool IsCompAssign, bool IsDiv) { | |||
8569 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); | |||
8570 | ||||
8571 | if (LHS.get()->getType()->isVectorType() || | |||
8572 | RHS.get()->getType()->isVectorType()) | |||
8573 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | |||
8574 | /*AllowBothBool*/getLangOpts().AltiVec, | |||
8575 | /*AllowBoolConversions*/false); | |||
8576 | ||||
8577 | QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); | |||
8578 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
8579 | return QualType(); | |||
8580 | ||||
8581 | ||||
8582 | if (compType.isNull() || !compType->isArithmeticType()) | |||
8583 | return InvalidOperands(Loc, LHS, RHS); | |||
8584 | if (IsDiv) | |||
8585 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); | |||
8586 | return compType; | |||
8587 | } | |||
8588 | ||||
8589 | QualType Sema::CheckRemainderOperands( | |||
8590 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { | |||
8591 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); | |||
8592 | ||||
8593 | if (LHS.get()->getType()->isVectorType() || | |||
8594 | RHS.get()->getType()->isVectorType()) { | |||
8595 | if (LHS.get()->getType()->hasIntegerRepresentation() && | |||
8596 | RHS.get()->getType()->hasIntegerRepresentation()) | |||
8597 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | |||
8598 | /*AllowBothBool*/getLangOpts().AltiVec, | |||
8599 | /*AllowBoolConversions*/false); | |||
8600 | return InvalidOperands(Loc, LHS, RHS); | |||
8601 | } | |||
8602 | ||||
8603 | QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); | |||
8604 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
8605 | return QualType(); | |||
8606 | ||||
8607 | if (compType.isNull() || !compType->isIntegerType()) | |||
8608 | return InvalidOperands(Loc, LHS, RHS); | |||
8609 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); | |||
8610 | return compType; | |||
8611 | } | |||
8612 | ||||
8613 | /// \brief Diagnose invalid arithmetic on two void pointers. | |||
8614 | static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, | |||
8615 | Expr *LHSExpr, Expr *RHSExpr) { | |||
8616 | S.Diag(Loc, S.getLangOpts().CPlusPlus | |||
8617 | ? diag::err_typecheck_pointer_arith_void_type | |||
8618 | : diag::ext_gnu_void_ptr) | |||
8619 | << 1 /* two pointers */ << LHSExpr->getSourceRange() | |||
8620 | << RHSExpr->getSourceRange(); | |||
8621 | } | |||
8622 | ||||
8623 | /// \brief Diagnose invalid arithmetic on a void pointer. | |||
8624 | static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, | |||
8625 | Expr *Pointer) { | |||
8626 | S.Diag(Loc, S.getLangOpts().CPlusPlus | |||
8627 | ? diag::err_typecheck_pointer_arith_void_type | |||
8628 | : diag::ext_gnu_void_ptr) | |||
8629 | << 0 /* one pointer */ << Pointer->getSourceRange(); | |||
8630 | } | |||
8631 | ||||
8632 | /// \brief Diagnose invalid arithmetic on a null pointer. | |||
8633 | /// | |||
8634 | /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' | |||
8635 | /// idiom, which we recognize as a GNU extension. | |||
8636 | /// | |||
8637 | static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, | |||
8638 | Expr *Pointer, bool IsGNUIdiom) { | |||
8639 | if (IsGNUIdiom) | |||
8640 | S.Diag(Loc, diag::warn_gnu_null_ptr_arith) | |||
8641 | << Pointer->getSourceRange(); | |||
8642 | else | |||
8643 | S.Diag(Loc, diag::warn_pointer_arith_null_ptr) | |||
8644 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); | |||
8645 | } | |||
8646 | ||||
8647 | /// \brief Diagnose invalid arithmetic on two function pointers. | |||
8648 | static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, | |||
8649 | Expr *LHS, Expr *RHS) { | |||
8650 | assert(LHS->getType()->isAnyPointerType())(static_cast <bool> (LHS->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("LHS->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 8650, __extension__ __PRETTY_FUNCTION__)); | |||
8651 | assert(RHS->getType()->isAnyPointerType())(static_cast <bool> (RHS->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("RHS->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 8651, __extension__ __PRETTY_FUNCTION__)); | |||
8652 | S.Diag(Loc, S.getLangOpts().CPlusPlus | |||
8653 | ? diag::err_typecheck_pointer_arith_function_type | |||
8654 | : diag::ext_gnu_ptr_func_arith) | |||
8655 | << 1 /* two pointers */ << LHS->getType()->getPointeeType() | |||
8656 | // We only show the second type if it differs from the first. | |||
8657 | << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), | |||
8658 | RHS->getType()) | |||
8659 | << RHS->getType()->getPointeeType() | |||
8660 | << LHS->getSourceRange() << RHS->getSourceRange(); | |||
8661 | } | |||
8662 | ||||
8663 | /// \brief Diagnose invalid arithmetic on a function pointer. | |||
8664 | static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, | |||
8665 | Expr *Pointer) { | |||
8666 | assert(Pointer->getType()->isAnyPointerType())(static_cast <bool> (Pointer->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 8666, __extension__ __PRETTY_FUNCTION__)); | |||
8667 | S.Diag(Loc, S.getLangOpts().CPlusPlus | |||
8668 | ? diag::err_typecheck_pointer_arith_function_type | |||
8669 | : diag::ext_gnu_ptr_func_arith) | |||
8670 | << 0 /* one pointer */ << Pointer->getType()->getPointeeType() | |||
8671 | << 0 /* one pointer, so only one type */ | |||
8672 | << Pointer->getSourceRange(); | |||
8673 | } | |||
8674 | ||||
8675 | /// \brief Emit error if Operand is incomplete pointer type | |||
8676 | /// | |||
8677 | /// \returns True if pointer has incomplete type | |||
8678 | static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, | |||
8679 | Expr *Operand) { | |||
8680 | QualType ResType = Operand->getType(); | |||
8681 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | |||
8682 | ResType = ResAtomicType->getValueType(); | |||
8683 | ||||
8684 | assert(ResType->isAnyPointerType() && !ResType->isDependentType())(static_cast <bool> (ResType->isAnyPointerType() && !ResType->isDependentType()) ? void (0) : __assert_fail ( "ResType->isAnyPointerType() && !ResType->isDependentType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 8684, __extension__ __PRETTY_FUNCTION__)); | |||
8685 | QualType PointeeTy = ResType->getPointeeType(); | |||
8686 | return S.RequireCompleteType(Loc, PointeeTy, | |||
8687 | diag::err_typecheck_arithmetic_incomplete_type, | |||
8688 | PointeeTy, Operand->getSourceRange()); | |||
8689 | } | |||
8690 | ||||
8691 | /// \brief Check the validity of an arithmetic pointer operand. | |||
8692 | /// | |||
8693 | /// If the operand has pointer type, this code will check for pointer types | |||
8694 | /// which are invalid in arithmetic operations. These will be diagnosed | |||
8695 | /// appropriately, including whether or not the use is supported as an | |||
8696 | /// extension. | |||
8697 | /// | |||
8698 | /// \returns True when the operand is valid to use (even if as an extension). | |||
8699 | static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, | |||
8700 | Expr *Operand) { | |||
8701 | QualType ResType = Operand->getType(); | |||
8702 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | |||
8703 | ResType = ResAtomicType->getValueType(); | |||
8704 | ||||
8705 | if (!ResType->isAnyPointerType()) return true; | |||
8706 | ||||
8707 | QualType PointeeTy = ResType->getPointeeType(); | |||
8708 | if (PointeeTy->isVoidType()) { | |||
8709 | diagnoseArithmeticOnVoidPointer(S, Loc, Operand); | |||
8710 | return !S.getLangOpts().CPlusPlus; | |||
8711 | } | |||
8712 | if (PointeeTy->isFunctionType()) { | |||
8713 | diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); | |||
8714 | return !S.getLangOpts().CPlusPlus; | |||
8715 | } | |||
8716 | ||||
8717 | if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; | |||
8718 | ||||
8719 | return true; | |||
8720 | } | |||
8721 | ||||
8722 | /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer | |||
8723 | /// operands. | |||
8724 | /// | |||
8725 | /// This routine will diagnose any invalid arithmetic on pointer operands much | |||
8726 | /// like \see checkArithmeticOpPointerOperand. However, it has special logic | |||
8727 | /// for emitting a single diagnostic even for operations where both LHS and RHS | |||
8728 | /// are (potentially problematic) pointers. | |||
8729 | /// | |||
8730 | /// \returns True when the operand is valid to use (even if as an extension). | |||
8731 | static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, | |||
8732 | Expr *LHSExpr, Expr *RHSExpr) { | |||
8733 | bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); | |||
8734 | bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); | |||
8735 | if (!isLHSPointer && !isRHSPointer) return true; | |||
8736 | ||||
8737 | QualType LHSPointeeTy, RHSPointeeTy; | |||
8738 | if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); | |||
8739 | if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); | |||
8740 | ||||
8741 | // if both are pointers check if operation is valid wrt address spaces | |||
8742 | if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { | |||
8743 | const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); | |||
8744 | const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); | |||
8745 | if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { | |||
8746 | S.Diag(Loc, | |||
8747 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | |||
8748 | << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ | |||
8749 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); | |||
8750 | return false; | |||
8751 | } | |||
8752 | } | |||
8753 | ||||
8754 | // Check for arithmetic on pointers to incomplete types. | |||
8755 | bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); | |||
8756 | bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); | |||
8757 | if (isLHSVoidPtr || isRHSVoidPtr) { | |||
8758 | if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); | |||
8759 | else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); | |||
8760 | else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); | |||
8761 | ||||
8762 | return !S.getLangOpts().CPlusPlus; | |||
8763 | } | |||
8764 | ||||
8765 | bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); | |||
8766 | bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); | |||
8767 | if (isLHSFuncPtr || isRHSFuncPtr) { | |||
8768 | if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); | |||
8769 | else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, | |||
8770 | RHSExpr); | |||
8771 | else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); | |||
8772 | ||||
8773 | return !S.getLangOpts().CPlusPlus; | |||
8774 | } | |||
8775 | ||||
8776 | if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) | |||
8777 | return false; | |||
8778 | if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) | |||
8779 | return false; | |||
8780 | ||||
8781 | return true; | |||
8782 | } | |||
8783 | ||||
8784 | /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string | |||
8785 | /// literal. | |||
8786 | static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, | |||
8787 | Expr *LHSExpr, Expr *RHSExpr) { | |||
8788 | StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); | |||
8789 | Expr* IndexExpr = RHSExpr; | |||
8790 | if (!StrExpr) { | |||
8791 | StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); | |||
8792 | IndexExpr = LHSExpr; | |||
8793 | } | |||
8794 | ||||
8795 | bool IsStringPlusInt = StrExpr && | |||
8796 | IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); | |||
8797 | if (!IsStringPlusInt || IndexExpr->isValueDependent()) | |||
8798 | return; | |||
8799 | ||||
8800 | llvm::APSInt index; | |||
8801 | if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { | |||
8802 | unsigned StrLenWithNull = StrExpr->getLength() + 1; | |||
8803 | if (index.isNonNegative() && | |||
8804 | index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), | |||
8805 | index.isUnsigned())) | |||
8806 | return; | |||
8807 | } | |||
8808 | ||||
8809 | SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); | |||
8810 | Self.Diag(OpLoc, diag::warn_string_plus_int) | |||
8811 | << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); | |||
8812 | ||||
8813 | // Only print a fixit for "str" + int, not for int + "str". | |||
8814 | if (IndexExpr == RHSExpr) { | |||
8815 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); | |||
8816 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | |||
8817 | << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") | |||
8818 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | |||
8819 | << FixItHint::CreateInsertion(EndLoc, "]"); | |||
8820 | } else | |||
8821 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | |||
8822 | } | |||
8823 | ||||
8824 | /// \brief Emit a warning when adding a char literal to a string. | |||
8825 | static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, | |||
8826 | Expr *LHSExpr, Expr *RHSExpr) { | |||
8827 | const Expr *StringRefExpr = LHSExpr; | |||
8828 | const CharacterLiteral *CharExpr = | |||
8829 | dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); | |||
8830 | ||||
8831 | if (!CharExpr) { | |||
8832 | CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); | |||
8833 | StringRefExpr = RHSExpr; | |||
8834 | } | |||
8835 | ||||
8836 | if (!CharExpr || !StringRefExpr) | |||
8837 | return; | |||
8838 | ||||
8839 | const QualType StringType = StringRefExpr->getType(); | |||
8840 | ||||
8841 | // Return if not a PointerType. | |||
8842 | if (!StringType->isAnyPointerType()) | |||
8843 | return; | |||
8844 | ||||
8845 | // Return if not a CharacterType. | |||
8846 | if (!StringType->getPointeeType()->isAnyCharacterType()) | |||
8847 | return; | |||
8848 | ||||
8849 | ASTContext &Ctx = Self.getASTContext(); | |||
8850 | SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); | |||
8851 | ||||
8852 | const QualType CharType = CharExpr->getType(); | |||
8853 | if (!CharType->isAnyCharacterType() && | |||
8854 | CharType->isIntegerType() && | |||
8855 | llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { | |||
8856 | Self.Diag(OpLoc, diag::warn_string_plus_char) | |||
8857 | << DiagRange << Ctx.CharTy; | |||
8858 | } else { | |||
8859 | Self.Diag(OpLoc, diag::warn_string_plus_char) | |||
8860 | << DiagRange << CharExpr->getType(); | |||
8861 | } | |||
8862 | ||||
8863 | // Only print a fixit for str + char, not for char + str. | |||
8864 | if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { | |||
8865 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); | |||
8866 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | |||
8867 | << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") | |||
8868 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | |||
8869 | << FixItHint::CreateInsertion(EndLoc, "]"); | |||
8870 | } else { | |||
8871 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | |||
8872 | } | |||
8873 | } | |||
8874 | ||||
8875 | /// \brief Emit error when two pointers are incompatible. | |||
8876 | static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, | |||
8877 | Expr *LHSExpr, Expr *RHSExpr) { | |||
8878 | assert(LHSExpr->getType()->isAnyPointerType())(static_cast <bool> (LHSExpr->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 8878, __extension__ __PRETTY_FUNCTION__)); | |||
8879 | assert(RHSExpr->getType()->isAnyPointerType())(static_cast <bool> (RHSExpr->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 8879, __extension__ __PRETTY_FUNCTION__)); | |||
8880 | S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) | |||
8881 | << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() | |||
8882 | << RHSExpr->getSourceRange(); | |||
8883 | } | |||
8884 | ||||
8885 | // C99 6.5.6 | |||
8886 | QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, | |||
8887 | SourceLocation Loc, BinaryOperatorKind Opc, | |||
8888 | QualType* CompLHSTy) { | |||
8889 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); | |||
8890 | ||||
8891 | if (LHS.get()->getType()->isVectorType() || | |||
8892 | RHS.get()->getType()->isVectorType()) { | |||
8893 | QualType compType = CheckVectorOperands( | |||
8894 | LHS, RHS, Loc, CompLHSTy, | |||
8895 | /*AllowBothBool*/getLangOpts().AltiVec, | |||
8896 | /*AllowBoolConversions*/getLangOpts().ZVector); | |||
8897 | if (CompLHSTy) *CompLHSTy = compType; | |||
8898 | return compType; | |||
8899 | } | |||
8900 | ||||
8901 | QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); | |||
8902 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
8903 | return QualType(); | |||
8904 | ||||
8905 | // Diagnose "string literal" '+' int and string '+' "char literal". | |||
8906 | if (Opc == BO_Add) { | |||
8907 | diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); | |||
8908 | diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); | |||
8909 | } | |||
8910 | ||||
8911 | // handle the common case first (both operands are arithmetic). | |||
8912 | if (!compType.isNull() && compType->isArithmeticType()) { | |||
8913 | if (CompLHSTy) *CompLHSTy = compType; | |||
8914 | return compType; | |||
8915 | } | |||
8916 | ||||
8917 | // Type-checking. Ultimately the pointer's going to be in PExp; | |||
8918 | // note that we bias towards the LHS being the pointer. | |||
8919 | Expr *PExp = LHS.get(), *IExp = RHS.get(); | |||
8920 | ||||
8921 | bool isObjCPointer; | |||
8922 | if (PExp->getType()->isPointerType()) { | |||
8923 | isObjCPointer = false; | |||
8924 | } else if (PExp->getType()->isObjCObjectPointerType()) { | |||
8925 | isObjCPointer = true; | |||
8926 | } else { | |||
8927 | std::swap(PExp, IExp); | |||
8928 | if (PExp->getType()->isPointerType()) { | |||
8929 | isObjCPointer = false; | |||
8930 | } else if (PExp->getType()->isObjCObjectPointerType()) { | |||
8931 | isObjCPointer = true; | |||
8932 | } else { | |||
8933 | return InvalidOperands(Loc, LHS, RHS); | |||
8934 | } | |||
8935 | } | |||
8936 | assert(PExp->getType()->isAnyPointerType())(static_cast <bool> (PExp->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("PExp->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 8936, __extension__ __PRETTY_FUNCTION__)); | |||
8937 | ||||
8938 | if (!IExp->getType()->isIntegerType()) | |||
8939 | return InvalidOperands(Loc, LHS, RHS); | |||
8940 | ||||
8941 | // Adding to a null pointer results in undefined behavior. | |||
8942 | if (PExp->IgnoreParenCasts()->isNullPointerConstant( | |||
8943 | Context, Expr::NPC_ValueDependentIsNotNull)) { | |||
8944 | // In C++ adding zero to a null pointer is defined. | |||
8945 | llvm::APSInt KnownVal; | |||
8946 | if (!getLangOpts().CPlusPlus || | |||
8947 | (!IExp->isValueDependent() && | |||
8948 | (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { | |||
8949 | // Check the conditions to see if this is the 'p = nullptr + n' idiom. | |||
8950 | bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( | |||
8951 | Context, BO_Add, PExp, IExp); | |||
8952 | diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); | |||
8953 | } | |||
8954 | } | |||
8955 | ||||
8956 | if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) | |||
8957 | return QualType(); | |||
8958 | ||||
8959 | if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) | |||
8960 | return QualType(); | |||
8961 | ||||
8962 | // Check array bounds for pointer arithemtic | |||
8963 | CheckArrayAccess(PExp, IExp); | |||
8964 | ||||
8965 | if (CompLHSTy) { | |||
8966 | QualType LHSTy = Context.isPromotableBitField(LHS.get()); | |||
8967 | if (LHSTy.isNull()) { | |||
8968 | LHSTy = LHS.get()->getType(); | |||
8969 | if (LHSTy->isPromotableIntegerType()) | |||
8970 | LHSTy = Context.getPromotedIntegerType(LHSTy); | |||
8971 | } | |||
8972 | *CompLHSTy = LHSTy; | |||
8973 | } | |||
8974 | ||||
8975 | return PExp->getType(); | |||
8976 | } | |||
8977 | ||||
8978 | // C99 6.5.6 | |||
8979 | QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, | |||
8980 | SourceLocation Loc, | |||
8981 | QualType* CompLHSTy) { | |||
8982 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); | |||
8983 | ||||
8984 | if (LHS.get()->getType()->isVectorType() || | |||
8985 | RHS.get()->getType()->isVectorType()) { | |||
8986 | QualType compType = CheckVectorOperands( | |||
8987 | LHS, RHS, Loc, CompLHSTy, | |||
8988 | /*AllowBothBool*/getLangOpts().AltiVec, | |||
8989 | /*AllowBoolConversions*/getLangOpts().ZVector); | |||
8990 | if (CompLHSTy) *CompLHSTy = compType; | |||
8991 | return compType; | |||
8992 | } | |||
8993 | ||||
8994 | QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); | |||
8995 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
8996 | return QualType(); | |||
8997 | ||||
8998 | // Enforce type constraints: C99 6.5.6p3. | |||
8999 | ||||
9000 | // Handle the common case first (both operands are arithmetic). | |||
9001 | if (!compType.isNull() && compType->isArithmeticType()) { | |||
9002 | if (CompLHSTy) *CompLHSTy = compType; | |||
9003 | return compType; | |||
9004 | } | |||
9005 | ||||
9006 | // Either ptr - int or ptr - ptr. | |||
9007 | if (LHS.get()->getType()->isAnyPointerType()) { | |||
9008 | QualType lpointee = LHS.get()->getType()->getPointeeType(); | |||
9009 | ||||
9010 | // Diagnose bad cases where we step over interface counts. | |||
9011 | if (LHS.get()->getType()->isObjCObjectPointerType() && | |||
9012 | checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) | |||
9013 | return QualType(); | |||
9014 | ||||
9015 | // The result type of a pointer-int computation is the pointer type. | |||
9016 | if (RHS.get()->getType()->isIntegerType()) { | |||
9017 | // Subtracting from a null pointer should produce a warning. | |||
9018 | // The last argument to the diagnose call says this doesn't match the | |||
9019 | // GNU int-to-pointer idiom. | |||
9020 | if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, | |||
9021 | Expr::NPC_ValueDependentIsNotNull)) { | |||
9022 | // In C++ adding zero to a null pointer is defined. | |||
9023 | llvm::APSInt KnownVal; | |||
9024 | if (!getLangOpts().CPlusPlus || | |||
9025 | (!RHS.get()->isValueDependent() && | |||
9026 | (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { | |||
9027 | diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); | |||
9028 | } | |||
9029 | } | |||
9030 | ||||
9031 | if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) | |||
9032 | return QualType(); | |||
9033 | ||||
9034 | // Check array bounds for pointer arithemtic | |||
9035 | CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, | |||
9036 | /*AllowOnePastEnd*/true, /*IndexNegated*/true); | |||
9037 | ||||
9038 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | |||
9039 | return LHS.get()->getType(); | |||
9040 | } | |||
9041 | ||||
9042 | // Handle pointer-pointer subtractions. | |||
9043 | if (const PointerType *RHSPTy | |||
9044 | = RHS.get()->getType()->getAs<PointerType>()) { | |||
9045 | QualType rpointee = RHSPTy->getPointeeType(); | |||
9046 | ||||
9047 | if (getLangOpts().CPlusPlus) { | |||
9048 | // Pointee types must be the same: C++ [expr.add] | |||
9049 | if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { | |||
9050 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | |||
9051 | } | |||
9052 | } else { | |||
9053 | // Pointee types must be compatible C99 6.5.6p3 | |||
9054 | if (!Context.typesAreCompatible( | |||
9055 | Context.getCanonicalType(lpointee).getUnqualifiedType(), | |||
9056 | Context.getCanonicalType(rpointee).getUnqualifiedType())) { | |||
9057 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | |||
9058 | return QualType(); | |||
9059 | } | |||
9060 | } | |||
9061 | ||||
9062 | if (!checkArithmeticBinOpPointerOperands(*this, Loc, | |||
9063 | LHS.get(), RHS.get())) | |||
9064 | return QualType(); | |||
9065 | ||||
9066 | // FIXME: Add warnings for nullptr - ptr. | |||
9067 | ||||
9068 | // The pointee type may have zero size. As an extension, a structure or | |||
9069 | // union may have zero size or an array may have zero length. In this | |||
9070 | // case subtraction does not make sense. | |||
9071 | if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { | |||
9072 | CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); | |||
9073 | if (ElementSize.isZero()) { | |||
9074 | Diag(Loc,diag::warn_sub_ptr_zero_size_types) | |||
9075 | << rpointee.getUnqualifiedType() | |||
9076 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
9077 | } | |||
9078 | } | |||
9079 | ||||
9080 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | |||
9081 | return Context.getPointerDiffType(); | |||
9082 | } | |||
9083 | } | |||
9084 | ||||
9085 | return InvalidOperands(Loc, LHS, RHS); | |||
9086 | } | |||
9087 | ||||
9088 | static bool isScopedEnumerationType(QualType T) { | |||
9089 | if (const EnumType *ET = T->getAs<EnumType>()) | |||
9090 | return ET->getDecl()->isScoped(); | |||
9091 | return false; | |||
9092 | } | |||
9093 | ||||
9094 | static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, | |||
9095 | SourceLocation Loc, BinaryOperatorKind Opc, | |||
9096 | QualType LHSType) { | |||
9097 | // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), | |||
9098 | // so skip remaining warnings as we don't want to modify values within Sema. | |||
9099 | if (S.getLangOpts().OpenCL) | |||
9100 | return; | |||
9101 | ||||
9102 | llvm::APSInt Right; | |||
9103 | // Check right/shifter operand | |||
9104 | if (RHS.get()->isValueDependent() || | |||
9105 | !RHS.get()->EvaluateAsInt(Right, S.Context)) | |||
9106 | return; | |||
9107 | ||||
9108 | if (Right.isNegative()) { | |||
9109 | S.DiagRuntimeBehavior(Loc, RHS.get(), | |||
9110 | S.PDiag(diag::warn_shift_negative) | |||
9111 | << RHS.get()->getSourceRange()); | |||
9112 | return; | |||
9113 | } | |||
9114 | llvm::APInt LeftBits(Right.getBitWidth(), | |||
9115 | S.Context.getTypeSize(LHS.get()->getType())); | |||
9116 | if (Right.uge(LeftBits)) { | |||
9117 | S.DiagRuntimeBehavior(Loc, RHS.get(), | |||
9118 | S.PDiag(diag::warn_shift_gt_typewidth) | |||
9119 | << RHS.get()->getSourceRange()); | |||
9120 | return; | |||
9121 | } | |||
9122 | if (Opc != BO_Shl) | |||
9123 | return; | |||
9124 | ||||
9125 | // When left shifting an ICE which is signed, we can check for overflow which | |||
9126 | // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned | |||
9127 | // integers have defined behavior modulo one more than the maximum value | |||
9128 | // representable in the result type, so never warn for those. | |||
9129 | llvm::APSInt Left; | |||
9130 | if (LHS.get()->isValueDependent() || | |||
9131 | LHSType->hasUnsignedIntegerRepresentation() || | |||
9132 | !LHS.get()->EvaluateAsInt(Left, S.Context)) | |||
9133 | return; | |||
9134 | ||||
9135 | // If LHS does not have a signed type and non-negative value | |||
9136 | // then, the behavior is undefined. Warn about it. | |||
9137 | if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { | |||
9138 | S.DiagRuntimeBehavior(Loc, LHS.get(), | |||
9139 | S.PDiag(diag::warn_shift_lhs_negative) | |||
9140 | << LHS.get()->getSourceRange()); | |||
9141 | return; | |||
9142 | } | |||
9143 | ||||
9144 | llvm::APInt ResultBits = | |||
9145 | static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); | |||
9146 | if (LeftBits.uge(ResultBits)) | |||
9147 | return; | |||
9148 | llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); | |||
9149 | Result = Result.shl(Right); | |||
9150 | ||||
9151 | // Print the bit representation of the signed integer as an unsigned | |||
9152 | // hexadecimal number. | |||
9153 | SmallString<40> HexResult; | |||
9154 | Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); | |||
9155 | ||||
9156 | // If we are only missing a sign bit, this is less likely to result in actual | |||
9157 | // bugs -- if the result is cast back to an unsigned type, it will have the | |||
9158 | // expected value. Thus we place this behind a different warning that can be | |||
9159 | // turned off separately if needed. | |||
9160 | if (LeftBits == ResultBits - 1) { | |||
9161 | S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) | |||
9162 | << HexResult << LHSType | |||
9163 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
9164 | return; | |||
9165 | } | |||
9166 | ||||
9167 | S.Diag(Loc, diag::warn_shift_result_gt_typewidth) | |||
9168 | << HexResult.str() << Result.getMinSignedBits() << LHSType | |||
9169 | << Left.getBitWidth() << LHS.get()->getSourceRange() | |||
9170 | << RHS.get()->getSourceRange(); | |||
9171 | } | |||
9172 | ||||
9173 | /// \brief Return the resulting type when a vector is shifted | |||
9174 | /// by a scalar or vector shift amount. | |||
9175 | static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, | |||
9176 | SourceLocation Loc, bool IsCompAssign) { | |||
9177 | // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. | |||
9178 | if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && | |||
9179 | !LHS.get()->getType()->isVectorType()) { | |||
9180 | S.Diag(Loc, diag::err_shift_rhs_only_vector) | |||
9181 | << RHS.get()->getType() << LHS.get()->getType() | |||
9182 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
9183 | return QualType(); | |||
9184 | } | |||
9185 | ||||
9186 | if (!IsCompAssign) { | |||
9187 | LHS = S.UsualUnaryConversions(LHS.get()); | |||
9188 | if (LHS.isInvalid()) return QualType(); | |||
9189 | } | |||
9190 | ||||
9191 | RHS = S.UsualUnaryConversions(RHS.get()); | |||
9192 | if (RHS.isInvalid()) return QualType(); | |||
9193 | ||||
9194 | QualType LHSType = LHS.get()->getType(); | |||
9195 | // Note that LHS might be a scalar because the routine calls not only in | |||
9196 | // OpenCL case. | |||
9197 | const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); | |||
9198 | QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; | |||
9199 | ||||
9200 | // Note that RHS might not be a vector. | |||
9201 | QualType RHSType = RHS.get()->getType(); | |||
9202 | const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); | |||
9203 | QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; | |||
9204 | ||||
9205 | // The operands need to be integers. | |||
9206 | if (!LHSEleType->isIntegerType()) { | |||
9207 | S.Diag(Loc, diag::err_typecheck_expect_int) | |||
9208 | << LHS.get()->getType() << LHS.get()->getSourceRange(); | |||
9209 | return QualType(); | |||
9210 | } | |||
9211 | ||||
9212 | if (!RHSEleType->isIntegerType()) { | |||
9213 | S.Diag(Loc, diag::err_typecheck_expect_int) | |||
9214 | << RHS.get()->getType() << RHS.get()->getSourceRange(); | |||
9215 | return QualType(); | |||
9216 | } | |||
9217 | ||||
9218 | if (!LHSVecTy) { | |||
9219 | assert(RHSVecTy)(static_cast <bool> (RHSVecTy) ? void (0) : __assert_fail ("RHSVecTy", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 9219, __extension__ __PRETTY_FUNCTION__)); | |||
9220 | if (IsCompAssign) | |||
9221 | return RHSType; | |||
9222 | if (LHSEleType != RHSEleType) { | |||
9223 | LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); | |||
9224 | LHSEleType = RHSEleType; | |||
9225 | } | |||
9226 | QualType VecTy = | |||
9227 | S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); | |||
9228 | LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); | |||
9229 | LHSType = VecTy; | |||
9230 | } else if (RHSVecTy) { | |||
9231 | // OpenCL v1.1 s6.3.j says that for vector types, the operators | |||
9232 | // are applied component-wise. So if RHS is a vector, then ensure | |||
9233 | // that the number of elements is the same as LHS... | |||
9234 | if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { | |||
9235 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) | |||
9236 | << LHS.get()->getType() << RHS.get()->getType() | |||
9237 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
9238 | return QualType(); | |||
9239 | } | |||
9240 | if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { | |||
9241 | const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); | |||
9242 | const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); | |||
9243 | if (LHSBT != RHSBT && | |||
9244 | S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { | |||
9245 | S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) | |||
9246 | << LHS.get()->getType() << RHS.get()->getType() | |||
9247 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
9248 | } | |||
9249 | } | |||
9250 | } else { | |||
9251 | // ...else expand RHS to match the number of elements in LHS. | |||
9252 | QualType VecTy = | |||
9253 | S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); | |||
9254 | RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); | |||
9255 | } | |||
9256 | ||||
9257 | return LHSType; | |||
9258 | } | |||
9259 | ||||
9260 | // C99 6.5.7 | |||
9261 | QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, | |||
9262 | SourceLocation Loc, BinaryOperatorKind Opc, | |||
9263 | bool IsCompAssign) { | |||
9264 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); | |||
9265 | ||||
9266 | // Vector shifts promote their scalar inputs to vector type. | |||
9267 | if (LHS.get()->getType()->isVectorType() || | |||
9268 | RHS.get()->getType()->isVectorType()) { | |||
9269 | if (LangOpts.ZVector) { | |||
9270 | // The shift operators for the z vector extensions work basically | |||
9271 | // like general shifts, except that neither the LHS nor the RHS is | |||
9272 | // allowed to be a "vector bool". | |||
9273 | if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) | |||
9274 | if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) | |||
9275 | return InvalidOperands(Loc, LHS, RHS); | |||
9276 | if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) | |||
9277 | if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) | |||
9278 | return InvalidOperands(Loc, LHS, RHS); | |||
9279 | } | |||
9280 | return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); | |||
9281 | } | |||
9282 | ||||
9283 | // Shifts don't perform usual arithmetic conversions, they just do integer | |||
9284 | // promotions on each operand. C99 6.5.7p3 | |||
9285 | ||||
9286 | // For the LHS, do usual unary conversions, but then reset them away | |||
9287 | // if this is a compound assignment. | |||
9288 | ExprResult OldLHS = LHS; | |||
9289 | LHS = UsualUnaryConversions(LHS.get()); | |||
9290 | if (LHS.isInvalid()) | |||
9291 | return QualType(); | |||
9292 | QualType LHSType = LHS.get()->getType(); | |||
9293 | if (IsCompAssign) LHS = OldLHS; | |||
9294 | ||||
9295 | // The RHS is simpler. | |||
9296 | RHS = UsualUnaryConversions(RHS.get()); | |||
9297 | if (RHS.isInvalid()) | |||
9298 | return QualType(); | |||
9299 | QualType RHSType = RHS.get()->getType(); | |||
9300 | ||||
9301 | // C99 6.5.7p2: Each of the operands shall have integer type. | |||
9302 | if (!LHSType->hasIntegerRepresentation() || | |||
9303 | !RHSType->hasIntegerRepresentation()) | |||
9304 | return InvalidOperands(Loc, LHS, RHS); | |||
9305 | ||||
9306 | // C++0x: Don't allow scoped enums. FIXME: Use something better than | |||
9307 | // hasIntegerRepresentation() above instead of this. | |||
9308 | if (isScopedEnumerationType(LHSType) || | |||
9309 | isScopedEnumerationType(RHSType)) { | |||
9310 | return InvalidOperands(Loc, LHS, RHS); | |||
9311 | } | |||
9312 | // Sanity-check shift operands | |||
9313 | DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); | |||
9314 | ||||
9315 | // "The type of the result is that of the promoted left operand." | |||
9316 | return LHSType; | |||
9317 | } | |||
9318 | ||||
9319 | /// If two different enums are compared, raise a warning. | |||
9320 | static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, | |||
9321 | Expr *RHS) { | |||
9322 | QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); | |||
9323 | QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); | |||
9324 | ||||
9325 | const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); | |||
9326 | if (!LHSEnumType) | |||
9327 | return; | |||
9328 | const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); | |||
9329 | if (!RHSEnumType) | |||
9330 | return; | |||
9331 | ||||
9332 | // Ignore anonymous enums. | |||
9333 | if (!LHSEnumType->getDecl()->getIdentifier() && | |||
9334 | !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) | |||
9335 | return; | |||
9336 | if (!RHSEnumType->getDecl()->getIdentifier() && | |||
9337 | !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) | |||
9338 | return; | |||
9339 | ||||
9340 | if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) | |||
9341 | return; | |||
9342 | ||||
9343 | S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) | |||
9344 | << LHSStrippedType << RHSStrippedType | |||
9345 | << LHS->getSourceRange() << RHS->getSourceRange(); | |||
9346 | } | |||
9347 | ||||
9348 | /// \brief Diagnose bad pointer comparisons. | |||
9349 | static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, | |||
9350 | ExprResult &LHS, ExprResult &RHS, | |||
9351 | bool IsError) { | |||
9352 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers | |||
9353 | : diag::ext_typecheck_comparison_of_distinct_pointers) | |||
9354 | << LHS.get()->getType() << RHS.get()->getType() | |||
9355 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
9356 | } | |||
9357 | ||||
9358 | /// \brief Returns false if the pointers are converted to a composite type, | |||
9359 | /// true otherwise. | |||
9360 | static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, | |||
9361 | ExprResult &LHS, ExprResult &RHS) { | |||
9362 | // C++ [expr.rel]p2: | |||
9363 | // [...] Pointer conversions (4.10) and qualification | |||
9364 | // conversions (4.4) are performed on pointer operands (or on | |||
9365 | // a pointer operand and a null pointer constant) to bring | |||
9366 | // them to their composite pointer type. [...] | |||
9367 | // | |||
9368 | // C++ [expr.eq]p1 uses the same notion for (in)equality | |||
9369 | // comparisons of pointers. | |||
9370 | ||||
9371 | QualType LHSType = LHS.get()->getType(); | |||
9372 | QualType RHSType = RHS.get()->getType(); | |||
9373 | 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()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 9374, __extension__ __PRETTY_FUNCTION__)) | |||
9374 | 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()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 9374, __extension__ __PRETTY_FUNCTION__)); | |||
9375 | ||||
9376 | QualType T = S.FindCompositePointerType(Loc, LHS, RHS); | |||
9377 | if (T.isNull()) { | |||
9378 | if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && | |||
9379 | (RHSType->isPointerType() || RHSType->isMemberPointerType())) | |||
9380 | diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); | |||
9381 | else | |||
9382 | S.InvalidOperands(Loc, LHS, RHS); | |||
9383 | return true; | |||
9384 | } | |||
9385 | ||||
9386 | LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); | |||
9387 | RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); | |||
9388 | return false; | |||
9389 | } | |||
9390 | ||||
9391 | static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, | |||
9392 | ExprResult &LHS, | |||
9393 | ExprResult &RHS, | |||
9394 | bool IsError) { | |||
9395 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void | |||
9396 | : diag::ext_typecheck_comparison_of_fptr_to_void) | |||
9397 | << LHS.get()->getType() << RHS.get()->getType() | |||
9398 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
9399 | } | |||
9400 | ||||
9401 | static bool isObjCObjectLiteral(ExprResult &E) { | |||
9402 | switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { | |||
9403 | case Stmt::ObjCArrayLiteralClass: | |||
9404 | case Stmt::ObjCDictionaryLiteralClass: | |||
9405 | case Stmt::ObjCStringLiteralClass: | |||
9406 | case Stmt::ObjCBoxedExprClass: | |||
9407 | return true; | |||
9408 | default: | |||
9409 | // Note that ObjCBoolLiteral is NOT an object literal! | |||
9410 | return false; | |||
9411 | } | |||
9412 | } | |||
9413 | ||||
9414 | static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { | |||
9415 | const ObjCObjectPointerType *Type = | |||
9416 | LHS->getType()->getAs<ObjCObjectPointerType>(); | |||
9417 | ||||
9418 | // If this is not actually an Objective-C object, bail out. | |||
9419 | if (!Type) | |||
9420 | return false; | |||
9421 | ||||
9422 | // Get the LHS object's interface type. | |||
9423 | QualType InterfaceType = Type->getPointeeType(); | |||
9424 | ||||
9425 | // If the RHS isn't an Objective-C object, bail out. | |||
9426 | if (!RHS->getType()->isObjCObjectPointerType()) | |||
9427 | return false; | |||
9428 | ||||
9429 | // Try to find the -isEqual: method. | |||
9430 | Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); | |||
9431 | ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, | |||
9432 | InterfaceType, | |||
9433 | /*instance=*/true); | |||
9434 | if (!Method) { | |||
9435 | if (Type->isObjCIdType()) { | |||
9436 | // For 'id', just check the global pool. | |||
9437 | Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), | |||
9438 | /*receiverId=*/true); | |||
9439 | } else { | |||
9440 | // Check protocols. | |||
9441 | Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, | |||
9442 | /*instance=*/true); | |||
9443 | } | |||
9444 | } | |||
9445 | ||||
9446 | if (!Method) | |||
9447 | return false; | |||
9448 | ||||
9449 | QualType T = Method->parameters()[0]->getType(); | |||
9450 | if (!T->isObjCObjectPointerType()) | |||
9451 | return false; | |||
9452 | ||||
9453 | QualType R = Method->getReturnType(); | |||
9454 | if (!R->isScalarType()) | |||
9455 | return false; | |||
9456 | ||||
9457 | return true; | |||
9458 | } | |||
9459 | ||||
9460 | Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { | |||
9461 | FromE = FromE->IgnoreParenImpCasts(); | |||
9462 | switch (FromE->getStmtClass()) { | |||
9463 | default: | |||
9464 | break; | |||
9465 | case Stmt::ObjCStringLiteralClass: | |||
9466 | // "string literal" | |||
9467 | return LK_String; | |||
9468 | case Stmt::ObjCArrayLiteralClass: | |||
9469 | // "array literal" | |||
9470 | return LK_Array; | |||
9471 | case Stmt::ObjCDictionaryLiteralClass: | |||
9472 | // "dictionary literal" | |||
9473 | return LK_Dictionary; | |||
9474 | case Stmt::BlockExprClass: | |||
9475 | return LK_Block; | |||
9476 | case Stmt::ObjCBoxedExprClass: { | |||
9477 | Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); | |||
9478 | switch (Inner->getStmtClass()) { | |||
9479 | case Stmt::IntegerLiteralClass: | |||
9480 | case Stmt::FloatingLiteralClass: | |||
9481 | case Stmt::CharacterLiteralClass: | |||
9482 | case Stmt::ObjCBoolLiteralExprClass: | |||
9483 | case Stmt::CXXBoolLiteralExprClass: | |||
9484 | // "numeric literal" | |||
9485 | return LK_Numeric; | |||
9486 | case Stmt::ImplicitCastExprClass: { | |||
9487 | CastKind CK = cast<CastExpr>(Inner)->getCastKind(); | |||
9488 | // Boolean literals can be represented by implicit casts. | |||
9489 | if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) | |||
9490 | return LK_Numeric; | |||
9491 | break; | |||
9492 | } | |||
9493 | default: | |||
9494 | break; | |||
9495 | } | |||
9496 | return LK_Boxed; | |||
9497 | } | |||
9498 | } | |||
9499 | return LK_None; | |||
9500 | } | |||
9501 | ||||
9502 | static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, | |||
9503 | ExprResult &LHS, ExprResult &RHS, | |||
9504 | BinaryOperator::Opcode Opc){ | |||
9505 | Expr *Literal; | |||
9506 | Expr *Other; | |||
9507 | if (isObjCObjectLiteral(LHS)) { | |||
9508 | Literal = LHS.get(); | |||
9509 | Other = RHS.get(); | |||
9510 | } else { | |||
9511 | Literal = RHS.get(); | |||
9512 | Other = LHS.get(); | |||
9513 | } | |||
9514 | ||||
9515 | // Don't warn on comparisons against nil. | |||
9516 | Other = Other->IgnoreParenCasts(); | |||
9517 | if (Other->isNullPointerConstant(S.getASTContext(), | |||
9518 | Expr::NPC_ValueDependentIsNotNull)) | |||
9519 | return; | |||
9520 | ||||
9521 | // This should be kept in sync with warn_objc_literal_comparison. | |||
9522 | // LK_String should always be after the other literals, since it has its own | |||
9523 | // warning flag. | |||
9524 | Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); | |||
9525 | assert(LiteralKind != Sema::LK_Block)(static_cast <bool> (LiteralKind != Sema::LK_Block) ? void (0) : __assert_fail ("LiteralKind != Sema::LK_Block", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 9525, __extension__ __PRETTY_FUNCTION__)); | |||
9526 | if (LiteralKind == Sema::LK_None) { | |||
9527 | llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 9527); | |||
9528 | } | |||
9529 | ||||
9530 | if (LiteralKind == Sema::LK_String) | |||
9531 | S.Diag(Loc, diag::warn_objc_string_literal_comparison) | |||
9532 | << Literal->getSourceRange(); | |||
9533 | else | |||
9534 | S.Diag(Loc, diag::warn_objc_literal_comparison) | |||
9535 | << LiteralKind << Literal->getSourceRange(); | |||
9536 | ||||
9537 | if (BinaryOperator::isEqualityOp(Opc) && | |||
9538 | hasIsEqualMethod(S, LHS.get(), RHS.get())) { | |||
9539 | SourceLocation Start = LHS.get()->getLocStart(); | |||
9540 | SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); | |||
9541 | CharSourceRange OpRange = | |||
9542 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | |||
9543 | ||||
9544 | S.Diag(Loc, diag::note_objc_literal_comparison_isequal) | |||
9545 | << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") | |||
9546 | << FixItHint::CreateReplacement(OpRange, " isEqual:") | |||
9547 | << FixItHint::CreateInsertion(End, "]"); | |||
9548 | } | |||
9549 | } | |||
9550 | ||||
9551 | /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. | |||
9552 | static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, | |||
9553 | ExprResult &RHS, SourceLocation Loc, | |||
9554 | BinaryOperatorKind Opc) { | |||
9555 | // Check that left hand side is !something. | |||
9556 | UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); | |||
9557 | if (!UO || UO->getOpcode() != UO_LNot) return; | |||
9558 | ||||
9559 | // Only check if the right hand side is non-bool arithmetic type. | |||
9560 | if (RHS.get()->isKnownToHaveBooleanValue()) return; | |||
9561 | ||||
9562 | // Make sure that the something in !something is not bool. | |||
9563 | Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); | |||
9564 | if (SubExpr->isKnownToHaveBooleanValue()) return; | |||
9565 | ||||
9566 | // Emit warning. | |||
9567 | bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; | |||
9568 | S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) | |||
9569 | << Loc << IsBitwiseOp; | |||
9570 | ||||
9571 | // First note suggest !(x < y) | |||
9572 | SourceLocation FirstOpen = SubExpr->getLocStart(); | |||
9573 | SourceLocation FirstClose = RHS.get()->getLocEnd(); | |||
9574 | FirstClose = S.getLocForEndOfToken(FirstClose); | |||
9575 | if (FirstClose.isInvalid()) | |||
9576 | FirstOpen = SourceLocation(); | |||
9577 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) | |||
9578 | << IsBitwiseOp | |||
9579 | << FixItHint::CreateInsertion(FirstOpen, "(") | |||
9580 | << FixItHint::CreateInsertion(FirstClose, ")"); | |||
9581 | ||||
9582 | // Second note suggests (!x) < y | |||
9583 | SourceLocation SecondOpen = LHS.get()->getLocStart(); | |||
9584 | SourceLocation SecondClose = LHS.get()->getLocEnd(); | |||
9585 | SecondClose = S.getLocForEndOfToken(SecondClose); | |||
9586 | if (SecondClose.isInvalid()) | |||
9587 | SecondOpen = SourceLocation(); | |||
9588 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) | |||
9589 | << FixItHint::CreateInsertion(SecondOpen, "(") | |||
9590 | << FixItHint::CreateInsertion(SecondClose, ")"); | |||
9591 | } | |||
9592 | ||||
9593 | // Get the decl for a simple expression: a reference to a variable, | |||
9594 | // an implicit C++ field reference, or an implicit ObjC ivar reference. | |||
9595 | static ValueDecl *getCompareDecl(Expr *E) { | |||
9596 | if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) | |||
9597 | return DR->getDecl(); | |||
9598 | if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { | |||
9599 | if (Ivar->isFreeIvar()) | |||
9600 | return Ivar->getDecl(); | |||
9601 | } | |||
9602 | if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { | |||
9603 | if (Mem->isImplicitAccess()) | |||
9604 | return Mem->getMemberDecl(); | |||
9605 | } | |||
9606 | return nullptr; | |||
9607 | } | |||
9608 | ||||
9609 | /// Diagnose some forms of syntactically-obvious tautological comparison. | |||
9610 | static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, | |||
9611 | Expr *LHS, Expr *RHS, | |||
9612 | BinaryOperatorKind Opc) { | |||
9613 | Expr *LHSStripped = LHS->IgnoreParenImpCasts(); | |||
9614 | Expr *RHSStripped = RHS->IgnoreParenImpCasts(); | |||
9615 | ||||
9616 | QualType LHSType = LHS->getType(); | |||
9617 | if (LHSType->hasFloatingRepresentation() || | |||
9618 | (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || | |||
9619 | LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() || | |||
9620 | S.inTemplateInstantiation()) | |||
9621 | return; | |||
9622 | ||||
9623 | // For non-floating point types, check for self-comparisons of the form | |||
9624 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | |||
9625 | // often indicate logic errors in the program. | |||
9626 | // | |||
9627 | // NOTE: Don't warn about comparison expressions resulting from macro | |||
9628 | // expansion. Also don't warn about comparisons which are only self | |||
9629 | // comparisons within a template instantiation. The warnings should catch | |||
9630 | // obvious cases in the definition of the template anyways. The idea is to | |||
9631 | // warn when the typed comparison operator will always evaluate to the same | |||
9632 | // result. | |||
9633 | ValueDecl *DL = getCompareDecl(LHSStripped); | |||
9634 | ValueDecl *DR = getCompareDecl(RHSStripped); | |||
9635 | if (DL && DR && declaresSameEntity(DL, DR)) { | |||
9636 | StringRef Result; | |||
9637 | switch (Opc) { | |||
9638 | case BO_EQ: case BO_LE: case BO_GE: | |||
9639 | Result = "true"; | |||
9640 | break; | |||
9641 | case BO_NE: case BO_LT: case BO_GT: | |||
9642 | Result = "false"; | |||
9643 | break; | |||
9644 | case BO_Cmp: | |||
9645 | Result = "'std::strong_ordering::equal'"; | |||
9646 | break; | |||
9647 | default: | |||
9648 | break; | |||
9649 | } | |||
9650 | S.DiagRuntimeBehavior(Loc, nullptr, | |||
9651 | S.PDiag(diag::warn_comparison_always) | |||
9652 | << 0 /*self-comparison*/ << !Result.empty() | |||
9653 | << Result); | |||
9654 | } else if (DL && DR && | |||
9655 | DL->getType()->isArrayType() && DR->getType()->isArrayType() && | |||
9656 | !DL->isWeak() && !DR->isWeak()) { | |||
9657 | // What is it always going to evaluate to? | |||
9658 | StringRef Result; | |||
9659 | switch(Opc) { | |||
9660 | case BO_EQ: // e.g. array1 == array2 | |||
9661 | Result = "false"; | |||
9662 | break; | |||
9663 | case BO_NE: // e.g. array1 != array2 | |||
9664 | Result = "true"; | |||
9665 | break; | |||
9666 | default: // e.g. array1 <= array2 | |||
9667 | // The best we can say is 'a constant' | |||
9668 | break; | |||
9669 | } | |||
9670 | S.DiagRuntimeBehavior(Loc, nullptr, | |||
9671 | S.PDiag(diag::warn_comparison_always) | |||
9672 | << 1 /*array comparison*/ | |||
9673 | << !Result.empty() << Result); | |||
9674 | } | |||
9675 | ||||
9676 | if (isa<CastExpr>(LHSStripped)) | |||
9677 | LHSStripped = LHSStripped->IgnoreParenCasts(); | |||
9678 | if (isa<CastExpr>(RHSStripped)) | |||
9679 | RHSStripped = RHSStripped->IgnoreParenCasts(); | |||
9680 | ||||
9681 | // Warn about comparisons against a string constant (unless the other | |||
9682 | // operand is null); the user probably wants strcmp. | |||
9683 | Expr *LiteralString = nullptr; | |||
9684 | Expr *LiteralStringStripped = nullptr; | |||
9685 | if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && | |||
9686 | !RHSStripped->isNullPointerConstant(S.Context, | |||
9687 | Expr::NPC_ValueDependentIsNull)) { | |||
9688 | LiteralString = LHS; | |||
9689 | LiteralStringStripped = LHSStripped; | |||
9690 | } else if ((isa<StringLiteral>(RHSStripped) || | |||
9691 | isa<ObjCEncodeExpr>(RHSStripped)) && | |||
9692 | !LHSStripped->isNullPointerConstant(S.Context, | |||
9693 | Expr::NPC_ValueDependentIsNull)) { | |||
9694 | LiteralString = RHS; | |||
9695 | LiteralStringStripped = RHSStripped; | |||
9696 | } | |||
9697 | ||||
9698 | if (LiteralString) { | |||
9699 | S.DiagRuntimeBehavior(Loc, nullptr, | |||
9700 | S.PDiag(diag::warn_stringcompare) | |||
9701 | << isa<ObjCEncodeExpr>(LiteralStringStripped) | |||
9702 | << LiteralString->getSourceRange()); | |||
9703 | } | |||
9704 | } | |||
9705 | ||||
9706 | static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, | |||
9707 | ExprResult &RHS, | |||
9708 | SourceLocation Loc, | |||
9709 | BinaryOperatorKind Opc) { | |||
9710 | // C99 6.5.8p3 / C99 6.5.9p4 | |||
9711 | QualType Type = S.UsualArithmeticConversions(LHS, RHS); | |||
9712 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
9713 | return QualType(); | |||
9714 | if (Type.isNull()) | |||
9715 | return S.InvalidOperands(Loc, LHS, RHS); | |||
9716 | assert(Type->isArithmeticType() || Type->isEnumeralType())(static_cast <bool> (Type->isArithmeticType() || Type ->isEnumeralType()) ? void (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 9716, __extension__ __PRETTY_FUNCTION__)); | |||
9717 | ||||
9718 | checkEnumComparison(S, Loc, LHS.get(), RHS.get()); | |||
9719 | ||||
9720 | enum { StrongEquality, PartialOrdering, StrongOrdering } Ordering; | |||
9721 | if (Type->isAnyComplexType()) | |||
9722 | Ordering = StrongEquality; | |||
9723 | else if (Type->isFloatingType()) | |||
9724 | Ordering = PartialOrdering; | |||
9725 | else | |||
9726 | Ordering = StrongOrdering; | |||
9727 | ||||
9728 | if (Ordering == StrongEquality && BinaryOperator::isRelationalOp(Opc)) | |||
9729 | return S.InvalidOperands(Loc, LHS, RHS); | |||
9730 | ||||
9731 | // Check for comparisons of floating point operands using != and ==. | |||
9732 | if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) | |||
9733 | S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); | |||
9734 | ||||
9735 | // The result of comparisons is 'bool' in C++, 'int' in C. | |||
9736 | // FIXME: For BO_Cmp, return the relevant comparison category type. | |||
9737 | return S.Context.getLogicalOperationType(); | |||
9738 | } | |||
9739 | ||||
9740 | // C99 6.5.8, C++ [expr.rel] | |||
9741 | QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, | |||
9742 | SourceLocation Loc, BinaryOperatorKind Opc, | |||
9743 | bool IsRelational) { | |||
9744 | // Comparisons expect an rvalue, so convert to rvalue before any | |||
9745 | // type-related checks. | |||
9746 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
9747 | if (LHS.isInvalid()) | |||
9748 | return QualType(); | |||
9749 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
9750 | if (RHS.isInvalid()) | |||
9751 | return QualType(); | |||
9752 | ||||
9753 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); | |||
9754 | ||||
9755 | // Handle vector comparisons separately. | |||
9756 | if (LHS.get()->getType()->isVectorType() || | |||
9757 | RHS.get()->getType()->isVectorType()) | |||
9758 | return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); | |||
9759 | ||||
9760 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | |||
9761 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | |||
9762 | ||||
9763 | QualType LHSType = LHS.get()->getType(); | |||
9764 | QualType RHSType = RHS.get()->getType(); | |||
9765 | if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && | |||
9766 | (RHSType->isArithmeticType() || RHSType->isEnumeralType())) | |||
9767 | return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); | |||
9768 | ||||
9769 | QualType ResultTy = Context.getLogicalOperationType(); | |||
9770 | ||||
9771 | const Expr::NullPointerConstantKind LHSNullKind = | |||
9772 | LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | |||
9773 | const Expr::NullPointerConstantKind RHSNullKind = | |||
9774 | RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | |||
9775 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; | |||
9776 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; | |||
9777 | ||||
9778 | if (!IsRelational && LHSIsNull != RHSIsNull) { | |||
9779 | bool IsEquality = Opc == BO_EQ; | |||
9780 | if (RHSIsNull) | |||
9781 | DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, | |||
9782 | RHS.get()->getSourceRange()); | |||
9783 | else | |||
9784 | DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, | |||
9785 | LHS.get()->getSourceRange()); | |||
9786 | } | |||
9787 | ||||
9788 | if ((LHSType->isIntegerType() && !LHSIsNull) || | |||
9789 | (RHSType->isIntegerType() && !RHSIsNull)) { | |||
9790 | // Skip normal pointer conversion checks in this case; we have better | |||
9791 | // diagnostics for this below. | |||
9792 | } else if (getLangOpts().CPlusPlus) { | |||
9793 | // Equality comparison of a function pointer to a void pointer is invalid, | |||
9794 | // but we allow it as an extension. | |||
9795 | // FIXME: If we really want to allow this, should it be part of composite | |||
9796 | // pointer type computation so it works in conditionals too? | |||
9797 | if (!IsRelational && | |||
9798 | ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || | |||
9799 | (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { | |||
9800 | // This is a gcc extension compatibility comparison. | |||
9801 | // In a SFINAE context, we treat this as a hard error to maintain | |||
9802 | // conformance with the C++ standard. | |||
9803 | diagnoseFunctionPointerToVoidComparison( | |||
9804 | *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); | |||
9805 | ||||
9806 | if (isSFINAEContext()) | |||
9807 | return QualType(); | |||
9808 | ||||
9809 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
9810 | return ResultTy; | |||
9811 | } | |||
9812 | ||||
9813 | // C++ [expr.eq]p2: | |||
9814 | // If at least one operand is a pointer [...] bring them to their | |||
9815 | // composite pointer type. | |||
9816 | // C++ [expr.rel]p2: | |||
9817 | // If both operands are pointers, [...] bring them to their composite | |||
9818 | // pointer type. | |||
9819 | if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= | |||
9820 | (IsRelational ? 2 : 1) && | |||
9821 | (!LangOpts.ObjCAutoRefCount || | |||
9822 | !(LHSType->isObjCObjectPointerType() || | |||
9823 | RHSType->isObjCObjectPointerType()))) { | |||
9824 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | |||
9825 | return QualType(); | |||
9826 | else | |||
9827 | return ResultTy; | |||
9828 | } | |||
9829 | } else if (LHSType->isPointerType() && | |||
9830 | RHSType->isPointerType()) { // C99 6.5.8p2 | |||
9831 | // All of the following pointer-related warnings are GCC extensions, except | |||
9832 | // when handling null pointer constants. | |||
9833 | QualType LCanPointeeTy = | |||
9834 | LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | |||
9835 | QualType RCanPointeeTy = | |||
9836 | RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | |||
9837 | ||||
9838 | // C99 6.5.9p2 and C99 6.5.8p2 | |||
9839 | if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), | |||
9840 | RCanPointeeTy.getUnqualifiedType())) { | |||
9841 | // Valid unless a relational comparison of function pointers | |||
9842 | if (IsRelational && LCanPointeeTy->isFunctionType()) { | |||
9843 | Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) | |||
9844 | << LHSType << RHSType << LHS.get()->getSourceRange() | |||
9845 | << RHS.get()->getSourceRange(); | |||
9846 | } | |||
9847 | } else if (!IsRelational && | |||
9848 | (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { | |||
9849 | // Valid unless comparison between non-null pointer and function pointer | |||
9850 | if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) | |||
9851 | && !LHSIsNull && !RHSIsNull) | |||
9852 | diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, | |||
9853 | /*isError*/false); | |||
9854 | } else { | |||
9855 | // Invalid | |||
9856 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); | |||
9857 | } | |||
9858 | if (LCanPointeeTy != RCanPointeeTy) { | |||
9859 | // Treat NULL constant as a special case in OpenCL. | |||
9860 | if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { | |||
9861 | const PointerType *LHSPtr = LHSType->getAs<PointerType>(); | |||
9862 | if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { | |||
9863 | Diag(Loc, | |||
9864 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | |||
9865 | << LHSType << RHSType << 0 /* comparison */ | |||
9866 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
9867 | } | |||
9868 | } | |||
9869 | LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); | |||
9870 | LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); | |||
9871 | CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion | |||
9872 | : CK_BitCast; | |||
9873 | if (LHSIsNull && !RHSIsNull) | |||
9874 | LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); | |||
9875 | else | |||
9876 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); | |||
9877 | } | |||
9878 | return ResultTy; | |||
9879 | } | |||
9880 | ||||
9881 | if (getLangOpts().CPlusPlus) { | |||
9882 | // C++ [expr.eq]p4: | |||
9883 | // Two operands of type std::nullptr_t or one operand of type | |||
9884 | // std::nullptr_t and the other a null pointer constant compare equal. | |||
9885 | if (!IsRelational && LHSIsNull && RHSIsNull) { | |||
9886 | if (LHSType->isNullPtrType()) { | |||
9887 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
9888 | return ResultTy; | |||
9889 | } | |||
9890 | if (RHSType->isNullPtrType()) { | |||
9891 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
9892 | return ResultTy; | |||
9893 | } | |||
9894 | } | |||
9895 | ||||
9896 | // Comparison of Objective-C pointers and block pointers against nullptr_t. | |||
9897 | // These aren't covered by the composite pointer type rules. | |||
9898 | if (!IsRelational && RHSType->isNullPtrType() && | |||
9899 | (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { | |||
9900 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
9901 | return ResultTy; | |||
9902 | } | |||
9903 | if (!IsRelational && LHSType->isNullPtrType() && | |||
9904 | (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { | |||
9905 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
9906 | return ResultTy; | |||
9907 | } | |||
9908 | ||||
9909 | if (IsRelational && | |||
9910 | ((LHSType->isNullPtrType() && RHSType->isPointerType()) || | |||
9911 | (RHSType->isNullPtrType() && LHSType->isPointerType()))) { | |||
9912 | // HACK: Relational comparison of nullptr_t against a pointer type is | |||
9913 | // invalid per DR583, but we allow it within std::less<> and friends, | |||
9914 | // since otherwise common uses of it break. | |||
9915 | // FIXME: Consider removing this hack once LWG fixes std::less<> and | |||
9916 | // friends to have std::nullptr_t overload candidates. | |||
9917 | DeclContext *DC = CurContext; | |||
9918 | if (isa<FunctionDecl>(DC)) | |||
9919 | DC = DC->getParent(); | |||
9920 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { | |||
9921 | if (CTSD->isInStdNamespace() && | |||
9922 | llvm::StringSwitch<bool>(CTSD->getName()) | |||
9923 | .Cases("less", "less_equal", "greater", "greater_equal", true) | |||
9924 | .Default(false)) { | |||
9925 | if (RHSType->isNullPtrType()) | |||
9926 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
9927 | else | |||
9928 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
9929 | return ResultTy; | |||
9930 | } | |||
9931 | } | |||
9932 | } | |||
9933 | ||||
9934 | // C++ [expr.eq]p2: | |||
9935 | // If at least one operand is a pointer to member, [...] bring them to | |||
9936 | // their composite pointer type. | |||
9937 | if (!IsRelational && | |||
9938 | (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { | |||
9939 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | |||
9940 | return QualType(); | |||
9941 | else | |||
9942 | return ResultTy; | |||
9943 | } | |||
9944 | } | |||
9945 | ||||
9946 | // Handle block pointer types. | |||
9947 | if (!IsRelational && LHSType->isBlockPointerType() && | |||
9948 | RHSType->isBlockPointerType()) { | |||
9949 | QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); | |||
9950 | QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); | |||
9951 | ||||
9952 | if (!LHSIsNull && !RHSIsNull && | |||
9953 | !Context.typesAreCompatible(lpointee, rpointee)) { | |||
9954 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | |||
9955 | << LHSType << RHSType << LHS.get()->getSourceRange() | |||
9956 | << RHS.get()->getSourceRange(); | |||
9957 | } | |||
9958 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
9959 | return ResultTy; | |||
9960 | } | |||
9961 | ||||
9962 | // Allow block pointers to be compared with null pointer constants. | |||
9963 | if (!IsRelational | |||
9964 | && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) | |||
9965 | || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { | |||
9966 | if (!LHSIsNull && !RHSIsNull) { | |||
9967 | if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() | |||
9968 | ->getPointeeType()->isVoidType()) | |||
9969 | || (LHSType->isPointerType() && LHSType->castAs<PointerType>() | |||
9970 | ->getPointeeType()->isVoidType()))) | |||
9971 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | |||
9972 | << LHSType << RHSType << LHS.get()->getSourceRange() | |||
9973 | << RHS.get()->getSourceRange(); | |||
9974 | } | |||
9975 | if (LHSIsNull && !RHSIsNull) | |||
9976 | LHS = ImpCastExprToType(LHS.get(), RHSType, | |||
9977 | RHSType->isPointerType() ? CK_BitCast | |||
9978 | : CK_AnyPointerToBlockPointerCast); | |||
9979 | else | |||
9980 | RHS = ImpCastExprToType(RHS.get(), LHSType, | |||
9981 | LHSType->isPointerType() ? CK_BitCast | |||
9982 | : CK_AnyPointerToBlockPointerCast); | |||
9983 | return ResultTy; | |||
9984 | } | |||
9985 | ||||
9986 | if (LHSType->isObjCObjectPointerType() || | |||
9987 | RHSType->isObjCObjectPointerType()) { | |||
9988 | const PointerType *LPT = LHSType->getAs<PointerType>(); | |||
9989 | const PointerType *RPT = RHSType->getAs<PointerType>(); | |||
9990 | if (LPT || RPT) { | |||
9991 | bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; | |||
9992 | bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; | |||
9993 | ||||
9994 | if (!LPtrToVoid && !RPtrToVoid && | |||
9995 | !Context.typesAreCompatible(LHSType, RHSType)) { | |||
9996 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | |||
9997 | /*isError*/false); | |||
9998 | } | |||
9999 | if (LHSIsNull && !RHSIsNull) { | |||
10000 | Expr *E = LHS.get(); | |||
10001 | if (getLangOpts().ObjCAutoRefCount) | |||
10002 | CheckObjCConversion(SourceRange(), RHSType, E, | |||
10003 | CCK_ImplicitConversion); | |||
10004 | LHS = ImpCastExprToType(E, RHSType, | |||
10005 | RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | |||
10006 | } | |||
10007 | else { | |||
10008 | Expr *E = RHS.get(); | |||
10009 | if (getLangOpts().ObjCAutoRefCount) | |||
10010 | CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, | |||
10011 | /*Diagnose=*/true, | |||
10012 | /*DiagnoseCFAudited=*/false, Opc); | |||
10013 | RHS = ImpCastExprToType(E, LHSType, | |||
10014 | LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | |||
10015 | } | |||
10016 | return ResultTy; | |||
10017 | } | |||
10018 | if (LHSType->isObjCObjectPointerType() && | |||
10019 | RHSType->isObjCObjectPointerType()) { | |||
10020 | if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) | |||
10021 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | |||
10022 | /*isError*/false); | |||
10023 | if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) | |||
10024 | diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); | |||
10025 | ||||
10026 | if (LHSIsNull && !RHSIsNull) | |||
10027 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | |||
10028 | else | |||
10029 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
10030 | return ResultTy; | |||
10031 | } | |||
10032 | ||||
10033 | if (!IsRelational && LHSType->isBlockPointerType() && | |||
10034 | RHSType->isBlockCompatibleObjCPointerType(Context)) { | |||
10035 | LHS = ImpCastExprToType(LHS.get(), RHSType, | |||
10036 | CK_BlockPointerToObjCPointerCast); | |||
10037 | return ResultTy; | |||
10038 | } else if (!IsRelational && | |||
10039 | LHSType->isBlockCompatibleObjCPointerType(Context) && | |||
10040 | RHSType->isBlockPointerType()) { | |||
10041 | RHS = ImpCastExprToType(RHS.get(), LHSType, | |||
10042 | CK_BlockPointerToObjCPointerCast); | |||
10043 | return ResultTy; | |||
10044 | } | |||
10045 | } | |||
10046 | if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || | |||
10047 | (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { | |||
10048 | unsigned DiagID = 0; | |||
10049 | bool isError = false; | |||
10050 | if (LangOpts.DebuggerSupport) { | |||
10051 | // Under a debugger, allow the comparison of pointers to integers, | |||
10052 | // since users tend to want to compare addresses. | |||
10053 | } else if ((LHSIsNull && LHSType->isIntegerType()) || | |||
10054 | (RHSIsNull && RHSType->isIntegerType())) { | |||
10055 | if (IsRelational) { | |||
10056 | isError = getLangOpts().CPlusPlus; | |||
10057 | DiagID = | |||
10058 | isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero | |||
10059 | : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; | |||
10060 | } | |||
10061 | } else if (getLangOpts().CPlusPlus) { | |||
10062 | DiagID = diag::err_typecheck_comparison_of_pointer_integer; | |||
10063 | isError = true; | |||
10064 | } else if (IsRelational) | |||
10065 | DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; | |||
10066 | else | |||
10067 | DiagID = diag::ext_typecheck_comparison_of_pointer_integer; | |||
10068 | ||||
10069 | if (DiagID) { | |||
10070 | Diag(Loc, DiagID) | |||
10071 | << LHSType << RHSType << LHS.get()->getSourceRange() | |||
10072 | << RHS.get()->getSourceRange(); | |||
10073 | if (isError) | |||
10074 | return QualType(); | |||
10075 | } | |||
10076 | ||||
10077 | if (LHSType->isIntegerType()) | |||
10078 | LHS = ImpCastExprToType(LHS.get(), RHSType, | |||
10079 | LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | |||
10080 | else | |||
10081 | RHS = ImpCastExprToType(RHS.get(), LHSType, | |||
10082 | RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | |||
10083 | return ResultTy; | |||
10084 | } | |||
10085 | ||||
10086 | // Handle block pointers. | |||
10087 | if (!IsRelational && RHSIsNull | |||
10088 | && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { | |||
10089 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
10090 | return ResultTy; | |||
10091 | } | |||
10092 | if (!IsRelational && LHSIsNull | |||
10093 | && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { | |||
10094 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
10095 | return ResultTy; | |||
10096 | } | |||
10097 | ||||
10098 | if (getLangOpts().OpenCLVersion >= 200) { | |||
10099 | if (LHSIsNull && RHSType->isQueueT()) { | |||
10100 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
10101 | return ResultTy; | |||
10102 | } | |||
10103 | ||||
10104 | if (LHSType->isQueueT() && RHSIsNull) { | |||
10105 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
10106 | return ResultTy; | |||
10107 | } | |||
10108 | } | |||
10109 | ||||
10110 | return InvalidOperands(Loc, LHS, RHS); | |||
10111 | } | |||
10112 | ||||
10113 | // Return a signed ext_vector_type that is of identical size and number of | |||
10114 | // elements. For floating point vectors, return an integer type of identical | |||
10115 | // size and number of elements. In the non ext_vector_type case, search from | |||
10116 | // the largest type to the smallest type to avoid cases where long long == long, | |||
10117 | // where long gets picked over long long. | |||
10118 | QualType Sema::GetSignedVectorType(QualType V) { | |||
10119 | const VectorType *VTy = V->getAs<VectorType>(); | |||
10120 | unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); | |||
10121 | ||||
10122 | if (isa<ExtVectorType>(VTy)) { | |||
10123 | if (TypeSize == Context.getTypeSize(Context.CharTy)) | |||
10124 | return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); | |||
10125 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) | |||
10126 | return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); | |||
10127 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) | |||
10128 | return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); | |||
10129 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) | |||
10130 | return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); | |||
10131 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10132, __extension__ __PRETTY_FUNCTION__)) | |||
10132 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10132, __extension__ __PRETTY_FUNCTION__)); | |||
10133 | return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); | |||
10134 | } | |||
10135 | ||||
10136 | if (TypeSize == Context.getTypeSize(Context.LongLongTy)) | |||
10137 | return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), | |||
10138 | VectorType::GenericVector); | |||
10139 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) | |||
10140 | return Context.getVectorType(Context.LongTy, VTy->getNumElements(), | |||
10141 | VectorType::GenericVector); | |||
10142 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) | |||
10143 | return Context.getVectorType(Context.IntTy, VTy->getNumElements(), | |||
10144 | VectorType::GenericVector); | |||
10145 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) | |||
10146 | return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), | |||
10147 | VectorType::GenericVector); | |||
10148 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10149, __extension__ __PRETTY_FUNCTION__)) | |||
10149 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10149, __extension__ __PRETTY_FUNCTION__)); | |||
10150 | return Context.getVectorType(Context.CharTy, VTy->getNumElements(), | |||
10151 | VectorType::GenericVector); | |||
10152 | } | |||
10153 | ||||
10154 | /// CheckVectorCompareOperands - vector comparisons are a clang extension that | |||
10155 | /// operates on extended vector types. Instead of producing an IntTy result, | |||
10156 | /// like a scalar comparison, a vector comparison produces a vector of integer | |||
10157 | /// types. | |||
10158 | QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, | |||
10159 | SourceLocation Loc, | |||
10160 | BinaryOperatorKind Opc) { | |||
10161 | // Check to make sure we're operating on vectors of the same type and width, | |||
10162 | // Allowing one side to be a scalar of element type. | |||
10163 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, | |||
10164 | /*AllowBothBool*/true, | |||
10165 | /*AllowBoolConversions*/getLangOpts().ZVector); | |||
10166 | if (vType.isNull()) | |||
10167 | return vType; | |||
10168 | ||||
10169 | QualType LHSType = LHS.get()->getType(); | |||
10170 | ||||
10171 | // If AltiVec, the comparison results in a numeric type, i.e. | |||
10172 | // bool for C++, int for C | |||
10173 | if (getLangOpts().AltiVec && | |||
10174 | vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) | |||
10175 | return Context.getLogicalOperationType(); | |||
10176 | ||||
10177 | // For non-floating point types, check for self-comparisons of the form | |||
10178 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | |||
10179 | // often indicate logic errors in the program. | |||
10180 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | |||
10181 | ||||
10182 | // Check for comparisons of floating point operands using != and ==. | |||
10183 | if (BinaryOperator::isEqualityOp(Opc) && | |||
10184 | LHSType->hasFloatingRepresentation()) { | |||
10185 | assert(RHS.get()->getType()->hasFloatingRepresentation())(static_cast <bool> (RHS.get()->getType()->hasFloatingRepresentation ()) ? void (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10185, __extension__ __PRETTY_FUNCTION__)); | |||
10186 | CheckFloatComparison(Loc, LHS.get(), RHS.get()); | |||
10187 | } | |||
10188 | ||||
10189 | // Return a signed type for the vector. | |||
10190 | return GetSignedVectorType(vType); | |||
10191 | } | |||
10192 | ||||
10193 | QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, | |||
10194 | SourceLocation Loc) { | |||
10195 | // Ensure that either both operands are of the same vector type, or | |||
10196 | // one operand is of a vector type and the other is of its element type. | |||
10197 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, | |||
10198 | /*AllowBothBool*/true, | |||
10199 | /*AllowBoolConversions*/false); | |||
10200 | if (vType.isNull()) | |||
10201 | return InvalidOperands(Loc, LHS, RHS); | |||
10202 | if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && | |||
10203 | vType->hasFloatingRepresentation()) | |||
10204 | return InvalidOperands(Loc, LHS, RHS); | |||
10205 | // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the | |||
10206 | // usage of the logical operators && and || with vectors in C. This | |||
10207 | // check could be notionally dropped. | |||
10208 | if (!getLangOpts().CPlusPlus && | |||
10209 | !(isa<ExtVectorType>(vType->getAs<VectorType>()))) | |||
10210 | return InvalidLogicalVectorOperands(Loc, LHS, RHS); | |||
10211 | ||||
10212 | return GetSignedVectorType(LHS.get()->getType()); | |||
10213 | } | |||
10214 | ||||
10215 | inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, | |||
10216 | SourceLocation Loc, | |||
10217 | BinaryOperatorKind Opc) { | |||
10218 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); | |||
10219 | ||||
10220 | bool IsCompAssign = | |||
10221 | Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; | |||
10222 | ||||
10223 | if (LHS.get()->getType()->isVectorType() || | |||
10224 | RHS.get()->getType()->isVectorType()) { | |||
10225 | if (LHS.get()->getType()->hasIntegerRepresentation() && | |||
10226 | RHS.get()->getType()->hasIntegerRepresentation()) | |||
10227 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | |||
10228 | /*AllowBothBool*/true, | |||
10229 | /*AllowBoolConversions*/getLangOpts().ZVector); | |||
10230 | return InvalidOperands(Loc, LHS, RHS); | |||
10231 | } | |||
10232 | ||||
10233 | if (Opc == BO_And) | |||
10234 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | |||
10235 | ||||
10236 | ExprResult LHSResult = LHS, RHSResult = RHS; | |||
10237 | QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, | |||
10238 | IsCompAssign); | |||
10239 | if (LHSResult.isInvalid() || RHSResult.isInvalid()) | |||
10240 | return QualType(); | |||
10241 | LHS = LHSResult.get(); | |||
10242 | RHS = RHSResult.get(); | |||
10243 | ||||
10244 | if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) | |||
10245 | return compType; | |||
10246 | return InvalidOperands(Loc, LHS, RHS); | |||
10247 | } | |||
10248 | ||||
10249 | // C99 6.5.[13,14] | |||
10250 | inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, | |||
10251 | SourceLocation Loc, | |||
10252 | BinaryOperatorKind Opc) { | |||
10253 | // Check vector operands differently. | |||
10254 | if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) | |||
10255 | return CheckVectorLogicalOperands(LHS, RHS, Loc); | |||
10256 | ||||
10257 | // Diagnose cases where the user write a logical and/or but probably meant a | |||
10258 | // bitwise one. We do this when the LHS is a non-bool integer and the RHS | |||
10259 | // is a constant. | |||
10260 | if (LHS.get()->getType()->isIntegerType() && | |||
10261 | !LHS.get()->getType()->isBooleanType() && | |||
10262 | RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && | |||
10263 | // Don't warn in macros or template instantiations. | |||
10264 | !Loc.isMacroID() && !inTemplateInstantiation()) { | |||
10265 | // If the RHS can be constant folded, and if it constant folds to something | |||
10266 | // that isn't 0 or 1 (which indicate a potential logical operation that | |||
10267 | // happened to fold to true/false) then warn. | |||
10268 | // Parens on the RHS are ignored. | |||
10269 | llvm::APSInt Result; | |||
10270 | if (RHS.get()->EvaluateAsInt(Result, Context)) | |||
10271 | if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && | |||
10272 | !RHS.get()->getExprLoc().isMacroID()) || | |||
10273 | (Result != 0 && Result != 1)) { | |||
10274 | Diag(Loc, diag::warn_logical_instead_of_bitwise) | |||
10275 | << RHS.get()->getSourceRange() | |||
10276 | << (Opc == BO_LAnd ? "&&" : "||"); | |||
10277 | // Suggest replacing the logical operator with the bitwise version | |||
10278 | Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) | |||
10279 | << (Opc == BO_LAnd ? "&" : "|") | |||
10280 | << FixItHint::CreateReplacement(SourceRange( | |||
10281 | Loc, getLocForEndOfToken(Loc)), | |||
10282 | Opc == BO_LAnd ? "&" : "|"); | |||
10283 | if (Opc == BO_LAnd) | |||
10284 | // Suggest replacing "Foo() && kNonZero" with "Foo()" | |||
10285 | Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) | |||
10286 | << FixItHint::CreateRemoval( | |||
10287 | SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), | |||
10288 | RHS.get()->getLocEnd())); | |||
10289 | } | |||
10290 | } | |||
10291 | ||||
10292 | if (!Context.getLangOpts().CPlusPlus) { | |||
10293 | // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do | |||
10294 | // not operate on the built-in scalar and vector float types. | |||
10295 | if (Context.getLangOpts().OpenCL && | |||
10296 | Context.getLangOpts().OpenCLVersion < 120) { | |||
10297 | if (LHS.get()->getType()->isFloatingType() || | |||
10298 | RHS.get()->getType()->isFloatingType()) | |||
10299 | return InvalidOperands(Loc, LHS, RHS); | |||
10300 | } | |||
10301 | ||||
10302 | LHS = UsualUnaryConversions(LHS.get()); | |||
10303 | if (LHS.isInvalid()) | |||
10304 | return QualType(); | |||
10305 | ||||
10306 | RHS = UsualUnaryConversions(RHS.get()); | |||
10307 | if (RHS.isInvalid()) | |||
10308 | return QualType(); | |||
10309 | ||||
10310 | if (!LHS.get()->getType()->isScalarType() || | |||
10311 | !RHS.get()->getType()->isScalarType()) | |||
10312 | return InvalidOperands(Loc, LHS, RHS); | |||
10313 | ||||
10314 | return Context.IntTy; | |||
10315 | } | |||
10316 | ||||
10317 | // The following is safe because we only use this method for | |||
10318 | // non-overloadable operands. | |||
10319 | ||||
10320 | // C++ [expr.log.and]p1 | |||
10321 | // C++ [expr.log.or]p1 | |||
10322 | // The operands are both contextually converted to type bool. | |||
10323 | ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); | |||
10324 | if (LHSRes.isInvalid()) | |||
10325 | return InvalidOperands(Loc, LHS, RHS); | |||
10326 | LHS = LHSRes; | |||
10327 | ||||
10328 | ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); | |||
10329 | if (RHSRes.isInvalid()) | |||
10330 | return InvalidOperands(Loc, LHS, RHS); | |||
10331 | RHS = RHSRes; | |||
10332 | ||||
10333 | // C++ [expr.log.and]p2 | |||
10334 | // C++ [expr.log.or]p2 | |||
10335 | // The result is a bool. | |||
10336 | return Context.BoolTy; | |||
10337 | } | |||
10338 | ||||
10339 | static bool IsReadonlyMessage(Expr *E, Sema &S) { | |||
10340 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | |||
10341 | if (!ME) return false; | |||
10342 | if (!isa<FieldDecl>(ME->getMemberDecl())) return false; | |||
10343 | ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( | |||
10344 | ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); | |||
10345 | if (!Base) return false; | |||
10346 | return Base->getMethodDecl() != nullptr; | |||
10347 | } | |||
10348 | ||||
10349 | /// Is the given expression (which must be 'const') a reference to a | |||
10350 | /// variable which was originally non-const, but which has become | |||
10351 | /// 'const' due to being captured within a block? | |||
10352 | enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; | |||
10353 | static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { | |||
10354 | assert(E->isLValue() && E->getType().isConstQualified())(static_cast <bool> (E->isLValue() && E-> getType().isConstQualified()) ? void (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10354, __extension__ __PRETTY_FUNCTION__)); | |||
10355 | E = E->IgnoreParens(); | |||
10356 | ||||
10357 | // Must be a reference to a declaration from an enclosing scope. | |||
10358 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | |||
10359 | if (!DRE) return NCCK_None; | |||
10360 | if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; | |||
10361 | ||||
10362 | // The declaration must be a variable which is not declared 'const'. | |||
10363 | VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); | |||
10364 | if (!var) return NCCK_None; | |||
10365 | if (var->getType().isConstQualified()) return NCCK_None; | |||
10366 | 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?\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10366, __extension__ __PRETTY_FUNCTION__)); | |||
10367 | ||||
10368 | // Decide whether the first capture was for a block or a lambda. | |||
10369 | DeclContext *DC = S.CurContext, *Prev = nullptr; | |||
10370 | // Decide whether the first capture was for a block or a lambda. | |||
10371 | while (DC) { | |||
10372 | // For init-capture, it is possible that the variable belongs to the | |||
10373 | // template pattern of the current context. | |||
10374 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) | |||
10375 | if (var->isInitCapture() && | |||
10376 | FD->getTemplateInstantiationPattern() == var->getDeclContext()) | |||
10377 | break; | |||
10378 | if (DC == var->getDeclContext()) | |||
10379 | break; | |||
10380 | Prev = DC; | |||
10381 | DC = DC->getParent(); | |||
10382 | } | |||
10383 | // Unless we have an init-capture, we've gone one step too far. | |||
10384 | if (!var->isInitCapture()) | |||
10385 | DC = Prev; | |||
10386 | return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); | |||
10387 | } | |||
10388 | ||||
10389 | static bool IsTypeModifiable(QualType Ty, bool IsDereference) { | |||
10390 | Ty = Ty.getNonReferenceType(); | |||
10391 | if (IsDereference && Ty->isPointerType()) | |||
10392 | Ty = Ty->getPointeeType(); | |||
10393 | return !Ty.isConstQualified(); | |||
10394 | } | |||
10395 | ||||
10396 | // Update err_typecheck_assign_const and note_typecheck_assign_const | |||
10397 | // when this enum is changed. | |||
10398 | enum { | |||
10399 | ConstFunction, | |||
10400 | ConstVariable, | |||
10401 | ConstMember, | |||
10402 | ConstMethod, | |||
10403 | NestedConstMember, | |||
10404 | ConstUnknown, // Keep as last element | |||
10405 | }; | |||
10406 | ||||
10407 | /// Emit the "read-only variable not assignable" error and print notes to give | |||
10408 | /// more information about why the variable is not assignable, such as pointing | |||
10409 | /// to the declaration of a const variable, showing that a method is const, or | |||
10410 | /// that the function is returning a const reference. | |||
10411 | static void DiagnoseConstAssignment(Sema &S, const Expr *E, | |||
10412 | SourceLocation Loc) { | |||
10413 | SourceRange ExprRange = E->getSourceRange(); | |||
10414 | ||||
10415 | // Only emit one error on the first const found. All other consts will emit | |||
10416 | // a note to the error. | |||
10417 | bool DiagnosticEmitted = false; | |||
10418 | ||||
10419 | // Track if the current expression is the result of a dereference, and if the | |||
10420 | // next checked expression is the result of a dereference. | |||
10421 | bool IsDereference = false; | |||
10422 | bool NextIsDereference = false; | |||
10423 | ||||
10424 | // Loop to process MemberExpr chains. | |||
10425 | while (true) { | |||
10426 | IsDereference = NextIsDereference; | |||
10427 | ||||
10428 | E = E->IgnoreImplicit()->IgnoreParenImpCasts(); | |||
10429 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | |||
10430 | NextIsDereference = ME->isArrow(); | |||
10431 | const ValueDecl *VD = ME->getMemberDecl(); | |||
10432 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { | |||
10433 | // Mutable fields can be modified even if the class is const. | |||
10434 | if (Field->isMutable()) { | |||
10435 | assert(DiagnosticEmitted && "Expected diagnostic not emitted.")(static_cast <bool> (DiagnosticEmitted && "Expected diagnostic not emitted." ) ? void (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10435, __extension__ __PRETTY_FUNCTION__)); | |||
10436 | break; | |||
10437 | } | |||
10438 | ||||
10439 | if (!IsTypeModifiable(Field->getType(), IsDereference)) { | |||
10440 | if (!DiagnosticEmitted) { | |||
10441 | S.Diag(Loc, diag::err_typecheck_assign_const) | |||
10442 | << ExprRange << ConstMember << false /*static*/ << Field | |||
10443 | << Field->getType(); | |||
10444 | DiagnosticEmitted = true; | |||
10445 | } | |||
10446 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | |||
10447 | << ConstMember << false /*static*/ << Field << Field->getType() | |||
10448 | << Field->getSourceRange(); | |||
10449 | } | |||
10450 | E = ME->getBase(); | |||
10451 | continue; | |||
10452 | } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { | |||
10453 | if (VDecl->getType().isConstQualified()) { | |||
10454 | if (!DiagnosticEmitted) { | |||
10455 | S.Diag(Loc, diag::err_typecheck_assign_const) | |||
10456 | << ExprRange << ConstMember << true /*static*/ << VDecl | |||
10457 | << VDecl->getType(); | |||
10458 | DiagnosticEmitted = true; | |||
10459 | } | |||
10460 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | |||
10461 | << ConstMember << true /*static*/ << VDecl << VDecl->getType() | |||
10462 | << VDecl->getSourceRange(); | |||
10463 | } | |||
10464 | // Static fields do not inherit constness from parents. | |||
10465 | break; | |||
10466 | } | |||
10467 | break; // End MemberExpr | |||
10468 | } else if (const ArraySubscriptExpr *ASE = | |||
10469 | dyn_cast<ArraySubscriptExpr>(E)) { | |||
10470 | E = ASE->getBase()->IgnoreParenImpCasts(); | |||
10471 | continue; | |||
10472 | } else if (const ExtVectorElementExpr *EVE = | |||
10473 | dyn_cast<ExtVectorElementExpr>(E)) { | |||
10474 | E = EVE->getBase()->IgnoreParenImpCasts(); | |||
10475 | continue; | |||
10476 | } | |||
10477 | break; | |||
10478 | } | |||
10479 | ||||
10480 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | |||
10481 | // Function calls | |||
10482 | const FunctionDecl *FD = CE->getDirectCallee(); | |||
10483 | if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { | |||
10484 | if (!DiagnosticEmitted) { | |||
10485 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | |||
10486 | << ConstFunction << FD; | |||
10487 | DiagnosticEmitted = true; | |||
10488 | } | |||
10489 | S.Diag(FD->getReturnTypeSourceRange().getBegin(), | |||
10490 | diag::note_typecheck_assign_const) | |||
10491 | << ConstFunction << FD << FD->getReturnType() | |||
10492 | << FD->getReturnTypeSourceRange(); | |||
10493 | } | |||
10494 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
10495 | // Point to variable declaration. | |||
10496 | if (const ValueDecl *VD = DRE->getDecl()) { | |||
10497 | if (!IsTypeModifiable(VD->getType(), IsDereference)) { | |||
10498 | if (!DiagnosticEmitted) { | |||
10499 | S.Diag(Loc, diag::err_typecheck_assign_const) | |||
10500 | << ExprRange << ConstVariable << VD << VD->getType(); | |||
10501 | DiagnosticEmitted = true; | |||
10502 | } | |||
10503 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | |||
10504 | << ConstVariable << VD << VD->getType() << VD->getSourceRange(); | |||
10505 | } | |||
10506 | } | |||
10507 | } else if (isa<CXXThisExpr>(E)) { | |||
10508 | if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { | |||
10509 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { | |||
10510 | if (MD->isConst()) { | |||
10511 | if (!DiagnosticEmitted) { | |||
10512 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | |||
10513 | << ConstMethod << MD; | |||
10514 | DiagnosticEmitted = true; | |||
10515 | } | |||
10516 | S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) | |||
10517 | << ConstMethod << MD << MD->getSourceRange(); | |||
10518 | } | |||
10519 | } | |||
10520 | } | |||
10521 | } | |||
10522 | ||||
10523 | if (DiagnosticEmitted) | |||
10524 | return; | |||
10525 | ||||
10526 | // Can't determine a more specific message, so display the generic error. | |||
10527 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; | |||
10528 | } | |||
10529 | ||||
10530 | enum OriginalExprKind { | |||
10531 | OEK_Variable, | |||
10532 | OEK_Member, | |||
10533 | OEK_LValue | |||
10534 | }; | |||
10535 | ||||
10536 | static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, | |||
10537 | const RecordType *Ty, | |||
10538 | SourceLocation Loc, SourceRange Range, | |||
10539 | OriginalExprKind OEK, | |||
10540 | bool &DiagnosticEmitted, | |||
10541 | bool IsNested = false) { | |||
10542 | // We walk the record hierarchy breadth-first to ensure that we print | |||
10543 | // diagnostics in field nesting order. | |||
10544 | // First, check every field for constness. | |||
10545 | for (const FieldDecl *Field : Ty->getDecl()->fields()) { | |||
10546 | if (Field->getType().isConstQualified()) { | |||
10547 | if (!DiagnosticEmitted) { | |||
10548 | S.Diag(Loc, diag::err_typecheck_assign_const) | |||
10549 | << Range << NestedConstMember << OEK << VD | |||
10550 | << IsNested << Field; | |||
10551 | DiagnosticEmitted = true; | |||
10552 | } | |||
10553 | S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) | |||
10554 | << NestedConstMember << IsNested << Field | |||
10555 | << Field->getType() << Field->getSourceRange(); | |||
10556 | } | |||
10557 | } | |||
10558 | // Then, recurse. | |||
10559 | for (const FieldDecl *Field : Ty->getDecl()->fields()) { | |||
10560 | QualType FTy = Field->getType(); | |||
10561 | if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) | |||
10562 | DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, | |||
10563 | OEK, DiagnosticEmitted, true); | |||
10564 | } | |||
10565 | } | |||
10566 | ||||
10567 | /// Emit an error for the case where a record we are trying to assign to has a | |||
10568 | /// const-qualified field somewhere in its hierarchy. | |||
10569 | static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, | |||
10570 | SourceLocation Loc) { | |||
10571 | QualType Ty = E->getType(); | |||
10572 | 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?\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10572, __extension__ __PRETTY_FUNCTION__)); | |||
10573 | SourceRange Range = E->getSourceRange(); | |||
10574 | const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); | |||
10575 | bool DiagEmitted = false; | |||
10576 | ||||
10577 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) | |||
10578 | DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, | |||
10579 | Range, OEK_Member, DiagEmitted); | |||
10580 | else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | |||
10581 | DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, | |||
10582 | Range, OEK_Variable, DiagEmitted); | |||
10583 | else | |||
10584 | DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, | |||
10585 | Range, OEK_LValue, DiagEmitted); | |||
10586 | if (!DiagEmitted) | |||
10587 | DiagnoseConstAssignment(S, E, Loc); | |||
10588 | } | |||
10589 | ||||
10590 | /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, | |||
10591 | /// emit an error and return true. If so, return false. | |||
10592 | static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { | |||
10593 | assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!E->hasPlaceholderType(BuiltinType ::PseudoObject)) ? void (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10593, __extension__ __PRETTY_FUNCTION__)); | |||
10594 | ||||
10595 | S.CheckShadowingDeclModification(E, Loc); | |||
10596 | ||||
10597 | SourceLocation OrigLoc = Loc; | |||
10598 | Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, | |||
10599 | &Loc); | |||
10600 | if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) | |||
10601 | IsLV = Expr::MLV_InvalidMessageExpression; | |||
10602 | if (IsLV == Expr::MLV_Valid) | |||
10603 | return false; | |||
10604 | ||||
10605 | unsigned DiagID = 0; | |||
10606 | bool NeedType = false; | |||
10607 | switch (IsLV) { // C99 6.5.16p2 | |||
10608 | case Expr::MLV_ConstQualified: | |||
10609 | // Use a specialized diagnostic when we're assigning to an object | |||
10610 | // from an enclosing function or block. | |||
10611 | if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { | |||
10612 | if (NCCK == NCCK_Block) | |||
10613 | DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; | |||
10614 | else | |||
10615 | DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; | |||
10616 | break; | |||
10617 | } | |||
10618 | ||||
10619 | // In ARC, use some specialized diagnostics for occasions where we | |||
10620 | // infer 'const'. These are always pseudo-strong variables. | |||
10621 | if (S.getLangOpts().ObjCAutoRefCount) { | |||
10622 | DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); | |||
10623 | if (declRef && isa<VarDecl>(declRef->getDecl())) { | |||
10624 | VarDecl *var = cast<VarDecl>(declRef->getDecl()); | |||
10625 | ||||
10626 | // Use the normal diagnostic if it's pseudo-__strong but the | |||
10627 | // user actually wrote 'const'. | |||
10628 | if (var->isARCPseudoStrong() && | |||
10629 | (!var->getTypeSourceInfo() || | |||
10630 | !var->getTypeSourceInfo()->getType().isConstQualified())) { | |||
10631 | // There are two pseudo-strong cases: | |||
10632 | // - self | |||
10633 | ObjCMethodDecl *method = S.getCurMethodDecl(); | |||
10634 | if (method && var == method->getSelfDecl()) | |||
10635 | DiagID = method->isClassMethod() | |||
10636 | ? diag::err_typecheck_arc_assign_self_class_method | |||
10637 | : diag::err_typecheck_arc_assign_self; | |||
10638 | ||||
10639 | // - fast enumeration variables | |||
10640 | else | |||
10641 | DiagID = diag::err_typecheck_arr_assign_enumeration; | |||
10642 | ||||
10643 | SourceRange Assign; | |||
10644 | if (Loc != OrigLoc) | |||
10645 | Assign = SourceRange(OrigLoc, OrigLoc); | |||
10646 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | |||
10647 | // We need to preserve the AST regardless, so migration tool | |||
10648 | // can do its job. | |||
10649 | return false; | |||
10650 | } | |||
10651 | } | |||
10652 | } | |||
10653 | ||||
10654 | // If none of the special cases above are triggered, then this is a | |||
10655 | // simple const assignment. | |||
10656 | if (DiagID == 0) { | |||
10657 | DiagnoseConstAssignment(S, E, Loc); | |||
10658 | return true; | |||
10659 | } | |||
10660 | ||||
10661 | break; | |||
10662 | case Expr::MLV_ConstAddrSpace: | |||
10663 | DiagnoseConstAssignment(S, E, Loc); | |||
10664 | return true; | |||
10665 | case Expr::MLV_ConstQualifiedField: | |||
10666 | DiagnoseRecursiveConstFields(S, E, Loc); | |||
10667 | return true; | |||
10668 | case Expr::MLV_ArrayType: | |||
10669 | case Expr::MLV_ArrayTemporary: | |||
10670 | DiagID = diag::err_typecheck_array_not_modifiable_lvalue; | |||
10671 | NeedType = true; | |||
10672 | break; | |||
10673 | case Expr::MLV_NotObjectType: | |||
10674 | DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; | |||
10675 | NeedType = true; | |||
10676 | break; | |||
10677 | case Expr::MLV_LValueCast: | |||
10678 | DiagID = diag::err_typecheck_lvalue_casts_not_supported; | |||
10679 | break; | |||
10680 | case Expr::MLV_Valid: | |||
10681 | llvm_unreachable("did not take early return for MLV_Valid")::llvm::llvm_unreachable_internal("did not take early return for MLV_Valid" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10681); | |||
10682 | case Expr::MLV_InvalidExpression: | |||
10683 | case Expr::MLV_MemberFunction: | |||
10684 | case Expr::MLV_ClassTemporary: | |||
10685 | DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; | |||
10686 | break; | |||
10687 | case Expr::MLV_IncompleteType: | |||
10688 | case Expr::MLV_IncompleteVoidType: | |||
10689 | return S.RequireCompleteType(Loc, E->getType(), | |||
10690 | diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); | |||
10691 | case Expr::MLV_DuplicateVectorComponents: | |||
10692 | DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; | |||
10693 | break; | |||
10694 | case Expr::MLV_NoSetterProperty: | |||
10695 | llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10695); | |||
10696 | case Expr::MLV_InvalidMessageExpression: | |||
10697 | DiagID = diag::err_readonly_message_assignment; | |||
10698 | break; | |||
10699 | case Expr::MLV_SubObjCPropertySetting: | |||
10700 | DiagID = diag::err_no_subobject_property_setting; | |||
10701 | break; | |||
10702 | } | |||
10703 | ||||
10704 | SourceRange Assign; | |||
10705 | if (Loc != OrigLoc) | |||
10706 | Assign = SourceRange(OrigLoc, OrigLoc); | |||
10707 | if (NeedType) | |||
10708 | S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; | |||
10709 | else | |||
10710 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | |||
10711 | return true; | |||
10712 | } | |||
10713 | ||||
10714 | static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, | |||
10715 | SourceLocation Loc, | |||
10716 | Sema &Sema) { | |||
10717 | if (Sema.inTemplateInstantiation()) | |||
10718 | return; | |||
10719 | if (Sema.isUnevaluatedContext()) | |||
10720 | return; | |||
10721 | if (Loc.isInvalid() || Loc.isMacroID()) | |||
10722 | return; | |||
10723 | if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) | |||
10724 | return; | |||
10725 | ||||
10726 | // C / C++ fields | |||
10727 | MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); | |||
10728 | MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); | |||
10729 | if (ML && MR) { | |||
10730 | if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) | |||
10731 | return; | |||
10732 | const ValueDecl *LHSDecl = | |||
10733 | cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); | |||
10734 | const ValueDecl *RHSDecl = | |||
10735 | cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); | |||
10736 | if (LHSDecl != RHSDecl) | |||
10737 | return; | |||
10738 | if (LHSDecl->getType().isVolatileQualified()) | |||
10739 | return; | |||
10740 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | |||
10741 | if (RefTy->getPointeeType().isVolatileQualified()) | |||
10742 | return; | |||
10743 | ||||
10744 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; | |||
10745 | } | |||
10746 | ||||
10747 | // Objective-C instance variables | |||
10748 | ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); | |||
10749 | ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); | |||
10750 | if (OL && OR && OL->getDecl() == OR->getDecl()) { | |||
10751 | DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); | |||
10752 | DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); | |||
10753 | if (RL && RR && RL->getDecl() == RR->getDecl()) | |||
10754 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; | |||
10755 | } | |||
10756 | } | |||
10757 | ||||
10758 | // C99 6.5.16.1 | |||
10759 | QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, | |||
10760 | SourceLocation Loc, | |||
10761 | QualType CompoundType) { | |||
10762 | assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!LHSExpr->hasPlaceholderType(BuiltinType ::PseudoObject)) ? void (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10762, __extension__ __PRETTY_FUNCTION__)); | |||
10763 | ||||
10764 | // Verify that LHS is a modifiable lvalue, and emit error if not. | |||
10765 | if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) | |||
10766 | return QualType(); | |||
10767 | ||||
10768 | QualType LHSType = LHSExpr->getType(); | |||
10769 | QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : | |||
10770 | CompoundType; | |||
10771 | // OpenCL v1.2 s6.1.1.1 p2: | |||
10772 | // The half data type can only be used to declare a pointer to a buffer that | |||
10773 | // contains half values | |||
10774 | if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && | |||
10775 | LHSType->isHalfType()) { | |||
10776 | Diag(Loc, diag::err_opencl_half_load_store) << 1 | |||
10777 | << LHSType.getUnqualifiedType(); | |||
10778 | return QualType(); | |||
10779 | } | |||
10780 | ||||
10781 | AssignConvertType ConvTy; | |||
10782 | if (CompoundType.isNull()) { | |||
10783 | Expr *RHSCheck = RHS.get(); | |||
10784 | ||||
10785 | CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); | |||
10786 | ||||
10787 | QualType LHSTy(LHSType); | |||
10788 | ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); | |||
10789 | if (RHS.isInvalid()) | |||
10790 | return QualType(); | |||
10791 | // Special case of NSObject attributes on c-style pointer types. | |||
10792 | if (ConvTy == IncompatiblePointer && | |||
10793 | ((Context.isObjCNSObjectType(LHSType) && | |||
10794 | RHSType->isObjCObjectPointerType()) || | |||
10795 | (Context.isObjCNSObjectType(RHSType) && | |||
10796 | LHSType->isObjCObjectPointerType()))) | |||
10797 | ConvTy = Compatible; | |||
10798 | ||||
10799 | if (ConvTy == Compatible && | |||
10800 | LHSType->isObjCObjectType()) | |||
10801 | Diag(Loc, diag::err_objc_object_assignment) | |||
10802 | << LHSType; | |||
10803 | ||||
10804 | // If the RHS is a unary plus or minus, check to see if they = and + are | |||
10805 | // right next to each other. If so, the user may have typo'd "x =+ 4" | |||
10806 | // instead of "x += 4". | |||
10807 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) | |||
10808 | RHSCheck = ICE->getSubExpr(); | |||
10809 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { | |||
10810 | if ((UO->getOpcode() == UO_Plus || | |||
10811 | UO->getOpcode() == UO_Minus) && | |||
10812 | Loc.isFileID() && UO->getOperatorLoc().isFileID() && | |||
10813 | // Only if the two operators are exactly adjacent. | |||
10814 | Loc.getLocWithOffset(1) == UO->getOperatorLoc() && | |||
10815 | // And there is a space or other character before the subexpr of the | |||
10816 | // unary +/-. We don't want to warn on "x=-1". | |||
10817 | Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && | |||
10818 | UO->getSubExpr()->getLocStart().isFileID()) { | |||
10819 | Diag(Loc, diag::warn_not_compound_assign) | |||
10820 | << (UO->getOpcode() == UO_Plus ? "+" : "-") | |||
10821 | << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); | |||
10822 | } | |||
10823 | } | |||
10824 | ||||
10825 | if (ConvTy == Compatible) { | |||
10826 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { | |||
10827 | // Warn about retain cycles where a block captures the LHS, but | |||
10828 | // not if the LHS is a simple variable into which the block is | |||
10829 | // being stored...unless that variable can be captured by reference! | |||
10830 | const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); | |||
10831 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); | |||
10832 | if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) | |||
10833 | checkRetainCycles(LHSExpr, RHS.get()); | |||
10834 | } | |||
10835 | ||||
10836 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || | |||
10837 | LHSType.isNonWeakInMRRWithObjCWeak(Context)) { | |||
10838 | // It is safe to assign a weak reference into a strong variable. | |||
10839 | // Although this code can still have problems: | |||
10840 | // id x = self.weakProp; | |||
10841 | // id y = self.weakProp; | |||
10842 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | |||
10843 | // paths through the function. This should be revisited if | |||
10844 | // -Wrepeated-use-of-weak is made flow-sensitive. | |||
10845 | // For ObjCWeak only, we do not warn if the assign is to a non-weak | |||
10846 | // variable, which will be valid for the current autorelease scope. | |||
10847 | if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | |||
10848 | RHS.get()->getLocStart())) | |||
10849 | getCurFunction()->markSafeWeakUse(RHS.get()); | |||
10850 | ||||
10851 | } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { | |||
10852 | checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); | |||
10853 | } | |||
10854 | } | |||
10855 | } else { | |||
10856 | // Compound assignment "x += y" | |||
10857 | ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); | |||
10858 | } | |||
10859 | ||||
10860 | if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, | |||
10861 | RHS.get(), AA_Assigning)) | |||
10862 | return QualType(); | |||
10863 | ||||
10864 | CheckForNullPointerDereference(*this, LHSExpr); | |||
10865 | ||||
10866 | // C99 6.5.16p3: The type of an assignment expression is the type of the | |||
10867 | // left operand unless the left operand has qualified type, in which case | |||
10868 | // it is the unqualified version of the type of the left operand. | |||
10869 | // C99 6.5.16.1p2: In simple assignment, the value of the right operand | |||
10870 | // is converted to the type of the assignment expression (above). | |||
10871 | // C++ 5.17p1: the type of the assignment expression is that of its left | |||
10872 | // operand. | |||
10873 | return (getLangOpts().CPlusPlus | |||
10874 | ? LHSType : LHSType.getUnqualifiedType()); | |||
10875 | } | |||
10876 | ||||
10877 | // Only ignore explicit casts to void. | |||
10878 | static bool IgnoreCommaOperand(const Expr *E) { | |||
10879 | E = E->IgnoreParens(); | |||
10880 | ||||
10881 | if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { | |||
10882 | if (CE->getCastKind() == CK_ToVoid) { | |||
10883 | return true; | |||
10884 | } | |||
10885 | } | |||
10886 | ||||
10887 | return false; | |||
10888 | } | |||
10889 | ||||
10890 | // Look for instances where it is likely the comma operator is confused with | |||
10891 | // another operator. There is a whitelist of acceptable expressions for the | |||
10892 | // left hand side of the comma operator, otherwise emit a warning. | |||
10893 | void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { | |||
10894 | // No warnings in macros | |||
10895 | if (Loc.isMacroID()) | |||
10896 | return; | |||
10897 | ||||
10898 | // Don't warn in template instantiations. | |||
10899 | if (inTemplateInstantiation()) | |||
10900 | return; | |||
10901 | ||||
10902 | // Scope isn't fine-grained enough to whitelist the specific cases, so | |||
10903 | // instead, skip more than needed, then call back into here with the | |||
10904 | // CommaVisitor in SemaStmt.cpp. | |||
10905 | // The whitelisted locations are the initialization and increment portions | |||
10906 | // of a for loop. The additional checks are on the condition of | |||
10907 | // if statements, do/while loops, and for loops. | |||
10908 | const unsigned ForIncrementFlags = | |||
10909 | Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; | |||
10910 | const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; | |||
10911 | const unsigned ScopeFlags = getCurScope()->getFlags(); | |||
10912 | if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || | |||
10913 | (ScopeFlags & ForInitFlags) == ForInitFlags) | |||
10914 | return; | |||
10915 | ||||
10916 | // If there are multiple comma operators used together, get the RHS of the | |||
10917 | // of the comma operator as the LHS. | |||
10918 | while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { | |||
10919 | if (BO->getOpcode() != BO_Comma) | |||
10920 | break; | |||
10921 | LHS = BO->getRHS(); | |||
10922 | } | |||
10923 | ||||
10924 | // Only allow some expressions on LHS to not warn. | |||
10925 | if (IgnoreCommaOperand(LHS)) | |||
10926 | return; | |||
10927 | ||||
10928 | Diag(Loc, diag::warn_comma_operator); | |||
10929 | Diag(LHS->getLocStart(), diag::note_cast_to_void) | |||
10930 | << LHS->getSourceRange() | |||
10931 | << FixItHint::CreateInsertion(LHS->getLocStart(), | |||
10932 | LangOpts.CPlusPlus ? "static_cast<void>(" | |||
10933 | : "(void)(") | |||
10934 | << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), | |||
10935 | ")"); | |||
10936 | } | |||
10937 | ||||
10938 | // C99 6.5.17 | |||
10939 | static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, | |||
10940 | SourceLocation Loc) { | |||
10941 | LHS = S.CheckPlaceholderExpr(LHS.get()); | |||
10942 | RHS = S.CheckPlaceholderExpr(RHS.get()); | |||
10943 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
10944 | return QualType(); | |||
10945 | ||||
10946 | // C's comma performs lvalue conversion (C99 6.3.2.1) on both its | |||
10947 | // operands, but not unary promotions. | |||
10948 | // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). | |||
10949 | ||||
10950 | // So we treat the LHS as a ignored value, and in C++ we allow the | |||
10951 | // containing site to determine what should be done with the RHS. | |||
10952 | LHS = S.IgnoredValueConversions(LHS.get()); | |||
10953 | if (LHS.isInvalid()) | |||
10954 | return QualType(); | |||
10955 | ||||
10956 | S.DiagnoseUnusedExprResult(LHS.get()); | |||
10957 | ||||
10958 | if (!S.getLangOpts().CPlusPlus) { | |||
10959 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
10960 | if (RHS.isInvalid()) | |||
10961 | return QualType(); | |||
10962 | if (!RHS.get()->getType()->isVoidType()) | |||
10963 | S.RequireCompleteType(Loc, RHS.get()->getType(), | |||
10964 | diag::err_incomplete_type); | |||
10965 | } | |||
10966 | ||||
10967 | if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) | |||
10968 | S.DiagnoseCommaOperator(LHS.get(), Loc); | |||
10969 | ||||
10970 | return RHS.get()->getType(); | |||
10971 | } | |||
10972 | ||||
10973 | /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine | |||
10974 | /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. | |||
10975 | static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, | |||
10976 | ExprValueKind &VK, | |||
10977 | ExprObjectKind &OK, | |||
10978 | SourceLocation OpLoc, | |||
10979 | bool IsInc, bool IsPrefix) { | |||
10980 | if (Op->isTypeDependent()) | |||
10981 | return S.Context.DependentTy; | |||
10982 | ||||
10983 | QualType ResType = Op->getType(); | |||
10984 | // Atomic types can be used for increment / decrement where the non-atomic | |||
10985 | // versions can, so ignore the _Atomic() specifier for the purpose of | |||
10986 | // checking. | |||
10987 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | |||
10988 | ResType = ResAtomicType->getValueType(); | |||
10989 | ||||
10990 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 10990, __extension__ __PRETTY_FUNCTION__)); | |||
10991 | ||||
10992 | if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { | |||
10993 | // Decrement of bool is not allowed. | |||
10994 | if (!IsInc) { | |||
10995 | S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); | |||
10996 | return QualType(); | |||
10997 | } | |||
10998 | // Increment of bool sets it to true, but is deprecated. | |||
10999 | S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool | |||
11000 | : diag::warn_increment_bool) | |||
11001 | << Op->getSourceRange(); | |||
11002 | } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { | |||
11003 | // Error on enum increments and decrements in C++ mode | |||
11004 | S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; | |||
11005 | return QualType(); | |||
11006 | } else if (ResType->isRealType()) { | |||
11007 | // OK! | |||
11008 | } else if (ResType->isPointerType()) { | |||
11009 | // C99 6.5.2.4p2, 6.5.6p2 | |||
11010 | if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) | |||
11011 | return QualType(); | |||
11012 | } else if (ResType->isObjCObjectPointerType()) { | |||
11013 | // On modern runtimes, ObjC pointer arithmetic is forbidden. | |||
11014 | // Otherwise, we just need a complete type. | |||
11015 | if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || | |||
11016 | checkArithmeticOnObjCPointer(S, OpLoc, Op)) | |||
11017 | return QualType(); | |||
11018 | } else if (ResType->isAnyComplexType()) { | |||
11019 | // C99 does not support ++/-- on complex types, we allow as an extension. | |||
11020 | S.Diag(OpLoc, diag::ext_integer_increment_complex) | |||
11021 | << ResType << Op->getSourceRange(); | |||
11022 | } else if (ResType->isPlaceholderType()) { | |||
11023 | ExprResult PR = S.CheckPlaceholderExpr(Op); | |||
11024 | if (PR.isInvalid()) return QualType(); | |||
11025 | return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, | |||
11026 | IsInc, IsPrefix); | |||
11027 | } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { | |||
11028 | // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) | |||
11029 | } else if (S.getLangOpts().ZVector && ResType->isVectorType() && | |||
11030 | (ResType->getAs<VectorType>()->getVectorKind() != | |||
11031 | VectorType::AltiVecBool)) { | |||
11032 | // The z vector extensions allow ++ and -- for non-bool vectors. | |||
11033 | } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && | |||
11034 | ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { | |||
11035 | // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. | |||
11036 | } else { | |||
11037 | S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) | |||
11038 | << ResType << int(IsInc) << Op->getSourceRange(); | |||
11039 | return QualType(); | |||
11040 | } | |||
11041 | // At this point, we know we have a real, complex or pointer type. | |||
11042 | // Now make sure the operand is a modifiable lvalue. | |||
11043 | if (CheckForModifiableLvalue(Op, OpLoc, S)) | |||
11044 | return QualType(); | |||
11045 | // In C++, a prefix increment is the same type as the operand. Otherwise | |||
11046 | // (in C or with postfix), the increment is the unqualified type of the | |||
11047 | // operand. | |||
11048 | if (IsPrefix && S.getLangOpts().CPlusPlus) { | |||
11049 | VK = VK_LValue; | |||
11050 | OK = Op->getObjectKind(); | |||
11051 | return ResType; | |||
11052 | } else { | |||
11053 | VK = VK_RValue; | |||
11054 | return ResType.getUnqualifiedType(); | |||
11055 | } | |||
11056 | } | |||
11057 | ||||
11058 | ||||
11059 | /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). | |||
11060 | /// This routine allows us to typecheck complex/recursive expressions | |||
11061 | /// where the declaration is needed for type checking. We only need to | |||
11062 | /// handle cases when the expression references a function designator | |||
11063 | /// or is an lvalue. Here are some examples: | |||
11064 | /// - &(x) => x | |||
11065 | /// - &*****f => f for f a function designator. | |||
11066 | /// - &s.xx => s | |||
11067 | /// - &s.zz[1].yy -> s, if zz is an array | |||
11068 | /// - *(x + 1) -> x, if x is an array | |||
11069 | /// - &"123"[2] -> 0 | |||
11070 | /// - & __real__ x -> x | |||
11071 | static ValueDecl *getPrimaryDecl(Expr *E) { | |||
11072 | switch (E->getStmtClass()) { | |||
11073 | case Stmt::DeclRefExprClass: | |||
11074 | return cast<DeclRefExpr>(E)->getDecl(); | |||
11075 | case Stmt::MemberExprClass: | |||
11076 | // If this is an arrow operator, the address is an offset from | |||
11077 | // the base's value, so the object the base refers to is | |||
11078 | // irrelevant. | |||
11079 | if (cast<MemberExpr>(E)->isArrow()) | |||
11080 | return nullptr; | |||
11081 | // Otherwise, the expression refers to a part of the base | |||
11082 | return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); | |||
11083 | case Stmt::ArraySubscriptExprClass: { | |||
11084 | // FIXME: This code shouldn't be necessary! We should catch the implicit | |||
11085 | // promotion of register arrays earlier. | |||
11086 | Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); | |||
11087 | if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { | |||
11088 | if (ICE->getSubExpr()->getType()->isArrayType()) | |||
11089 | return getPrimaryDecl(ICE->getSubExpr()); | |||
11090 | } | |||
11091 | return nullptr; | |||
11092 | } | |||
11093 | case Stmt::UnaryOperatorClass: { | |||
11094 | UnaryOperator *UO = cast<UnaryOperator>(E); | |||
11095 | ||||
11096 | switch(UO->getOpcode()) { | |||
11097 | case UO_Real: | |||
11098 | case UO_Imag: | |||
11099 | case UO_Extension: | |||
11100 | return getPrimaryDecl(UO->getSubExpr()); | |||
11101 | default: | |||
11102 | return nullptr; | |||
11103 | } | |||
11104 | } | |||
11105 | case Stmt::ParenExprClass: | |||
11106 | return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); | |||
11107 | case Stmt::ImplicitCastExprClass: | |||
11108 | // If the result of an implicit cast is an l-value, we care about | |||
11109 | // the sub-expression; otherwise, the result here doesn't matter. | |||
11110 | return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); | |||
11111 | default: | |||
11112 | return nullptr; | |||
11113 | } | |||
11114 | } | |||
11115 | ||||
11116 | namespace { | |||
11117 | enum { | |||
11118 | AO_Bit_Field = 0, | |||
11119 | AO_Vector_Element = 1, | |||
11120 | AO_Property_Expansion = 2, | |||
11121 | AO_Register_Variable = 3, | |||
11122 | AO_No_Error = 4 | |||
11123 | }; | |||
11124 | } | |||
11125 | /// \brief Diagnose invalid operand for address of operations. | |||
11126 | /// | |||
11127 | /// \param Type The type of operand which cannot have its address taken. | |||
11128 | static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, | |||
11129 | Expr *E, unsigned Type) { | |||
11130 | S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); | |||
11131 | } | |||
11132 | ||||
11133 | /// CheckAddressOfOperand - The operand of & must be either a function | |||
11134 | /// designator or an lvalue designating an object. If it is an lvalue, the | |||
11135 | /// object cannot be declared with storage class register or be a bit field. | |||
11136 | /// Note: The usual conversions are *not* applied to the operand of the & | |||
11137 | /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. | |||
11138 | /// In C++, the operand might be an overloaded function name, in which case | |||
11139 | /// we allow the '&' but retain the overloaded-function type. | |||
11140 | QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { | |||
11141 | if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ | |||
11142 | if (PTy->getKind() == BuiltinType::Overload) { | |||
11143 | Expr *E = OrigOp.get()->IgnoreParens(); | |||
11144 | if (!isa<OverloadExpr>(E)) { | |||
11145 | 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" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11145, __extension__ __PRETTY_FUNCTION__)); | |||
11146 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) | |||
11147 | << OrigOp.get()->getSourceRange(); | |||
11148 | return QualType(); | |||
11149 | } | |||
11150 | ||||
11151 | OverloadExpr *Ovl = cast<OverloadExpr>(E); | |||
11152 | if (isa<UnresolvedMemberExpr>(Ovl)) | |||
11153 | if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { | |||
11154 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | |||
11155 | << OrigOp.get()->getSourceRange(); | |||
11156 | return QualType(); | |||
11157 | } | |||
11158 | ||||
11159 | return Context.OverloadTy; | |||
11160 | } | |||
11161 | ||||
11162 | if (PTy->getKind() == BuiltinType::UnknownAny) | |||
11163 | return Context.UnknownAnyTy; | |||
11164 | ||||
11165 | if (PTy->getKind() == BuiltinType::BoundMember) { | |||
11166 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | |||
11167 | << OrigOp.get()->getSourceRange(); | |||
11168 | return QualType(); | |||
11169 | } | |||
11170 | ||||
11171 | OrigOp = CheckPlaceholderExpr(OrigOp.get()); | |||
11172 | if (OrigOp.isInvalid()) return QualType(); | |||
11173 | } | |||
11174 | ||||
11175 | if (OrigOp.get()->isTypeDependent()) | |||
11176 | return Context.DependentTy; | |||
11177 | ||||
11178 | assert(!OrigOp.get()->getType()->isPlaceholderType())(static_cast <bool> (!OrigOp.get()->getType()->isPlaceholderType ()) ? void (0) : __assert_fail ("!OrigOp.get()->getType()->isPlaceholderType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11178, __extension__ __PRETTY_FUNCTION__)); | |||
11179 | ||||
11180 | // Make sure to ignore parentheses in subsequent checks | |||
11181 | Expr *op = OrigOp.get()->IgnoreParens(); | |||
11182 | ||||
11183 | // In OpenCL captures for blocks called as lambda functions | |||
11184 | // are located in the private address space. Blocks used in | |||
11185 | // enqueue_kernel can be located in a different address space | |||
11186 | // depending on a vendor implementation. Thus preventing | |||
11187 | // taking an address of the capture to avoid invalid AS casts. | |||
11188 | if (LangOpts.OpenCL) { | |||
11189 | auto* VarRef = dyn_cast<DeclRefExpr>(op); | |||
11190 | if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { | |||
11191 | Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); | |||
11192 | return QualType(); | |||
11193 | } | |||
11194 | } | |||
11195 | ||||
11196 | if (getLangOpts().C99) { | |||
11197 | // Implement C99-only parts of addressof rules. | |||
11198 | if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { | |||
11199 | if (uOp->getOpcode() == UO_Deref) | |||
11200 | // Per C99 6.5.3.2, the address of a deref always returns a valid result | |||
11201 | // (assuming the deref expression is valid). | |||
11202 | return uOp->getSubExpr()->getType(); | |||
11203 | } | |||
11204 | // Technically, there should be a check for array subscript | |||
11205 | // expressions here, but the result of one is always an lvalue anyway. | |||
11206 | } | |||
11207 | ValueDecl *dcl = getPrimaryDecl(op); | |||
11208 | ||||
11209 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) | |||
11210 | if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | |||
11211 | op->getLocStart())) | |||
11212 | return QualType(); | |||
11213 | ||||
11214 | Expr::LValueClassification lval = op->ClassifyLValue(Context); | |||
11215 | unsigned AddressOfError = AO_No_Error; | |||
11216 | ||||
11217 | if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { | |||
11218 | bool sfinae = (bool)isSFINAEContext(); | |||
11219 | Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary | |||
11220 | : diag::ext_typecheck_addrof_temporary) | |||
11221 | << op->getType() << op->getSourceRange(); | |||
11222 | if (sfinae) | |||
11223 | return QualType(); | |||
11224 | // Materialize the temporary as an lvalue so that we can take its address. | |||
11225 | OrigOp = op = | |||
11226 | CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); | |||
11227 | } else if (isa<ObjCSelectorExpr>(op)) { | |||
11228 | return Context.getPointerType(op->getType()); | |||
11229 | } else if (lval == Expr::LV_MemberFunction) { | |||
11230 | // If it's an instance method, make a member pointer. | |||
11231 | // The expression must have exactly the form &A::foo. | |||
11232 | ||||
11233 | // If the underlying expression isn't a decl ref, give up. | |||
11234 | if (!isa<DeclRefExpr>(op)) { | |||
11235 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | |||
11236 | << OrigOp.get()->getSourceRange(); | |||
11237 | return QualType(); | |||
11238 | } | |||
11239 | DeclRefExpr *DRE = cast<DeclRefExpr>(op); | |||
11240 | CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); | |||
11241 | ||||
11242 | // The id-expression was parenthesized. | |||
11243 | if (OrigOp.get() != DRE) { | |||
11244 | Diag(OpLoc, diag::err_parens_pointer_member_function) | |||
11245 | << OrigOp.get()->getSourceRange(); | |||
11246 | ||||
11247 | // The method was named without a qualifier. | |||
11248 | } else if (!DRE->getQualifier()) { | |||
11249 | if (MD->getParent()->getName().empty()) | |||
11250 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | |||
11251 | << op->getSourceRange(); | |||
11252 | else { | |||
11253 | SmallString<32> Str; | |||
11254 | StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); | |||
11255 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | |||
11256 | << op->getSourceRange() | |||
11257 | << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); | |||
11258 | } | |||
11259 | } | |||
11260 | ||||
11261 | // Taking the address of a dtor is illegal per C++ [class.dtor]p2. | |||
11262 | if (isa<CXXDestructorDecl>(MD)) | |||
11263 | Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); | |||
11264 | ||||
11265 | QualType MPTy = Context.getMemberPointerType( | |||
11266 | op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); | |||
11267 | // Under the MS ABI, lock down the inheritance model now. | |||
11268 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
11269 | (void)isCompleteType(OpLoc, MPTy); | |||
11270 | return MPTy; | |||
11271 | } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { | |||
11272 | // C99 6.5.3.2p1 | |||
11273 | // The operand must be either an l-value or a function designator | |||
11274 | if (!op->getType()->isFunctionType()) { | |||
11275 | // Use a special diagnostic for loads from property references. | |||
11276 | if (isa<PseudoObjectExpr>(op)) { | |||
11277 | AddressOfError = AO_Property_Expansion; | |||
11278 | } else { | |||
11279 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) | |||
11280 | << op->getType() << op->getSourceRange(); | |||
11281 | return QualType(); | |||
11282 | } | |||
11283 | } | |||
11284 | } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 | |||
11285 | // The operand cannot be a bit-field | |||
11286 | AddressOfError = AO_Bit_Field; | |||
11287 | } else if (op->getObjectKind() == OK_VectorComponent) { | |||
11288 | // The operand cannot be an element of a vector | |||
11289 | AddressOfError = AO_Vector_Element; | |||
11290 | } else if (dcl) { // C99 6.5.3.2p1 | |||
11291 | // We have an lvalue with a decl. Make sure the decl is not declared | |||
11292 | // with the register storage-class specifier. | |||
11293 | if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { | |||
11294 | // in C++ it is not error to take address of a register | |||
11295 | // variable (c++03 7.1.1P3) | |||
11296 | if (vd->getStorageClass() == SC_Register && | |||
11297 | !getLangOpts().CPlusPlus) { | |||
11298 | AddressOfError = AO_Register_Variable; | |||
11299 | } | |||
11300 | } else if (isa<MSPropertyDecl>(dcl)) { | |||
11301 | AddressOfError = AO_Property_Expansion; | |||
11302 | } else if (isa<FunctionTemplateDecl>(dcl)) { | |||
11303 | return Context.OverloadTy; | |||
11304 | } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { | |||
11305 | // Okay: we can take the address of a field. | |||
11306 | // Could be a pointer to member, though, if there is an explicit | |||
11307 | // scope qualifier for the class. | |||
11308 | if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { | |||
11309 | DeclContext *Ctx = dcl->getDeclContext(); | |||
11310 | if (Ctx && Ctx->isRecord()) { | |||
11311 | if (dcl->getType()->isReferenceType()) { | |||
11312 | Diag(OpLoc, | |||
11313 | diag::err_cannot_form_pointer_to_member_of_reference_type) | |||
11314 | << dcl->getDeclName() << dcl->getType(); | |||
11315 | return QualType(); | |||
11316 | } | |||
11317 | ||||
11318 | while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) | |||
11319 | Ctx = Ctx->getParent(); | |||
11320 | ||||
11321 | QualType MPTy = Context.getMemberPointerType( | |||
11322 | op->getType(), | |||
11323 | Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); | |||
11324 | // Under the MS ABI, lock down the inheritance model now. | |||
11325 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
11326 | (void)isCompleteType(OpLoc, MPTy); | |||
11327 | return MPTy; | |||
11328 | } | |||
11329 | } | |||
11330 | } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && | |||
11331 | !isa<BindingDecl>(dcl)) | |||
11332 | llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11332); | |||
11333 | } | |||
11334 | ||||
11335 | if (AddressOfError != AO_No_Error) { | |||
11336 | diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); | |||
11337 | return QualType(); | |||
11338 | } | |||
11339 | ||||
11340 | if (lval == Expr::LV_IncompleteVoidType) { | |||
11341 | // Taking the address of a void variable is technically illegal, but we | |||
11342 | // allow it in cases which are otherwise valid. | |||
11343 | // Example: "extern void x; void* y = &x;". | |||
11344 | Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); | |||
11345 | } | |||
11346 | ||||
11347 | // If the operand has type "type", the result has type "pointer to type". | |||
11348 | if (op->getType()->isObjCObjectType()) | |||
11349 | return Context.getObjCObjectPointerType(op->getType()); | |||
11350 | ||||
11351 | CheckAddressOfPackedMember(op); | |||
11352 | ||||
11353 | return Context.getPointerType(op->getType()); | |||
11354 | } | |||
11355 | ||||
11356 | static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { | |||
11357 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); | |||
11358 | if (!DRE) | |||
11359 | return; | |||
11360 | const Decl *D = DRE->getDecl(); | |||
11361 | if (!D) | |||
11362 | return; | |||
11363 | const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); | |||
11364 | if (!Param) | |||
11365 | return; | |||
11366 | if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) | |||
11367 | if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) | |||
11368 | return; | |||
11369 | if (FunctionScopeInfo *FD = S.getCurFunction()) | |||
11370 | if (!FD->ModifiedNonNullParams.count(Param)) | |||
11371 | FD->ModifiedNonNullParams.insert(Param); | |||
11372 | } | |||
11373 | ||||
11374 | /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). | |||
11375 | static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, | |||
11376 | SourceLocation OpLoc) { | |||
11377 | if (Op->isTypeDependent()) | |||
11378 | return S.Context.DependentTy; | |||
11379 | ||||
11380 | ExprResult ConvResult = S.UsualUnaryConversions(Op); | |||
11381 | if (ConvResult.isInvalid()) | |||
11382 | return QualType(); | |||
11383 | Op = ConvResult.get(); | |||
11384 | QualType OpTy = Op->getType(); | |||
11385 | QualType Result; | |||
11386 | ||||
11387 | if (isa<CXXReinterpretCastExpr>(Op)) { | |||
11388 | QualType OpOrigType = Op->IgnoreParenCasts()->getType(); | |||
11389 | S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, | |||
11390 | Op->getSourceRange()); | |||
11391 | } | |||
11392 | ||||
11393 | if (const PointerType *PT = OpTy->getAs<PointerType>()) | |||
11394 | { | |||
11395 | Result = PT->getPointeeType(); | |||
11396 | } | |||
11397 | else if (const ObjCObjectPointerType *OPT = | |||
11398 | OpTy->getAs<ObjCObjectPointerType>()) | |||
11399 | Result = OPT->getPointeeType(); | |||
11400 | else { | |||
11401 | ExprResult PR = S.CheckPlaceholderExpr(Op); | |||
11402 | if (PR.isInvalid()) return QualType(); | |||
11403 | if (PR.get() != Op) | |||
11404 | return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); | |||
11405 | } | |||
11406 | ||||
11407 | if (Result.isNull()) { | |||
11408 | S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) | |||
11409 | << OpTy << Op->getSourceRange(); | |||
11410 | return QualType(); | |||
11411 | } | |||
11412 | ||||
11413 | // Note that per both C89 and C99, indirection is always legal, even if Result | |||
11414 | // is an incomplete type or void. It would be possible to warn about | |||
11415 | // dereferencing a void pointer, but it's completely well-defined, and such a | |||
11416 | // warning is unlikely to catch any mistakes. In C++, indirection is not valid | |||
11417 | // for pointers to 'void' but is fine for any other pointer type: | |||
11418 | // | |||
11419 | // C++ [expr.unary.op]p1: | |||
11420 | // [...] the expression to which [the unary * operator] is applied shall | |||
11421 | // be a pointer to an object type, or a pointer to a function type | |||
11422 | if (S.getLangOpts().CPlusPlus && Result->isVoidType()) | |||
11423 | S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) | |||
11424 | << OpTy << Op->getSourceRange(); | |||
11425 | ||||
11426 | // Dereferences are usually l-values... | |||
11427 | VK = VK_LValue; | |||
11428 | ||||
11429 | // ...except that certain expressions are never l-values in C. | |||
11430 | if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) | |||
11431 | VK = VK_RValue; | |||
11432 | ||||
11433 | return Result; | |||
11434 | } | |||
11435 | ||||
11436 | BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { | |||
11437 | BinaryOperatorKind Opc; | |||
11438 | switch (Kind) { | |||
11439 | default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11439); | |||
11440 | case tok::periodstar: Opc = BO_PtrMemD; break; | |||
11441 | case tok::arrowstar: Opc = BO_PtrMemI; break; | |||
11442 | case tok::star: Opc = BO_Mul; break; | |||
11443 | case tok::slash: Opc = BO_Div; break; | |||
11444 | case tok::percent: Opc = BO_Rem; break; | |||
11445 | case tok::plus: Opc = BO_Add; break; | |||
11446 | case tok::minus: Opc = BO_Sub; break; | |||
11447 | case tok::lessless: Opc = BO_Shl; break; | |||
11448 | case tok::greatergreater: Opc = BO_Shr; break; | |||
11449 | case tok::lessequal: Opc = BO_LE; break; | |||
11450 | case tok::less: Opc = BO_LT; break; | |||
11451 | case tok::greaterequal: Opc = BO_GE; break; | |||
11452 | case tok::greater: Opc = BO_GT; break; | |||
11453 | case tok::exclaimequal: Opc = BO_NE; break; | |||
11454 | case tok::equalequal: Opc = BO_EQ; break; | |||
11455 | case tok::spaceship: Opc = BO_Cmp; break; | |||
11456 | case tok::amp: Opc = BO_And; break; | |||
11457 | case tok::caret: Opc = BO_Xor; break; | |||
11458 | case tok::pipe: Opc = BO_Or; break; | |||
11459 | case tok::ampamp: Opc = BO_LAnd; break; | |||
11460 | case tok::pipepipe: Opc = BO_LOr; break; | |||
11461 | case tok::equal: Opc = BO_Assign; break; | |||
11462 | case tok::starequal: Opc = BO_MulAssign; break; | |||
11463 | case tok::slashequal: Opc = BO_DivAssign; break; | |||
11464 | case tok::percentequal: Opc = BO_RemAssign; break; | |||
11465 | case tok::plusequal: Opc = BO_AddAssign; break; | |||
11466 | case tok::minusequal: Opc = BO_SubAssign; break; | |||
11467 | case tok::lesslessequal: Opc = BO_ShlAssign; break; | |||
11468 | case tok::greatergreaterequal: Opc = BO_ShrAssign; break; | |||
11469 | case tok::ampequal: Opc = BO_AndAssign; break; | |||
11470 | case tok::caretequal: Opc = BO_XorAssign; break; | |||
11471 | case tok::pipeequal: Opc = BO_OrAssign; break; | |||
11472 | case tok::comma: Opc = BO_Comma; break; | |||
11473 | } | |||
11474 | return Opc; | |||
11475 | } | |||
11476 | ||||
11477 | static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( | |||
11478 | tok::TokenKind Kind) { | |||
11479 | UnaryOperatorKind Opc; | |||
11480 | switch (Kind) { | |||
11481 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11481); | |||
11482 | case tok::plusplus: Opc = UO_PreInc; break; | |||
11483 | case tok::minusminus: Opc = UO_PreDec; break; | |||
11484 | case tok::amp: Opc = UO_AddrOf; break; | |||
11485 | case tok::star: Opc = UO_Deref; break; | |||
11486 | case tok::plus: Opc = UO_Plus; break; | |||
11487 | case tok::minus: Opc = UO_Minus; break; | |||
11488 | case tok::tilde: Opc = UO_Not; break; | |||
11489 | case tok::exclaim: Opc = UO_LNot; break; | |||
11490 | case tok::kw___real: Opc = UO_Real; break; | |||
11491 | case tok::kw___imag: Opc = UO_Imag; break; | |||
11492 | case tok::kw___extension__: Opc = UO_Extension; break; | |||
11493 | } | |||
11494 | return Opc; | |||
11495 | } | |||
11496 | ||||
11497 | /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. | |||
11498 | /// This warning suppressed in the event of macro expansions. | |||
11499 | static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, | |||
11500 | SourceLocation OpLoc) { | |||
11501 | if (S.inTemplateInstantiation()) | |||
11502 | return; | |||
11503 | if (S.isUnevaluatedContext()) | |||
11504 | return; | |||
11505 | if (OpLoc.isInvalid() || OpLoc.isMacroID()) | |||
11506 | return; | |||
11507 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); | |||
11508 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); | |||
11509 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); | |||
11510 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); | |||
11511 | if (!LHSDeclRef || !RHSDeclRef || | |||
11512 | LHSDeclRef->getLocation().isMacroID() || | |||
11513 | RHSDeclRef->getLocation().isMacroID()) | |||
11514 | return; | |||
11515 | const ValueDecl *LHSDecl = | |||
11516 | cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); | |||
11517 | const ValueDecl *RHSDecl = | |||
11518 | cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); | |||
11519 | if (LHSDecl != RHSDecl) | |||
11520 | return; | |||
11521 | if (LHSDecl->getType().isVolatileQualified()) | |||
11522 | return; | |||
11523 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | |||
11524 | if (RefTy->getPointeeType().isVolatileQualified()) | |||
11525 | return; | |||
11526 | ||||
11527 | S.Diag(OpLoc, diag::warn_self_assignment) | |||
11528 | << LHSDeclRef->getType() | |||
11529 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); | |||
11530 | } | |||
11531 | ||||
11532 | /// Check if a bitwise-& is performed on an Objective-C pointer. This | |||
11533 | /// is usually indicative of introspection within the Objective-C pointer. | |||
11534 | static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, | |||
11535 | SourceLocation OpLoc) { | |||
11536 | if (!S.getLangOpts().ObjC1) | |||
11537 | return; | |||
11538 | ||||
11539 | const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; | |||
11540 | const Expr *LHS = L.get(); | |||
11541 | const Expr *RHS = R.get(); | |||
11542 | ||||
11543 | if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | |||
11544 | ObjCPointerExpr = LHS; | |||
11545 | OtherExpr = RHS; | |||
11546 | } | |||
11547 | else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | |||
11548 | ObjCPointerExpr = RHS; | |||
11549 | OtherExpr = LHS; | |||
11550 | } | |||
11551 | ||||
11552 | // This warning is deliberately made very specific to reduce false | |||
11553 | // positives with logic that uses '&' for hashing. This logic mainly | |||
11554 | // looks for code trying to introspect into tagged pointers, which | |||
11555 | // code should generally never do. | |||
11556 | if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { | |||
11557 | unsigned Diag = diag::warn_objc_pointer_masking; | |||
11558 | // Determine if we are introspecting the result of performSelectorXXX. | |||
11559 | const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); | |||
11560 | // Special case messages to -performSelector and friends, which | |||
11561 | // can return non-pointer values boxed in a pointer value. | |||
11562 | // Some clients may wish to silence warnings in this subcase. | |||
11563 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { | |||
11564 | Selector S = ME->getSelector(); | |||
11565 | StringRef SelArg0 = S.getNameForSlot(0); | |||
11566 | if (SelArg0.startswith("performSelector")) | |||
11567 | Diag = diag::warn_objc_pointer_masking_performSelector; | |||
11568 | } | |||
11569 | ||||
11570 | S.Diag(OpLoc, Diag) | |||
11571 | << ObjCPointerExpr->getSourceRange(); | |||
11572 | } | |||
11573 | } | |||
11574 | ||||
11575 | static NamedDecl *getDeclFromExpr(Expr *E) { | |||
11576 | if (!E) | |||
11577 | return nullptr; | |||
11578 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) | |||
11579 | return DRE->getDecl(); | |||
11580 | if (auto *ME = dyn_cast<MemberExpr>(E)) | |||
11581 | return ME->getMemberDecl(); | |||
11582 | if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) | |||
11583 | return IRE->getDecl(); | |||
11584 | return nullptr; | |||
11585 | } | |||
11586 | ||||
11587 | // This helper function promotes a binary operator's operands (which are of a | |||
11588 | // half vector type) to a vector of floats and then truncates the result to | |||
11589 | // a vector of either half or short. | |||
11590 | static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, | |||
11591 | BinaryOperatorKind Opc, QualType ResultTy, | |||
11592 | ExprValueKind VK, ExprObjectKind OK, | |||
11593 | bool IsCompAssign, SourceLocation OpLoc, | |||
11594 | FPOptions FPFeatures) { | |||
11595 | auto &Context = S.getASTContext(); | |||
11596 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11598, __extension__ __PRETTY_FUNCTION__)) | |||
11597 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11598, __extension__ __PRETTY_FUNCTION__)) | |||
11598 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11598, __extension__ __PRETTY_FUNCTION__)); | |||
11599 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11601, __extension__ __PRETTY_FUNCTION__)) | |||
11600 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11601, __extension__ __PRETTY_FUNCTION__)) | |||
11601 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11601, __extension__ __PRETTY_FUNCTION__)); | |||
11602 | ||||
11603 | RHS = convertVector(RHS.get(), Context.FloatTy, S); | |||
11604 | QualType BinOpResTy = RHS.get()->getType(); | |||
11605 | ||||
11606 | // If Opc is a comparison, ResultType is a vector of shorts. In that case, | |||
11607 | // change BinOpResTy to a vector of ints. | |||
11608 | if (isVector(ResultTy, Context.ShortTy)) | |||
11609 | BinOpResTy = S.GetSignedVectorType(BinOpResTy); | |||
11610 | ||||
11611 | if (IsCompAssign) | |||
11612 | return new (Context) CompoundAssignOperator( | |||
11613 | LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, | |||
11614 | OpLoc, FPFeatures); | |||
11615 | ||||
11616 | LHS = convertVector(LHS.get(), Context.FloatTy, S); | |||
11617 | auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, | |||
11618 | VK, OK, OpLoc, FPFeatures); | |||
11619 | return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); | |||
11620 | } | |||
11621 | ||||
11622 | static std::pair<ExprResult, ExprResult> | |||
11623 | CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, | |||
11624 | Expr *RHSExpr) { | |||
11625 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | |||
11626 | if (!S.getLangOpts().CPlusPlus) { | |||
11627 | // C cannot handle TypoExpr nodes on either side of a binop because it | |||
11628 | // doesn't handle dependent types properly, so make sure any TypoExprs have | |||
11629 | // been dealt with before checking the operands. | |||
11630 | LHS = S.CorrectDelayedTyposInExpr(LHS); | |||
11631 | RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { | |||
11632 | if (Opc != BO_Assign) | |||
11633 | return ExprResult(E); | |||
11634 | // Avoid correcting the RHS to the same Expr as the LHS. | |||
11635 | Decl *D = getDeclFromExpr(E); | |||
11636 | return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; | |||
11637 | }); | |||
11638 | } | |||
11639 | return std::make_pair(LHS, RHS); | |||
11640 | } | |||
11641 | ||||
11642 | /// Returns true if conversion between vectors of halfs and vectors of floats | |||
11643 | /// is needed. | |||
11644 | static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, | |||
11645 | QualType SrcType) { | |||
11646 | return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && | |||
11647 | !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && | |||
11648 | isVector(SrcType, Ctx.HalfTy); | |||
11649 | } | |||
11650 | ||||
11651 | /// CreateBuiltinBinOp - Creates a new built-in binary operation with | |||
11652 | /// operator @p Opc at location @c TokLoc. This routine only supports | |||
11653 | /// built-in operations; ActOnBinOp handles overloaded operators. | |||
11654 | ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, | |||
11655 | BinaryOperatorKind Opc, | |||
11656 | Expr *LHSExpr, Expr *RHSExpr) { | |||
11657 | if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { | |||
11658 | // The syntax only allows initializer lists on the RHS of assignment, | |||
11659 | // so we don't need to worry about accepting invalid code for | |||
11660 | // non-assignment operators. | |||
11661 | // C++11 5.17p9: | |||
11662 | // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning | |||
11663 | // of x = {} is x = T(). | |||
11664 | InitializationKind Kind = InitializationKind::CreateDirectList( | |||
11665 | RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd()); | |||
11666 | InitializedEntity Entity = | |||
11667 | InitializedEntity::InitializeTemporary(LHSExpr->getType()); | |||
11668 | InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); | |||
11669 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); | |||
11670 | if (Init.isInvalid()) | |||
11671 | return Init; | |||
11672 | RHSExpr = Init.get(); | |||
11673 | } | |||
11674 | ||||
11675 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | |||
11676 | QualType ResultTy; // Result type of the binary operator. | |||
11677 | // The following two variables are used for compound assignment operators | |||
11678 | QualType CompLHSTy; // Type of LHS after promotions for computation | |||
11679 | QualType CompResultTy; // Type of computation result | |||
11680 | ExprValueKind VK = VK_RValue; | |||
11681 | ExprObjectKind OK = OK_Ordinary; | |||
11682 | bool ConvertHalfVec = false; | |||
11683 | ||||
11684 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | |||
11685 | if (!LHS.isUsable() || !RHS.isUsable()) | |||
11686 | return ExprError(); | |||
11687 | ||||
11688 | if (getLangOpts().OpenCL) { | |||
11689 | QualType LHSTy = LHSExpr->getType(); | |||
11690 | QualType RHSTy = RHSExpr->getType(); | |||
11691 | // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by | |||
11692 | // the ATOMIC_VAR_INIT macro. | |||
11693 | if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { | |||
11694 | SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); | |||
11695 | if (BO_Assign == Opc) | |||
11696 | Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; | |||
11697 | else | |||
11698 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | |||
11699 | return ExprError(); | |||
11700 | } | |||
11701 | ||||
11702 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | |||
11703 | // only with a builtin functions and therefore should be disallowed here. | |||
11704 | if (LHSTy->isImageType() || RHSTy->isImageType() || | |||
11705 | LHSTy->isSamplerT() || RHSTy->isSamplerT() || | |||
11706 | LHSTy->isPipeType() || RHSTy->isPipeType() || | |||
11707 | LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { | |||
11708 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | |||
11709 | return ExprError(); | |||
11710 | } | |||
11711 | } | |||
11712 | ||||
11713 | switch (Opc) { | |||
11714 | case BO_Assign: | |||
11715 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); | |||
11716 | if (getLangOpts().CPlusPlus && | |||
11717 | LHS.get()->getObjectKind() != OK_ObjCProperty) { | |||
11718 | VK = LHS.get()->getValueKind(); | |||
11719 | OK = LHS.get()->getObjectKind(); | |||
11720 | } | |||
11721 | if (!ResultTy.isNull()) { | |||
11722 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); | |||
11723 | DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); | |||
11724 | } | |||
11725 | RecordModifiableNonNullParam(*this, LHS.get()); | |||
11726 | break; | |||
11727 | case BO_PtrMemD: | |||
11728 | case BO_PtrMemI: | |||
11729 | ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, | |||
11730 | Opc == BO_PtrMemI); | |||
11731 | break; | |||
11732 | case BO_Mul: | |||
11733 | case BO_Div: | |||
11734 | ConvertHalfVec = true; | |||
11735 | ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, | |||
11736 | Opc == BO_Div); | |||
11737 | break; | |||
11738 | case BO_Rem: | |||
11739 | ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); | |||
11740 | break; | |||
11741 | case BO_Add: | |||
11742 | ConvertHalfVec = true; | |||
11743 | ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); | |||
11744 | break; | |||
11745 | case BO_Sub: | |||
11746 | ConvertHalfVec = true; | |||
11747 | ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); | |||
11748 | break; | |||
11749 | case BO_Shl: | |||
11750 | case BO_Shr: | |||
11751 | ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); | |||
11752 | break; | |||
11753 | case BO_LE: | |||
11754 | case BO_LT: | |||
11755 | case BO_GE: | |||
11756 | case BO_GT: | |||
11757 | ConvertHalfVec = true; | |||
11758 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); | |||
11759 | break; | |||
11760 | case BO_EQ: | |||
11761 | case BO_NE: | |||
11762 | ConvertHalfVec = true; | |||
11763 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); | |||
11764 | break; | |||
11765 | case BO_Cmp: | |||
11766 | // FIXME: Implement proper semantic checking of '<=>'. | |||
11767 | ConvertHalfVec = true; | |||
11768 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); | |||
11769 | if (!ResultTy.isNull()) | |||
11770 | ResultTy = Context.VoidTy; | |||
11771 | break; | |||
11772 | case BO_And: | |||
11773 | checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); | |||
11774 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
11775 | case BO_Xor: | |||
11776 | case BO_Or: | |||
11777 | ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | |||
11778 | break; | |||
11779 | case BO_LAnd: | |||
11780 | case BO_LOr: | |||
11781 | ConvertHalfVec = true; | |||
11782 | ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); | |||
11783 | break; | |||
11784 | case BO_MulAssign: | |||
11785 | case BO_DivAssign: | |||
11786 | ConvertHalfVec = true; | |||
11787 | CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, | |||
11788 | Opc == BO_DivAssign); | |||
11789 | CompLHSTy = CompResultTy; | |||
11790 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
11791 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
11792 | break; | |||
11793 | case BO_RemAssign: | |||
11794 | CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); | |||
11795 | CompLHSTy = CompResultTy; | |||
11796 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
11797 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
11798 | break; | |||
11799 | case BO_AddAssign: | |||
11800 | ConvertHalfVec = true; | |||
11801 | CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); | |||
11802 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
11803 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
11804 | break; | |||
11805 | case BO_SubAssign: | |||
11806 | ConvertHalfVec = true; | |||
11807 | CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); | |||
11808 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
11809 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
11810 | break; | |||
11811 | case BO_ShlAssign: | |||
11812 | case BO_ShrAssign: | |||
11813 | CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); | |||
11814 | CompLHSTy = CompResultTy; | |||
11815 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
11816 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
11817 | break; | |||
11818 | case BO_AndAssign: | |||
11819 | case BO_OrAssign: // fallthrough | |||
11820 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); | |||
11821 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
11822 | case BO_XorAssign: | |||
11823 | CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | |||
11824 | CompLHSTy = CompResultTy; | |||
11825 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
11826 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
11827 | break; | |||
11828 | case BO_Comma: | |||
11829 | ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); | |||
11830 | if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { | |||
11831 | VK = RHS.get()->getValueKind(); | |||
11832 | OK = RHS.get()->getObjectKind(); | |||
11833 | } | |||
11834 | break; | |||
11835 | } | |||
11836 | if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) | |||
11837 | return ExprError(); | |||
11838 | ||||
11839 | // Some of the binary operations require promoting operands of half vector to | |||
11840 | // float vectors and truncating the result back to half vector. For now, we do | |||
11841 | // this only when HalfArgsAndReturn is set (that is, when the target is arm or | |||
11842 | // arm64). | |||
11843 | assert(isVector(RHS.get()->getType(), Context.HalfTy) ==(static_cast <bool> (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 ("isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11845, __extension__ __PRETTY_FUNCTION__)) | |||
11844 | isVector(LHS.get()->getType(), Context.HalfTy) &&(static_cast <bool> (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 ("isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11845, __extension__ __PRETTY_FUNCTION__)) | |||
11845 | "both sides are half vectors or neither sides are")(static_cast <bool> (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 ("isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11845, __extension__ __PRETTY_FUNCTION__)); | |||
11846 | ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, | |||
11847 | LHS.get()->getType()); | |||
11848 | ||||
11849 | // Check for array bounds violations for both sides of the BinaryOperator | |||
11850 | CheckArrayAccess(LHS.get()); | |||
11851 | CheckArrayAccess(RHS.get()); | |||
11852 | ||||
11853 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { | |||
11854 | NamedDecl *ObjectSetClass = LookupSingleName(TUScope, | |||
11855 | &Context.Idents.get("object_setClass"), | |||
11856 | SourceLocation(), LookupOrdinaryName); | |||
11857 | if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { | |||
11858 | SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); | |||
11859 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << | |||
11860 | FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << | |||
11861 | FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << | |||
11862 | FixItHint::CreateInsertion(RHSLocEnd, ")"); | |||
11863 | } | |||
11864 | else | |||
11865 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); | |||
11866 | } | |||
11867 | else if (const ObjCIvarRefExpr *OIRE = | |||
11868 | dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) | |||
11869 | DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); | |||
11870 | ||||
11871 | // Opc is not a compound assignment if CompResultTy is null. | |||
11872 | if (CompResultTy.isNull()) { | |||
11873 | if (ConvertHalfVec) | |||
11874 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, | |||
11875 | OpLoc, FPFeatures); | |||
11876 | return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, | |||
11877 | OK, OpLoc, FPFeatures); | |||
11878 | } | |||
11879 | ||||
11880 | // Handle compound assignments. | |||
11881 | if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != | |||
11882 | OK_ObjCProperty) { | |||
11883 | VK = VK_LValue; | |||
11884 | OK = LHS.get()->getObjectKind(); | |||
11885 | } | |||
11886 | ||||
11887 | if (ConvertHalfVec) | |||
11888 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, | |||
11889 | OpLoc, FPFeatures); | |||
11890 | ||||
11891 | return new (Context) CompoundAssignOperator( | |||
11892 | LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, | |||
11893 | OpLoc, FPFeatures); | |||
11894 | } | |||
11895 | ||||
11896 | /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison | |||
11897 | /// operators are mixed in a way that suggests that the programmer forgot that | |||
11898 | /// comparison operators have higher precedence. The most typical example of | |||
11899 | /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". | |||
11900 | static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, | |||
11901 | SourceLocation OpLoc, Expr *LHSExpr, | |||
11902 | Expr *RHSExpr) { | |||
11903 | BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); | |||
11904 | BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); | |||
11905 | ||||
11906 | // Check that one of the sides is a comparison operator and the other isn't. | |||
11907 | bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); | |||
11908 | bool isRightComp = RHSBO && RHSBO->isComparisonOp(); | |||
11909 | if (isLeftComp == isRightComp) | |||
11910 | return; | |||
11911 | ||||
11912 | // Bitwise operations are sometimes used as eager logical ops. | |||
11913 | // Don't diagnose this. | |||
11914 | bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); | |||
11915 | bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); | |||
11916 | if (isLeftBitwise || isRightBitwise) | |||
11917 | return; | |||
11918 | ||||
11919 | SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), | |||
11920 | OpLoc) | |||
11921 | : SourceRange(OpLoc, RHSExpr->getLocEnd()); | |||
11922 | StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); | |||
11923 | SourceRange ParensRange = isLeftComp ? | |||
11924 | SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) | |||
11925 | : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); | |||
11926 | ||||
11927 | Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) | |||
11928 | << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; | |||
11929 | SuggestParentheses(Self, OpLoc, | |||
11930 | Self.PDiag(diag::note_precedence_silence) << OpStr, | |||
11931 | (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); | |||
11932 | SuggestParentheses(Self, OpLoc, | |||
11933 | Self.PDiag(diag::note_precedence_bitwise_first) | |||
11934 | << BinaryOperator::getOpcodeStr(Opc), | |||
11935 | ParensRange); | |||
11936 | } | |||
11937 | ||||
11938 | /// \brief It accepts a '&&' expr that is inside a '||' one. | |||
11939 | /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression | |||
11940 | /// in parentheses. | |||
11941 | static void | |||
11942 | EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, | |||
11943 | BinaryOperator *Bop) { | |||
11944 | assert(Bop->getOpcode() == BO_LAnd)(static_cast <bool> (Bop->getOpcode() == BO_LAnd) ? void (0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 11944, __extension__ __PRETTY_FUNCTION__)); | |||
11945 | Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) | |||
11946 | << Bop->getSourceRange() << OpLoc; | |||
11947 | SuggestParentheses(Self, Bop->getOperatorLoc(), | |||
11948 | Self.PDiag(diag::note_precedence_silence) | |||
11949 | << Bop->getOpcodeStr(), | |||
11950 | Bop->getSourceRange()); | |||
11951 | } | |||
11952 | ||||
11953 | /// \brief Returns true if the given expression can be evaluated as a constant | |||
11954 | /// 'true'. | |||
11955 | static bool EvaluatesAsTrue(Sema &S, Expr *E) { | |||
11956 | bool Res; | |||
11957 | return !E->isValueDependent() && | |||
11958 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; | |||
11959 | } | |||
11960 | ||||
11961 | /// \brief Returns true if the given expression can be evaluated as a constant | |||
11962 | /// 'false'. | |||
11963 | static bool EvaluatesAsFalse(Sema &S, Expr *E) { | |||
11964 | bool Res; | |||
11965 | return !E->isValueDependent() && | |||
11966 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; | |||
11967 | } | |||
11968 | ||||
11969 | /// \brief Look for '&&' in the left hand of a '||' expr. | |||
11970 | static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, | |||
11971 | Expr *LHSExpr, Expr *RHSExpr) { | |||
11972 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { | |||
11973 | if (Bop->getOpcode() == BO_LAnd) { | |||
11974 | // If it's "a && b || 0" don't warn since the precedence doesn't matter. | |||
11975 | if (EvaluatesAsFalse(S, RHSExpr)) | |||
11976 | return; | |||
11977 | // If it's "1 && a || b" don't warn since the precedence doesn't matter. | |||
11978 | if (!EvaluatesAsTrue(S, Bop->getLHS())) | |||
11979 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | |||
11980 | } else if (Bop->getOpcode() == BO_LOr) { | |||
11981 | if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { | |||
11982 | // If it's "a || b && 1 || c" we didn't warn earlier for | |||
11983 | // "a || b && 1", but warn now. | |||
11984 | if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) | |||
11985 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); | |||
11986 | } | |||
11987 | } | |||
11988 | } | |||
11989 | } | |||
11990 | ||||
11991 | /// \brief Look for '&&' in the right hand of a '||' expr. | |||
11992 | static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, | |||
11993 | Expr *LHSExpr, Expr *RHSExpr) { | |||
11994 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { | |||
11995 | if (Bop->getOpcode() == BO_LAnd) { | |||
11996 | // If it's "0 || a && b" don't warn since the precedence doesn't matter. | |||
11997 | if (EvaluatesAsFalse(S, LHSExpr)) | |||
11998 | return; | |||
11999 | // If it's "a || b && 1" don't warn since the precedence doesn't matter. | |||
12000 | if (!EvaluatesAsTrue(S, Bop->getRHS())) | |||
12001 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | |||
12002 | } | |||
12003 | } | |||
12004 | } | |||
12005 | ||||
12006 | /// \brief Look for bitwise op in the left or right hand of a bitwise op with | |||
12007 | /// lower precedence and emit a diagnostic together with a fixit hint that wraps | |||
12008 | /// the '&' expression in parentheses. | |||
12009 | static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, | |||
12010 | SourceLocation OpLoc, Expr *SubExpr) { | |||
12011 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | |||
12012 | if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { | |||
12013 | S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) | |||
12014 | << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) | |||
12015 | << Bop->getSourceRange() << OpLoc; | |||
12016 | SuggestParentheses(S, Bop->getOperatorLoc(), | |||
12017 | S.PDiag(diag::note_precedence_silence) | |||
12018 | << Bop->getOpcodeStr(), | |||
12019 | Bop->getSourceRange()); | |||
12020 | } | |||
12021 | } | |||
12022 | } | |||
12023 | ||||
12024 | static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, | |||
12025 | Expr *SubExpr, StringRef Shift) { | |||
12026 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | |||
12027 | if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { | |||
12028 | StringRef Op = Bop->getOpcodeStr(); | |||
12029 | S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) | |||
12030 | << Bop->getSourceRange() << OpLoc << Shift << Op; | |||
12031 | SuggestParentheses(S, Bop->getOperatorLoc(), | |||
12032 | S.PDiag(diag::note_precedence_silence) << Op, | |||
12033 | Bop->getSourceRange()); | |||
12034 | } | |||
12035 | } | |||
12036 | } | |||
12037 | ||||
12038 | static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, | |||
12039 | Expr *LHSExpr, Expr *RHSExpr) { | |||
12040 | CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); | |||
12041 | if (!OCE) | |||
12042 | return; | |||
12043 | ||||
12044 | FunctionDecl *FD = OCE->getDirectCallee(); | |||
12045 | if (!FD || !FD->isOverloadedOperator()) | |||
12046 | return; | |||
12047 | ||||
12048 | OverloadedOperatorKind Kind = FD->getOverloadedOperator(); | |||
12049 | if (Kind != OO_LessLess && Kind != OO_GreaterGreater) | |||
12050 | return; | |||
12051 | ||||
12052 | S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) | |||
12053 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() | |||
12054 | << (Kind == OO_LessLess); | |||
12055 | SuggestParentheses(S, OCE->getOperatorLoc(), | |||
12056 | S.PDiag(diag::note_precedence_silence) | |||
12057 | << (Kind == OO_LessLess ? "<<" : ">>"), | |||
12058 | OCE->getSourceRange()); | |||
12059 | SuggestParentheses(S, OpLoc, | |||
12060 | S.PDiag(diag::note_evaluate_comparison_first), | |||
12061 | SourceRange(OCE->getArg(1)->getLocStart(), | |||
12062 | RHSExpr->getLocEnd())); | |||
12063 | } | |||
12064 | ||||
12065 | /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky | |||
12066 | /// precedence. | |||
12067 | static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, | |||
12068 | SourceLocation OpLoc, Expr *LHSExpr, | |||
12069 | Expr *RHSExpr){ | |||
12070 | // Diagnose "arg1 'bitwise' arg2 'eq' arg3". | |||
12071 | if (BinaryOperator::isBitwiseOp(Opc)) | |||
12072 | DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); | |||
12073 | ||||
12074 | // Diagnose "arg1 & arg2 | arg3" | |||
12075 | if ((Opc == BO_Or || Opc == BO_Xor) && | |||
12076 | !OpLoc.isMacroID()/* Don't warn in macros. */) { | |||
12077 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); | |||
12078 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); | |||
12079 | } | |||
12080 | ||||
12081 | // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. | |||
12082 | // We don't warn for 'assert(a || b && "bad")' since this is safe. | |||
12083 | if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { | |||
12084 | DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); | |||
12085 | DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); | |||
12086 | } | |||
12087 | ||||
12088 | if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) | |||
12089 | || Opc == BO_Shr) { | |||
12090 | StringRef Shift = BinaryOperator::getOpcodeStr(Opc); | |||
12091 | DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); | |||
12092 | DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); | |||
12093 | } | |||
12094 | ||||
12095 | // Warn on overloaded shift operators and comparisons, such as: | |||
12096 | // cout << 5 == 4; | |||
12097 | if (BinaryOperator::isComparisonOp(Opc)) | |||
12098 | DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); | |||
12099 | } | |||
12100 | ||||
12101 | // Binary Operators. 'Tok' is the token for the operator. | |||
12102 | ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, | |||
12103 | tok::TokenKind Kind, | |||
12104 | Expr *LHSExpr, Expr *RHSExpr) { | |||
12105 | BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); | |||
12106 | assert(LHSExpr && "ActOnBinOp(): missing left expression")(static_cast <bool> (LHSExpr && "ActOnBinOp(): missing left expression" ) ? void (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12106, __extension__ __PRETTY_FUNCTION__)); | |||
12107 | assert(RHSExpr && "ActOnBinOp(): missing right expression")(static_cast <bool> (RHSExpr && "ActOnBinOp(): missing right expression" ) ? void (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12107, __extension__ __PRETTY_FUNCTION__)); | |||
12108 | ||||
12109 | // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" | |||
12110 | DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); | |||
12111 | ||||
12112 | return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); | |||
12113 | } | |||
12114 | ||||
12115 | /// Build an overloaded binary operator expression in the given scope. | |||
12116 | static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, | |||
12117 | BinaryOperatorKind Opc, | |||
12118 | Expr *LHS, Expr *RHS) { | |||
12119 | switch (Opc) { | |||
12120 | case BO_Assign: | |||
12121 | case BO_DivAssign: | |||
12122 | case BO_RemAssign: | |||
12123 | case BO_SubAssign: | |||
12124 | case BO_AndAssign: | |||
12125 | case BO_OrAssign: | |||
12126 | case BO_XorAssign: | |||
12127 | DiagnoseSelfAssignment(S, LHS, RHS, OpLoc); | |||
12128 | CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); | |||
12129 | break; | |||
12130 | default: | |||
12131 | break; | |||
12132 | } | |||
12133 | ||||
12134 | // Find all of the overloaded operators visible from this | |||
12135 | // point. We perform both an operator-name lookup from the local | |||
12136 | // scope and an argument-dependent lookup based on the types of | |||
12137 | // the arguments. | |||
12138 | UnresolvedSet<16> Functions; | |||
12139 | OverloadedOperatorKind OverOp | |||
12140 | = BinaryOperator::getOverloadedOperator(Opc); | |||
12141 | if (Sc && OverOp != OO_None && OverOp != OO_Equal) | |||
12142 | S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), | |||
12143 | RHS->getType(), Functions); | |||
12144 | ||||
12145 | // Build the (potentially-overloaded, potentially-dependent) | |||
12146 | // binary operation. | |||
12147 | return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); | |||
12148 | } | |||
12149 | ||||
12150 | ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, | |||
12151 | BinaryOperatorKind Opc, | |||
12152 | Expr *LHSExpr, Expr *RHSExpr) { | |||
12153 | ExprResult LHS, RHS; | |||
12154 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | |||
12155 | if (!LHS.isUsable() || !RHS.isUsable()) | |||
12156 | return ExprError(); | |||
12157 | LHSExpr = LHS.get(); | |||
12158 | RHSExpr = RHS.get(); | |||
12159 | ||||
12160 | // We want to end up calling one of checkPseudoObjectAssignment | |||
12161 | // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if | |||
12162 | // both expressions are overloadable or either is type-dependent), | |||
12163 | // or CreateBuiltinBinOp (in any other case). We also want to get | |||
12164 | // any placeholder types out of the way. | |||
12165 | ||||
12166 | // Handle pseudo-objects in the LHS. | |||
12167 | if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { | |||
12168 | // Assignments with a pseudo-object l-value need special analysis. | |||
12169 | if (pty->getKind() == BuiltinType::PseudoObject && | |||
12170 | BinaryOperator::isAssignmentOp(Opc)) | |||
12171 | return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
12172 | ||||
12173 | // Don't resolve overloads if the other type is overloadable. | |||
12174 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { | |||
12175 | // We can't actually test that if we still have a placeholder, | |||
12176 | // though. Fortunately, none of the exceptions we see in that | |||
12177 | // code below are valid when the LHS is an overload set. Note | |||
12178 | // that an overload set can be dependently-typed, but it never | |||
12179 | // instantiates to having an overloadable type. | |||
12180 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | |||
12181 | if (resolvedRHS.isInvalid()) return ExprError(); | |||
12182 | RHSExpr = resolvedRHS.get(); | |||
12183 | ||||
12184 | if (RHSExpr->isTypeDependent() || | |||
12185 | RHSExpr->getType()->isOverloadableType()) | |||
12186 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
12187 | } | |||
12188 | ||||
12189 | // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function | |||
12190 | // template, diagnose the missing 'template' keyword instead of diagnosing | |||
12191 | // an invalid use of a bound member function. | |||
12192 | // | |||
12193 | // Note that "A::x < b" might be valid if 'b' has an overloadable type due | |||
12194 | // to C++1z [over.over]/1.4, but we already checked for that case above. | |||
12195 | if (Opc == BO_LT && inTemplateInstantiation() && | |||
12196 | (pty->getKind() == BuiltinType::BoundMember || | |||
12197 | pty->getKind() == BuiltinType::Overload)) { | |||
12198 | auto *OE = dyn_cast<OverloadExpr>(LHSExpr); | |||
12199 | if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && | |||
12200 | std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { | |||
12201 | return isa<FunctionTemplateDecl>(ND); | |||
12202 | })) { | |||
12203 | Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() | |||
12204 | : OE->getNameLoc(), | |||
12205 | diag::err_template_kw_missing) | |||
12206 | << OE->getName().getAsString() << ""; | |||
12207 | return ExprError(); | |||
12208 | } | |||
12209 | } | |||
12210 | ||||
12211 | ExprResult LHS = CheckPlaceholderExpr(LHSExpr); | |||
12212 | if (LHS.isInvalid()) return ExprError(); | |||
12213 | LHSExpr = LHS.get(); | |||
12214 | } | |||
12215 | ||||
12216 | // Handle pseudo-objects in the RHS. | |||
12217 | if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { | |||
12218 | // An overload in the RHS can potentially be resolved by the type | |||
12219 | // being assigned to. | |||
12220 | if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { | |||
12221 | if (getLangOpts().CPlusPlus && | |||
12222 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || | |||
12223 | LHSExpr->getType()->isOverloadableType())) | |||
12224 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
12225 | ||||
12226 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | |||
12227 | } | |||
12228 | ||||
12229 | // Don't resolve overloads if the other type is overloadable. | |||
12230 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && | |||
12231 | LHSExpr->getType()->isOverloadableType()) | |||
12232 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
12233 | ||||
12234 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | |||
12235 | if (!resolvedRHS.isUsable()) return ExprError(); | |||
12236 | RHSExpr = resolvedRHS.get(); | |||
12237 | } | |||
12238 | ||||
12239 | if (getLangOpts().CPlusPlus) { | |||
12240 | // If either expression is type-dependent, always build an | |||
12241 | // overloaded op. | |||
12242 | if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) | |||
12243 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
12244 | ||||
12245 | // Otherwise, build an overloaded op if either expression has an | |||
12246 | // overloadable type. | |||
12247 | if (LHSExpr->getType()->isOverloadableType() || | |||
12248 | RHSExpr->getType()->isOverloadableType()) | |||
12249 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
12250 | } | |||
12251 | ||||
12252 | // Build a built-in binary operation. | |||
12253 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | |||
12254 | } | |||
12255 | ||||
12256 | static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { | |||
12257 | if (T.isNull() || T->isDependentType()) | |||
12258 | return false; | |||
12259 | ||||
12260 | if (!T->isPromotableIntegerType()) | |||
12261 | return true; | |||
12262 | ||||
12263 | return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); | |||
12264 | } | |||
12265 | ||||
12266 | ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, | |||
12267 | UnaryOperatorKind Opc, | |||
12268 | Expr *InputExpr) { | |||
12269 | ExprResult Input = InputExpr; | |||
12270 | ExprValueKind VK = VK_RValue; | |||
12271 | ExprObjectKind OK = OK_Ordinary; | |||
12272 | QualType resultType; | |||
12273 | bool CanOverflow = false; | |||
12274 | ||||
12275 | bool ConvertHalfVec = false; | |||
12276 | if (getLangOpts().OpenCL) { | |||
12277 | QualType Ty = InputExpr->getType(); | |||
12278 | // The only legal unary operation for atomics is '&'. | |||
12279 | if ((Opc != UO_AddrOf && Ty->isAtomicType()) || | |||
12280 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | |||
12281 | // only with a builtin functions and therefore should be disallowed here. | |||
12282 | (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() | |||
12283 | || Ty->isBlockPointerType())) { | |||
12284 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
12285 | << InputExpr->getType() | |||
12286 | << Input.get()->getSourceRange()); | |||
12287 | } | |||
12288 | } | |||
12289 | switch (Opc) { | |||
12290 | case UO_PreInc: | |||
12291 | case UO_PreDec: | |||
12292 | case UO_PostInc: | |||
12293 | case UO_PostDec: | |||
12294 | resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, | |||
12295 | OpLoc, | |||
12296 | Opc == UO_PreInc || | |||
12297 | Opc == UO_PostInc, | |||
12298 | Opc == UO_PreInc || | |||
12299 | Opc == UO_PreDec); | |||
12300 | CanOverflow = isOverflowingIntegerType(Context, resultType); | |||
12301 | break; | |||
12302 | case UO_AddrOf: | |||
12303 | resultType = CheckAddressOfOperand(Input, OpLoc); | |||
12304 | RecordModifiableNonNullParam(*this, InputExpr); | |||
12305 | break; | |||
12306 | case UO_Deref: { | |||
12307 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | |||
12308 | if (Input.isInvalid()) return ExprError(); | |||
12309 | resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); | |||
12310 | break; | |||
12311 | } | |||
12312 | case UO_Plus: | |||
12313 | case UO_Minus: | |||
12314 | CanOverflow = Opc == UO_Minus && | |||
12315 | isOverflowingIntegerType(Context, Input.get()->getType()); | |||
12316 | Input = UsualUnaryConversions(Input.get()); | |||
12317 | if (Input.isInvalid()) return ExprError(); | |||
12318 | // Unary plus and minus require promoting an operand of half vector to a | |||
12319 | // float vector and truncating the result back to a half vector. For now, we | |||
12320 | // do this only when HalfArgsAndReturns is set (that is, when the target is | |||
12321 | // arm or arm64). | |||
12322 | ConvertHalfVec = | |||
12323 | needsConversionOfHalfVec(true, Context, Input.get()->getType()); | |||
12324 | ||||
12325 | // If the operand is a half vector, promote it to a float vector. | |||
12326 | if (ConvertHalfVec) | |||
12327 | Input = convertVector(Input.get(), Context.FloatTy, *this); | |||
12328 | resultType = Input.get()->getType(); | |||
12329 | if (resultType->isDependentType()) | |||
12330 | break; | |||
12331 | if (resultType->isArithmeticType()) // C99 6.5.3.3p1 | |||
12332 | break; | |||
12333 | else if (resultType->isVectorType() && | |||
12334 | // The z vector extensions don't allow + or - with bool vectors. | |||
12335 | (!Context.getLangOpts().ZVector || | |||
12336 | resultType->getAs<VectorType>()->getVectorKind() != | |||
12337 | VectorType::AltiVecBool)) | |||
12338 | break; | |||
12339 | else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 | |||
12340 | Opc == UO_Plus && | |||
12341 | resultType->isPointerType()) | |||
12342 | break; | |||
12343 | ||||
12344 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
12345 | << resultType << Input.get()->getSourceRange()); | |||
12346 | ||||
12347 | case UO_Not: // bitwise complement | |||
12348 | Input = UsualUnaryConversions(Input.get()); | |||
12349 | if (Input.isInvalid()) | |||
12350 | return ExprError(); | |||
12351 | resultType = Input.get()->getType(); | |||
12352 | ||||
12353 | if (resultType->isDependentType()) | |||
12354 | break; | |||
12355 | // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. | |||
12356 | if (resultType->isComplexType() || resultType->isComplexIntegerType()) | |||
12357 | // C99 does not support '~' for complex conjugation. | |||
12358 | Diag(OpLoc, diag::ext_integer_complement_complex) | |||
12359 | << resultType << Input.get()->getSourceRange(); | |||
12360 | else if (resultType->hasIntegerRepresentation()) | |||
12361 | break; | |||
12362 | else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { | |||
12363 | // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate | |||
12364 | // on vector float types. | |||
12365 | QualType T = resultType->getAs<ExtVectorType>()->getElementType(); | |||
12366 | if (!T->isIntegerType()) | |||
12367 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
12368 | << resultType << Input.get()->getSourceRange()); | |||
12369 | } else { | |||
12370 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
12371 | << resultType << Input.get()->getSourceRange()); | |||
12372 | } | |||
12373 | break; | |||
12374 | ||||
12375 | case UO_LNot: // logical negation | |||
12376 | // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). | |||
12377 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | |||
12378 | if (Input.isInvalid()) return ExprError(); | |||
12379 | resultType = Input.get()->getType(); | |||
12380 | ||||
12381 | // Though we still have to promote half FP to float... | |||
12382 | if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { | |||
12383 | Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); | |||
12384 | resultType = Context.FloatTy; | |||
12385 | } | |||
12386 | ||||
12387 | if (resultType->isDependentType()) | |||
12388 | break; | |||
12389 | if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { | |||
12390 | // C99 6.5.3.3p1: ok, fallthrough; | |||
12391 | if (Context.getLangOpts().CPlusPlus) { | |||
12392 | // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: | |||
12393 | // operand contextually converted to bool. | |||
12394 | Input = ImpCastExprToType(Input.get(), Context.BoolTy, | |||
12395 | ScalarTypeToBooleanCastKind(resultType)); | |||
12396 | } else if (Context.getLangOpts().OpenCL && | |||
12397 | Context.getLangOpts().OpenCLVersion < 120) { | |||
12398 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | |||
12399 | // operate on scalar float types. | |||
12400 | if (!resultType->isIntegerType() && !resultType->isPointerType()) | |||
12401 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
12402 | << resultType << Input.get()->getSourceRange()); | |||
12403 | } | |||
12404 | } else if (resultType->isExtVectorType()) { | |||
12405 | if (Context.getLangOpts().OpenCL && | |||
12406 | Context.getLangOpts().OpenCLVersion < 120) { | |||
12407 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | |||
12408 | // operate on vector float types. | |||
12409 | QualType T = resultType->getAs<ExtVectorType>()->getElementType(); | |||
12410 | if (!T->isIntegerType()) | |||
12411 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
12412 | << resultType << Input.get()->getSourceRange()); | |||
12413 | } | |||
12414 | // Vector logical not returns the signed variant of the operand type. | |||
12415 | resultType = GetSignedVectorType(resultType); | |||
12416 | break; | |||
12417 | } else { | |||
12418 | // FIXME: GCC's vector extension permits the usage of '!' with a vector | |||
12419 | // type in C++. We should allow that here too. | |||
12420 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
12421 | << resultType << Input.get()->getSourceRange()); | |||
12422 | } | |||
12423 | ||||
12424 | // LNot always has type int. C99 6.5.3.3p5. | |||
12425 | // In C++, it's bool. C++ 5.3.1p8 | |||
12426 | resultType = Context.getLogicalOperationType(); | |||
12427 | break; | |||
12428 | case UO_Real: | |||
12429 | case UO_Imag: | |||
12430 | resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); | |||
12431 | // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary | |||
12432 | // complex l-values to ordinary l-values and all other values to r-values. | |||
12433 | if (Input.isInvalid()) return ExprError(); | |||
12434 | if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { | |||
12435 | if (Input.get()->getValueKind() != VK_RValue && | |||
12436 | Input.get()->getObjectKind() == OK_Ordinary) | |||
12437 | VK = Input.get()->getValueKind(); | |||
12438 | } else if (!getLangOpts().CPlusPlus) { | |||
12439 | // In C, a volatile scalar is read by __imag. In C++, it is not. | |||
12440 | Input = DefaultLvalueConversion(Input.get()); | |||
12441 | } | |||
12442 | break; | |||
12443 | case UO_Extension: | |||
12444 | resultType = Input.get()->getType(); | |||
12445 | VK = Input.get()->getValueKind(); | |||
12446 | OK = Input.get()->getObjectKind(); | |||
12447 | break; | |||
12448 | case UO_Coawait: | |||
12449 | // It's unnecessary to represent the pass-through operator co_await in the | |||
12450 | // AST; just return the input expression instead. | |||
12451 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12453, __extension__ __PRETTY_FUNCTION__)) | |||
12452 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12453, __extension__ __PRETTY_FUNCTION__)) | |||
12453 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12453, __extension__ __PRETTY_FUNCTION__)); | |||
12454 | return Input; | |||
12455 | } | |||
12456 | if (resultType.isNull() || Input.isInvalid()) | |||
12457 | return ExprError(); | |||
12458 | ||||
12459 | // Check for array bounds violations in the operand of the UnaryOperator, | |||
12460 | // except for the '*' and '&' operators that have to be handled specially | |||
12461 | // by CheckArrayAccess (as there are special cases like &array[arraysize] | |||
12462 | // that are explicitly defined as valid by the standard). | |||
12463 | if (Opc != UO_AddrOf && Opc != UO_Deref) | |||
12464 | CheckArrayAccess(Input.get()); | |||
12465 | ||||
12466 | auto *UO = new (Context) | |||
12467 | UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); | |||
12468 | // Convert the result back to a half vector. | |||
12469 | if (ConvertHalfVec) | |||
12470 | return convertVector(UO, Context.HalfTy, *this); | |||
12471 | return UO; | |||
12472 | } | |||
12473 | ||||
12474 | /// \brief Determine whether the given expression is a qualified member | |||
12475 | /// access expression, of a form that could be turned into a pointer to member | |||
12476 | /// with the address-of operator. | |||
12477 | static bool isQualifiedMemberAccess(Expr *E) { | |||
12478 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
12479 | if (!DRE->getQualifier()) | |||
12480 | return false; | |||
12481 | ||||
12482 | ValueDecl *VD = DRE->getDecl(); | |||
12483 | if (!VD->isCXXClassMember()) | |||
12484 | return false; | |||
12485 | ||||
12486 | if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) | |||
12487 | return true; | |||
12488 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) | |||
12489 | return Method->isInstance(); | |||
12490 | ||||
12491 | return false; | |||
12492 | } | |||
12493 | ||||
12494 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { | |||
12495 | if (!ULE->getQualifier()) | |||
12496 | return false; | |||
12497 | ||||
12498 | for (NamedDecl *D : ULE->decls()) { | |||
12499 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { | |||
12500 | if (Method->isInstance()) | |||
12501 | return true; | |||
12502 | } else { | |||
12503 | // Overload set does not contain methods. | |||
12504 | break; | |||
12505 | } | |||
12506 | } | |||
12507 | ||||
12508 | return false; | |||
12509 | } | |||
12510 | ||||
12511 | return false; | |||
12512 | } | |||
12513 | ||||
12514 | ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, | |||
12515 | UnaryOperatorKind Opc, Expr *Input) { | |||
12516 | // First things first: handle placeholders so that the | |||
12517 | // overloaded-operator check considers the right type. | |||
12518 | if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { | |||
12519 | // Increment and decrement of pseudo-object references. | |||
12520 | if (pty->getKind() == BuiltinType::PseudoObject && | |||
12521 | UnaryOperator::isIncrementDecrementOp(Opc)) | |||
12522 | return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); | |||
12523 | ||||
12524 | // extension is always a builtin operator. | |||
12525 | if (Opc == UO_Extension) | |||
12526 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | |||
12527 | ||||
12528 | // & gets special logic for several kinds of placeholder. | |||
12529 | // The builtin code knows what to do. | |||
12530 | if (Opc == UO_AddrOf && | |||
12531 | (pty->getKind() == BuiltinType::Overload || | |||
12532 | pty->getKind() == BuiltinType::UnknownAny || | |||
12533 | pty->getKind() == BuiltinType::BoundMember)) | |||
12534 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | |||
12535 | ||||
12536 | // Anything else needs to be handled now. | |||
12537 | ExprResult Result = CheckPlaceholderExpr(Input); | |||
12538 | if (Result.isInvalid()) return ExprError(); | |||
12539 | Input = Result.get(); | |||
12540 | } | |||
12541 | ||||
12542 | if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && | |||
12543 | UnaryOperator::getOverloadedOperator(Opc) != OO_None && | |||
12544 | !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { | |||
12545 | // Find all of the overloaded operators visible from this | |||
12546 | // point. We perform both an operator-name lookup from the local | |||
12547 | // scope and an argument-dependent lookup based on the types of | |||
12548 | // the arguments. | |||
12549 | UnresolvedSet<16> Functions; | |||
12550 | OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); | |||
12551 | if (S && OverOp != OO_None) | |||
12552 | LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), | |||
12553 | Functions); | |||
12554 | ||||
12555 | return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); | |||
12556 | } | |||
12557 | ||||
12558 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | |||
12559 | } | |||
12560 | ||||
12561 | // Unary Operators. 'Tok' is the token for the operator. | |||
12562 | ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, | |||
12563 | tok::TokenKind Op, Expr *Input) { | |||
12564 | return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); | |||
12565 | } | |||
12566 | ||||
12567 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". | |||
12568 | ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, | |||
12569 | LabelDecl *TheDecl) { | |||
12570 | TheDecl->markUsed(Context); | |||
12571 | // Create the AST node. The address of a label always has type 'void*'. | |||
12572 | return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, | |||
12573 | Context.getPointerType(Context.VoidTy)); | |||
12574 | } | |||
12575 | ||||
12576 | /// Given the last statement in a statement-expression, check whether | |||
12577 | /// the result is a producing expression (like a call to an | |||
12578 | /// ns_returns_retained function) and, if so, rebuild it to hoist the | |||
12579 | /// release out of the full-expression. Otherwise, return null. | |||
12580 | /// Cannot fail. | |||
12581 | static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { | |||
12582 | // Should always be wrapped with one of these. | |||
12583 | ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); | |||
12584 | if (!cleanups) return nullptr; | |||
12585 | ||||
12586 | ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); | |||
12587 | if (!cast || cast->getCastKind() != CK_ARCConsumeObject) | |||
12588 | return nullptr; | |||
12589 | ||||
12590 | // Splice out the cast. This shouldn't modify any interesting | |||
12591 | // features of the statement. | |||
12592 | Expr *producer = cast->getSubExpr(); | |||
12593 | assert(producer->getType() == cast->getType())(static_cast <bool> (producer->getType() == cast-> getType()) ? void (0) : __assert_fail ("producer->getType() == cast->getType()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12593, __extension__ __PRETTY_FUNCTION__)); | |||
12594 | assert(producer->getValueKind() == cast->getValueKind())(static_cast <bool> (producer->getValueKind() == cast ->getValueKind()) ? void (0) : __assert_fail ("producer->getValueKind() == cast->getValueKind()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12594, __extension__ __PRETTY_FUNCTION__)); | |||
12595 | cleanups->setSubExpr(producer); | |||
12596 | return cleanups; | |||
12597 | } | |||
12598 | ||||
12599 | void Sema::ActOnStartStmtExpr() { | |||
12600 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | |||
12601 | } | |||
12602 | ||||
12603 | void Sema::ActOnStmtExprError() { | |||
12604 | // Note that function is also called by TreeTransform when leaving a | |||
12605 | // StmtExpr scope without rebuilding anything. | |||
12606 | ||||
12607 | DiscardCleanupsInEvaluationContext(); | |||
12608 | PopExpressionEvaluationContext(); | |||
12609 | } | |||
12610 | ||||
12611 | ExprResult | |||
12612 | Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, | |||
12613 | SourceLocation RPLoc) { // "({..})" | |||
12614 | 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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12614, __extension__ __PRETTY_FUNCTION__)); | |||
12615 | CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); | |||
12616 | ||||
12617 | if (hasAnyUnrecoverableErrorsInThisFunction()) | |||
12618 | DiscardCleanupsInEvaluationContext(); | |||
12619 | 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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12620, __extension__ __PRETTY_FUNCTION__)) | |||
12620 | "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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12620, __extension__ __PRETTY_FUNCTION__)); | |||
12621 | PopExpressionEvaluationContext(); | |||
12622 | ||||
12623 | // FIXME: there are a variety of strange constraints to enforce here, for | |||
12624 | // example, it is not possible to goto into a stmt expression apparently. | |||
12625 | // More semantic analysis is needed. | |||
12626 | ||||
12627 | // If there are sub-stmts in the compound stmt, take the type of the last one | |||
12628 | // as the type of the stmtexpr. | |||
12629 | QualType Ty = Context.VoidTy; | |||
12630 | bool StmtExprMayBindToTemp = false; | |||
12631 | if (!Compound->body_empty()) { | |||
12632 | Stmt *LastStmt = Compound->body_back(); | |||
12633 | LabelStmt *LastLabelStmt = nullptr; | |||
12634 | // If LastStmt is a label, skip down through into the body. | |||
12635 | while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { | |||
12636 | LastLabelStmt = Label; | |||
12637 | LastStmt = Label->getSubStmt(); | |||
12638 | } | |||
12639 | ||||
12640 | if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { | |||
12641 | // Do function/array conversion on the last expression, but not | |||
12642 | // lvalue-to-rvalue. However, initialize an unqualified type. | |||
12643 | ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); | |||
12644 | if (LastExpr.isInvalid()) | |||
12645 | return ExprError(); | |||
12646 | Ty = LastExpr.get()->getType().getUnqualifiedType(); | |||
12647 | ||||
12648 | if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { | |||
12649 | // In ARC, if the final expression ends in a consume, splice | |||
12650 | // the consume out and bind it later. In the alternate case | |||
12651 | // (when dealing with a retainable type), the result | |||
12652 | // initialization will create a produce. In both cases the | |||
12653 | // result will be +1, and we'll need to balance that out with | |||
12654 | // a bind. | |||
12655 | if (Expr *rebuiltLastStmt | |||
12656 | = maybeRebuildARCConsumingStmt(LastExpr.get())) { | |||
12657 | LastExpr = rebuiltLastStmt; | |||
12658 | } else { | |||
12659 | LastExpr = PerformCopyInitialization( | |||
12660 | InitializedEntity::InitializeResult(LPLoc, | |||
12661 | Ty, | |||
12662 | false), | |||
12663 | SourceLocation(), | |||
12664 | LastExpr); | |||
12665 | } | |||
12666 | ||||
12667 | if (LastExpr.isInvalid()) | |||
12668 | return ExprError(); | |||
12669 | if (LastExpr.get() != nullptr) { | |||
12670 | if (!LastLabelStmt) | |||
12671 | Compound->setLastStmt(LastExpr.get()); | |||
12672 | else | |||
12673 | LastLabelStmt->setSubStmt(LastExpr.get()); | |||
12674 | StmtExprMayBindToTemp = true; | |||
12675 | } | |||
12676 | } | |||
12677 | } | |||
12678 | } | |||
12679 | ||||
12680 | // FIXME: Check that expression type is complete/non-abstract; statement | |||
12681 | // expressions are not lvalues. | |||
12682 | Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); | |||
12683 | if (StmtExprMayBindToTemp) | |||
12684 | return MaybeBindToTemporary(ResStmtExpr); | |||
12685 | return ResStmtExpr; | |||
12686 | } | |||
12687 | ||||
12688 | ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, | |||
12689 | TypeSourceInfo *TInfo, | |||
12690 | ArrayRef<OffsetOfComponent> Components, | |||
12691 | SourceLocation RParenLoc) { | |||
12692 | QualType ArgTy = TInfo->getType(); | |||
12693 | bool Dependent = ArgTy->isDependentType(); | |||
12694 | SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); | |||
12695 | ||||
12696 | // We must have at least one component that refers to the type, and the first | |||
12697 | // one is known to be a field designator. Verify that the ArgTy represents | |||
12698 | // a struct/union/class. | |||
12699 | if (!Dependent && !ArgTy->isRecordType()) | |||
12700 | return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) | |||
12701 | << ArgTy << TypeRange); | |||
12702 | ||||
12703 | // Type must be complete per C99 7.17p3 because a declaring a variable | |||
12704 | // with an incomplete type would be ill-formed. | |||
12705 | if (!Dependent | |||
12706 | && RequireCompleteType(BuiltinLoc, ArgTy, | |||
12707 | diag::err_offsetof_incomplete_type, TypeRange)) | |||
12708 | return ExprError(); | |||
12709 | ||||
12710 | bool DidWarnAboutNonPOD = false; | |||
12711 | QualType CurrentType = ArgTy; | |||
12712 | SmallVector<OffsetOfNode, 4> Comps; | |||
12713 | SmallVector<Expr*, 4> Exprs; | |||
12714 | for (const OffsetOfComponent &OC : Components) { | |||
12715 | if (OC.isBrackets) { | |||
12716 | // Offset of an array sub-field. TODO: Should we allow vector elements? | |||
12717 | if (!CurrentType->isDependentType()) { | |||
12718 | const ArrayType *AT = Context.getAsArrayType(CurrentType); | |||
12719 | if(!AT) | |||
12720 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) | |||
12721 | << CurrentType); | |||
12722 | CurrentType = AT->getElementType(); | |||
12723 | } else | |||
12724 | CurrentType = Context.DependentTy; | |||
12725 | ||||
12726 | ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); | |||
12727 | if (IdxRval.isInvalid()) | |||
12728 | return ExprError(); | |||
12729 | Expr *Idx = IdxRval.get(); | |||
12730 | ||||
12731 | // The expression must be an integral expression. | |||
12732 | // FIXME: An integral constant expression? | |||
12733 | if (!Idx->isTypeDependent() && !Idx->isValueDependent() && | |||
12734 | !Idx->getType()->isIntegerType()) | |||
12735 | return ExprError(Diag(Idx->getLocStart(), | |||
12736 | diag::err_typecheck_subscript_not_integer) | |||
12737 | << Idx->getSourceRange()); | |||
12738 | ||||
12739 | // Record this array index. | |||
12740 | Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); | |||
12741 | Exprs.push_back(Idx); | |||
12742 | continue; | |||
12743 | } | |||
12744 | ||||
12745 | // Offset of a field. | |||
12746 | if (CurrentType->isDependentType()) { | |||
12747 | // We have the offset of a field, but we can't look into the dependent | |||
12748 | // type. Just record the identifier of the field. | |||
12749 | Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); | |||
12750 | CurrentType = Context.DependentTy; | |||
12751 | continue; | |||
12752 | } | |||
12753 | ||||
12754 | // We need to have a complete type to look into. | |||
12755 | if (RequireCompleteType(OC.LocStart, CurrentType, | |||
12756 | diag::err_offsetof_incomplete_type)) | |||
12757 | return ExprError(); | |||
12758 | ||||
12759 | // Look for the designated field. | |||
12760 | const RecordType *RC = CurrentType->getAs<RecordType>(); | |||
12761 | if (!RC) | |||
12762 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) | |||
12763 | << CurrentType); | |||
12764 | RecordDecl *RD = RC->getDecl(); | |||
12765 | ||||
12766 | // C++ [lib.support.types]p5: | |||
12767 | // The macro offsetof accepts a restricted set of type arguments in this | |||
12768 | // International Standard. type shall be a POD structure or a POD union | |||
12769 | // (clause 9). | |||
12770 | // C++11 [support.types]p4: | |||
12771 | // If type is not a standard-layout class (Clause 9), the results are | |||
12772 | // undefined. | |||
12773 | if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { | |||
12774 | bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); | |||
12775 | unsigned DiagID = | |||
12776 | LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type | |||
12777 | : diag::ext_offsetof_non_pod_type; | |||
12778 | ||||
12779 | if (!IsSafe && !DidWarnAboutNonPOD && | |||
12780 | DiagRuntimeBehavior(BuiltinLoc, nullptr, | |||
12781 | PDiag(DiagID) | |||
12782 | << SourceRange(Components[0].LocStart, OC.LocEnd) | |||
12783 | << CurrentType)) | |||
12784 | DidWarnAboutNonPOD = true; | |||
12785 | } | |||
12786 | ||||
12787 | // Look for the field. | |||
12788 | LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); | |||
12789 | LookupQualifiedName(R, RD); | |||
12790 | FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); | |||
12791 | IndirectFieldDecl *IndirectMemberDecl = nullptr; | |||
12792 | if (!MemberDecl) { | |||
12793 | if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) | |||
12794 | MemberDecl = IndirectMemberDecl->getAnonField(); | |||
12795 | } | |||
12796 | ||||
12797 | if (!MemberDecl) | |||
12798 | return ExprError(Diag(BuiltinLoc, diag::err_no_member) | |||
12799 | << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, | |||
12800 | OC.LocEnd)); | |||
12801 | ||||
12802 | // C99 7.17p3: | |||
12803 | // (If the specified member is a bit-field, the behavior is undefined.) | |||
12804 | // | |||
12805 | // We diagnose this as an error. | |||
12806 | if (MemberDecl->isBitField()) { | |||
12807 | Diag(OC.LocEnd, diag::err_offsetof_bitfield) | |||
12808 | << MemberDecl->getDeclName() | |||
12809 | << SourceRange(BuiltinLoc, RParenLoc); | |||
12810 | Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); | |||
12811 | return ExprError(); | |||
12812 | } | |||
12813 | ||||
12814 | RecordDecl *Parent = MemberDecl->getParent(); | |||
12815 | if (IndirectMemberDecl) | |||
12816 | Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); | |||
12817 | ||||
12818 | // If the member was found in a base class, introduce OffsetOfNodes for | |||
12819 | // the base class indirections. | |||
12820 | CXXBasePaths Paths; | |||
12821 | if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), | |||
12822 | Paths)) { | |||
12823 | if (Paths.getDetectedVirtual()) { | |||
12824 | Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) | |||
12825 | << MemberDecl->getDeclName() | |||
12826 | << SourceRange(BuiltinLoc, RParenLoc); | |||
12827 | return ExprError(); | |||
12828 | } | |||
12829 | ||||
12830 | CXXBasePath &Path = Paths.front(); | |||
12831 | for (const CXXBasePathElement &B : Path) | |||
12832 | Comps.push_back(OffsetOfNode(B.Base)); | |||
12833 | } | |||
12834 | ||||
12835 | if (IndirectMemberDecl) { | |||
12836 | for (auto *FI : IndirectMemberDecl->chain()) { | |||
12837 | assert(isa<FieldDecl>(FI))(static_cast <bool> (isa<FieldDecl>(FI)) ? void ( 0) : __assert_fail ("isa<FieldDecl>(FI)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12837, __extension__ __PRETTY_FUNCTION__)); | |||
12838 | Comps.push_back(OffsetOfNode(OC.LocStart, | |||
12839 | cast<FieldDecl>(FI), OC.LocEnd)); | |||
12840 | } | |||
12841 | } else | |||
12842 | Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); | |||
12843 | ||||
12844 | CurrentType = MemberDecl->getType().getNonReferenceType(); | |||
12845 | } | |||
12846 | ||||
12847 | return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, | |||
12848 | Comps, Exprs, RParenLoc); | |||
12849 | } | |||
12850 | ||||
12851 | ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, | |||
12852 | SourceLocation BuiltinLoc, | |||
12853 | SourceLocation TypeLoc, | |||
12854 | ParsedType ParsedArgTy, | |||
12855 | ArrayRef<OffsetOfComponent> Components, | |||
12856 | SourceLocation RParenLoc) { | |||
12857 | ||||
12858 | TypeSourceInfo *ArgTInfo; | |||
12859 | QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); | |||
12860 | if (ArgTy.isNull()) | |||
12861 | return ExprError(); | |||
12862 | ||||
12863 | if (!ArgTInfo) | |||
12864 | ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); | |||
12865 | ||||
12866 | return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); | |||
12867 | } | |||
12868 | ||||
12869 | ||||
12870 | ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, | |||
12871 | Expr *CondExpr, | |||
12872 | Expr *LHSExpr, Expr *RHSExpr, | |||
12873 | SourceLocation RPLoc) { | |||
12874 | 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)\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12874, __extension__ __PRETTY_FUNCTION__)); | |||
12875 | ||||
12876 | ExprValueKind VK = VK_RValue; | |||
12877 | ExprObjectKind OK = OK_Ordinary; | |||
12878 | QualType resType; | |||
12879 | bool ValueDependent = false; | |||
12880 | bool CondIsTrue = false; | |||
12881 | if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { | |||
12882 | resType = Context.DependentTy; | |||
12883 | ValueDependent = true; | |||
12884 | } else { | |||
12885 | // The conditional expression is required to be a constant expression. | |||
12886 | llvm::APSInt condEval(32); | |||
12887 | ExprResult CondICE | |||
12888 | = VerifyIntegerConstantExpression(CondExpr, &condEval, | |||
12889 | diag::err_typecheck_choose_expr_requires_constant, false); | |||
12890 | if (CondICE.isInvalid()) | |||
12891 | return ExprError(); | |||
12892 | CondExpr = CondICE.get(); | |||
12893 | CondIsTrue = condEval.getZExtValue(); | |||
12894 | ||||
12895 | // If the condition is > zero, then the AST type is the same as the LSHExpr. | |||
12896 | Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; | |||
12897 | ||||
12898 | resType = ActiveExpr->getType(); | |||
12899 | ValueDependent = ActiveExpr->isValueDependent(); | |||
12900 | VK = ActiveExpr->getValueKind(); | |||
12901 | OK = ActiveExpr->getObjectKind(); | |||
12902 | } | |||
12903 | ||||
12904 | return new (Context) | |||
12905 | ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, | |||
12906 | CondIsTrue, resType->isDependentType(), ValueDependent); | |||
12907 | } | |||
12908 | ||||
12909 | //===----------------------------------------------------------------------===// | |||
12910 | // Clang Extensions. | |||
12911 | //===----------------------------------------------------------------------===// | |||
12912 | ||||
12913 | /// ActOnBlockStart - This callback is invoked when a block literal is started. | |||
12914 | void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { | |||
12915 | BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); | |||
12916 | ||||
12917 | if (LangOpts.CPlusPlus) { | |||
12918 | Decl *ManglingContextDecl; | |||
12919 | if (MangleNumberingContext *MCtx = | |||
12920 | getCurrentMangleNumberContext(Block->getDeclContext(), | |||
12921 | ManglingContextDecl)) { | |||
12922 | unsigned ManglingNumber = MCtx->getManglingNumber(Block); | |||
12923 | Block->setBlockMangling(ManglingNumber, ManglingContextDecl); | |||
12924 | } | |||
12925 | } | |||
12926 | ||||
12927 | PushBlockScope(CurScope, Block); | |||
12928 | CurContext->addDecl(Block); | |||
12929 | if (CurScope) | |||
12930 | PushDeclContext(CurScope, Block); | |||
12931 | else | |||
12932 | CurContext = Block; | |||
12933 | ||||
12934 | getCurBlock()->HasImplicitReturnType = true; | |||
12935 | ||||
12936 | // Enter a new evaluation context to insulate the block from any | |||
12937 | // cleanups from the enclosing full-expression. | |||
12938 | PushExpressionEvaluationContext( | |||
12939 | ExpressionEvaluationContext::PotentiallyEvaluated); | |||
12940 | } | |||
12941 | ||||
12942 | void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, | |||
12943 | Scope *CurScope) { | |||
12944 | 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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12945, __extension__ __PRETTY_FUNCTION__)) | |||
12945 | "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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12945, __extension__ __PRETTY_FUNCTION__)); | |||
12946 | assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext)(static_cast <bool> (ParamInfo.getContext() == DeclaratorContext ::BlockLiteralContext) ? void (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12946, __extension__ __PRETTY_FUNCTION__)); | |||
12947 | BlockScopeInfo *CurBlock = getCurBlock(); | |||
12948 | ||||
12949 | TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); | |||
12950 | QualType T = Sig->getType(); | |||
12951 | ||||
12952 | // FIXME: We should allow unexpanded parameter packs here, but that would, | |||
12953 | // in turn, make the block expression contain unexpanded parameter packs. | |||
12954 | if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { | |||
12955 | // Drop the parameters. | |||
12956 | FunctionProtoType::ExtProtoInfo EPI; | |||
12957 | EPI.HasTrailingReturn = false; | |||
12958 | EPI.TypeQuals |= DeclSpec::TQ_const; | |||
12959 | T = Context.getFunctionType(Context.DependentTy, None, EPI); | |||
12960 | Sig = Context.getTrivialTypeSourceInfo(T); | |||
12961 | } | |||
12962 | ||||
12963 | // GetTypeForDeclarator always produces a function type for a block | |||
12964 | // literal signature. Furthermore, it is always a FunctionProtoType | |||
12965 | // unless the function was written with a typedef. | |||
12966 | 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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12967, __extension__ __PRETTY_FUNCTION__)) | |||
12967 | "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\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 12967, __extension__ __PRETTY_FUNCTION__)); | |||
12968 | ||||
12969 | // Look for an explicit signature in that function type. | |||
12970 | FunctionProtoTypeLoc ExplicitSignature; | |||
12971 | ||||
12972 | if ((ExplicitSignature = | |||
12973 | Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { | |||
12974 | ||||
12975 | // Check whether that explicit signature was synthesized by | |||
12976 | // GetTypeForDeclarator. If so, don't save that as part of the | |||
12977 | // written signature. | |||
12978 | if (ExplicitSignature.getLocalRangeBegin() == | |||
12979 | ExplicitSignature.getLocalRangeEnd()) { | |||
12980 | // This would be much cheaper if we stored TypeLocs instead of | |||
12981 | // TypeSourceInfos. | |||
12982 | TypeLoc Result = ExplicitSignature.getReturnLoc(); | |||
12983 | unsigned Size = Result.getFullDataSize(); | |||
12984 | Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); | |||
12985 | Sig->getTypeLoc().initializeFullCopy(Result, Size); | |||
12986 | ||||
12987 | ExplicitSignature = FunctionProtoTypeLoc(); | |||
12988 | } | |||
12989 | } | |||
12990 | ||||
12991 | CurBlock->TheDecl->setSignatureAsWritten(Sig); | |||
12992 | CurBlock->FunctionType = T; | |||
12993 | ||||
12994 | const FunctionType *Fn = T->getAs<FunctionType>(); | |||
12995 | QualType RetTy = Fn->getReturnType(); | |||
12996 | bool isVariadic = | |||
12997 | (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); | |||
12998 | ||||
12999 | CurBlock->TheDecl->setIsVariadic(isVariadic); | |||
13000 | ||||
13001 | // Context.DependentTy is used as a placeholder for a missing block | |||
13002 | // return type. TODO: what should we do with declarators like: | |||
13003 | // ^ * { ... } | |||
13004 | // If the answer is "apply template argument deduction".... | |||
13005 | if (RetTy != Context.DependentTy) { | |||
13006 | CurBlock->ReturnType = RetTy; | |||
13007 | CurBlock->TheDecl->setBlockMissingReturnType(false); | |||
13008 | CurBlock->HasImplicitReturnType = false; | |||
13009 | } | |||
13010 | ||||
13011 | // Push block parameters from the declarator if we had them. | |||
13012 | SmallVector<ParmVarDecl*, 8> Params; | |||
13013 | if (ExplicitSignature) { | |||
13014 | for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { | |||
13015 | ParmVarDecl *Param = ExplicitSignature.getParam(I); | |||
13016 | if (Param->getIdentifier() == nullptr && | |||
13017 | !Param->isImplicit() && | |||
13018 | !Param->isInvalidDecl() && | |||
13019 | !getLangOpts().CPlusPlus) | |||
13020 | Diag(Param->getLocation(), diag::err_parameter_name_omitted); | |||
13021 | Params.push_back(Param); | |||
13022 | } | |||
13023 | ||||
13024 | // Fake up parameter variables if we have a typedef, like | |||
13025 | // ^ fntype { ... } | |||
13026 | } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { | |||
13027 | for (const auto &I : Fn->param_types()) { | |||
13028 | ParmVarDecl *Param = BuildParmVarDeclForTypedef( | |||
13029 | CurBlock->TheDecl, ParamInfo.getLocStart(), I); | |||
13030 | Params.push_back(Param); | |||
13031 | } | |||
13032 | } | |||
13033 | ||||
13034 | // Set the parameters on the block decl. | |||
13035 | if (!Params.empty()) { | |||
13036 | CurBlock->TheDecl->setParams(Params); | |||
13037 | CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), | |||
13038 | /*CheckParameterNames=*/false); | |||
13039 | } | |||
13040 | ||||
13041 | // Finally we can process decl attributes. | |||
13042 | ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); | |||
13043 | ||||
13044 | // Put the parameter variables in scope. | |||
13045 | for (auto AI : CurBlock->TheDecl->parameters()) { | |||
13046 | AI->setOwningFunction(CurBlock->TheDecl); | |||
13047 | ||||
13048 | // If this has an identifier, add it to the scope stack. | |||
13049 | if (AI->getIdentifier()) { | |||
13050 | CheckShadow(CurBlock->TheScope, AI); | |||
13051 | ||||
13052 | PushOnScopeChains(AI, CurBlock->TheScope); | |||
13053 | } | |||
13054 | } | |||
13055 | } | |||
13056 | ||||
13057 | /// ActOnBlockError - If there is an error parsing a block, this callback | |||
13058 | /// is invoked to pop the information about the block from the action impl. | |||
13059 | void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { | |||
13060 | // Leave the expression-evaluation context. | |||
13061 | DiscardCleanupsInEvaluationContext(); | |||
13062 | PopExpressionEvaluationContext(); | |||
13063 | ||||
13064 | // Pop off CurBlock, handle nested blocks. | |||
13065 | PopDeclContext(); | |||
13066 | PopFunctionScopeInfo(); | |||
13067 | } | |||
13068 | ||||
13069 | /// ActOnBlockStmtExpr - This is called when the body of a block statement | |||
13070 | /// literal was successfully completed. ^(int x){...} | |||
13071 | ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, | |||
13072 | Stmt *Body, Scope *CurScope) { | |||
13073 | // If blocks are disabled, emit an error. | |||
13074 | if (!LangOpts.Blocks) | |||
13075 | Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; | |||
13076 | ||||
13077 | // Leave the expression-evaluation context. | |||
13078 | if (hasAnyUnrecoverableErrorsInThisFunction()) | |||
13079 | DiscardCleanupsInEvaluationContext(); | |||
13080 | 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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 13081, __extension__ __PRETTY_FUNCTION__)) | |||
13081 | "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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 13081, __extension__ __PRETTY_FUNCTION__)); | |||
13082 | PopExpressionEvaluationContext(); | |||
13083 | ||||
13084 | BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); | |||
13085 | ||||
13086 | if (BSI->HasImplicitReturnType) | |||
13087 | deduceClosureReturnType(*BSI); | |||
13088 | ||||
13089 | PopDeclContext(); | |||
13090 | ||||
13091 | QualType RetTy = Context.VoidTy; | |||
13092 | if (!BSI->ReturnType.isNull()) | |||
13093 | RetTy = BSI->ReturnType; | |||
13094 | ||||
13095 | bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); | |||
13096 | QualType BlockTy; | |||
13097 | ||||
13098 | // Set the captured variables on the block. | |||
13099 | // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! | |||
13100 | SmallVector<BlockDecl::Capture, 4> Captures; | |||
13101 | for (Capture &Cap : BSI->Captures) { | |||
13102 | if (Cap.isThisCapture()) | |||
13103 | continue; | |||
13104 | BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), | |||
13105 | Cap.isNested(), Cap.getInitExpr()); | |||
13106 | Captures.push_back(NewCap); | |||
13107 | } | |||
13108 | BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); | |||
13109 | ||||
13110 | // If the user wrote a function type in some form, try to use that. | |||
13111 | if (!BSI->FunctionType.isNull()) { | |||
13112 | const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); | |||
13113 | ||||
13114 | FunctionType::ExtInfo Ext = FTy->getExtInfo(); | |||
13115 | if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); | |||
13116 | ||||
13117 | // Turn protoless block types into nullary block types. | |||
13118 | if (isa<FunctionNoProtoType>(FTy)) { | |||
13119 | FunctionProtoType::ExtProtoInfo EPI; | |||
13120 | EPI.ExtInfo = Ext; | |||
13121 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | |||
13122 | ||||
13123 | // Otherwise, if we don't need to change anything about the function type, | |||
13124 | // preserve its sugar structure. | |||
13125 | } else if (FTy->getReturnType() == RetTy && | |||
13126 | (!NoReturn || FTy->getNoReturnAttr())) { | |||
13127 | BlockTy = BSI->FunctionType; | |||
13128 | ||||
13129 | // Otherwise, make the minimal modifications to the function type. | |||
13130 | } else { | |||
13131 | const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); | |||
13132 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | |||
13133 | EPI.TypeQuals = 0; // FIXME: silently? | |||
13134 | EPI.ExtInfo = Ext; | |||
13135 | BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); | |||
13136 | } | |||
13137 | ||||
13138 | // If we don't have a function type, just build one from nothing. | |||
13139 | } else { | |||
13140 | FunctionProtoType::ExtProtoInfo EPI; | |||
13141 | EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); | |||
13142 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | |||
13143 | } | |||
13144 | ||||
13145 | DiagnoseUnusedParameters(BSI->TheDecl->parameters()); | |||
13146 | BlockTy = Context.getBlockPointerType(BlockTy); | |||
13147 | ||||
13148 | // If needed, diagnose invalid gotos and switches in the block. | |||
13149 | if (getCurFunction()->NeedsScopeChecking() && | |||
13150 | !PP.isCodeCompletionEnabled()) | |||
13151 | DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); | |||
13152 | ||||
13153 | BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); | |||
13154 | ||||
13155 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | |||
13156 | DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); | |||
13157 | ||||
13158 | // Try to apply the named return value optimization. We have to check again | |||
13159 | // if we can do this, though, because blocks keep return statements around | |||
13160 | // to deduce an implicit return type. | |||
13161 | if (getLangOpts().CPlusPlus && RetTy->isRecordType() && | |||
13162 | !BSI->TheDecl->isDependentContext()) | |||
13163 | computeNRVO(Body, BSI); | |||
13164 | ||||
13165 | BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); | |||
13166 | AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | |||
13167 | PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); | |||
13168 | ||||
13169 | // If the block isn't obviously global, i.e. it captures anything at | |||
13170 | // all, then we need to do a few things in the surrounding context: | |||
13171 | if (Result->getBlockDecl()->hasCaptures()) { | |||
13172 | // First, this expression has a new cleanup object. | |||
13173 | ExprCleanupObjects.push_back(Result->getBlockDecl()); | |||
13174 | Cleanup.setExprNeedsCleanups(true); | |||
13175 | ||||
13176 | // It also gets a branch-protected scope if any of the captured | |||
13177 | // variables needs destruction. | |||
13178 | for (const auto &CI : Result->getBlockDecl()->captures()) { | |||
13179 | const VarDecl *var = CI.getVariable(); | |||
13180 | if (var->getType().isDestructedType() != QualType::DK_none) { | |||
13181 | setFunctionHasBranchProtectedScope(); | |||
13182 | break; | |||
13183 | } | |||
13184 | } | |||
13185 | } | |||
13186 | ||||
13187 | return Result; | |||
13188 | } | |||
13189 | ||||
13190 | ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, | |||
13191 | SourceLocation RPLoc) { | |||
13192 | TypeSourceInfo *TInfo; | |||
13193 | GetTypeFromParser(Ty, &TInfo); | |||
13194 | return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); | |||
13195 | } | |||
13196 | ||||
13197 | ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, | |||
13198 | Expr *E, TypeSourceInfo *TInfo, | |||
13199 | SourceLocation RPLoc) { | |||
13200 | Expr *OrigExpr = E; | |||
13201 | bool IsMS = false; | |||
13202 | ||||
13203 | // CUDA device code does not support varargs. | |||
13204 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { | |||
13205 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { | |||
13206 | CUDAFunctionTarget T = IdentifyCUDATarget(F); | |||
13207 | if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) | |||
13208 | return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); | |||
13209 | } | |||
13210 | } | |||
13211 | ||||
13212 | // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() | |||
13213 | // as Microsoft ABI on an actual Microsoft platform, where | |||
13214 | // __builtin_ms_va_list and __builtin_va_list are the same.) | |||
13215 | if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && | |||
13216 | Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { | |||
13217 | QualType MSVaListType = Context.getBuiltinMSVaListType(); | |||
13218 | if (Context.hasSameType(MSVaListType, E->getType())) { | |||
13219 | if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) | |||
13220 | return ExprError(); | |||
13221 | IsMS = true; | |||
13222 | } | |||
13223 | } | |||
13224 | ||||
13225 | // Get the va_list type | |||
13226 | QualType VaListType = Context.getBuiltinVaListType(); | |||
13227 | if (!IsMS) { | |||
13228 | if (VaListType->isArrayType()) { | |||
13229 | // Deal with implicit array decay; for example, on x86-64, | |||
13230 | // va_list is an array, but it's supposed to decay to | |||
13231 | // a pointer for va_arg. | |||
13232 | VaListType = Context.getArrayDecayedType(VaListType); | |||
13233 | // Make sure the input expression also decays appropriately. | |||
13234 | ExprResult Result = UsualUnaryConversions(E); | |||
13235 | if (Result.isInvalid()) | |||
13236 | return ExprError(); | |||
13237 | E = Result.get(); | |||
13238 | } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { | |||
13239 | // If va_list is a record type and we are compiling in C++ mode, | |||
13240 | // check the argument using reference binding. | |||
13241 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | |||
13242 | Context, Context.getLValueReferenceType(VaListType), false); | |||
13243 | ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); | |||
13244 | if (Init.isInvalid()) | |||
13245 | return ExprError(); | |||
13246 | E = Init.getAs<Expr>(); | |||
13247 | } else { | |||
13248 | // Otherwise, the va_list argument must be an l-value because | |||
13249 | // it is modified by va_arg. | |||
13250 | if (!E->isTypeDependent() && | |||
13251 | CheckForModifiableLvalue(E, BuiltinLoc, *this)) | |||
13252 | return ExprError(); | |||
13253 | } | |||
13254 | } | |||
13255 | ||||
13256 | if (!IsMS && !E->isTypeDependent() && | |||
13257 | !Context.hasSameType(VaListType, E->getType())) | |||
13258 | return ExprError(Diag(E->getLocStart(), | |||
13259 | diag::err_first_argument_to_va_arg_not_of_type_va_list) | |||
13260 | << OrigExpr->getType() << E->getSourceRange()); | |||
13261 | ||||
13262 | if (!TInfo->getType()->isDependentType()) { | |||
13263 | if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), | |||
13264 | diag::err_second_parameter_to_va_arg_incomplete, | |||
13265 | TInfo->getTypeLoc())) | |||
13266 | return ExprError(); | |||
13267 | ||||
13268 | if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), | |||
13269 | TInfo->getType(), | |||
13270 | diag::err_second_parameter_to_va_arg_abstract, | |||
13271 | TInfo->getTypeLoc())) | |||
13272 | return ExprError(); | |||
13273 | ||||
13274 | if (!TInfo->getType().isPODType(Context)) { | |||
13275 | Diag(TInfo->getTypeLoc().getBeginLoc(), | |||
13276 | TInfo->getType()->isObjCLifetimeType() | |||
13277 | ? diag::warn_second_parameter_to_va_arg_ownership_qualified | |||
13278 | : diag::warn_second_parameter_to_va_arg_not_pod) | |||
13279 | << TInfo->getType() | |||
13280 | << TInfo->getTypeLoc().getSourceRange(); | |||
13281 | } | |||
13282 | ||||
13283 | // Check for va_arg where arguments of the given type will be promoted | |||
13284 | // (i.e. this va_arg is guaranteed to have undefined behavior). | |||
13285 | QualType PromoteType; | |||
13286 | if (TInfo->getType()->isPromotableIntegerType()) { | |||
13287 | PromoteType = Context.getPromotedIntegerType(TInfo->getType()); | |||
13288 | if (Context.typesAreCompatible(PromoteType, TInfo->getType())) | |||
13289 | PromoteType = QualType(); | |||
13290 | } | |||
13291 | if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) | |||
13292 | PromoteType = Context.DoubleTy; | |||
13293 | if (!PromoteType.isNull()) | |||
13294 | DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, | |||
13295 | PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) | |||
13296 | << TInfo->getType() | |||
13297 | << PromoteType | |||
13298 | << TInfo->getTypeLoc().getSourceRange()); | |||
13299 | } | |||
13300 | ||||
13301 | QualType T = TInfo->getType().getNonLValueExprType(Context); | |||
13302 | return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); | |||
13303 | } | |||
13304 | ||||
13305 | ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { | |||
13306 | // The type of __null will be int or long, depending on the size of | |||
13307 | // pointers on the target. | |||
13308 | QualType Ty; | |||
13309 | unsigned pw = Context.getTargetInfo().getPointerWidth(0); | |||
13310 | if (pw == Context.getTargetInfo().getIntWidth()) | |||
13311 | Ty = Context.IntTy; | |||
13312 | else if (pw == Context.getTargetInfo().getLongWidth()) | |||
13313 | Ty = Context.LongTy; | |||
13314 | else if (pw == Context.getTargetInfo().getLongLongWidth()) | |||
13315 | Ty = Context.LongLongTy; | |||
13316 | else { | |||
13317 | llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 13317); | |||
13318 | } | |||
13319 | ||||
13320 | return new (Context) GNUNullExpr(Ty, TokenLoc); | |||
13321 | } | |||
13322 | ||||
13323 | bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, | |||
13324 | bool Diagnose) { | |||
13325 | if (!getLangOpts().ObjC1) | |||
13326 | return false; | |||
13327 | ||||
13328 | const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); | |||
13329 | if (!PT) | |||
13330 | return false; | |||
13331 | ||||
13332 | if (!PT->isObjCIdType()) { | |||
13333 | // Check if the destination is the 'NSString' interface. | |||
13334 | const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); | |||
13335 | if (!ID || !ID->getIdentifier()->isStr("NSString")) | |||
13336 | return false; | |||
13337 | } | |||
13338 | ||||
13339 | // Ignore any parens, implicit casts (should only be | |||
13340 | // array-to-pointer decays), and not-so-opaque values. The last is | |||
13341 | // important for making this trigger for property assignments. | |||
13342 | Expr *SrcExpr = Exp->IgnoreParenImpCasts(); | |||
13343 | if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) | |||
13344 | if (OV->getSourceExpr()) | |||
13345 | SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); | |||
13346 | ||||
13347 | StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); | |||
13348 | if (!SL || !SL->isAscii()) | |||
13349 | return false; | |||
13350 | if (Diagnose) { | |||
13351 | Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) | |||
13352 | << FixItHint::CreateInsertion(SL->getLocStart(), "@"); | |||
13353 | Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); | |||
13354 | } | |||
13355 | return true; | |||
13356 | } | |||
13357 | ||||
13358 | static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, | |||
13359 | const Expr *SrcExpr) { | |||
13360 | if (!DstType->isFunctionPointerType() || | |||
13361 | !SrcExpr->getType()->isFunctionType()) | |||
13362 | return false; | |||
13363 | ||||
13364 | auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); | |||
13365 | if (!DRE) | |||
13366 | return false; | |||
13367 | ||||
13368 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); | |||
13369 | if (!FD) | |||
13370 | return false; | |||
13371 | ||||
13372 | return !S.checkAddressOfFunctionIsAvailable(FD, | |||
13373 | /*Complain=*/true, | |||
13374 | SrcExpr->getLocStart()); | |||
13375 | } | |||
13376 | ||||
13377 | bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, | |||
13378 | SourceLocation Loc, | |||
13379 | QualType DstType, QualType SrcType, | |||
13380 | Expr *SrcExpr, AssignmentAction Action, | |||
13381 | bool *Complained) { | |||
13382 | if (Complained) | |||
13383 | *Complained = false; | |||
13384 | ||||
13385 | // Decode the result (notice that AST's are still created for extensions). | |||
13386 | bool CheckInferredResultType = false; | |||
13387 | bool isInvalid = false; | |||
13388 | unsigned DiagKind = 0; | |||
13389 | FixItHint Hint; | |||
13390 | ConversionFixItGenerator ConvHints; | |||
13391 | bool MayHaveConvFixit = false; | |||
13392 | bool MayHaveFunctionDiff = false; | |||
13393 | const ObjCInterfaceDecl *IFace = nullptr; | |||
13394 | const ObjCProtocolDecl *PDecl = nullptr; | |||
13395 | ||||
13396 | switch (ConvTy) { | |||
13397 | case Compatible: | |||
13398 | DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); | |||
13399 | return false; | |||
13400 | ||||
13401 | case PointerToInt: | |||
13402 | DiagKind = diag::ext_typecheck_convert_pointer_int; | |||
13403 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
13404 | MayHaveConvFixit = true; | |||
13405 | break; | |||
13406 | case IntToPointer: | |||
13407 | DiagKind = diag::ext_typecheck_convert_int_pointer; | |||
13408 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
13409 | MayHaveConvFixit = true; | |||
13410 | break; | |||
13411 | case IncompatiblePointer: | |||
13412 | if (Action == AA_Passing_CFAudited) | |||
13413 | DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; | |||
13414 | else if (SrcType->isFunctionPointerType() && | |||
13415 | DstType->isFunctionPointerType()) | |||
13416 | DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; | |||
13417 | else | |||
13418 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer; | |||
13419 | ||||
13420 | CheckInferredResultType = DstType->isObjCObjectPointerType() && | |||
13421 | SrcType->isObjCObjectPointerType(); | |||
13422 | if (Hint.isNull() && !CheckInferredResultType) { | |||
13423 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
13424 | } | |||
13425 | else if (CheckInferredResultType) { | |||
13426 | SrcType = SrcType.getUnqualifiedType(); | |||
13427 | DstType = DstType.getUnqualifiedType(); | |||
13428 | } | |||
13429 | MayHaveConvFixit = true; | |||
13430 | break; | |||
13431 | case IncompatiblePointerSign: | |||
13432 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; | |||
13433 | break; | |||
13434 | case FunctionVoidPointer: | |||
13435 | DiagKind = diag::ext_typecheck_convert_pointer_void_func; | |||
13436 | break; | |||
13437 | case IncompatiblePointerDiscardsQualifiers: { | |||
13438 | // Perform array-to-pointer decay if necessary. | |||
13439 | if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); | |||
13440 | ||||
13441 | Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); | |||
13442 | Qualifiers rhq = DstType->getPointeeType().getQualifiers(); | |||
13443 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) { | |||
13444 | DiagKind = diag::err_typecheck_incompatible_address_space; | |||
13445 | break; | |||
13446 | ||||
13447 | ||||
13448 | } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { | |||
13449 | DiagKind = diag::err_typecheck_incompatible_ownership; | |||
13450 | break; | |||
13451 | } | |||
13452 | ||||
13453 | llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 13453); | |||
13454 | // fallthrough | |||
13455 | } | |||
13456 | case CompatiblePointerDiscardsQualifiers: | |||
13457 | // If the qualifiers lost were because we were applying the | |||
13458 | // (deprecated) C++ conversion from a string literal to a char* | |||
13459 | // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: | |||
13460 | // Ideally, this check would be performed in | |||
13461 | // checkPointerTypesForAssignment. However, that would require a | |||
13462 | // bit of refactoring (so that the second argument is an | |||
13463 | // expression, rather than a type), which should be done as part | |||
13464 | // of a larger effort to fix checkPointerTypesForAssignment for | |||
13465 | // C++ semantics. | |||
13466 | if (getLangOpts().CPlusPlus && | |||
13467 | IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) | |||
13468 | return false; | |||
13469 | DiagKind = diag::ext_typecheck_convert_discards_qualifiers; | |||
13470 | break; | |||
13471 | case IncompatibleNestedPointerQualifiers: | |||
13472 | DiagKind = diag::ext_nested_pointer_qualifier_mismatch; | |||
13473 | break; | |||
13474 | case IntToBlockPointer: | |||
13475 | DiagKind = diag::err_int_to_block_pointer; | |||
13476 | break; | |||
13477 | case IncompatibleBlockPointer: | |||
13478 | DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; | |||
13479 | break; | |||
13480 | case IncompatibleObjCQualifiedId: { | |||
13481 | if (SrcType->isObjCQualifiedIdType()) { | |||
13482 | const ObjCObjectPointerType *srcOPT = | |||
13483 | SrcType->getAs<ObjCObjectPointerType>(); | |||
13484 | for (auto *srcProto : srcOPT->quals()) { | |||
13485 | PDecl = srcProto; | |||
13486 | break; | |||
13487 | } | |||
13488 | if (const ObjCInterfaceType *IFaceT = | |||
13489 | DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) | |||
13490 | IFace = IFaceT->getDecl(); | |||
13491 | } | |||
13492 | else if (DstType->isObjCQualifiedIdType()) { | |||
13493 | const ObjCObjectPointerType *dstOPT = | |||
13494 | DstType->getAs<ObjCObjectPointerType>(); | |||
13495 | for (auto *dstProto : dstOPT->quals()) { | |||
13496 | PDecl = dstProto; | |||
13497 | break; | |||
13498 | } | |||
13499 | if (const ObjCInterfaceType *IFaceT = | |||
13500 | SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) | |||
13501 | IFace = IFaceT->getDecl(); | |||
13502 | } | |||
13503 | DiagKind = diag::warn_incompatible_qualified_id; | |||
13504 | break; | |||
13505 | } | |||
13506 | case IncompatibleVectors: | |||
13507 | DiagKind = diag::warn_incompatible_vectors; | |||
13508 | break; | |||
13509 | case IncompatibleObjCWeakRef: | |||
13510 | DiagKind = diag::err_arc_weak_unavailable_assign; | |||
13511 | break; | |||
13512 | case Incompatible: | |||
13513 | if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { | |||
13514 | if (Complained) | |||
13515 | *Complained = true; | |||
13516 | return true; | |||
13517 | } | |||
13518 | ||||
13519 | DiagKind = diag::err_typecheck_convert_incompatible; | |||
13520 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
13521 | MayHaveConvFixit = true; | |||
13522 | isInvalid = true; | |||
13523 | MayHaveFunctionDiff = true; | |||
13524 | break; | |||
13525 | } | |||
13526 | ||||
13527 | QualType FirstType, SecondType; | |||
13528 | switch (Action) { | |||
13529 | case AA_Assigning: | |||
13530 | case AA_Initializing: | |||
13531 | // The destination type comes first. | |||
13532 | FirstType = DstType; | |||
13533 | SecondType = SrcType; | |||
13534 | break; | |||
13535 | ||||
13536 | case AA_Returning: | |||
13537 | case AA_Passing: | |||
13538 | case AA_Passing_CFAudited: | |||
13539 | case AA_Converting: | |||
13540 | case AA_Sending: | |||
13541 | case AA_Casting: | |||
13542 | // The source type comes first. | |||
13543 | FirstType = SrcType; | |||
13544 | SecondType = DstType; | |||
13545 | break; | |||
13546 | } | |||
13547 | ||||
13548 | PartialDiagnostic FDiag = PDiag(DiagKind); | |||
13549 | if (Action == AA_Passing_CFAudited) | |||
13550 | FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); | |||
13551 | else | |||
13552 | FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); | |||
13553 | ||||
13554 | // If we can fix the conversion, suggest the FixIts. | |||
13555 | assert(ConvHints.isNull() || Hint.isNull())(static_cast <bool> (ConvHints.isNull() || Hint.isNull( )) ? void (0) : __assert_fail ("ConvHints.isNull() || Hint.isNull()" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 13555, __extension__ __PRETTY_FUNCTION__)); | |||
13556 | if (!ConvHints.isNull()) { | |||
13557 | for (FixItHint &H : ConvHints.Hints) | |||
13558 | FDiag << H; | |||
13559 | } else { | |||
13560 | FDiag << Hint; | |||
13561 | } | |||
13562 | if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } | |||
13563 | ||||
13564 | if (MayHaveFunctionDiff) | |||
13565 | HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); | |||
13566 | ||||
13567 | Diag(Loc, FDiag); | |||
13568 | if (DiagKind == diag::warn_incompatible_qualified_id && | |||
13569 | PDecl && IFace && !IFace->hasDefinition()) | |||
13570 | Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) | |||
13571 | << IFace << PDecl; | |||
13572 | ||||
13573 | if (SecondType == Context.OverloadTy) | |||
13574 | NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, | |||
13575 | FirstType, /*TakingAddress=*/true); | |||
13576 | ||||
13577 | if (CheckInferredResultType) | |||
13578 | EmitRelatedResultTypeNote(SrcExpr); | |||
13579 | ||||
13580 | if (Action == AA_Returning && ConvTy == IncompatiblePointer) | |||
13581 | EmitRelatedResultTypeNoteForReturn(DstType); | |||
13582 | ||||
13583 | if (Complained) | |||
13584 | *Complained = true; | |||
13585 | return isInvalid; | |||
13586 | } | |||
13587 | ||||
13588 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | |||
13589 | llvm::APSInt *Result) { | |||
13590 | class SimpleICEDiagnoser : public VerifyICEDiagnoser { | |||
13591 | public: | |||
13592 | void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { | |||
13593 | S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; | |||
13594 | } | |||
13595 | } Diagnoser; | |||
13596 | ||||
13597 | return VerifyIntegerConstantExpression(E, Result, Diagnoser); | |||
13598 | } | |||
13599 | ||||
13600 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | |||
13601 | llvm::APSInt *Result, | |||
13602 | unsigned DiagID, | |||
13603 | bool AllowFold) { | |||
13604 | class IDDiagnoser : public VerifyICEDiagnoser { | |||
13605 | unsigned DiagID; | |||
13606 | ||||
13607 | public: | |||
13608 | IDDiagnoser(unsigned DiagID) | |||
13609 | : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } | |||
13610 | ||||
13611 | void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { | |||
13612 | S.Diag(Loc, DiagID) << SR; | |||
13613 | } | |||
13614 | } Diagnoser(DiagID); | |||
13615 | ||||
13616 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); | |||
13617 | } | |||
13618 | ||||
13619 | void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, | |||
13620 | SourceRange SR) { | |||
13621 | S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; | |||
13622 | } | |||
13623 | ||||
13624 | ExprResult | |||
13625 | Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, | |||
13626 | VerifyICEDiagnoser &Diagnoser, | |||
13627 | bool AllowFold) { | |||
13628 | SourceLocation DiagLoc = E->getLocStart(); | |||
13629 | ||||
13630 | if (getLangOpts().CPlusPlus11) { | |||
13631 | // C++11 [expr.const]p5: | |||
13632 | // If an expression of literal class type is used in a context where an | |||
13633 | // integral constant expression is required, then that class type shall | |||
13634 | // have a single non-explicit conversion function to an integral or | |||
13635 | // unscoped enumeration type | |||
13636 | ExprResult Converted; | |||
13637 | class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { | |||
13638 | public: | |||
13639 | CXX11ConvertDiagnoser(bool Silent) | |||
13640 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, | |||
13641 | Silent, true) {} | |||
13642 | ||||
13643 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, | |||
13644 | QualType T) override { | |||
13645 | return S.Diag(Loc, diag::err_ice_not_integral) << T; | |||
13646 | } | |||
13647 | ||||
13648 | SemaDiagnosticBuilder diagnoseIncomplete( | |||
13649 | Sema &S, SourceLocation Loc, QualType T) override { | |||
13650 | return S.Diag(Loc, diag::err_ice_incomplete_type) << T; | |||
13651 | } | |||
13652 | ||||
13653 | SemaDiagnosticBuilder diagnoseExplicitConv( | |||
13654 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | |||
13655 | return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; | |||
13656 | } | |||
13657 | ||||
13658 | SemaDiagnosticBuilder noteExplicitConv( | |||
13659 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | |||
13660 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | |||
13661 | << ConvTy->isEnumeralType() << ConvTy; | |||
13662 | } | |||
13663 | ||||
13664 | SemaDiagnosticBuilder diagnoseAmbiguous( | |||
13665 | Sema &S, SourceLocation Loc, QualType T) override { | |||
13666 | return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; | |||
13667 | } | |||
13668 | ||||
13669 | SemaDiagnosticBuilder noteAmbiguous( | |||
13670 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | |||
13671 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | |||
13672 | << ConvTy->isEnumeralType() << ConvTy; | |||
13673 | } | |||
13674 | ||||
13675 | SemaDiagnosticBuilder diagnoseConversion( | |||
13676 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | |||
13677 | llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 13677); | |||
13678 | } | |||
13679 | } ConvertDiagnoser(Diagnoser.Suppress); | |||
13680 | ||||
13681 | Converted = PerformContextualImplicitConversion(DiagLoc, E, | |||
13682 | ConvertDiagnoser); | |||
13683 | if (Converted.isInvalid()) | |||
13684 | return Converted; | |||
13685 | E = Converted.get(); | |||
13686 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) | |||
13687 | return ExprError(); | |||
13688 | } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { | |||
13689 | // An ICE must be of integral or unscoped enumeration type. | |||
13690 | if (!Diagnoser.Suppress) | |||
13691 | Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); | |||
13692 | return ExprError(); | |||
13693 | } | |||
13694 | ||||
13695 | // Circumvent ICE checking in C++11 to avoid evaluating the expression twice | |||
13696 | // in the non-ICE case. | |||
13697 | if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { | |||
13698 | if (Result) | |||
13699 | *Result = E->EvaluateKnownConstInt(Context); | |||
13700 | return E; | |||
13701 | } | |||
13702 | ||||
13703 | Expr::EvalResult EvalResult; | |||
13704 | SmallVector<PartialDiagnosticAt, 8> Notes; | |||
13705 | EvalResult.Diag = &Notes; | |||
13706 | ||||
13707 | // Try to evaluate the expression, and produce diagnostics explaining why it's | |||
13708 | // not a constant expression as a side-effect. | |||
13709 | bool Folded = E->EvaluateAsRValue(EvalResult, Context) && | |||
13710 | EvalResult.Val.isInt() && !EvalResult.HasSideEffects; | |||
13711 | ||||
13712 | // In C++11, we can rely on diagnostics being produced for any expression | |||
13713 | // which is not a constant expression. If no diagnostics were produced, then | |||
13714 | // this is a constant expression. | |||
13715 | if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { | |||
13716 | if (Result) | |||
13717 | *Result = EvalResult.Val.getInt(); | |||
13718 | return E; | |||
13719 | } | |||
13720 | ||||
13721 | // If our only note is the usual "invalid subexpression" note, just point | |||
13722 | // the caret at its location rather than producing an essentially | |||
13723 | // redundant note. | |||
13724 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | |||
13725 | diag::note_invalid_subexpr_in_const_expr) { | |||
13726 | DiagLoc = Notes[0].first; | |||
13727 | Notes.clear(); | |||
13728 | } | |||
13729 | ||||
13730 | if (!Folded || !AllowFold) { | |||
13731 | if (!Diagnoser.Suppress) { | |||
13732 | Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); | |||
13733 | for (const PartialDiagnosticAt &Note : Notes) | |||
13734 | Diag(Note.first, Note.second); | |||
13735 | } | |||
13736 | ||||
13737 | return ExprError(); | |||
13738 | } | |||
13739 | ||||
13740 | Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); | |||
13741 | for (const PartialDiagnosticAt &Note : Notes) | |||
13742 | Diag(Note.first, Note.second); | |||
13743 | ||||
13744 | if (Result) | |||
13745 | *Result = EvalResult.Val.getInt(); | |||
13746 | return E; | |||
13747 | } | |||
13748 | ||||
13749 | namespace { | |||
13750 | // Handle the case where we conclude a expression which we speculatively | |||
13751 | // considered to be unevaluated is actually evaluated. | |||
13752 | class TransformToPE : public TreeTransform<TransformToPE> { | |||
13753 | typedef TreeTransform<TransformToPE> BaseTransform; | |||
13754 | ||||
13755 | public: | |||
13756 | TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } | |||
13757 | ||||
13758 | // Make sure we redo semantic analysis | |||
13759 | bool AlwaysRebuild() { return true; } | |||
13760 | ||||
13761 | // Make sure we handle LabelStmts correctly. | |||
13762 | // FIXME: This does the right thing, but maybe we need a more general | |||
13763 | // fix to TreeTransform? | |||
13764 | StmtResult TransformLabelStmt(LabelStmt *S) { | |||
13765 | S->getDecl()->setStmt(nullptr); | |||
13766 | return BaseTransform::TransformLabelStmt(S); | |||
13767 | } | |||
13768 | ||||
13769 | // We need to special-case DeclRefExprs referring to FieldDecls which | |||
13770 | // are not part of a member pointer formation; normal TreeTransforming | |||
13771 | // doesn't catch this case because of the way we represent them in the AST. | |||
13772 | // FIXME: This is a bit ugly; is it really the best way to handle this | |||
13773 | // case? | |||
13774 | // | |||
13775 | // Error on DeclRefExprs referring to FieldDecls. | |||
13776 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | |||
13777 | if (isa<FieldDecl>(E->getDecl()) && | |||
13778 | !SemaRef.isUnevaluatedContext()) | |||
13779 | return SemaRef.Diag(E->getLocation(), | |||
13780 | diag::err_invalid_non_static_member_use) | |||
13781 | << E->getDecl() << E->getSourceRange(); | |||
13782 | ||||
13783 | return BaseTransform::TransformDeclRefExpr(E); | |||
13784 | } | |||
13785 | ||||
13786 | // Exception: filter out member pointer formation | |||
13787 | ExprResult TransformUnaryOperator(UnaryOperator *E) { | |||
13788 | if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) | |||
13789 | return E; | |||
13790 | ||||
13791 | return BaseTransform::TransformUnaryOperator(E); | |||
13792 | } | |||
13793 | ||||
13794 | ExprResult TransformLambdaExpr(LambdaExpr *E) { | |||
13795 | // Lambdas never need to be transformed. | |||
13796 | return E; | |||
13797 | } | |||
13798 | }; | |||
13799 | } | |||
13800 | ||||
13801 | ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { | |||
13802 | assert(isUnevaluatedContext() &&(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 13803, __extension__ __PRETTY_FUNCTION__)) | |||
13803 | "Should only transform unevaluated expressions")(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 13803, __extension__ __PRETTY_FUNCTION__)); | |||
13804 | ExprEvalContexts.back().Context = | |||
13805 | ExprEvalContexts[ExprEvalContexts.size()-2].Context; | |||
13806 | if (isUnevaluatedContext()) | |||
13807 | return E; | |||
13808 | return TransformToPE(*this).TransformExpr(E); | |||
13809 | } | |||
13810 | ||||
13811 | void | |||
13812 | Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, | |||
13813 | Decl *LambdaContextDecl, | |||
13814 | bool IsDecltype) { | |||
13815 | ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, | |||
13816 | LambdaContextDecl, IsDecltype); | |||
13817 | Cleanup.reset(); | |||
13818 | if (!MaybeODRUseExprs.empty()) | |||
13819 | std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); | |||
13820 | } | |||
13821 | ||||
13822 | void | |||
13823 | Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, | |||
13824 | ReuseLambdaContextDecl_t, | |||
13825 | bool IsDecltype) { | |||
13826 | Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; | |||
13827 | PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); | |||
13828 | } | |||
13829 | ||||
13830 | void Sema::PopExpressionEvaluationContext() { | |||
13831 | ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); | |||
13832 | unsigned NumTypos = Rec.NumTypos; | |||
13833 | ||||
13834 | if (!Rec.Lambdas.empty()) { | |||
13835 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { | |||
13836 | unsigned D; | |||
13837 | if (Rec.isUnevaluated()) { | |||
13838 | // C++11 [expr.prim.lambda]p2: | |||
13839 | // A lambda-expression shall not appear in an unevaluated operand | |||
13840 | // (Clause 5). | |||
13841 | D = diag::err_lambda_unevaluated_operand; | |||
13842 | } else { | |||
13843 | // C++1y [expr.const]p2: | |||
13844 | // A conditional-expression e is a core constant expression unless the | |||
13845 | // evaluation of e, following the rules of the abstract machine, would | |||
13846 | // evaluate [...] a lambda-expression. | |||
13847 | D = diag::err_lambda_in_constant_expression; | |||
13848 | } | |||
13849 | ||||
13850 | // C++1z allows lambda expressions as core constant expressions. | |||
13851 | // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG | |||
13852 | // 1607) from appearing within template-arguments and array-bounds that | |||
13853 | // are part of function-signatures. Be mindful that P0315 (Lambdas in | |||
13854 | // unevaluated contexts) might lift some of these restrictions in a | |||
13855 | // future version. | |||
13856 | if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17) | |||
13857 | for (const auto *L : Rec.Lambdas) | |||
13858 | Diag(L->getLocStart(), D); | |||
13859 | } else { | |||
13860 | // Mark the capture expressions odr-used. This was deferred | |||
13861 | // during lambda expression creation. | |||
13862 | for (auto *Lambda : Rec.Lambdas) { | |||
13863 | for (auto *C : Lambda->capture_inits()) | |||
13864 | MarkDeclarationsReferencedInExpr(C); | |||
13865 | } | |||
13866 | } | |||
13867 | } | |||
13868 | ||||
13869 | // When are coming out of an unevaluated context, clear out any | |||
13870 | // temporaries that we may have created as part of the evaluation of | |||
13871 | // the expression in that context: they aren't relevant because they | |||
13872 | // will never be constructed. | |||
13873 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { | |||
13874 | ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, | |||
13875 | ExprCleanupObjects.end()); | |||
13876 | Cleanup = Rec.ParentCleanup; | |||
13877 | CleanupVarDeclMarking(); | |||
13878 | std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); | |||
13879 | // Otherwise, merge the contexts together. | |||
13880 | } else { | |||
13881 | Cleanup.mergeFrom(Rec.ParentCleanup); | |||
13882 | MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), | |||
13883 | Rec.SavedMaybeODRUseExprs.end()); | |||
13884 | } | |||
13885 | ||||
13886 | // Pop the current expression evaluation context off the stack. | |||
13887 | ExprEvalContexts.pop_back(); | |||
13888 | ||||
13889 | if (!ExprEvalContexts.empty()) | |||
13890 | ExprEvalContexts.back().NumTypos += NumTypos; | |||
13891 | else | |||
13892 | assert(NumTypos == 0 && "There are outstanding typos after popping the "(static_cast <bool> (NumTypos == 0 && "There are outstanding typos after popping the " "last ExpressionEvaluationContextRecord") ? void (0) : __assert_fail ("NumTypos == 0 && \"There are outstanding typos after popping the \" \"last ExpressionEvaluationContextRecord\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 13893, __extension__ __PRETTY_FUNCTION__)) | |||
13893 | "last ExpressionEvaluationContextRecord")(static_cast <bool> (NumTypos == 0 && "There are outstanding typos after popping the " "last ExpressionEvaluationContextRecord") ? void (0) : __assert_fail ("NumTypos == 0 && \"There are outstanding typos after popping the \" \"last ExpressionEvaluationContextRecord\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 13893, __extension__ __PRETTY_FUNCTION__)); | |||
13894 | } | |||
13895 | ||||
13896 | void Sema::DiscardCleanupsInEvaluationContext() { | |||
13897 | ExprCleanupObjects.erase( | |||
13898 | ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, | |||
13899 | ExprCleanupObjects.end()); | |||
13900 | Cleanup.reset(); | |||
13901 | MaybeODRUseExprs.clear(); | |||
13902 | } | |||
13903 | ||||
13904 | ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { | |||
13905 | if (!E->getType()->isVariablyModifiedType()) | |||
13906 | return E; | |||
13907 | return TransformToPotentiallyEvaluated(E); | |||
13908 | } | |||
13909 | ||||
13910 | /// Are we within a context in which some evaluation could be performed (be it | |||
13911 | /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite | |||
13912 | /// captured by C++'s idea of an "unevaluated context". | |||
13913 | static bool isEvaluatableContext(Sema &SemaRef) { | |||
13914 | switch (SemaRef.ExprEvalContexts.back().Context) { | |||
13915 | case Sema::ExpressionEvaluationContext::Unevaluated: | |||
13916 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | |||
13917 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | |||
13918 | // Expressions in this context are never evaluated. | |||
13919 | return false; | |||
13920 | ||||
13921 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | |||
13922 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | |||
13923 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | |||
13924 | // Expressions in this context could be evaluated. | |||
13925 | return true; | |||
13926 | ||||
13927 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | |||
13928 | // Referenced declarations will only be used if the construct in the | |||
13929 | // containing expression is used, at which point we'll be given another | |||
13930 | // turn to mark them. | |||
13931 | return false; | |||
13932 | } | |||
13933 | llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 13933); | |||
13934 | } | |||
13935 | ||||
13936 | /// Are we within a context in which references to resolved functions or to | |||
13937 | /// variables result in odr-use? | |||
13938 | static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { | |||
13939 | // An expression in a template is not really an expression until it's been | |||
13940 | // instantiated, so it doesn't trigger odr-use. | |||
13941 | if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) | |||
13942 | return false; | |||
13943 | ||||
13944 | switch (SemaRef.ExprEvalContexts.back().Context) { | |||
13945 | case Sema::ExpressionEvaluationContext::Unevaluated: | |||
13946 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | |||
13947 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | |||
13948 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | |||
13949 | return false; | |||
13950 | ||||
13951 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | |||
13952 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | |||
13953 | return true; | |||
13954 | ||||
13955 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | |||
13956 | return false; | |||
13957 | } | |||
13958 | llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 13958); | |||
13959 | } | |||
13960 | ||||
13961 | static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { | |||
13962 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); | |||
13963 | return Func->isConstexpr() && | |||
13964 | (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); | |||
13965 | } | |||
13966 | ||||
13967 | /// \brief Mark a function referenced, and check whether it is odr-used | |||
13968 | /// (C++ [basic.def.odr]p2, C99 6.9p3) | |||
13969 | void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, | |||
13970 | bool MightBeOdrUse) { | |||
13971 | assert(Func && "No function?")(static_cast <bool> (Func && "No function?") ? void (0) : __assert_fail ("Func && \"No function?\"", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 13971, __extension__ __PRETTY_FUNCTION__)); | |||
13972 | ||||
13973 | Func->setReferenced(); | |||
13974 | ||||
13975 | // C++11 [basic.def.odr]p3: | |||
13976 | // A function whose name appears as a potentially-evaluated expression is | |||
13977 | // odr-used if it is the unique lookup result or the selected member of a | |||
13978 | // set of overloaded functions [...]. | |||
13979 | // | |||
13980 | // We (incorrectly) mark overload resolution as an unevaluated context, so we | |||
13981 | // can just check that here. | |||
13982 | bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); | |||
13983 | ||||
13984 | // Determine whether we require a function definition to exist, per | |||
13985 | // C++11 [temp.inst]p3: | |||
13986 | // Unless a function template specialization has been explicitly | |||
13987 | // instantiated or explicitly specialized, the function template | |||
13988 | // specialization is implicitly instantiated when the specialization is | |||
13989 | // referenced in a context that requires a function definition to exist. | |||
13990 | // | |||
13991 | // That is either when this is an odr-use, or when a usage of a constexpr | |||
13992 | // function occurs within an evaluatable context. | |||
13993 | bool NeedDefinition = | |||
13994 | OdrUse || (isEvaluatableContext(*this) && | |||
13995 | isImplicitlyDefinableConstexprFunction(Func)); | |||
13996 | ||||
13997 | // C++14 [temp.expl.spec]p6: | |||
13998 | // If a template [...] is explicitly specialized then that specialization | |||
13999 | // shall be declared before the first use of that specialization that would | |||
14000 | // cause an implicit instantiation to take place, in every translation unit | |||
14001 | // in which such a use occurs | |||
14002 | if (NeedDefinition && | |||
14003 | (Func->getTemplateSpecializationKind() != TSK_Undeclared || | |||
14004 | Func->getMemberSpecializationInfo())) | |||
14005 | checkSpecializationVisibility(Loc, Func); | |||
14006 | ||||
14007 | // C++14 [except.spec]p17: | |||
14008 | // An exception-specification is considered to be needed when: | |||
14009 | // - the function is odr-used or, if it appears in an unevaluated operand, | |||
14010 | // would be odr-used if the expression were potentially-evaluated; | |||
14011 | // | |||
14012 | // Note, we do this even if MightBeOdrUse is false. That indicates that the | |||
14013 | // function is a pure virtual function we're calling, and in that case the | |||
14014 | // function was selected by overload resolution and we need to resolve its | |||
14015 | // exception specification for a different reason. | |||
14016 | const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); | |||
14017 | if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) | |||
14018 | ResolveExceptionSpec(Loc, FPT); | |||
14019 | ||||
14020 | // If we don't need to mark the function as used, and we don't need to | |||
14021 | // try to provide a definition, there's nothing more to do. | |||
14022 | if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && | |||
14023 | (!NeedDefinition || Func->getBody())) | |||
14024 | return; | |||
14025 | ||||
14026 | // Note that this declaration has been used. | |||
14027 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { | |||
14028 | Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); | |||
14029 | if (Constructor->isDefaulted() && !Constructor->isDeleted()) { | |||
14030 | if (Constructor->isDefaultConstructor()) { | |||
14031 | if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) | |||
14032 | return; | |||
14033 | DefineImplicitDefaultConstructor(Loc, Constructor); | |||
14034 | } else if (Constructor->isCopyConstructor()) { | |||
14035 | DefineImplicitCopyConstructor(Loc, Constructor); | |||
14036 | } else if (Constructor->isMoveConstructor()) { | |||
14037 | DefineImplicitMoveConstructor(Loc, Constructor); | |||
14038 | } | |||
14039 | } else if (Constructor->getInheritedConstructor()) { | |||
14040 | DefineInheritingConstructor(Loc, Constructor); | |||
14041 | } | |||
14042 | } else if (CXXDestructorDecl *Destructor = | |||
14043 | dyn_cast<CXXDestructorDecl>(Func)) { | |||
14044 | Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); | |||
14045 | if (Destructor->isDefaulted() && !Destructor->isDeleted()) { | |||
14046 | if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) | |||
14047 | return; | |||
14048 | DefineImplicitDestructor(Loc, Destructor); | |||
14049 | } | |||
14050 | if (Destructor->isVirtual() && getLangOpts().AppleKext) | |||
14051 | MarkVTableUsed(Loc, Destructor->getParent()); | |||
14052 | } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { | |||
14053 | if (MethodDecl->isOverloadedOperator() && | |||
14054 | MethodDecl->getOverloadedOperator() == OO_Equal) { | |||
14055 | MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); | |||
14056 | if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { | |||
14057 | if (MethodDecl->isCopyAssignmentOperator()) | |||
14058 | DefineImplicitCopyAssignment(Loc, MethodDecl); | |||
14059 | else if (MethodDecl->isMoveAssignmentOperator()) | |||
14060 | DefineImplicitMoveAssignment(Loc, MethodDecl); | |||
14061 | } | |||
14062 | } else if (isa<CXXConversionDecl>(MethodDecl) && | |||
14063 | MethodDecl->getParent()->isLambda()) { | |||
14064 | CXXConversionDecl *Conversion = | |||
14065 | cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); | |||
14066 | if (Conversion->isLambdaToBlockPointerConversion()) | |||
14067 | DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); | |||
14068 | else | |||
14069 | DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); | |||
14070 | } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) | |||
14071 | MarkVTableUsed(Loc, MethodDecl->getParent()); | |||
14072 | } | |||
14073 | ||||
14074 | // Recursive functions should be marked when used from another function. | |||
14075 | // FIXME: Is this really right? | |||
14076 | if (CurContext == Func) return; | |||
14077 | ||||
14078 | // Implicit instantiation of function templates and member functions of | |||
14079 | // class templates. | |||
14080 | if (Func->isImplicitlyInstantiable()) { | |||
14081 | TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); | |||
14082 | SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); | |||
14083 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | |||
14084 | if (FirstInstantiation) { | |||
14085 | PointOfInstantiation = Loc; | |||
14086 | Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); | |||
14087 | } else if (TSK != TSK_ImplicitInstantiation) { | |||
14088 | // Use the point of use as the point of instantiation, instead of the | |||
14089 | // point of explicit instantiation (which we track as the actual point of | |||
14090 | // instantiation). This gives better backtraces in diagnostics. | |||
14091 | PointOfInstantiation = Loc; | |||
14092 | } | |||
14093 | ||||
14094 | if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || | |||
14095 | Func->isConstexpr()) { | |||
14096 | if (isa<CXXRecordDecl>(Func->getDeclContext()) && | |||
14097 | cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && | |||
14098 | CodeSynthesisContexts.size()) | |||
14099 | PendingLocalImplicitInstantiations.push_back( | |||
14100 | std::make_pair(Func, PointOfInstantiation)); | |||
14101 | else if (Func->isConstexpr()) | |||
14102 | // Do not defer instantiations of constexpr functions, to avoid the | |||
14103 | // expression evaluator needing to call back into Sema if it sees a | |||
14104 | // call to such a function. | |||
14105 | InstantiateFunctionDefinition(PointOfInstantiation, Func); | |||
14106 | else { | |||
14107 | Func->setInstantiationIsPending(true); | |||
14108 | PendingInstantiations.push_back(std::make_pair(Func, | |||
14109 | PointOfInstantiation)); | |||
14110 | // Notify the consumer that a function was implicitly instantiated. | |||
14111 | Consumer.HandleCXXImplicitFunctionInstantiation(Func); | |||
14112 | } | |||
14113 | } | |||
14114 | } else { | |||
14115 | // Walk redefinitions, as some of them may be instantiable. | |||
14116 | for (auto i : Func->redecls()) { | |||
14117 | if (!i->isUsed(false) && i->isImplicitlyInstantiable()) | |||
14118 | MarkFunctionReferenced(Loc, i, OdrUse); | |||
14119 | } | |||
14120 | } | |||
14121 | ||||
14122 | if (!OdrUse) return; | |||
14123 | ||||
14124 | // Keep track of used but undefined functions. | |||
14125 | if (!Func->isDefined()) { | |||
14126 | if (mightHaveNonExternalLinkage(Func)) | |||
14127 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | |||
14128 | else if (Func->getMostRecentDecl()->isInlined() && | |||
14129 | !LangOpts.GNUInline && | |||
14130 | !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) | |||
14131 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | |||
14132 | else if (isExternalWithNoLinkageType(Func)) | |||
14133 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | |||
14134 | } | |||
14135 | ||||
14136 | Func->markUsed(Context); | |||
14137 | } | |||
14138 | ||||
14139 | static void | |||
14140 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | |||
14141 | ValueDecl *var, DeclContext *DC) { | |||
14142 | DeclContext *VarDC = var->getDeclContext(); | |||
14143 | ||||
14144 | // If the parameter still belongs to the translation unit, then | |||
14145 | // we're actually just using one parameter in the declaration of | |||
14146 | // the next. | |||
14147 | if (isa<ParmVarDecl>(var) && | |||
14148 | isa<TranslationUnitDecl>(VarDC)) | |||
14149 | return; | |||
14150 | ||||
14151 | // For C code, don't diagnose about capture if we're not actually in code | |||
14152 | // right now; it's impossible to write a non-constant expression outside of | |||
14153 | // function context, so we'll get other (more useful) diagnostics later. | |||
14154 | // | |||
14155 | // For C++, things get a bit more nasty... it would be nice to suppress this | |||
14156 | // diagnostic for certain cases like using a local variable in an array bound | |||
14157 | // for a member of a local class, but the correct predicate is not obvious. | |||
14158 | if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) | |||
14159 | return; | |||
14160 | ||||
14161 | unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; | |||
14162 | unsigned ContextKind = 3; // unknown | |||
14163 | if (isa<CXXMethodDecl>(VarDC) && | |||
14164 | cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { | |||
14165 | ContextKind = 2; | |||
14166 | } else if (isa<FunctionDecl>(VarDC)) { | |||
14167 | ContextKind = 0; | |||
14168 | } else if (isa<BlockDecl>(VarDC)) { | |||
14169 | ContextKind = 1; | |||
14170 | } | |||
14171 | ||||
14172 | S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) | |||
14173 | << var << ValueKind << ContextKind << VarDC; | |||
14174 | S.Diag(var->getLocation(), diag::note_entity_declared_at) | |||
14175 | << var; | |||
14176 | ||||
14177 | // FIXME: Add additional diagnostic info about class etc. which prevents | |||
14178 | // capture. | |||
14179 | } | |||
14180 | ||||
14181 | ||||
14182 | static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, | |||
14183 | bool &SubCapturesAreNested, | |||
14184 | QualType &CaptureType, | |||
14185 | QualType &DeclRefType) { | |||
14186 | // Check whether we've already captured it. | |||
14187 | if (CSI->CaptureMap.count(Var)) { | |||
14188 | // If we found a capture, any subcaptures are nested. | |||
14189 | SubCapturesAreNested = true; | |||
14190 | ||||
14191 | // Retrieve the capture type for this variable. | |||
14192 | CaptureType = CSI->getCapture(Var).getCaptureType(); | |||
14193 | ||||
14194 | // Compute the type of an expression that refers to this variable. | |||
14195 | DeclRefType = CaptureType.getNonReferenceType(); | |||
14196 | ||||
14197 | // Similarly to mutable captures in lambda, all the OpenMP captures by copy | |||
14198 | // are mutable in the sense that user can change their value - they are | |||
14199 | // private instances of the captured declarations. | |||
14200 | const Capture &Cap = CSI->getCapture(Var); | |||
14201 | if (Cap.isCopyCapture() && | |||
14202 | !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && | |||
14203 | !(isa<CapturedRegionScopeInfo>(CSI) && | |||
14204 | cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) | |||
14205 | DeclRefType.addConst(); | |||
14206 | return true; | |||
14207 | } | |||
14208 | return false; | |||
14209 | } | |||
14210 | ||||
14211 | // Only block literals, captured statements, and lambda expressions can | |||
14212 | // capture; other scopes don't work. | |||
14213 | static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, | |||
14214 | SourceLocation Loc, | |||
14215 | const bool Diagnose, Sema &S) { | |||
14216 | if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) | |||
14217 | return getLambdaAwareParentOfDeclContext(DC); | |||
14218 | else if (Var->hasLocalStorage()) { | |||
14219 | if (Diagnose) | |||
14220 | diagnoseUncapturableValueReference(S, Loc, Var, DC); | |||
14221 | } | |||
14222 | return nullptr; | |||
14223 | } | |||
14224 | ||||
14225 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | |||
14226 | // certain types of variables (unnamed, variably modified types etc.) | |||
14227 | // so check for eligibility. | |||
14228 | static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, | |||
14229 | SourceLocation Loc, | |||
14230 | const bool Diagnose, Sema &S) { | |||
14231 | ||||
14232 | bool IsBlock = isa<BlockScopeInfo>(CSI); | |||
14233 | bool IsLambda = isa<LambdaScopeInfo>(CSI); | |||
14234 | ||||
14235 | // Lambdas are not allowed to capture unnamed variables | |||
14236 | // (e.g. anonymous unions). | |||
14237 | // FIXME: The C++11 rule don't actually state this explicitly, but I'm | |||
14238 | // assuming that's the intent. | |||
14239 | if (IsLambda && !Var->getDeclName()) { | |||
14240 | if (Diagnose) { | |||
14241 | S.Diag(Loc, diag::err_lambda_capture_anonymous_var); | |||
14242 | S.Diag(Var->getLocation(), diag::note_declared_at); | |||
14243 | } | |||
14244 | return false; | |||
14245 | } | |||
14246 | ||||
14247 | // Prohibit variably-modified types in blocks; they're difficult to deal with. | |||
14248 | if (Var->getType()->isVariablyModifiedType() && IsBlock) { | |||
14249 | if (Diagnose) { | |||
14250 | S.Diag(Loc, diag::err_ref_vm_type); | |||
14251 | S.Diag(Var->getLocation(), diag::note_previous_decl) | |||
14252 | << Var->getDeclName(); | |||
14253 | } | |||
14254 | return false; | |||
14255 | } | |||
14256 | // Prohibit structs with flexible array members too. | |||
14257 | // We cannot capture what is in the tail end of the struct. | |||
14258 | if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { | |||
14259 | if (VTTy->getDecl()->hasFlexibleArrayMember()) { | |||
14260 | if (Diagnose) { | |||
14261 | if (IsBlock) | |||
14262 | S.Diag(Loc, diag::err_ref_flexarray_type); | |||
14263 | else | |||
14264 | S.Diag(Loc, diag::err_lambda_capture_flexarray_type) | |||
14265 | << Var->getDeclName(); | |||
14266 | S.Diag(Var->getLocation(), diag::note_previous_decl) | |||
14267 | << Var->getDeclName(); | |||
14268 | } | |||
14269 | return false; | |||
14270 | } | |||
14271 | } | |||
14272 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | |||
14273 | // Lambdas and captured statements are not allowed to capture __block | |||
14274 | // variables; they don't support the expected semantics. | |||
14275 | if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { | |||
14276 | if (Diagnose) { | |||
14277 | S.Diag(Loc, diag::err_capture_block_variable) | |||
14278 | << Var->getDeclName() << !IsLambda; | |||
14279 | S.Diag(Var->getLocation(), diag::note_previous_decl) | |||
14280 | << Var->getDeclName(); | |||
14281 | } | |||
14282 | return false; | |||
14283 | } | |||
14284 | // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks | |||
14285 | if (S.getLangOpts().OpenCL && IsBlock && | |||
14286 | Var->getType()->isBlockPointerType()) { | |||
14287 | if (Diagnose) | |||
14288 | S.Diag(Loc, diag::err_opencl_block_ref_block); | |||
14289 | return false; | |||
14290 | } | |||
14291 | ||||
14292 | return true; | |||
14293 | } | |||
14294 | ||||
14295 | // Returns true if the capture by block was successful. | |||
14296 | static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, | |||
14297 | SourceLocation Loc, | |||
14298 | const bool BuildAndDiagnose, | |||
14299 | QualType &CaptureType, | |||
14300 | QualType &DeclRefType, | |||
14301 | const bool Nested, | |||
14302 | Sema &S) { | |||
14303 | Expr *CopyExpr = nullptr; | |||
14304 | bool ByRef = false; | |||
14305 | ||||
14306 | // Blocks are not allowed to capture arrays. | |||
14307 | if (CaptureType->isArrayType()) { | |||
14308 | if (BuildAndDiagnose) { | |||
14309 | S.Diag(Loc, diag::err_ref_array_type); | |||
14310 | S.Diag(Var->getLocation(), diag::note_previous_decl) | |||
14311 | << Var->getDeclName(); | |||
14312 | } | |||
14313 | return false; | |||
14314 | } | |||
14315 | ||||
14316 | // Forbid the block-capture of autoreleasing variables. | |||
14317 | if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | |||
14318 | if (BuildAndDiagnose) { | |||
14319 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) | |||
14320 | << /*block*/ 0; | |||
14321 | S.Diag(Var->getLocation(), diag::note_previous_decl) | |||
14322 | << Var->getDeclName(); | |||
14323 | } | |||
14324 | return false; | |||
14325 | } | |||
14326 | ||||
14327 | // Warn about implicitly autoreleasing indirect parameters captured by blocks. | |||
14328 | if (const auto *PT = CaptureType->getAs<PointerType>()) { | |||
14329 | // This function finds out whether there is an AttributedType of kind | |||
14330 | // attr_objc_ownership in Ty. The existence of AttributedType of kind | |||
14331 | // attr_objc_ownership implies __autoreleasing was explicitly specified | |||
14332 | // rather than being added implicitly by the compiler. | |||
14333 | auto IsObjCOwnershipAttributedType = [](QualType Ty) { | |||
14334 | while (const auto *AttrTy = Ty->getAs<AttributedType>()) { | |||
14335 | if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) | |||
14336 | return true; | |||
14337 | ||||
14338 | // Peel off AttributedTypes that are not of kind objc_ownership. | |||
14339 | Ty = AttrTy->getModifiedType(); | |||
14340 | } | |||
14341 | ||||
14342 | return false; | |||
14343 | }; | |||
14344 | ||||
14345 | QualType PointeeTy = PT->getPointeeType(); | |||
14346 | ||||
14347 | if (PointeeTy->getAs<ObjCObjectPointerType>() && | |||
14348 | PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && | |||
14349 | !IsObjCOwnershipAttributedType(PointeeTy)) { | |||
14350 | if (BuildAndDiagnose) { | |||
14351 | SourceLocation VarLoc = Var->getLocation(); | |||
14352 | S.Diag(Loc, diag::warn_block_capture_autoreleasing); | |||
14353 | { | |||
14354 | auto AddAutoreleaseNote = | |||
14355 | S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); | |||
14356 | // Provide a fix-it for the '__autoreleasing' keyword at the | |||
14357 | // appropriate location in the variable's type. | |||
14358 | if (const auto *TSI = Var->getTypeSourceInfo()) { | |||
14359 | PointerTypeLoc PTL = | |||
14360 | TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); | |||
14361 | if (PTL) { | |||
14362 | SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); | |||
14363 | Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), | |||
14364 | S.getLangOpts()); | |||
14365 | if (Loc.isValid()) { | |||
14366 | StringRef CharAtLoc = Lexer::getSourceText( | |||
14367 | CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), | |||
14368 | S.getSourceManager(), S.getLangOpts()); | |||
14369 | AddAutoreleaseNote << FixItHint::CreateInsertion( | |||
14370 | Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) | |||
14371 | ? " __autoreleasing " | |||
14372 | : " __autoreleasing"); | |||
14373 | } | |||
14374 | } | |||
14375 | } | |||
14376 | } | |||
14377 | S.Diag(VarLoc, diag::note_declare_parameter_strong); | |||
14378 | } | |||
14379 | } | |||
14380 | } | |||
14381 | ||||
14382 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | |||
14383 | if (HasBlocksAttr || CaptureType->isReferenceType() || | |||
14384 | (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { | |||
14385 | // Block capture by reference does not change the capture or | |||
14386 | // declaration reference types. | |||
14387 | ByRef = true; | |||
14388 | } else { | |||
14389 | // Block capture by copy introduces 'const'. | |||
14390 | CaptureType = CaptureType.getNonReferenceType().withConst(); | |||
14391 | DeclRefType = CaptureType; | |||
14392 | ||||
14393 | if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { | |||
14394 | if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { | |||
14395 | // The capture logic needs the destructor, so make sure we mark it. | |||
14396 | // Usually this is unnecessary because most local variables have | |||
14397 | // their destructors marked at declaration time, but parameters are | |||
14398 | // an exception because it's technically only the call site that | |||
14399 | // actually requires the destructor. | |||
14400 | if (isa<ParmVarDecl>(Var)) | |||
14401 | S.FinalizeVarWithDestructor(Var, Record); | |||
14402 | ||||
14403 | // Enter a new evaluation context to insulate the copy | |||
14404 | // full-expression. | |||
14405 | EnterExpressionEvaluationContext scope( | |||
14406 | S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); | |||
14407 | ||||
14408 | // According to the blocks spec, the capture of a variable from | |||
14409 | // the stack requires a const copy constructor. This is not true | |||
14410 | // of the copy/move done to move a __block variable to the heap. | |||
14411 | Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, | |||
14412 | DeclRefType.withConst(), | |||
14413 | VK_LValue, Loc); | |||
14414 | ||||
14415 | ExprResult Result | |||
14416 | = S.PerformCopyInitialization( | |||
14417 | InitializedEntity::InitializeBlock(Var->getLocation(), | |||
14418 | CaptureType, false), | |||
14419 | Loc, DeclRef); | |||
14420 | ||||
14421 | // Build a full-expression copy expression if initialization | |||
14422 | // succeeded and used a non-trivial constructor. Recover from | |||
14423 | // errors by pretending that the copy isn't necessary. | |||
14424 | if (!Result.isInvalid() && | |||
14425 | !cast<CXXConstructExpr>(Result.get())->getConstructor() | |||
14426 | ->isTrivial()) { | |||
14427 | Result = S.MaybeCreateExprWithCleanups(Result); | |||
14428 | CopyExpr = Result.get(); | |||
14429 | } | |||
14430 | } | |||
14431 | } | |||
14432 | } | |||
14433 | ||||
14434 | // Actually capture the variable. | |||
14435 | if (BuildAndDiagnose) | |||
14436 | BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, | |||
14437 | SourceLocation(), CaptureType, CopyExpr); | |||
14438 | ||||
14439 | return true; | |||
14440 | ||||
14441 | } | |||
14442 | ||||
14443 | ||||
14444 | /// \brief Capture the given variable in the captured region. | |||
14445 | static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, | |||
14446 | VarDecl *Var, | |||
14447 | SourceLocation Loc, | |||
14448 | const bool BuildAndDiagnose, | |||
14449 | QualType &CaptureType, | |||
14450 | QualType &DeclRefType, | |||
14451 | const bool RefersToCapturedVariable, | |||
14452 | Sema &S) { | |||
14453 | // By default, capture variables by reference. | |||
14454 | bool ByRef = true; | |||
14455 | // Using an LValue reference type is consistent with Lambdas (see below). | |||
14456 | if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { | |||
14457 | if (S.IsOpenMPCapturedDecl(Var)) { | |||
14458 | bool HasConst = DeclRefType.isConstQualified(); | |||
14459 | DeclRefType = DeclRefType.getUnqualifiedType(); | |||
14460 | // Don't lose diagnostics about assignments to const. | |||
14461 | if (HasConst) | |||
14462 | DeclRefType.addConst(); | |||
14463 | } | |||
14464 | ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); | |||
14465 | } | |||
14466 | ||||
14467 | if (ByRef) | |||
14468 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | |||
14469 | else | |||
14470 | CaptureType = DeclRefType; | |||
14471 | ||||
14472 | Expr *CopyExpr = nullptr; | |||
14473 | if (BuildAndDiagnose) { | |||
14474 | // The current implementation assumes that all variables are captured | |||
14475 | // by references. Since there is no capture by copy, no expression | |||
14476 | // evaluation will be needed. | |||
14477 | RecordDecl *RD = RSI->TheRecordDecl; | |||
14478 | ||||
14479 | FieldDecl *Field | |||
14480 | = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, | |||
14481 | S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), | |||
14482 | nullptr, false, ICIS_NoInit); | |||
14483 | Field->setImplicit(true); | |||
14484 | Field->setAccess(AS_private); | |||
14485 | RD->addDecl(Field); | |||
14486 | if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) | |||
14487 | S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); | |||
14488 | ||||
14489 | CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, | |||
14490 | DeclRefType, VK_LValue, Loc); | |||
14491 | Var->setReferenced(true); | |||
14492 | Var->markUsed(S.Context); | |||
14493 | } | |||
14494 | ||||
14495 | // Actually capture the variable. | |||
14496 | if (BuildAndDiagnose) | |||
14497 | RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, | |||
14498 | SourceLocation(), CaptureType, CopyExpr); | |||
14499 | ||||
14500 | ||||
14501 | return true; | |||
14502 | } | |||
14503 | ||||
14504 | /// \brief Create a field within the lambda class for the variable | |||
14505 | /// being captured. | |||
14506 | static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, | |||
14507 | QualType FieldType, QualType DeclRefType, | |||
14508 | SourceLocation Loc, | |||
14509 | bool RefersToCapturedVariable) { | |||
14510 | CXXRecordDecl *Lambda = LSI->Lambda; | |||
14511 | ||||
14512 | // Build the non-static data member. | |||
14513 | FieldDecl *Field | |||
14514 | = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, | |||
14515 | S.Context.getTrivialTypeSourceInfo(FieldType, Loc), | |||
14516 | nullptr, false, ICIS_NoInit); | |||
14517 | Field->setImplicit(true); | |||
14518 | Field->setAccess(AS_private); | |||
14519 | Lambda->addDecl(Field); | |||
14520 | } | |||
14521 | ||||
14522 | /// \brief Capture the given variable in the lambda. | |||
14523 | static bool captureInLambda(LambdaScopeInfo *LSI, | |||
14524 | VarDecl *Var, | |||
14525 | SourceLocation Loc, | |||
14526 | const bool BuildAndDiagnose, | |||
14527 | QualType &CaptureType, | |||
14528 | QualType &DeclRefType, | |||
14529 | const bool RefersToCapturedVariable, | |||
14530 | const Sema::TryCaptureKind Kind, | |||
14531 | SourceLocation EllipsisLoc, | |||
14532 | const bool IsTopScope, | |||
14533 | Sema &S) { | |||
14534 | ||||
14535 | // Determine whether we are capturing by reference or by value. | |||
14536 | bool ByRef = false; | |||
14537 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | |||
14538 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | |||
14539 | } else { | |||
14540 | ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); | |||
14541 | } | |||
14542 | ||||
14543 | // Compute the type of the field that will capture this variable. | |||
14544 | if (ByRef) { | |||
14545 | // C++11 [expr.prim.lambda]p15: | |||
14546 | // An entity is captured by reference if it is implicitly or | |||
14547 | // explicitly captured but not captured by copy. It is | |||
14548 | // unspecified whether additional unnamed non-static data | |||
14549 | // members are declared in the closure type for entities | |||
14550 | // captured by reference. | |||
14551 | // | |||
14552 | // FIXME: It is not clear whether we want to build an lvalue reference | |||
14553 | // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears | |||
14554 | // to do the former, while EDG does the latter. Core issue 1249 will | |||
14555 | // clarify, but for now we follow GCC because it's a more permissive and | |||
14556 | // easily defensible position. | |||
14557 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | |||
14558 | } else { | |||
14559 | // C++11 [expr.prim.lambda]p14: | |||
14560 | // For each entity captured by copy, an unnamed non-static | |||
14561 | // data member is declared in the closure type. The | |||
14562 | // declaration order of these members is unspecified. The type | |||
14563 | // of such a data member is the type of the corresponding | |||
14564 | // captured entity if the entity is not a reference to an | |||
14565 | // object, or the referenced type otherwise. [Note: If the | |||
14566 | // captured entity is a reference to a function, the | |||
14567 | // corresponding data member is also a reference to a | |||
14568 | // function. - end note ] | |||
14569 | if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ | |||
14570 | if (!RefType->getPointeeType()->isFunctionType()) | |||
14571 | CaptureType = RefType->getPointeeType(); | |||
14572 | } | |||
14573 | ||||
14574 | // Forbid the lambda copy-capture of autoreleasing variables. | |||
14575 | if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | |||
14576 | if (BuildAndDiagnose) { | |||
14577 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; | |||
14578 | S.Diag(Var->getLocation(), diag::note_previous_decl) | |||
14579 | << Var->getDeclName(); | |||
14580 | } | |||
14581 | return false; | |||
14582 | } | |||
14583 | ||||
14584 | // Make sure that by-copy captures are of a complete and non-abstract type. | |||
14585 | if (BuildAndDiagnose) { | |||
14586 | if (!CaptureType->isDependentType() && | |||
14587 | S.RequireCompleteType(Loc, CaptureType, | |||
14588 | diag::err_capture_of_incomplete_type, | |||
14589 | Var->getDeclName())) | |||
14590 | return false; | |||
14591 | ||||
14592 | if (S.RequireNonAbstractType(Loc, CaptureType, | |||
14593 | diag::err_capture_of_abstract_type)) | |||
14594 | return false; | |||
14595 | } | |||
14596 | } | |||
14597 | ||||
14598 | // Capture this variable in the lambda. | |||
14599 | if (BuildAndDiagnose) | |||
14600 | addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, | |||
14601 | RefersToCapturedVariable); | |||
14602 | ||||
14603 | // Compute the type of a reference to this captured variable. | |||
14604 | if (ByRef) | |||
14605 | DeclRefType = CaptureType.getNonReferenceType(); | |||
14606 | else { | |||
14607 | // C++ [expr.prim.lambda]p5: | |||
14608 | // The closure type for a lambda-expression has a public inline | |||
14609 | // function call operator [...]. This function call operator is | |||
14610 | // declared const (9.3.1) if and only if the lambda-expression's | |||
14611 | // parameter-declaration-clause is not followed by mutable. | |||
14612 | DeclRefType = CaptureType.getNonReferenceType(); | |||
14613 | if (!LSI->Mutable && !CaptureType->isReferenceType()) | |||
14614 | DeclRefType.addConst(); | |||
14615 | } | |||
14616 | ||||
14617 | // Add the capture. | |||
14618 | if (BuildAndDiagnose) | |||
14619 | LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, | |||
14620 | Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); | |||
14621 | ||||
14622 | return true; | |||
14623 | } | |||
14624 | ||||
14625 | bool Sema::tryCaptureVariable( | |||
14626 | VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, | |||
14627 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, | |||
14628 | QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { | |||
14629 | // An init-capture is notionally from the context surrounding its | |||
14630 | // declaration, but its parent DC is the lambda class. | |||
14631 | DeclContext *VarDC = Var->getDeclContext(); | |||
14632 | if (Var->isInitCapture()) | |||
14633 | VarDC = VarDC->getParent(); | |||
14634 | ||||
14635 | DeclContext *DC = CurContext; | |||
14636 | const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt | |||
14637 | ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; | |||
14638 | // We need to sync up the Declaration Context with the | |||
14639 | // FunctionScopeIndexToStopAt | |||
14640 | if (FunctionScopeIndexToStopAt) { | |||
14641 | unsigned FSIndex = FunctionScopes.size() - 1; | |||
14642 | while (FSIndex != MaxFunctionScopesIndex) { | |||
14643 | DC = getLambdaAwareParentOfDeclContext(DC); | |||
14644 | --FSIndex; | |||
14645 | } | |||
14646 | } | |||
14647 | ||||
14648 | ||||
14649 | // If the variable is declared in the current context, there is no need to | |||
14650 | // capture it. | |||
14651 | if (VarDC == DC) return true; | |||
14652 | ||||
14653 | // Capture global variables if it is required to use private copy of this | |||
14654 | // variable. | |||
14655 | bool IsGlobal = !Var->hasLocalStorage(); | |||
14656 | if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) | |||
14657 | return true; | |||
14658 | Var = Var->getCanonicalDecl(); | |||
14659 | ||||
14660 | // Walk up the stack to determine whether we can capture the variable, | |||
14661 | // performing the "simple" checks that don't depend on type. We stop when | |||
14662 | // we've either hit the declared scope of the variable or find an existing | |||
14663 | // capture of that variable. We start from the innermost capturing-entity | |||
14664 | // (the DC) and ensure that all intervening capturing-entities | |||
14665 | // (blocks/lambdas etc.) between the innermost capturer and the variable`s | |||
14666 | // declcontext can either capture the variable or have already captured | |||
14667 | // the variable. | |||
14668 | CaptureType = Var->getType(); | |||
14669 | DeclRefType = CaptureType.getNonReferenceType(); | |||
14670 | bool Nested = false; | |||
14671 | bool Explicit = (Kind != TryCapture_Implicit); | |||
14672 | unsigned FunctionScopesIndex = MaxFunctionScopesIndex; | |||
14673 | do { | |||
14674 | // Only block literals, captured statements, and lambda expressions can | |||
14675 | // capture; other scopes don't work. | |||
14676 | DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, | |||
14677 | ExprLoc, | |||
14678 | BuildAndDiagnose, | |||
14679 | *this); | |||
14680 | // We need to check for the parent *first* because, if we *have* | |||
14681 | // private-captured a global variable, we need to recursively capture it in | |||
14682 | // intermediate blocks, lambdas, etc. | |||
14683 | if (!ParentDC) { | |||
14684 | if (IsGlobal) { | |||
14685 | FunctionScopesIndex = MaxFunctionScopesIndex - 1; | |||
14686 | break; | |||
14687 | } | |||
14688 | return true; | |||
14689 | } | |||
14690 | ||||
14691 | FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; | |||
14692 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); | |||
14693 | ||||
14694 | ||||
14695 | // Check whether we've already captured it. | |||
14696 | if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, | |||
14697 | DeclRefType)) { | |||
14698 | CSI->getCapture(Var).markUsed(BuildAndDiagnose); | |||
14699 | break; | |||
14700 | } | |||
14701 | // If we are instantiating a generic lambda call operator body, | |||
14702 | // we do not want to capture new variables. What was captured | |||
14703 | // during either a lambdas transformation or initial parsing | |||
14704 | // should be used. | |||
14705 | if (isGenericLambdaCallOperatorSpecialization(DC)) { | |||
14706 | if (BuildAndDiagnose) { | |||
14707 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | |||
14708 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { | |||
14709 | Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); | |||
14710 | Diag(Var->getLocation(), diag::note_previous_decl) | |||
14711 | << Var->getDeclName(); | |||
14712 | Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); | |||
14713 | } else | |||
14714 | diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); | |||
14715 | } | |||
14716 | return true; | |||
14717 | } | |||
14718 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | |||
14719 | // certain types of variables (unnamed, variably modified types etc.) | |||
14720 | // so check for eligibility. | |||
14721 | if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) | |||
14722 | return true; | |||
14723 | ||||
14724 | // Try to capture variable-length arrays types. | |||
14725 | if (Var->getType()->isVariablyModifiedType()) { | |||
14726 | // We're going to walk down into the type and look for VLA | |||
14727 | // expressions. | |||
14728 | QualType QTy = Var->getType(); | |||
14729 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | |||
14730 | QTy = PVD->getOriginalType(); | |||
14731 | captureVariablyModifiedType(Context, QTy, CSI); | |||
14732 | } | |||
14733 | ||||
14734 | if (getLangOpts().OpenMP) { | |||
14735 | if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | |||
14736 | // OpenMP private variables should not be captured in outer scope, so | |||
14737 | // just break here. Similarly, global variables that are captured in a | |||
14738 | // target region should not be captured outside the scope of the region. | |||
14739 | if (RSI->CapRegionKind == CR_OpenMP) { | |||
14740 | bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); | |||
14741 | auto IsTargetCap = !IsOpenMPPrivateDecl && | |||
14742 | isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); | |||
14743 | // When we detect target captures we are looking from inside the | |||
14744 | // target region, therefore we need to propagate the capture from the | |||
14745 | // enclosing region. Therefore, the capture is not initially nested. | |||
14746 | if (IsTargetCap) | |||
14747 | adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); | |||
14748 | ||||
14749 | if (IsTargetCap || IsOpenMPPrivateDecl) { | |||
14750 | Nested = !IsTargetCap; | |||
14751 | DeclRefType = DeclRefType.getUnqualifiedType(); | |||
14752 | CaptureType = Context.getLValueReferenceType(DeclRefType); | |||
14753 | break; | |||
14754 | } | |||
14755 | } | |||
14756 | } | |||
14757 | } | |||
14758 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { | |||
14759 | // No capture-default, and this is not an explicit capture | |||
14760 | // so cannot capture this variable. | |||
14761 | if (BuildAndDiagnose) { | |||
14762 | Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); | |||
14763 | Diag(Var->getLocation(), diag::note_previous_decl) | |||
14764 | << Var->getDeclName(); | |||
14765 | if (cast<LambdaScopeInfo>(CSI)->Lambda) | |||
14766 | Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), | |||
14767 | diag::note_lambda_decl); | |||
14768 | // FIXME: If we error out because an outer lambda can not implicitly | |||
14769 | // capture a variable that an inner lambda explicitly captures, we | |||
14770 | // should have the inner lambda do the explicit capture - because | |||
14771 | // it makes for cleaner diagnostics later. This would purely be done | |||
14772 | // so that the diagnostic does not misleadingly claim that a variable | |||
14773 | // can not be captured by a lambda implicitly even though it is captured | |||
14774 | // explicitly. Suggestion: | |||
14775 | // - create const bool VariableCaptureWasInitiallyExplicit = Explicit | |||
14776 | // at the function head | |||
14777 | // - cache the StartingDeclContext - this must be a lambda | |||
14778 | // - captureInLambda in the innermost lambda the variable. | |||
14779 | } | |||
14780 | return true; | |||
14781 | } | |||
14782 | ||||
14783 | FunctionScopesIndex--; | |||
14784 | DC = ParentDC; | |||
14785 | Explicit = false; | |||
14786 | } while (!VarDC->Equals(DC)); | |||
14787 | ||||
14788 | // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) | |||
14789 | // computing the type of the capture at each step, checking type-specific | |||
14790 | // requirements, and adding captures if requested. | |||
14791 | // If the variable had already been captured previously, we start capturing | |||
14792 | // at the lambda nested within that one. | |||
14793 | for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; | |||
14794 | ++I) { | |||
14795 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); | |||
14796 | ||||
14797 | if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { | |||
14798 | if (!captureInBlock(BSI, Var, ExprLoc, | |||
14799 | BuildAndDiagnose, CaptureType, | |||
14800 | DeclRefType, Nested, *this)) | |||
14801 | return true; | |||
14802 | Nested = true; | |||
14803 | } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | |||
14804 | if (!captureInCapturedRegion(RSI, Var, ExprLoc, | |||
14805 | BuildAndDiagnose, CaptureType, | |||
14806 | DeclRefType, Nested, *this)) | |||
14807 | return true; | |||
14808 | Nested = true; | |||
14809 | } else { | |||
14810 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | |||
14811 | if (!captureInLambda(LSI, Var, ExprLoc, | |||
14812 | BuildAndDiagnose, CaptureType, | |||
14813 | DeclRefType, Nested, Kind, EllipsisLoc, | |||
14814 | /*IsTopScope*/I == N - 1, *this)) | |||
14815 | return true; | |||
14816 | Nested = true; | |||
14817 | } | |||
14818 | } | |||
14819 | return false; | |||
14820 | } | |||
14821 | ||||
14822 | bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, | |||
14823 | TryCaptureKind Kind, SourceLocation EllipsisLoc) { | |||
14824 | QualType CaptureType; | |||
14825 | QualType DeclRefType; | |||
14826 | return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, | |||
14827 | /*BuildAndDiagnose=*/true, CaptureType, | |||
14828 | DeclRefType, nullptr); | |||
14829 | } | |||
14830 | ||||
14831 | bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { | |||
14832 | QualType CaptureType; | |||
14833 | QualType DeclRefType; | |||
14834 | return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | |||
14835 | /*BuildAndDiagnose=*/false, CaptureType, | |||
14836 | DeclRefType, nullptr); | |||
14837 | } | |||
14838 | ||||
14839 | QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { | |||
14840 | QualType CaptureType; | |||
14841 | QualType DeclRefType; | |||
14842 | ||||
14843 | // Determine whether we can capture this variable. | |||
14844 | if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | |||
14845 | /*BuildAndDiagnose=*/false, CaptureType, | |||
14846 | DeclRefType, nullptr)) | |||
14847 | return QualType(); | |||
14848 | ||||
14849 | return DeclRefType; | |||
14850 | } | |||
14851 | ||||
14852 | ||||
14853 | ||||
14854 | // If either the type of the variable or the initializer is dependent, | |||
14855 | // return false. Otherwise, determine whether the variable is a constant | |||
14856 | // expression. Use this if you need to know if a variable that might or | |||
14857 | // might not be dependent is truly a constant expression. | |||
14858 | static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, | |||
14859 | ASTContext &Context) { | |||
14860 | ||||
14861 | if (Var->getType()->isDependentType()) | |||
14862 | return false; | |||
14863 | const VarDecl *DefVD = nullptr; | |||
14864 | Var->getAnyInitializer(DefVD); | |||
14865 | if (!DefVD) | |||
14866 | return false; | |||
14867 | EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); | |||
14868 | Expr *Init = cast<Expr>(Eval->Value); | |||
14869 | if (Init->isValueDependent()) | |||
14870 | return false; | |||
14871 | return IsVariableAConstantExpression(Var, Context); | |||
14872 | } | |||
14873 | ||||
14874 | ||||
14875 | void Sema::UpdateMarkingForLValueToRValue(Expr *E) { | |||
14876 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it is | |||
14877 | // an object that satisfies the requirements for appearing in a | |||
14878 | // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) | |||
14879 | // is immediately applied." This function handles the lvalue-to-rvalue | |||
14880 | // conversion part. | |||
14881 | MaybeODRUseExprs.erase(E->IgnoreParens()); | |||
14882 | ||||
14883 | // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers | |||
14884 | // to a variable that is a constant expression, and if so, identify it as | |||
14885 | // a reference to a variable that does not involve an odr-use of that | |||
14886 | // variable. | |||
14887 | if (LambdaScopeInfo *LSI = getCurLambda()) { | |||
14888 | Expr *SansParensExpr = E->IgnoreParens(); | |||
14889 | VarDecl *Var = nullptr; | |||
14890 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) | |||
14891 | Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); | |||
14892 | else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) | |||
14893 | Var = dyn_cast<VarDecl>(ME->getMemberDecl()); | |||
14894 | ||||
14895 | if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) | |||
14896 | LSI->markVariableExprAsNonODRUsed(SansParensExpr); | |||
14897 | } | |||
14898 | } | |||
14899 | ||||
14900 | ExprResult Sema::ActOnConstantExpression(ExprResult Res) { | |||
14901 | Res = CorrectDelayedTyposInExpr(Res); | |||
14902 | ||||
14903 | if (!Res.isUsable()) | |||
14904 | return Res; | |||
14905 | ||||
14906 | // If a constant-expression is a reference to a variable where we delay | |||
14907 | // deciding whether it is an odr-use, just assume we will apply the | |||
14908 | // lvalue-to-rvalue conversion. In the one case where this doesn't happen | |||
14909 | // (a non-type template argument), we have special handling anyway. | |||
14910 | UpdateMarkingForLValueToRValue(Res.get()); | |||
14911 | return Res; | |||
14912 | } | |||
14913 | ||||
14914 | void Sema::CleanupVarDeclMarking() { | |||
14915 | for (Expr *E : MaybeODRUseExprs) { | |||
14916 | VarDecl *Var; | |||
14917 | SourceLocation Loc; | |||
14918 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
14919 | Var = cast<VarDecl>(DRE->getDecl()); | |||
14920 | Loc = DRE->getLocation(); | |||
14921 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | |||
14922 | Var = cast<VarDecl>(ME->getMemberDecl()); | |||
14923 | Loc = ME->getMemberLoc(); | |||
14924 | } else { | |||
14925 | llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 14925); | |||
14926 | } | |||
14927 | ||||
14928 | MarkVarDeclODRUsed(Var, Loc, *this, | |||
14929 | /*MaxFunctionScopeIndex Pointer*/ nullptr); | |||
14930 | } | |||
14931 | ||||
14932 | MaybeODRUseExprs.clear(); | |||
14933 | } | |||
14934 | ||||
14935 | ||||
14936 | static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, | |||
14937 | VarDecl *Var, Expr *E) { | |||
14938 | assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 14939, __extension__ __PRETTY_FUNCTION__)) | |||
14939 | "Invalid Expr argument to DoMarkVarDeclReferenced")(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 14939, __extension__ __PRETTY_FUNCTION__)); | |||
14940 | Var->setReferenced(); | |||
14941 | ||||
14942 | TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); | |||
14943 | ||||
14944 | bool OdrUseContext = isOdrUseContext(SemaRef); | |||
14945 | bool UsableInConstantExpr = | |||
14946 | Var->isUsableInConstantExpressions(SemaRef.Context); | |||
14947 | bool NeedDefinition = | |||
14948 | OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); | |||
14949 | ||||
14950 | VarTemplateSpecializationDecl *VarSpec = | |||
14951 | dyn_cast<VarTemplateSpecializationDecl>(Var); | |||
14952 | 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.\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 14953, __extension__ __PRETTY_FUNCTION__)) | |||
14953 | "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.\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 14953, __extension__ __PRETTY_FUNCTION__)); | |||
14954 | ||||
14955 | // If this might be a member specialization of a static data member, check | |||
14956 | // the specialization is visible. We already did the checks for variable | |||
14957 | // template specializations when we created them. | |||
14958 | if (NeedDefinition && TSK != TSK_Undeclared && | |||
14959 | !isa<VarTemplateSpecializationDecl>(Var)) | |||
14960 | SemaRef.checkSpecializationVisibility(Loc, Var); | |||
14961 | ||||
14962 | // Perform implicit instantiation of static data members, static data member | |||
14963 | // templates of class templates, and variable template specializations. Delay | |||
14964 | // instantiations of variable templates, except for those that could be used | |||
14965 | // in a constant expression. | |||
14966 | if (NeedDefinition && isTemplateInstantiation(TSK)) { | |||
14967 | // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit | |||
14968 | // instantiation declaration if a variable is usable in a constant | |||
14969 | // expression (among other cases). | |||
14970 | bool TryInstantiating = | |||
14971 | TSK == TSK_ImplicitInstantiation || | |||
14972 | (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); | |||
14973 | ||||
14974 | if (TryInstantiating) { | |||
14975 | SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); | |||
14976 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | |||
14977 | if (FirstInstantiation) { | |||
14978 | PointOfInstantiation = Loc; | |||
14979 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); | |||
14980 | } | |||
14981 | ||||
14982 | bool InstantiationDependent = false; | |||
14983 | bool IsNonDependent = | |||
14984 | VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( | |||
14985 | VarSpec->getTemplateArgsInfo(), InstantiationDependent) | |||
14986 | : true; | |||
14987 | ||||
14988 | // Do not instantiate specializations that are still type-dependent. | |||
14989 | if (IsNonDependent) { | |||
14990 | if (UsableInConstantExpr) { | |||
14991 | // Do not defer instantiations of variables that could be used in a | |||
14992 | // constant expression. | |||
14993 | SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); | |||
14994 | } else if (FirstInstantiation || | |||
14995 | isa<VarTemplateSpecializationDecl>(Var)) { | |||
14996 | // FIXME: For a specialization of a variable template, we don't | |||
14997 | // distinguish between "declaration and type implicitly instantiated" | |||
14998 | // and "implicit instantiation of definition requested", so we have | |||
14999 | // no direct way to avoid enqueueing the pending instantiation | |||
15000 | // multiple times. | |||
15001 | SemaRef.PendingInstantiations | |||
15002 | .push_back(std::make_pair(Var, PointOfInstantiation)); | |||
15003 | } | |||
15004 | } | |||
15005 | } | |||
15006 | } | |||
15007 | ||||
15008 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies | |||
15009 | // the requirements for appearing in a constant expression (5.19) and, if | |||
15010 | // it is an object, the lvalue-to-rvalue conversion (4.1) | |||
15011 | // is immediately applied." We check the first part here, and | |||
15012 | // Sema::UpdateMarkingForLValueToRValue deals with the second part. | |||
15013 | // Note that we use the C++11 definition everywhere because nothing in | |||
15014 | // C++03 depends on whether we get the C++03 version correct. The second | |||
15015 | // part does not apply to references, since they are not objects. | |||
15016 | if (OdrUseContext && E && | |||
15017 | IsVariableAConstantExpression(Var, SemaRef.Context)) { | |||
15018 | // A reference initialized by a constant expression can never be | |||
15019 | // odr-used, so simply ignore it. | |||
15020 | if (!Var->getType()->isReferenceType() || | |||
15021 | (SemaRef.LangOpts.OpenMP && SemaRef.IsOpenMPCapturedDecl(Var))) | |||
15022 | SemaRef.MaybeODRUseExprs.insert(E); | |||
15023 | } else if (OdrUseContext) { | |||
15024 | MarkVarDeclODRUsed(Var, Loc, SemaRef, | |||
15025 | /*MaxFunctionScopeIndex ptr*/ nullptr); | |||
15026 | } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { | |||
15027 | // If this is a dependent context, we don't need to mark variables as | |||
15028 | // odr-used, but we may still need to track them for lambda capture. | |||
15029 | // FIXME: Do we also need to do this inside dependent typeid expressions | |||
15030 | // (which are modeled as unevaluated at this point)? | |||
15031 | const bool RefersToEnclosingScope = | |||
15032 | (SemaRef.CurContext != Var->getDeclContext() && | |||
15033 | Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); | |||
15034 | if (RefersToEnclosingScope) { | |||
15035 | LambdaScopeInfo *const LSI = | |||
15036 | SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); | |||
15037 | if (LSI && (!LSI->CallOperator || | |||
15038 | !LSI->CallOperator->Encloses(Var->getDeclContext()))) { | |||
15039 | // If a variable could potentially be odr-used, defer marking it so | |||
15040 | // until we finish analyzing the full expression for any | |||
15041 | // lvalue-to-rvalue | |||
15042 | // or discarded value conversions that would obviate odr-use. | |||
15043 | // Add it to the list of potential captures that will be analyzed | |||
15044 | // later (ActOnFinishFullExpr) for eventual capture and odr-use marking | |||
15045 | // unless the variable is a reference that was initialized by a constant | |||
15046 | // expression (this will never need to be captured or odr-used). | |||
15047 | 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.\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15047, __extension__ __PRETTY_FUNCTION__)); | |||
15048 | if (!Var->getType()->isReferenceType() || | |||
15049 | !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) | |||
15050 | LSI->addPotentialCapture(E->IgnoreParens()); | |||
15051 | } | |||
15052 | } | |||
15053 | } | |||
15054 | } | |||
15055 | ||||
15056 | /// \brief Mark a variable referenced, and check whether it is odr-used | |||
15057 | /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be | |||
15058 | /// used directly for normal expressions referring to VarDecl. | |||
15059 | void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { | |||
15060 | DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); | |||
15061 | } | |||
15062 | ||||
15063 | static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, | |||
15064 | Decl *D, Expr *E, bool MightBeOdrUse) { | |||
15065 | if (SemaRef.isInOpenMPDeclareTargetContext()) | |||
15066 | SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); | |||
15067 | ||||
15068 | if (VarDecl *Var = dyn_cast<VarDecl>(D)) { | |||
15069 | DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); | |||
15070 | return; | |||
15071 | } | |||
15072 | ||||
15073 | SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); | |||
15074 | ||||
15075 | // If this is a call to a method via a cast, also mark the method in the | |||
15076 | // derived class used in case codegen can devirtualize the call. | |||
15077 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | |||
15078 | if (!ME) | |||
15079 | return; | |||
15080 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); | |||
15081 | if (!MD) | |||
15082 | return; | |||
15083 | // Only attempt to devirtualize if this is truly a virtual call. | |||
15084 | bool IsVirtualCall = MD->isVirtual() && | |||
15085 | ME->performsVirtualDispatch(SemaRef.getLangOpts()); | |||
15086 | if (!IsVirtualCall) | |||
15087 | return; | |||
15088 | ||||
15089 | // If it's possible to devirtualize the call, mark the called function | |||
15090 | // referenced. | |||
15091 | CXXMethodDecl *DM = MD->getDevirtualizedMethod( | |||
15092 | ME->getBase(), SemaRef.getLangOpts().AppleKext); | |||
15093 | if (DM) | |||
15094 | SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); | |||
15095 | } | |||
15096 | ||||
15097 | /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. | |||
15098 | void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { | |||
15099 | // TODO: update this with DR# once a defect report is filed. | |||
15100 | // C++11 defect. The address of a pure member should not be an ODR use, even | |||
15101 | // if it's a qualified reference. | |||
15102 | bool OdrUse = true; | |||
15103 | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) | |||
15104 | if (Method->isVirtual() && | |||
15105 | !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) | |||
15106 | OdrUse = false; | |||
15107 | MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); | |||
15108 | } | |||
15109 | ||||
15110 | /// \brief Perform reference-marking and odr-use handling for a MemberExpr. | |||
15111 | void Sema::MarkMemberReferenced(MemberExpr *E) { | |||
15112 | // C++11 [basic.def.odr]p2: | |||
15113 | // A non-overloaded function whose name appears as a potentially-evaluated | |||
15114 | // expression or a member of a set of candidate functions, if selected by | |||
15115 | // overload resolution when referred to from a potentially-evaluated | |||
15116 | // expression, is odr-used, unless it is a pure virtual function and its | |||
15117 | // name is not explicitly qualified. | |||
15118 | bool MightBeOdrUse = true; | |||
15119 | if (E->performsVirtualDispatch(getLangOpts())) { | |||
15120 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) | |||
15121 | if (Method->isPure()) | |||
15122 | MightBeOdrUse = false; | |||
15123 | } | |||
15124 | SourceLocation Loc = E->getMemberLoc().isValid() ? | |||
15125 | E->getMemberLoc() : E->getLocStart(); | |||
15126 | MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); | |||
15127 | } | |||
15128 | ||||
15129 | /// \brief Perform marking for a reference to an arbitrary declaration. It | |||
15130 | /// marks the declaration referenced, and performs odr-use checking for | |||
15131 | /// functions and variables. This method should not be used when building a | |||
15132 | /// normal expression which refers to a variable. | |||
15133 | void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, | |||
15134 | bool MightBeOdrUse) { | |||
15135 | if (MightBeOdrUse) { | |||
15136 | if (auto *VD = dyn_cast<VarDecl>(D)) { | |||
15137 | MarkVariableReferenced(Loc, VD); | |||
15138 | return; | |||
15139 | } | |||
15140 | } | |||
15141 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { | |||
15142 | MarkFunctionReferenced(Loc, FD, MightBeOdrUse); | |||
15143 | return; | |||
15144 | } | |||
15145 | D->setReferenced(); | |||
15146 | } | |||
15147 | ||||
15148 | namespace { | |||
15149 | // Mark all of the declarations used by a type as referenced. | |||
15150 | // FIXME: Not fully implemented yet! We need to have a better understanding | |||
15151 | // of when we're entering a context we should not recurse into. | |||
15152 | // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to | |||
15153 | // TreeTransforms rebuilding the type in a new context. Rather than | |||
15154 | // duplicating the TreeTransform logic, we should consider reusing it here. | |||
15155 | // Currently that causes problems when rebuilding LambdaExprs. | |||
15156 | class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { | |||
15157 | Sema &S; | |||
15158 | SourceLocation Loc; | |||
15159 | ||||
15160 | public: | |||
15161 | typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; | |||
15162 | ||||
15163 | MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } | |||
15164 | ||||
15165 | bool TraverseTemplateArgument(const TemplateArgument &Arg); | |||
15166 | }; | |||
15167 | } | |||
15168 | ||||
15169 | bool MarkReferencedDecls::TraverseTemplateArgument( | |||
15170 | const TemplateArgument &Arg) { | |||
15171 | { | |||
15172 | // A non-type template argument is a constant-evaluated context. | |||
15173 | EnterExpressionEvaluationContext Evaluated( | |||
15174 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); | |||
15175 | if (Arg.getKind() == TemplateArgument::Declaration) { | |||
15176 | if (Decl *D = Arg.getAsDecl()) | |||
15177 | S.MarkAnyDeclReferenced(Loc, D, true); | |||
15178 | } else if (Arg.getKind() == TemplateArgument::Expression) { | |||
15179 | S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); | |||
15180 | } | |||
15181 | } | |||
15182 | ||||
15183 | return Inherited::TraverseTemplateArgument(Arg); | |||
15184 | } | |||
15185 | ||||
15186 | void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { | |||
15187 | MarkReferencedDecls Marker(*this, Loc); | |||
15188 | Marker.TraverseType(T); | |||
15189 | } | |||
15190 | ||||
15191 | namespace { | |||
15192 | /// \brief Helper class that marks all of the declarations referenced by | |||
15193 | /// potentially-evaluated subexpressions as "referenced". | |||
15194 | class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { | |||
15195 | Sema &S; | |||
15196 | bool SkipLocalVariables; | |||
15197 | ||||
15198 | public: | |||
15199 | typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; | |||
15200 | ||||
15201 | EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) | |||
15202 | : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } | |||
15203 | ||||
15204 | void VisitDeclRefExpr(DeclRefExpr *E) { | |||
15205 | // If we were asked not to visit local variables, don't. | |||
15206 | if (SkipLocalVariables) { | |||
15207 | if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) | |||
15208 | if (VD->hasLocalStorage()) | |||
15209 | return; | |||
15210 | } | |||
15211 | ||||
15212 | S.MarkDeclRefReferenced(E); | |||
15213 | } | |||
15214 | ||||
15215 | void VisitMemberExpr(MemberExpr *E) { | |||
15216 | S.MarkMemberReferenced(E); | |||
15217 | Inherited::VisitMemberExpr(E); | |||
15218 | } | |||
15219 | ||||
15220 | void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { | |||
15221 | S.MarkFunctionReferenced(E->getLocStart(), | |||
15222 | const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); | |||
15223 | Visit(E->getSubExpr()); | |||
15224 | } | |||
15225 | ||||
15226 | void VisitCXXNewExpr(CXXNewExpr *E) { | |||
15227 | if (E->getOperatorNew()) | |||
15228 | S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); | |||
15229 | if (E->getOperatorDelete()) | |||
15230 | S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); | |||
15231 | Inherited::VisitCXXNewExpr(E); | |||
15232 | } | |||
15233 | ||||
15234 | void VisitCXXDeleteExpr(CXXDeleteExpr *E) { | |||
15235 | if (E->getOperatorDelete()) | |||
15236 | S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); | |||
15237 | QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); | |||
15238 | if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { | |||
15239 | CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); | |||
15240 | S.MarkFunctionReferenced(E->getLocStart(), | |||
15241 | S.LookupDestructor(Record)); | |||
15242 | } | |||
15243 | ||||
15244 | Inherited::VisitCXXDeleteExpr(E); | |||
15245 | } | |||
15246 | ||||
15247 | void VisitCXXConstructExpr(CXXConstructExpr *E) { | |||
15248 | S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); | |||
15249 | Inherited::VisitCXXConstructExpr(E); | |||
15250 | } | |||
15251 | ||||
15252 | void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { | |||
15253 | Visit(E->getExpr()); | |||
15254 | } | |||
15255 | ||||
15256 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { | |||
15257 | Inherited::VisitImplicitCastExpr(E); | |||
15258 | ||||
15259 | if (E->getCastKind() == CK_LValueToRValue) | |||
15260 | S.UpdateMarkingForLValueToRValue(E->getSubExpr()); | |||
15261 | } | |||
15262 | }; | |||
15263 | } | |||
15264 | ||||
15265 | /// \brief Mark any declarations that appear within this expression or any | |||
15266 | /// potentially-evaluated subexpressions as "referenced". | |||
15267 | /// | |||
15268 | /// \param SkipLocalVariables If true, don't mark local variables as | |||
15269 | /// 'referenced'. | |||
15270 | void Sema::MarkDeclarationsReferencedInExpr(Expr *E, | |||
15271 | bool SkipLocalVariables) { | |||
15272 | EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); | |||
15273 | } | |||
15274 | ||||
15275 | /// \brief Emit a diagnostic that describes an effect on the run-time behavior | |||
15276 | /// of the program being compiled. | |||
15277 | /// | |||
15278 | /// This routine emits the given diagnostic when the code currently being | |||
15279 | /// type-checked is "potentially evaluated", meaning that there is a | |||
15280 | /// possibility that the code will actually be executable. Code in sizeof() | |||
15281 | /// expressions, code used only during overload resolution, etc., are not | |||
15282 | /// potentially evaluated. This routine will suppress such diagnostics or, | |||
15283 | /// in the absolutely nutty case of potentially potentially evaluated | |||
15284 | /// expressions (C++ typeid), queue the diagnostic to potentially emit it | |||
15285 | /// later. | |||
15286 | /// | |||
15287 | /// This routine should be used for all diagnostics that describe the run-time | |||
15288 | /// behavior of a program, such as passing a non-POD value through an ellipsis. | |||
15289 | /// Failure to do so will likely result in spurious diagnostics or failures | |||
15290 | /// during overload resolution or within sizeof/alignof/typeof/typeid. | |||
15291 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, | |||
15292 | const PartialDiagnostic &PD) { | |||
15293 | switch (ExprEvalContexts.back().Context) { | |||
15294 | case ExpressionEvaluationContext::Unevaluated: | |||
15295 | case ExpressionEvaluationContext::UnevaluatedList: | |||
15296 | case ExpressionEvaluationContext::UnevaluatedAbstract: | |||
15297 | case ExpressionEvaluationContext::DiscardedStatement: | |||
15298 | // The argument will never be evaluated, so don't complain. | |||
15299 | break; | |||
15300 | ||||
15301 | case ExpressionEvaluationContext::ConstantEvaluated: | |||
15302 | // Relevant diagnostics should be produced by constant evaluation. | |||
15303 | break; | |||
15304 | ||||
15305 | case ExpressionEvaluationContext::PotentiallyEvaluated: | |||
15306 | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | |||
15307 | if (Statement && getCurFunctionOrMethodDecl()) { | |||
15308 | FunctionScopes.back()->PossiblyUnreachableDiags. | |||
15309 | push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); | |||
15310 | return true; | |||
15311 | } | |||
15312 | ||||
15313 | // The initializer of a constexpr variable or of the first declaration of a | |||
15314 | // static data member is not syntactically a constant evaluated constant, | |||
15315 | // but nonetheless is always required to be a constant expression, so we | |||
15316 | // can skip diagnosing. | |||
15317 | // FIXME: Using the mangling context here is a hack. | |||
15318 | if (auto *VD = dyn_cast_or_null<VarDecl>( | |||
15319 | ExprEvalContexts.back().ManglingContextDecl)) { | |||
15320 | if (VD->isConstexpr() || | |||
15321 | (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) | |||
15322 | break; | |||
15323 | // FIXME: For any other kind of variable, we should build a CFG for its | |||
15324 | // initializer and check whether the context in question is reachable. | |||
15325 | } | |||
15326 | ||||
15327 | Diag(Loc, PD); | |||
15328 | return true; | |||
15329 | } | |||
15330 | ||||
15331 | return false; | |||
15332 | } | |||
15333 | ||||
15334 | bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, | |||
15335 | CallExpr *CE, FunctionDecl *FD) { | |||
15336 | if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) | |||
15337 | return false; | |||
15338 | ||||
15339 | // If we're inside a decltype's expression, don't check for a valid return | |||
15340 | // type or construct temporaries until we know whether this is the last call. | |||
15341 | if (ExprEvalContexts.back().IsDecltype) { | |||
15342 | ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); | |||
15343 | return false; | |||
15344 | } | |||
15345 | ||||
15346 | class CallReturnIncompleteDiagnoser : public TypeDiagnoser { | |||
15347 | FunctionDecl *FD; | |||
15348 | CallExpr *CE; | |||
15349 | ||||
15350 | public: | |||
15351 | CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) | |||
15352 | : FD(FD), CE(CE) { } | |||
15353 | ||||
15354 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | |||
15355 | if (!FD) { | |||
15356 | S.Diag(Loc, diag::err_call_incomplete_return) | |||
15357 | << T << CE->getSourceRange(); | |||
15358 | return; | |||
15359 | } | |||
15360 | ||||
15361 | S.Diag(Loc, diag::err_call_function_incomplete_return) | |||
15362 | << CE->getSourceRange() << FD->getDeclName() << T; | |||
15363 | S.Diag(FD->getLocation(), diag::note_entity_declared_at) | |||
15364 | << FD->getDeclName(); | |||
15365 | } | |||
15366 | } Diagnoser(FD, CE); | |||
15367 | ||||
15368 | if (RequireCompleteType(Loc, ReturnType, Diagnoser)) | |||
15369 | return true; | |||
15370 | ||||
15371 | return false; | |||
15372 | } | |||
15373 | ||||
15374 | // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses | |||
15375 | // will prevent this condition from triggering, which is what we want. | |||
15376 | void Sema::DiagnoseAssignmentAsCondition(Expr *E) { | |||
15377 | SourceLocation Loc; | |||
15378 | ||||
15379 | unsigned diagnostic = diag::warn_condition_is_assignment; | |||
15380 | bool IsOrAssign = false; | |||
15381 | ||||
15382 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { | |||
15383 | if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) | |||
15384 | return; | |||
15385 | ||||
15386 | IsOrAssign = Op->getOpcode() == BO_OrAssign; | |||
15387 | ||||
15388 | // Greylist some idioms by putting them into a warning subcategory. | |||
15389 | if (ObjCMessageExpr *ME | |||
15390 | = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { | |||
15391 | Selector Sel = ME->getSelector(); | |||
15392 | ||||
15393 | // self = [<foo> init...] | |||
15394 | if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) | |||
15395 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | |||
15396 | ||||
15397 | // <foo> = [<bar> nextObject] | |||
15398 | else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") | |||
15399 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | |||
15400 | } | |||
15401 | ||||
15402 | Loc = Op->getOperatorLoc(); | |||
15403 | } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { | |||
15404 | if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) | |||
15405 | return; | |||
15406 | ||||
15407 | IsOrAssign = Op->getOperator() == OO_PipeEqual; | |||
15408 | Loc = Op->getOperatorLoc(); | |||
15409 | } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) | |||
15410 | return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); | |||
15411 | else { | |||
15412 | // Not an assignment. | |||
15413 | return; | |||
15414 | } | |||
15415 | ||||
15416 | Diag(Loc, diagnostic) << E->getSourceRange(); | |||
15417 | ||||
15418 | SourceLocation Open = E->getLocStart(); | |||
15419 | SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); | |||
15420 | Diag(Loc, diag::note_condition_assign_silence) | |||
15421 | << FixItHint::CreateInsertion(Open, "(") | |||
15422 | << FixItHint::CreateInsertion(Close, ")"); | |||
15423 | ||||
15424 | if (IsOrAssign) | |||
15425 | Diag(Loc, diag::note_condition_or_assign_to_comparison) | |||
15426 | << FixItHint::CreateReplacement(Loc, "!="); | |||
15427 | else | |||
15428 | Diag(Loc, diag::note_condition_assign_to_comparison) | |||
15429 | << FixItHint::CreateReplacement(Loc, "=="); | |||
15430 | } | |||
15431 | ||||
15432 | /// \brief Redundant parentheses over an equality comparison can indicate | |||
15433 | /// that the user intended an assignment used as condition. | |||
15434 | void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { | |||
15435 | // Don't warn if the parens came from a macro. | |||
15436 | SourceLocation parenLoc = ParenE->getLocStart(); | |||
15437 | if (parenLoc.isInvalid() || parenLoc.isMacroID()) | |||
15438 | return; | |||
15439 | // Don't warn for dependent expressions. | |||
15440 | if (ParenE->isTypeDependent()) | |||
15441 | return; | |||
15442 | ||||
15443 | Expr *E = ParenE->IgnoreParens(); | |||
15444 | ||||
15445 | if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) | |||
15446 | if (opE->getOpcode() == BO_EQ && | |||
15447 | opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) | |||
15448 | == Expr::MLV_Valid) { | |||
15449 | SourceLocation Loc = opE->getOperatorLoc(); | |||
15450 | ||||
15451 | Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); | |||
15452 | SourceRange ParenERange = ParenE->getSourceRange(); | |||
15453 | Diag(Loc, diag::note_equality_comparison_silence) | |||
15454 | << FixItHint::CreateRemoval(ParenERange.getBegin()) | |||
15455 | << FixItHint::CreateRemoval(ParenERange.getEnd()); | |||
15456 | Diag(Loc, diag::note_equality_comparison_to_assign) | |||
15457 | << FixItHint::CreateReplacement(Loc, "="); | |||
15458 | } | |||
15459 | } | |||
15460 | ||||
15461 | ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, | |||
15462 | bool IsConstexpr) { | |||
15463 | DiagnoseAssignmentAsCondition(E); | |||
15464 | if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) | |||
15465 | DiagnoseEqualityWithExtraParens(parenE); | |||
15466 | ||||
15467 | ExprResult result = CheckPlaceholderExpr(E); | |||
15468 | if (result.isInvalid()) return ExprError(); | |||
15469 | E = result.get(); | |||
15470 | ||||
15471 | if (!E->isTypeDependent()) { | |||
15472 | if (getLangOpts().CPlusPlus) | |||
15473 | return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 | |||
15474 | ||||
15475 | ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); | |||
15476 | if (ERes.isInvalid()) | |||
15477 | return ExprError(); | |||
15478 | E = ERes.get(); | |||
15479 | ||||
15480 | QualType T = E->getType(); | |||
15481 | if (!T->isScalarType()) { // C99 6.8.4.1p1 | |||
15482 | Diag(Loc, diag::err_typecheck_statement_requires_scalar) | |||
15483 | << T << E->getSourceRange(); | |||
15484 | return ExprError(); | |||
15485 | } | |||
15486 | CheckBoolLikeConversion(E, Loc); | |||
15487 | } | |||
15488 | ||||
15489 | return E; | |||
15490 | } | |||
15491 | ||||
15492 | Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, | |||
15493 | Expr *SubExpr, ConditionKind CK) { | |||
15494 | // Empty conditions are valid in for-statements. | |||
15495 | if (!SubExpr) | |||
15496 | return ConditionResult(); | |||
15497 | ||||
15498 | ExprResult Cond; | |||
15499 | switch (CK) { | |||
15500 | case ConditionKind::Boolean: | |||
15501 | Cond = CheckBooleanCondition(Loc, SubExpr); | |||
15502 | break; | |||
15503 | ||||
15504 | case ConditionKind::ConstexprIf: | |||
15505 | Cond = CheckBooleanCondition(Loc, SubExpr, true); | |||
15506 | break; | |||
15507 | ||||
15508 | case ConditionKind::Switch: | |||
15509 | Cond = CheckSwitchCondition(Loc, SubExpr); | |||
15510 | break; | |||
15511 | } | |||
15512 | if (Cond.isInvalid()) | |||
15513 | return ConditionError(); | |||
15514 | ||||
15515 | // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. | |||
15516 | FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); | |||
15517 | if (!FullExpr.get()) | |||
15518 | return ConditionError(); | |||
15519 | ||||
15520 | return ConditionResult(*this, nullptr, FullExpr, | |||
15521 | CK == ConditionKind::ConstexprIf); | |||
15522 | } | |||
15523 | ||||
15524 | namespace { | |||
15525 | /// A visitor for rebuilding a call to an __unknown_any expression | |||
15526 | /// to have an appropriate type. | |||
15527 | struct RebuildUnknownAnyFunction | |||
15528 | : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { | |||
15529 | ||||
15530 | Sema &S; | |||
15531 | ||||
15532 | RebuildUnknownAnyFunction(Sema &S) : S(S) {} | |||
15533 | ||||
15534 | ExprResult VisitStmt(Stmt *S) { | |||
15535 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15535); | |||
15536 | } | |||
15537 | ||||
15538 | ExprResult VisitExpr(Expr *E) { | |||
15539 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) | |||
15540 | << E->getSourceRange(); | |||
15541 | return ExprError(); | |||
15542 | } | |||
15543 | ||||
15544 | /// Rebuild an expression which simply semantically wraps another | |||
15545 | /// expression which it shares the type and value kind of. | |||
15546 | template <class T> ExprResult rebuildSugarExpr(T *E) { | |||
15547 | ExprResult SubResult = Visit(E->getSubExpr()); | |||
15548 | if (SubResult.isInvalid()) return ExprError(); | |||
15549 | ||||
15550 | Expr *SubExpr = SubResult.get(); | |||
15551 | E->setSubExpr(SubExpr); | |||
15552 | E->setType(SubExpr->getType()); | |||
15553 | E->setValueKind(SubExpr->getValueKind()); | |||
15554 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15554, __extension__ __PRETTY_FUNCTION__)); | |||
15555 | return E; | |||
15556 | } | |||
15557 | ||||
15558 | ExprResult VisitParenExpr(ParenExpr *E) { | |||
15559 | return rebuildSugarExpr(E); | |||
15560 | } | |||
15561 | ||||
15562 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | |||
15563 | return rebuildSugarExpr(E); | |||
15564 | } | |||
15565 | ||||
15566 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | |||
15567 | ExprResult SubResult = Visit(E->getSubExpr()); | |||
15568 | if (SubResult.isInvalid()) return ExprError(); | |||
15569 | ||||
15570 | Expr *SubExpr = SubResult.get(); | |||
15571 | E->setSubExpr(SubExpr); | |||
15572 | E->setType(S.Context.getPointerType(SubExpr->getType())); | |||
15573 | assert(E->getValueKind() == VK_RValue)(static_cast <bool> (E->getValueKind() == VK_RValue) ? void (0) : __assert_fail ("E->getValueKind() == VK_RValue" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15573, __extension__ __PRETTY_FUNCTION__)); | |||
15574 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15574, __extension__ __PRETTY_FUNCTION__)); | |||
15575 | return E; | |||
15576 | } | |||
15577 | ||||
15578 | ExprResult resolveDecl(Expr *E, ValueDecl *VD) { | |||
15579 | if (!isa<FunctionDecl>(VD)) return VisitExpr(E); | |||
15580 | ||||
15581 | E->setType(VD->getType()); | |||
15582 | ||||
15583 | assert(E->getValueKind() == VK_RValue)(static_cast <bool> (E->getValueKind() == VK_RValue) ? void (0) : __assert_fail ("E->getValueKind() == VK_RValue" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15583, __extension__ __PRETTY_FUNCTION__)); | |||
15584 | if (S.getLangOpts().CPlusPlus && | |||
15585 | !(isa<CXXMethodDecl>(VD) && | |||
15586 | cast<CXXMethodDecl>(VD)->isInstance())) | |||
15587 | E->setValueKind(VK_LValue); | |||
15588 | ||||
15589 | return E; | |||
15590 | } | |||
15591 | ||||
15592 | ExprResult VisitMemberExpr(MemberExpr *E) { | |||
15593 | return resolveDecl(E, E->getMemberDecl()); | |||
15594 | } | |||
15595 | ||||
15596 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | |||
15597 | return resolveDecl(E, E->getDecl()); | |||
15598 | } | |||
15599 | }; | |||
15600 | } | |||
15601 | ||||
15602 | /// Given a function expression of unknown-any type, try to rebuild it | |||
15603 | /// to have a function type. | |||
15604 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { | |||
15605 | ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); | |||
15606 | if (Result.isInvalid()) return ExprError(); | |||
15607 | return S.DefaultFunctionArrayConversion(Result.get()); | |||
15608 | } | |||
15609 | ||||
15610 | namespace { | |||
15611 | /// A visitor for rebuilding an expression of type __unknown_anytype | |||
15612 | /// into one which resolves the type directly on the referring | |||
15613 | /// expression. Strict preservation of the original source | |||
15614 | /// structure is not a goal. | |||
15615 | struct RebuildUnknownAnyExpr | |||
15616 | : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { | |||
15617 | ||||
15618 | Sema &S; | |||
15619 | ||||
15620 | /// The current destination type. | |||
15621 | QualType DestType; | |||
15622 | ||||
15623 | RebuildUnknownAnyExpr(Sema &S, QualType CastType) | |||
15624 | : S(S), DestType(CastType) {} | |||
15625 | ||||
15626 | ExprResult VisitStmt(Stmt *S) { | |||
15627 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15627); | |||
15628 | } | |||
15629 | ||||
15630 | ExprResult VisitExpr(Expr *E) { | |||
15631 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | |||
15632 | << E->getSourceRange(); | |||
15633 | return ExprError(); | |||
15634 | } | |||
15635 | ||||
15636 | ExprResult VisitCallExpr(CallExpr *E); | |||
15637 | ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); | |||
15638 | ||||
15639 | /// Rebuild an expression which simply semantically wraps another | |||
15640 | /// expression which it shares the type and value kind of. | |||
15641 | template <class T> ExprResult rebuildSugarExpr(T *E) { | |||
15642 | ExprResult SubResult = Visit(E->getSubExpr()); | |||
15643 | if (SubResult.isInvalid()) return ExprError(); | |||
15644 | Expr *SubExpr = SubResult.get(); | |||
15645 | E->setSubExpr(SubExpr); | |||
15646 | E->setType(SubExpr->getType()); | |||
15647 | E->setValueKind(SubExpr->getValueKind()); | |||
15648 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15648, __extension__ __PRETTY_FUNCTION__)); | |||
15649 | return E; | |||
15650 | } | |||
15651 | ||||
15652 | ExprResult VisitParenExpr(ParenExpr *E) { | |||
15653 | return rebuildSugarExpr(E); | |||
15654 | } | |||
15655 | ||||
15656 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | |||
15657 | return rebuildSugarExpr(E); | |||
15658 | } | |||
15659 | ||||
15660 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | |||
15661 | const PointerType *Ptr = DestType->getAs<PointerType>(); | |||
15662 | if (!Ptr) { | |||
15663 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) | |||
15664 | << E->getSourceRange(); | |||
15665 | return ExprError(); | |||
15666 | } | |||
15667 | ||||
15668 | if (isa<CallExpr>(E->getSubExpr())) { | |||
15669 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) | |||
15670 | << E->getSourceRange(); | |||
15671 | return ExprError(); | |||
15672 | } | |||
15673 | ||||
15674 | assert(E->getValueKind() == VK_RValue)(static_cast <bool> (E->getValueKind() == VK_RValue) ? void (0) : __assert_fail ("E->getValueKind() == VK_RValue" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15674, __extension__ __PRETTY_FUNCTION__)); | |||
15675 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15675, __extension__ __PRETTY_FUNCTION__)); | |||
15676 | E->setType(DestType); | |||
15677 | ||||
15678 | // Build the sub-expression as if it were an object of the pointee type. | |||
15679 | DestType = Ptr->getPointeeType(); | |||
15680 | ExprResult SubResult = Visit(E->getSubExpr()); | |||
15681 | if (SubResult.isInvalid()) return ExprError(); | |||
15682 | E->setSubExpr(SubResult.get()); | |||
15683 | return E; | |||
15684 | } | |||
15685 | ||||
15686 | ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); | |||
15687 | ||||
15688 | ExprResult resolveDecl(Expr *E, ValueDecl *VD); | |||
15689 | ||||
15690 | ExprResult VisitMemberExpr(MemberExpr *E) { | |||
15691 | return resolveDecl(E, E->getMemberDecl()); | |||
15692 | } | |||
15693 | ||||
15694 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | |||
15695 | return resolveDecl(E, E->getDecl()); | |||
15696 | } | |||
15697 | }; | |||
15698 | } | |||
15699 | ||||
15700 | /// Rebuilds a call expression which yielded __unknown_anytype. | |||
15701 | ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { | |||
15702 | Expr *CalleeExpr = E->getCallee(); | |||
15703 | ||||
15704 | enum FnKind { | |||
15705 | FK_MemberFunction, | |||
15706 | FK_FunctionPointer, | |||
15707 | FK_BlockPointer | |||
15708 | }; | |||
15709 | ||||
15710 | FnKind Kind; | |||
15711 | QualType CalleeType = CalleeExpr->getType(); | |||
15712 | if (CalleeType == S.Context.BoundMemberTy) { | |||
15713 | 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)" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15713, __extension__ __PRETTY_FUNCTION__)); | |||
15714 | Kind = FK_MemberFunction; | |||
15715 | CalleeType = Expr::findBoundMemberType(CalleeExpr); | |||
15716 | } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { | |||
15717 | CalleeType = Ptr->getPointeeType(); | |||
15718 | Kind = FK_FunctionPointer; | |||
15719 | } else { | |||
15720 | CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); | |||
15721 | Kind = FK_BlockPointer; | |||
15722 | } | |||
15723 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); | |||
15724 | ||||
15725 | // Verify that this is a legal result type of a function. | |||
15726 | if (DestType->isArrayType() || DestType->isFunctionType()) { | |||
15727 | unsigned diagID = diag::err_func_returning_array_function; | |||
15728 | if (Kind == FK_BlockPointer) | |||
15729 | diagID = diag::err_block_returning_array_function; | |||
15730 | ||||
15731 | S.Diag(E->getExprLoc(), diagID) | |||
15732 | << DestType->isFunctionType() << DestType; | |||
15733 | return ExprError(); | |||
15734 | } | |||
15735 | ||||
15736 | // Otherwise, go ahead and set DestType as the call's result. | |||
15737 | E->setType(DestType.getNonLValueExprType(S.Context)); | |||
15738 | E->setValueKind(Expr::getValueKindForType(DestType)); | |||
15739 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15739, __extension__ __PRETTY_FUNCTION__)); | |||
15740 | ||||
15741 | // Rebuild the function type, replacing the result type with DestType. | |||
15742 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); | |||
15743 | if (Proto) { | |||
15744 | // __unknown_anytype(...) is a special case used by the debugger when | |||
15745 | // it has no idea what a function's signature is. | |||
15746 | // | |||
15747 | // We want to build this call essentially under the K&R | |||
15748 | // unprototyped rules, but making a FunctionNoProtoType in C++ | |||
15749 | // would foul up all sorts of assumptions. However, we cannot | |||
15750 | // simply pass all arguments as variadic arguments, nor can we | |||
15751 | // portably just call the function under a non-variadic type; see | |||
15752 | // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. | |||
15753 | // However, it turns out that in practice it is generally safe to | |||
15754 | // call a function declared as "A foo(B,C,D);" under the prototype | |||
15755 | // "A foo(B,C,D,...);". The only known exception is with the | |||
15756 | // Windows ABI, where any variadic function is implicitly cdecl | |||
15757 | // regardless of its normal CC. Therefore we change the parameter | |||
15758 | // types to match the types of the arguments. | |||
15759 | // | |||
15760 | // This is a hack, but it is far superior to moving the | |||
15761 | // corresponding target-specific code from IR-gen to Sema/AST. | |||
15762 | ||||
15763 | ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); | |||
15764 | SmallVector<QualType, 8> ArgTypes; | |||
15765 | if (ParamTypes.empty() && Proto->isVariadic()) { // the special case | |||
15766 | ArgTypes.reserve(E->getNumArgs()); | |||
15767 | for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { | |||
15768 | Expr *Arg = E->getArg(i); | |||
15769 | QualType ArgType = Arg->getType(); | |||
15770 | if (E->isLValue()) { | |||
15771 | ArgType = S.Context.getLValueReferenceType(ArgType); | |||
15772 | } else if (E->isXValue()) { | |||
15773 | ArgType = S.Context.getRValueReferenceType(ArgType); | |||
15774 | } | |||
15775 | ArgTypes.push_back(ArgType); | |||
15776 | } | |||
15777 | ParamTypes = ArgTypes; | |||
15778 | } | |||
15779 | DestType = S.Context.getFunctionType(DestType, ParamTypes, | |||
15780 | Proto->getExtProtoInfo()); | |||
15781 | } else { | |||
15782 | DestType = S.Context.getFunctionNoProtoType(DestType, | |||
15783 | FnType->getExtInfo()); | |||
15784 | } | |||
15785 | ||||
15786 | // Rebuild the appropriate pointer-to-function type. | |||
15787 | switch (Kind) { | |||
15788 | case FK_MemberFunction: | |||
15789 | // Nothing to do. | |||
15790 | break; | |||
15791 | ||||
15792 | case FK_FunctionPointer: | |||
15793 | DestType = S.Context.getPointerType(DestType); | |||
15794 | break; | |||
15795 | ||||
15796 | case FK_BlockPointer: | |||
15797 | DestType = S.Context.getBlockPointerType(DestType); | |||
15798 | break; | |||
15799 | } | |||
15800 | ||||
15801 | // Finally, we can recurse. | |||
15802 | ExprResult CalleeResult = Visit(CalleeExpr); | |||
15803 | if (!CalleeResult.isUsable()) return ExprError(); | |||
15804 | E->setCallee(CalleeResult.get()); | |||
15805 | ||||
15806 | // Bind a temporary if necessary. | |||
15807 | return S.MaybeBindToTemporary(E); | |||
15808 | } | |||
15809 | ||||
15810 | ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { | |||
15811 | // Verify that this is a legal result type of a call. | |||
15812 | if (DestType->isArrayType() || DestType->isFunctionType()) { | |||
15813 | S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) | |||
15814 | << DestType->isFunctionType() << DestType; | |||
15815 | return ExprError(); | |||
15816 | } | |||
15817 | ||||
15818 | // Rewrite the method result type if available. | |||
15819 | if (ObjCMethodDecl *Method = E->getMethodDecl()) { | |||
15820 | assert(Method->getReturnType() == S.Context.UnknownAnyTy)(static_cast <bool> (Method->getReturnType() == S.Context .UnknownAnyTy) ? void (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15820, __extension__ __PRETTY_FUNCTION__)); | |||
15821 | Method->setReturnType(DestType); | |||
15822 | } | |||
15823 | ||||
15824 | // Change the type of the message. | |||
15825 | E->setType(DestType.getNonReferenceType()); | |||
15826 | E->setValueKind(Expr::getValueKindForType(DestType)); | |||
15827 | ||||
15828 | return S.MaybeBindToTemporary(E); | |||
15829 | } | |||
15830 | ||||
15831 | ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { | |||
15832 | // The only case we should ever see here is a function-to-pointer decay. | |||
15833 | if (E->getCastKind() == CK_FunctionToPointerDecay) { | |||
15834 | assert(E->getValueKind() == VK_RValue)(static_cast <bool> (E->getValueKind() == VK_RValue) ? void (0) : __assert_fail ("E->getValueKind() == VK_RValue" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15834, __extension__ __PRETTY_FUNCTION__)); | |||
15835 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15835, __extension__ __PRETTY_FUNCTION__)); | |||
15836 | ||||
15837 | E->setType(DestType); | |||
15838 | ||||
15839 | // Rebuild the sub-expression as the pointee (function) type. | |||
15840 | DestType = DestType->castAs<PointerType>()->getPointeeType(); | |||
15841 | ||||
15842 | ExprResult Result = Visit(E->getSubExpr()); | |||
15843 | if (!Result.isUsable()) return ExprError(); | |||
15844 | ||||
15845 | E->setSubExpr(Result.get()); | |||
15846 | return E; | |||
15847 | } else if (E->getCastKind() == CK_LValueToRValue) { | |||
15848 | assert(E->getValueKind() == VK_RValue)(static_cast <bool> (E->getValueKind() == VK_RValue) ? void (0) : __assert_fail ("E->getValueKind() == VK_RValue" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15848, __extension__ __PRETTY_FUNCTION__)); | |||
15849 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15849, __extension__ __PRETTY_FUNCTION__)); | |||
15850 | ||||
15851 | assert(isa<BlockPointerType>(E->getType()))(static_cast <bool> (isa<BlockPointerType>(E-> getType())) ? void (0) : __assert_fail ("isa<BlockPointerType>(E->getType())" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15851, __extension__ __PRETTY_FUNCTION__)); | |||
15852 | ||||
15853 | E->setType(DestType); | |||
15854 | ||||
15855 | // The sub-expression has to be a lvalue reference, so rebuild it as such. | |||
15856 | DestType = S.Context.getLValueReferenceType(DestType); | |||
15857 | ||||
15858 | ExprResult Result = Visit(E->getSubExpr()); | |||
15859 | if (!Result.isUsable()) return ExprError(); | |||
15860 | ||||
15861 | E->setSubExpr(Result.get()); | |||
15862 | return E; | |||
15863 | } else { | |||
15864 | llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15864); | |||
15865 | } | |||
15866 | } | |||
15867 | ||||
15868 | ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { | |||
15869 | ExprValueKind ValueKind = VK_LValue; | |||
15870 | QualType Type = DestType; | |||
15871 | ||||
15872 | // We know how to make this work for certain kinds of decls: | |||
15873 | ||||
15874 | // - functions | |||
15875 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { | |||
15876 | if (const PointerType *Ptr = Type->getAs<PointerType>()) { | |||
15877 | DestType = Ptr->getPointeeType(); | |||
15878 | ExprResult Result = resolveDecl(E, VD); | |||
15879 | if (Result.isInvalid()) return ExprError(); | |||
15880 | return S.ImpCastExprToType(Result.get(), Type, | |||
15881 | CK_FunctionToPointerDecay, VK_RValue); | |||
15882 | } | |||
15883 | ||||
15884 | if (!Type->isFunctionType()) { | |||
15885 | S.Diag(E->getExprLoc(), diag::err_unknown_any_function) | |||
15886 | << VD << E->getSourceRange(); | |||
15887 | return ExprError(); | |||
15888 | } | |||
15889 | if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { | |||
15890 | // We must match the FunctionDecl's type to the hack introduced in | |||
15891 | // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown | |||
15892 | // type. See the lengthy commentary in that routine. | |||
15893 | QualType FDT = FD->getType(); | |||
15894 | const FunctionType *FnType = FDT->castAs<FunctionType>(); | |||
15895 | const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); | |||
15896 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | |||
15897 | if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { | |||
15898 | SourceLocation Loc = FD->getLocation(); | |||
15899 | FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), | |||
15900 | FD->getDeclContext(), | |||
15901 | Loc, Loc, FD->getNameInfo().getName(), | |||
15902 | DestType, FD->getTypeSourceInfo(), | |||
15903 | SC_None, false/*isInlineSpecified*/, | |||
15904 | FD->hasPrototype(), | |||
15905 | false/*isConstexprSpecified*/); | |||
15906 | ||||
15907 | if (FD->getQualifier()) | |||
15908 | NewFD->setQualifierInfo(FD->getQualifierLoc()); | |||
15909 | ||||
15910 | SmallVector<ParmVarDecl*, 16> Params; | |||
15911 | for (const auto &AI : FT->param_types()) { | |||
15912 | ParmVarDecl *Param = | |||
15913 | S.BuildParmVarDeclForTypedef(FD, Loc, AI); | |||
15914 | Param->setScopeInfo(0, Params.size()); | |||
15915 | Params.push_back(Param); | |||
15916 | } | |||
15917 | NewFD->setParams(Params); | |||
15918 | DRE->setDecl(NewFD); | |||
15919 | VD = DRE->getDecl(); | |||
15920 | } | |||
15921 | } | |||
15922 | ||||
15923 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) | |||
15924 | if (MD->isInstance()) { | |||
15925 | ValueKind = VK_RValue; | |||
15926 | Type = S.Context.BoundMemberTy; | |||
15927 | } | |||
15928 | ||||
15929 | // Function references aren't l-values in C. | |||
15930 | if (!S.getLangOpts().CPlusPlus) | |||
15931 | ValueKind = VK_RValue; | |||
15932 | ||||
15933 | // - variables | |||
15934 | } else if (isa<VarDecl>(VD)) { | |||
15935 | if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { | |||
15936 | Type = RefTy->getPointeeType(); | |||
15937 | } else if (Type->isFunctionType()) { | |||
15938 | S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) | |||
15939 | << VD << E->getSourceRange(); | |||
15940 | return ExprError(); | |||
15941 | } | |||
15942 | ||||
15943 | // - nothing else | |||
15944 | } else { | |||
15945 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) | |||
15946 | << VD << E->getSourceRange(); | |||
15947 | return ExprError(); | |||
15948 | } | |||
15949 | ||||
15950 | // Modifying the declaration like this is friendly to IR-gen but | |||
15951 | // also really dangerous. | |||
15952 | VD->setType(DestType); | |||
15953 | E->setType(Type); | |||
15954 | E->setValueKind(ValueKind); | |||
15955 | return E; | |||
15956 | } | |||
15957 | ||||
15958 | /// Check a cast of an unknown-any type. We intentionally only | |||
15959 | /// trigger this for C-style casts. | |||
15960 | ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, | |||
15961 | Expr *CastExpr, CastKind &CastKind, | |||
15962 | ExprValueKind &VK, CXXCastPath &Path) { | |||
15963 | // The type we're casting to must be either void or complete. | |||
15964 | if (!CastType->isVoidType() && | |||
15965 | RequireCompleteType(TypeRange.getBegin(), CastType, | |||
15966 | diag::err_typecheck_cast_to_incomplete)) | |||
15967 | return ExprError(); | |||
15968 | ||||
15969 | // Rewrite the casted expression from scratch. | |||
15970 | ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); | |||
15971 | if (!result.isUsable()) return ExprError(); | |||
15972 | ||||
15973 | CastExpr = result.get(); | |||
15974 | VK = CastExpr->getValueKind(); | |||
15975 | CastKind = CK_NoOp; | |||
15976 | ||||
15977 | return CastExpr; | |||
15978 | } | |||
15979 | ||||
15980 | ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { | |||
15981 | return RebuildUnknownAnyExpr(*this, ToType).Visit(E); | |||
15982 | } | |||
15983 | ||||
15984 | ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, | |||
15985 | Expr *arg, QualType ¶mType) { | |||
15986 | // If the syntactic form of the argument is not an explicit cast of | |||
15987 | // any sort, just do default argument promotion. | |||
15988 | ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); | |||
15989 | if (!castArg) { | |||
15990 | ExprResult result = DefaultArgumentPromotion(arg); | |||
15991 | if (result.isInvalid()) return ExprError(); | |||
15992 | paramType = result.get()->getType(); | |||
15993 | return result; | |||
15994 | } | |||
15995 | ||||
15996 | // Otherwise, use the type that was written in the explicit cast. | |||
15997 | assert(!arg->hasPlaceholderType())(static_cast <bool> (!arg->hasPlaceholderType()) ? void (0) : __assert_fail ("!arg->hasPlaceholderType()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 15997, __extension__ __PRETTY_FUNCTION__)); | |||
15998 | paramType = castArg->getTypeAsWritten(); | |||
15999 | ||||
16000 | // Copy-initialize a parameter of that type. | |||
16001 | InitializedEntity entity = | |||
16002 | InitializedEntity::InitializeParameter(Context, paramType, | |||
16003 | /*consumed*/ false); | |||
16004 | return PerformCopyInitialization(entity, callLoc, arg); | |||
16005 | } | |||
16006 | ||||
16007 | static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { | |||
16008 | Expr *orig = E; | |||
16009 | unsigned diagID = diag::err_uncasted_use_of_unknown_any; | |||
16010 | while (true) { | |||
16011 | E = E->IgnoreParenImpCasts(); | |||
16012 | if (CallExpr *call = dyn_cast<CallExpr>(E)) { | |||
16013 | E = call->getCallee(); | |||
16014 | diagID = diag::err_uncasted_call_of_unknown_any; | |||
16015 | } else { | |||
16016 | break; | |||
16017 | } | |||
16018 | } | |||
16019 | ||||
16020 | SourceLocation loc; | |||
16021 | NamedDecl *d; | |||
16022 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { | |||
16023 | loc = ref->getLocation(); | |||
16024 | d = ref->getDecl(); | |||
16025 | } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { | |||
16026 | loc = mem->getMemberLoc(); | |||
16027 | d = mem->getMemberDecl(); | |||
16028 | } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { | |||
16029 | diagID = diag::err_uncasted_call_of_unknown_any; | |||
16030 | loc = msg->getSelectorStartLoc(); | |||
16031 | d = msg->getMethodDecl(); | |||
16032 | if (!d) { | |||
16033 | S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) | |||
16034 | << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() | |||
16035 | << orig->getSourceRange(); | |||
16036 | return ExprError(); | |||
16037 | } | |||
16038 | } else { | |||
16039 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | |||
16040 | << E->getSourceRange(); | |||
16041 | return ExprError(); | |||
16042 | } | |||
16043 | ||||
16044 | S.Diag(loc, diagID) << d << orig->getSourceRange(); | |||
16045 | ||||
16046 | // Never recoverable. | |||
16047 | return ExprError(); | |||
16048 | } | |||
16049 | ||||
16050 | /// Check for operands with placeholder types and complain if found. | |||
16051 | /// Returns ExprError() if there was an error and no recovery was possible. | |||
16052 | ExprResult Sema::CheckPlaceholderExpr(Expr *E) { | |||
16053 | if (!getLangOpts().CPlusPlus) { | |||
16054 | // C cannot handle TypoExpr nodes on either side of a binop because it | |||
16055 | // doesn't handle dependent types properly, so make sure any TypoExprs have | |||
16056 | // been dealt with before checking the operands. | |||
16057 | ExprResult Result = CorrectDelayedTyposInExpr(E); | |||
16058 | if (!Result.isUsable()) return ExprError(); | |||
16059 | E = Result.get(); | |||
16060 | } | |||
16061 | ||||
16062 | const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); | |||
16063 | if (!placeholderType) return E; | |||
16064 | ||||
16065 | switch (placeholderType->getKind()) { | |||
16066 | ||||
16067 | // Overloaded expressions. | |||
16068 | case BuiltinType::Overload: { | |||
16069 | // Try to resolve a single function template specialization. | |||
16070 | // This is obligatory. | |||
16071 | ExprResult Result = E; | |||
16072 | if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) | |||
16073 | return Result; | |||
16074 | ||||
16075 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization | |||
16076 | // leaves Result unchanged on failure. | |||
16077 | Result = E; | |||
16078 | if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) | |||
16079 | return Result; | |||
16080 | ||||
16081 | // If that failed, try to recover with a call. | |||
16082 | tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), | |||
16083 | /*complain*/ true); | |||
16084 | return Result; | |||
16085 | } | |||
16086 | ||||
16087 | // Bound member functions. | |||
16088 | case BuiltinType::BoundMember: { | |||
16089 | ExprResult result = E; | |||
16090 | const Expr *BME = E->IgnoreParens(); | |||
16091 | PartialDiagnostic PD = PDiag(diag::err_bound_member_function); | |||
16092 | // Try to give a nicer diagnostic if it is a bound member that we recognize. | |||
16093 | if (isa<CXXPseudoDestructorExpr>(BME)) { | |||
16094 | PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; | |||
16095 | } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { | |||
16096 | if (ME->getMemberNameInfo().getName().getNameKind() == | |||
16097 | DeclarationName::CXXDestructorName) | |||
16098 | PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; | |||
16099 | } | |||
16100 | tryToRecoverWithCall(result, PD, | |||
16101 | /*complain*/ true); | |||
16102 | return result; | |||
16103 | } | |||
16104 | ||||
16105 | // ARC unbridged casts. | |||
16106 | case BuiltinType::ARCUnbridgedCast: { | |||
16107 | Expr *realCast = stripARCUnbridgedCast(E); | |||
16108 | diagnoseARCUnbridgedCast(realCast); | |||
16109 | return realCast; | |||
16110 | } | |||
16111 | ||||
16112 | // Expressions of unknown type. | |||
16113 | case BuiltinType::UnknownAny: | |||
16114 | return diagnoseUnknownAnyExpr(*this, E); | |||
16115 | ||||
16116 | // Pseudo-objects. | |||
16117 | case BuiltinType::PseudoObject: | |||
16118 | return checkPseudoObjectRValue(E); | |||
16119 | ||||
16120 | case BuiltinType::BuiltinFn: { | |||
16121 | // Accept __noop without parens by implicitly converting it to a call expr. | |||
16122 | auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); | |||
16123 | if (DRE) { | |||
16124 | auto *FD = cast<FunctionDecl>(DRE->getDecl()); | |||
16125 | if (FD->getBuiltinID() == Builtin::BI__noop) { | |||
16126 | E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), | |||
16127 | CK_BuiltinFnToFnPtr).get(); | |||
16128 | return new (Context) CallExpr(Context, E, None, Context.IntTy, | |||
16129 | VK_RValue, SourceLocation()); | |||
16130 | } | |||
16131 | } | |||
16132 | ||||
16133 | Diag(E->getLocStart(), diag::err_builtin_fn_use); | |||
16134 | return ExprError(); | |||
16135 | } | |||
16136 | ||||
16137 | // Expressions of unknown type. | |||
16138 | case BuiltinType::OMPArraySection: | |||
16139 | Diag(E->getLocStart(), diag::err_omp_array_section_use); | |||
16140 | return ExprError(); | |||
16141 | ||||
16142 | // Everything else should be impossible. | |||
16143 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | |||
16144 | case BuiltinType::Id: | |||
16145 | #include "clang/Basic/OpenCLImageTypes.def" | |||
16146 | #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: | |||
16147 | #define PLACEHOLDER_TYPE(Id, SingletonId) | |||
16148 | #include "clang/AST/BuiltinTypes.def" | |||
16149 | break; | |||
16150 | } | |||
16151 | ||||
16152 | llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 16152); | |||
16153 | } | |||
16154 | ||||
16155 | bool Sema::CheckCaseExpression(Expr *E) { | |||
16156 | if (E->isTypeDependent()) | |||
16157 | return true; | |||
16158 | if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) | |||
16159 | return E->getType()->isIntegralOrEnumerationType(); | |||
16160 | return false; | |||
16161 | } | |||
16162 | ||||
16163 | /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. | |||
16164 | ExprResult | |||
16165 | Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { | |||
16166 | 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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 16167, __extension__ __PRETTY_FUNCTION__)) | |||
16167 | "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!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaExpr.cpp" , 16167, __extension__ __PRETTY_FUNCTION__)); | |||
16168 | QualType BoolT = Context.ObjCBuiltinBoolTy; | |||
16169 | if (!Context.getBOOLDecl()) { | |||
16170 | LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, | |||
16171 | Sema::LookupOrdinaryName); | |||
16172 | if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { | |||
16173 | NamedDecl *ND = Result.getFoundDecl(); | |||
16174 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) | |||
16175 | Context.setBOOLDecl(TD); | |||
16176 | } | |||
16177 | } | |||
16178 | if (Context.getBOOLDecl()) | |||
16179 | BoolT = Context.getBOOLType(); | |||
16180 | return new (Context) | |||
16181 | ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); | |||
16182 | } | |||
16183 | ||||
16184 | ExprResult Sema::ActOnObjCAvailabilityCheckExpr( | |||
16185 | llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, | |||
16186 | SourceLocation RParen) { | |||
16187 | ||||
16188 | StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); | |||
16189 | ||||
16190 | auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), | |||
16191 | [&](const AvailabilitySpec &Spec) { | |||
16192 | return Spec.getPlatform() == Platform; | |||
16193 | }); | |||
16194 | ||||
16195 | VersionTuple Version; | |||
16196 | if (Spec != AvailSpecs.end()) | |||
16197 | Version = Spec->getVersion(); | |||
16198 | ||||
16199 | // The use of `@available` in the enclosing function should be analyzed to | |||
16200 | // warn when it's used inappropriately (i.e. not if(@available)). | |||
16201 | if (getCurFunctionOrMethodDecl()) | |||
16202 | getEnclosingFunction()->HasPotentialAvailabilityViolations = true; | |||
16203 | else if (getCurBlock() || getCurLambda()) | |||
16204 | getCurFunction()->HasPotentialAvailabilityViolations = true; | |||
16205 | ||||
16206 | return new (Context) | |||
16207 | ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); | |||
16208 | } |
1 | //===- DeclarationName.h - Representation of declaration names --*- C++ -*-===// |
2 | // |
3 | // The LLVM Compiler Infrastructure |
4 | // |
5 | // This file is distributed under the University of Illinois Open Source |
6 | // License. See LICENSE.TXT for details. |
7 | // |
8 | //===----------------------------------------------------------------------===// |
9 | // |
10 | // This file declares the DeclarationName and DeclarationNameTable classes. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_CLANG_AST_DECLARATIONNAME_H |
15 | #define LLVM_CLANG_AST_DECLARATIONNAME_H |
16 | |
17 | #include "clang/Basic/Diagnostic.h" |
18 | #include "clang/Basic/IdentifierTable.h" |
19 | #include "clang/Basic/PartialDiagnostic.h" |
20 | #include "clang/Basic/SourceLocation.h" |
21 | #include "llvm/ADT/DenseMapInfo.h" |
22 | #include "llvm/Support/Compiler.h" |
23 | #include "llvm/Support/type_traits.h" |
24 | #include <cassert> |
25 | #include <cstdint> |
26 | #include <cstring> |
27 | #include <string> |
28 | |
29 | namespace clang { |
30 | |
31 | class ASTContext; |
32 | template <typename> class CanQual; |
33 | class CXXDeductionGuideNameExtra; |
34 | class CXXLiteralOperatorIdName; |
35 | class CXXOperatorIdName; |
36 | class CXXSpecialName; |
37 | class DeclarationNameExtra; |
38 | class IdentifierInfo; |
39 | class MultiKeywordSelector; |
40 | enum OverloadedOperatorKind : int; |
41 | struct PrintingPolicy; |
42 | class QualType; |
43 | class TemplateDecl; |
44 | class Type; |
45 | class TypeSourceInfo; |
46 | class UsingDirectiveDecl; |
47 | |
48 | using CanQualType = CanQual<Type>; |
49 | |
50 | /// DeclarationName - The name of a declaration. In the common case, |
51 | /// this just stores an IdentifierInfo pointer to a normal |
52 | /// name. However, it also provides encodings for Objective-C |
53 | /// selectors (optimizing zero- and one-argument selectors, which make |
54 | /// up 78% percent of all selectors in Cocoa.h) and special C++ names |
55 | /// for constructors, destructors, and conversion functions. |
56 | class DeclarationName { |
57 | public: |
58 | /// NameKind - The kind of name this object contains. |
59 | enum NameKind { |
60 | Identifier, |
61 | ObjCZeroArgSelector, |
62 | ObjCOneArgSelector, |
63 | ObjCMultiArgSelector, |
64 | CXXConstructorName, |
65 | CXXDestructorName, |
66 | CXXConversionFunctionName, |
67 | CXXDeductionGuideName, |
68 | CXXOperatorName, |
69 | CXXLiteralOperatorName, |
70 | CXXUsingDirective |
71 | }; |
72 | |
73 | static const unsigned NumNameKinds = CXXUsingDirective + 1; |
74 | |
75 | private: |
76 | friend class DeclarationNameTable; |
77 | friend class NamedDecl; |
78 | |
79 | /// StoredNameKind - The kind of name that is actually stored in the |
80 | /// upper bits of the Ptr field. This is only used internally. |
81 | /// |
82 | /// Note: The entries here are synchronized with the entries in Selector, |
83 | /// for efficient translation between the two. |
84 | enum StoredNameKind { |
85 | StoredIdentifier = 0, |
86 | StoredObjCZeroArgSelector = 0x01, |
87 | StoredObjCOneArgSelector = 0x02, |
88 | StoredDeclarationNameExtra = 0x03, |
89 | PtrMask = 0x03 |
90 | }; |
91 | |
92 | /// Ptr - The lowest two bits are used to express what kind of name |
93 | /// we're actually storing, using the values of NameKind. Depending |
94 | /// on the kind of name this is, the upper bits of Ptr may have one |
95 | /// of several different meanings: |
96 | /// |
97 | /// StoredIdentifier - The name is a normal identifier, and Ptr is |
98 | /// a normal IdentifierInfo pointer. |
99 | /// |
100 | /// StoredObjCZeroArgSelector - The name is an Objective-C |
101 | /// selector with zero arguments, and Ptr is an IdentifierInfo |
102 | /// pointer pointing to the selector name. |
103 | /// |
104 | /// StoredObjCOneArgSelector - The name is an Objective-C selector |
105 | /// with one argument, and Ptr is an IdentifierInfo pointer |
106 | /// pointing to the selector name. |
107 | /// |
108 | /// StoredDeclarationNameExtra - Ptr is actually a pointer to a |
109 | /// DeclarationNameExtra structure, whose first value will tell us |
110 | /// whether this is an Objective-C selector, C++ operator-id name, |
111 | /// or special C++ name. |
112 | uintptr_t Ptr = 0; |
113 | |
114 | // Construct a declaration name from the name of a C++ constructor, |
115 | // destructor, or conversion function. |
116 | DeclarationName(DeclarationNameExtra *Name) |
117 | : Ptr(reinterpret_cast<uintptr_t>(Name)) { |
118 | assert((Ptr & PtrMask) == 0 && "Improperly aligned DeclarationNameExtra")(static_cast <bool> ((Ptr & PtrMask) == 0 && "Improperly aligned DeclarationNameExtra") ? void (0) : __assert_fail ("(Ptr & PtrMask) == 0 && \"Improperly aligned DeclarationNameExtra\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 118, __extension__ __PRETTY_FUNCTION__)); |
119 | Ptr |= StoredDeclarationNameExtra; |
120 | } |
121 | |
122 | /// Construct a declaration name from a raw pointer. |
123 | DeclarationName(uintptr_t Ptr) : Ptr(Ptr) {} |
124 | |
125 | /// getStoredNameKind - Return the kind of object that is stored in |
126 | /// Ptr. |
127 | StoredNameKind getStoredNameKind() const { |
128 | return static_cast<StoredNameKind>(Ptr & PtrMask); |
129 | } |
130 | |
131 | /// getExtra - Get the "extra" information associated with this |
132 | /// multi-argument selector or C++ special name. |
133 | DeclarationNameExtra *getExtra() const { |
134 | assert(getStoredNameKind() == StoredDeclarationNameExtra &&(static_cast <bool> (getStoredNameKind() == StoredDeclarationNameExtra && "Declaration name does not store an Extra structure" ) ? void (0) : __assert_fail ("getStoredNameKind() == StoredDeclarationNameExtra && \"Declaration name does not store an Extra structure\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 135, __extension__ __PRETTY_FUNCTION__)) |
135 | "Declaration name does not store an Extra structure")(static_cast <bool> (getStoredNameKind() == StoredDeclarationNameExtra && "Declaration name does not store an Extra structure" ) ? void (0) : __assert_fail ("getStoredNameKind() == StoredDeclarationNameExtra && \"Declaration name does not store an Extra structure\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 135, __extension__ __PRETTY_FUNCTION__)); |
136 | return reinterpret_cast<DeclarationNameExtra *>(Ptr & ~PtrMask); |
137 | } |
138 | |
139 | /// getAsCXXSpecialName - If the stored pointer is actually a |
140 | /// CXXSpecialName, returns a pointer to it. Otherwise, returns |
141 | /// a NULL pointer. |
142 | CXXSpecialName *getAsCXXSpecialName() const { |
143 | NameKind Kind = getNameKind(); |
144 | if (Kind >= CXXConstructorName && Kind <= CXXConversionFunctionName) |
145 | return reinterpret_cast<CXXSpecialName *>(getExtra()); |
146 | return nullptr; |
147 | } |
148 | |
149 | /// If the stored pointer is actually a CXXDeductionGuideNameExtra, returns a |
150 | /// pointer to it. Otherwise, returns a NULL pointer. |
151 | CXXDeductionGuideNameExtra *getAsCXXDeductionGuideNameExtra() const { |
152 | if (getNameKind() == CXXDeductionGuideName) |
153 | return reinterpret_cast<CXXDeductionGuideNameExtra *>(getExtra()); |
154 | return nullptr; |
155 | } |
156 | |
157 | /// getAsCXXOperatorIdName |
158 | CXXOperatorIdName *getAsCXXOperatorIdName() const { |
159 | if (getNameKind() == CXXOperatorName) |
160 | return reinterpret_cast<CXXOperatorIdName *>(getExtra()); |
161 | return nullptr; |
162 | } |
163 | |
164 | CXXLiteralOperatorIdName *getAsCXXLiteralOperatorIdName() const { |
165 | if (getNameKind() == CXXLiteralOperatorName) |
166 | return reinterpret_cast<CXXLiteralOperatorIdName *>(getExtra()); |
167 | return nullptr; |
168 | } |
169 | |
170 | /// getFETokenInfoAsVoidSlow - Retrieves the front end-specified pointer |
171 | /// for this name as a void pointer if it's not an identifier. |
172 | void *getFETokenInfoAsVoidSlow() const; |
173 | |
174 | public: |
175 | /// DeclarationName - Used to create an empty selector. |
176 | DeclarationName() = default; |
177 | |
178 | // Construct a declaration name from an IdentifierInfo *. |
179 | DeclarationName(const IdentifierInfo *II) |
180 | : Ptr(reinterpret_cast<uintptr_t>(II)) { |
181 | assert((Ptr & PtrMask) == 0 && "Improperly aligned IdentifierInfo")(static_cast <bool> ((Ptr & PtrMask) == 0 && "Improperly aligned IdentifierInfo") ? void (0) : __assert_fail ("(Ptr & PtrMask) == 0 && \"Improperly aligned IdentifierInfo\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 181, __extension__ __PRETTY_FUNCTION__)); |
182 | } |
183 | |
184 | // Construct a declaration name from an Objective-C selector. |
185 | DeclarationName(Selector Sel) : Ptr(Sel.InfoPtr) {} |
186 | |
187 | /// getUsingDirectiveName - Return name for all using-directives. |
188 | static DeclarationName getUsingDirectiveName(); |
189 | |
190 | // operator bool() - Evaluates true when this declaration name is |
191 | // non-empty. |
192 | explicit operator bool() const { |
193 | return ((Ptr & PtrMask) != 0) || |
194 | (reinterpret_cast<IdentifierInfo *>(Ptr & ~PtrMask)); |
195 | } |
196 | |
197 | /// \brief Evaluates true when this declaration name is empty. |
198 | bool isEmpty() const { |
199 | return !*this; |
200 | } |
201 | |
202 | /// Predicate functions for querying what type of name this is. |
203 | bool isIdentifier() const { return getStoredNameKind() == StoredIdentifier; } |
204 | bool isObjCZeroArgSelector() const { |
205 | return getStoredNameKind() == StoredObjCZeroArgSelector; |
206 | } |
207 | bool isObjCOneArgSelector() const { |
208 | return getStoredNameKind() == StoredObjCOneArgSelector; |
209 | } |
210 | |
211 | /// getNameKind - Determine what kind of name this is. |
212 | NameKind getNameKind() const; |
213 | |
214 | /// \brief Determines whether the name itself is dependent, e.g., because it |
215 | /// involves a C++ type that is itself dependent. |
216 | /// |
217 | /// Note that this does not capture all of the notions of "dependent name", |
218 | /// because an identifier can be a dependent name if it is used as the |
219 | /// callee in a call expression with dependent arguments. |
220 | bool isDependentName() const; |
221 | |
222 | /// getNameAsString - Retrieve the human-readable string for this name. |
223 | std::string getAsString() const; |
224 | |
225 | /// getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in |
226 | /// this declaration name, or NULL if this declaration name isn't a |
227 | /// simple identifier. |
228 | IdentifierInfo *getAsIdentifierInfo() const { |
229 | if (isIdentifier()) |
230 | return reinterpret_cast<IdentifierInfo *>(Ptr); |
231 | return nullptr; |
232 | } |
233 | |
234 | /// getAsOpaqueInteger - Get the representation of this declaration |
235 | /// name as an opaque integer. |
236 | uintptr_t getAsOpaqueInteger() const { return Ptr; } |
237 | |
238 | /// getAsOpaquePtr - Get the representation of this declaration name as |
239 | /// an opaque pointer. |
240 | void *getAsOpaquePtr() const { return reinterpret_cast<void*>(Ptr); } |
241 | |
242 | static DeclarationName getFromOpaquePtr(void *P) { |
243 | DeclarationName N; |
244 | N.Ptr = reinterpret_cast<uintptr_t> (P); |
245 | return N; |
246 | } |
247 | |
248 | static DeclarationName getFromOpaqueInteger(uintptr_t P) { |
249 | DeclarationName N; |
250 | N.Ptr = P; |
251 | return N; |
252 | } |
253 | |
254 | /// getCXXNameType - If this name is one of the C++ names (of a |
255 | /// constructor, destructor, or conversion function), return the |
256 | /// type associated with that name. |
257 | QualType getCXXNameType() const; |
258 | |
259 | /// If this name is the name of a C++ deduction guide, return the |
260 | /// template associated with that name. |
261 | TemplateDecl *getCXXDeductionGuideTemplate() const; |
262 | |
263 | /// getCXXOverloadedOperator - If this name is the name of an |
264 | /// overloadable operator in C++ (e.g., @c operator+), retrieve the |
265 | /// kind of overloaded operator. |
266 | OverloadedOperatorKind getCXXOverloadedOperator() const; |
267 | |
268 | /// getCXXLiteralIdentifier - If this name is the name of a literal |
269 | /// operator, retrieve the identifier associated with it. |
270 | IdentifierInfo *getCXXLiteralIdentifier() const; |
271 | |
272 | /// getObjCSelector - Get the Objective-C selector stored in this |
273 | /// declaration name. |
274 | Selector getObjCSelector() const { |
275 | assert((getNameKind() == ObjCZeroArgSelector ||(static_cast <bool> ((getNameKind() == ObjCZeroArgSelector || getNameKind() == ObjCOneArgSelector || getNameKind() == ObjCMultiArgSelector || Ptr == 0) && "Not a selector!") ? void (0) : __assert_fail ("(getNameKind() == ObjCZeroArgSelector || getNameKind() == ObjCOneArgSelector || getNameKind() == ObjCMultiArgSelector || Ptr == 0) && \"Not a selector!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 278, __extension__ __PRETTY_FUNCTION__)) |
276 | getNameKind() == ObjCOneArgSelector ||(static_cast <bool> ((getNameKind() == ObjCZeroArgSelector || getNameKind() == ObjCOneArgSelector || getNameKind() == ObjCMultiArgSelector || Ptr == 0) && "Not a selector!") ? void (0) : __assert_fail ("(getNameKind() == ObjCZeroArgSelector || getNameKind() == ObjCOneArgSelector || getNameKind() == ObjCMultiArgSelector || Ptr == 0) && \"Not a selector!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 278, __extension__ __PRETTY_FUNCTION__)) |
277 | getNameKind() == ObjCMultiArgSelector ||(static_cast <bool> ((getNameKind() == ObjCZeroArgSelector || getNameKind() == ObjCOneArgSelector || getNameKind() == ObjCMultiArgSelector || Ptr == 0) && "Not a selector!") ? void (0) : __assert_fail ("(getNameKind() == ObjCZeroArgSelector || getNameKind() == ObjCOneArgSelector || getNameKind() == ObjCMultiArgSelector || Ptr == 0) && \"Not a selector!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 278, __extension__ __PRETTY_FUNCTION__)) |
278 | Ptr == 0) && "Not a selector!")(static_cast <bool> ((getNameKind() == ObjCZeroArgSelector || getNameKind() == ObjCOneArgSelector || getNameKind() == ObjCMultiArgSelector || Ptr == 0) && "Not a selector!") ? void (0) : __assert_fail ("(getNameKind() == ObjCZeroArgSelector || getNameKind() == ObjCOneArgSelector || getNameKind() == ObjCMultiArgSelector || Ptr == 0) && \"Not a selector!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 278, __extension__ __PRETTY_FUNCTION__)); |
279 | return Selector(Ptr); |
280 | } |
281 | |
282 | /// getFETokenInfo/setFETokenInfo - The language front-end is |
283 | /// allowed to associate arbitrary metadata with some kinds of |
284 | /// declaration names, including normal identifiers and C++ |
285 | /// constructors, destructors, and conversion functions. |
286 | template<typename T> |
287 | T *getFETokenInfo() const { |
288 | if (const IdentifierInfo *Info = getAsIdentifierInfo()) |
289 | return Info->getFETokenInfo<T>(); |
290 | return static_cast<T*>(getFETokenInfoAsVoidSlow()); |
291 | } |
292 | |
293 | void setFETokenInfo(void *T); |
294 | |
295 | /// operator== - Determine whether the specified names are identical.. |
296 | friend bool operator==(DeclarationName LHS, DeclarationName RHS) { |
297 | return LHS.Ptr == RHS.Ptr; |
298 | } |
299 | |
300 | /// operator!= - Determine whether the specified names are different. |
301 | friend bool operator!=(DeclarationName LHS, DeclarationName RHS) { |
302 | return LHS.Ptr != RHS.Ptr; |
303 | } |
304 | |
305 | static DeclarationName getEmptyMarker() { |
306 | return DeclarationName(uintptr_t(-1)); |
307 | } |
308 | |
309 | static DeclarationName getTombstoneMarker() { |
310 | return DeclarationName(uintptr_t(-2)); |
311 | } |
312 | |
313 | static int compare(DeclarationName LHS, DeclarationName RHS); |
314 | |
315 | void print(raw_ostream &OS, const PrintingPolicy &Policy); |
316 | |
317 | void dump() const; |
318 | }; |
319 | |
320 | raw_ostream &operator<<(raw_ostream &OS, DeclarationName N); |
321 | |
322 | /// Ordering on two declaration names. If both names are identifiers, |
323 | /// this provides a lexicographical ordering. |
324 | inline bool operator<(DeclarationName LHS, DeclarationName RHS) { |
325 | return DeclarationName::compare(LHS, RHS) < 0; |
326 | } |
327 | |
328 | /// Ordering on two declaration names. If both names are identifiers, |
329 | /// this provides a lexicographical ordering. |
330 | inline bool operator>(DeclarationName LHS, DeclarationName RHS) { |
331 | return DeclarationName::compare(LHS, RHS) > 0; |
332 | } |
333 | |
334 | /// Ordering on two declaration names. If both names are identifiers, |
335 | /// this provides a lexicographical ordering. |
336 | inline bool operator<=(DeclarationName LHS, DeclarationName RHS) { |
337 | return DeclarationName::compare(LHS, RHS) <= 0; |
338 | } |
339 | |
340 | /// Ordering on two declaration names. If both names are identifiers, |
341 | /// this provides a lexicographical ordering. |
342 | inline bool operator>=(DeclarationName LHS, DeclarationName RHS) { |
343 | return DeclarationName::compare(LHS, RHS) >= 0; |
344 | } |
345 | |
346 | /// DeclarationNameTable - Used to store and retrieve DeclarationName |
347 | /// instances for the various kinds of declaration names, e.g., normal |
348 | /// identifiers, C++ constructor names, etc. This class contains |
349 | /// uniqued versions of each of the C++ special names, which can be |
350 | /// retrieved using its member functions (e.g., |
351 | /// getCXXConstructorName). |
352 | class DeclarationNameTable { |
353 | const ASTContext &Ctx; |
354 | |
355 | // Actually a FoldingSet<CXXSpecialName> * |
356 | void *CXXSpecialNamesImpl; |
357 | |
358 | // Operator names |
359 | CXXOperatorIdName *CXXOperatorNames; |
360 | |
361 | // Actually a CXXOperatorIdName* |
362 | void *CXXLiteralOperatorNames; |
363 | |
364 | // FoldingSet<CXXDeductionGuideNameExtra> * |
365 | void *CXXDeductionGuideNames; |
366 | |
367 | public: |
368 | DeclarationNameTable(const ASTContext &C); |
369 | DeclarationNameTable(const DeclarationNameTable &) = delete; |
370 | DeclarationNameTable &operator=(const DeclarationNameTable &) = delete; |
371 | |
372 | ~DeclarationNameTable(); |
373 | |
374 | /// getIdentifier - Create a declaration name that is a simple |
375 | /// identifier. |
376 | DeclarationName getIdentifier(const IdentifierInfo *ID) { |
377 | return DeclarationName(ID); |
378 | } |
379 | |
380 | /// getCXXConstructorName - Returns the name of a C++ constructor |
381 | /// for the given Type. |
382 | DeclarationName getCXXConstructorName(CanQualType Ty); |
383 | |
384 | /// getCXXDestructorName - Returns the name of a C++ destructor |
385 | /// for the given Type. |
386 | DeclarationName getCXXDestructorName(CanQualType Ty); |
387 | |
388 | /// Returns the name of a C++ deduction guide for the given template. |
389 | DeclarationName getCXXDeductionGuideName(TemplateDecl *TD); |
390 | |
391 | /// getCXXConversionFunctionName - Returns the name of a C++ |
392 | /// conversion function for the given Type. |
393 | DeclarationName getCXXConversionFunctionName(CanQualType Ty); |
394 | |
395 | /// getCXXSpecialName - Returns a declaration name for special kind |
396 | /// of C++ name, e.g., for a constructor, destructor, or conversion |
397 | /// function. |
398 | DeclarationName getCXXSpecialName(DeclarationName::NameKind Kind, |
399 | CanQualType Ty); |
400 | |
401 | /// getCXXOperatorName - Get the name of the overloadable C++ |
402 | /// operator corresponding to Op. |
403 | DeclarationName getCXXOperatorName(OverloadedOperatorKind Op); |
404 | |
405 | /// getCXXLiteralOperatorName - Get the name of the literal operator function |
406 | /// with II as the identifier. |
407 | DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II); |
408 | }; |
409 | |
410 | /// DeclarationNameLoc - Additional source/type location info |
411 | /// for a declaration name. Needs a DeclarationName in order |
412 | /// to be interpreted correctly. |
413 | struct DeclarationNameLoc { |
414 | // The source location for identifier stored elsewhere. |
415 | // struct {} Identifier; |
416 | |
417 | // Type info for constructors, destructors and conversion functions. |
418 | // Locations (if any) for the tilde (destructor) or operator keyword |
419 | // (conversion) are stored elsewhere. |
420 | struct NT { |
421 | TypeSourceInfo *TInfo; |
422 | }; |
423 | |
424 | // The location (if any) of the operator keyword is stored elsewhere. |
425 | struct CXXOpName { |
426 | unsigned BeginOpNameLoc; |
427 | unsigned EndOpNameLoc; |
428 | }; |
429 | |
430 | // The location (if any) of the operator keyword is stored elsewhere. |
431 | struct CXXLitOpName { |
432 | unsigned OpNameLoc; |
433 | }; |
434 | |
435 | // struct {} CXXUsingDirective; |
436 | // struct {} ObjCZeroArgSelector; |
437 | // struct {} ObjCOneArgSelector; |
438 | // struct {} ObjCMultiArgSelector; |
439 | union { |
440 | struct NT NamedType; |
441 | struct CXXOpName CXXOperatorName; |
442 | struct CXXLitOpName CXXLiteralOperatorName; |
443 | }; |
444 | |
445 | DeclarationNameLoc(DeclarationName Name); |
446 | |
447 | // FIXME: this should go away once all DNLocs are properly initialized. |
448 | DeclarationNameLoc() { memset((void*) this, 0, sizeof(*this)); } |
449 | }; |
450 | |
451 | /// DeclarationNameInfo - A collector data type for bundling together |
452 | /// a DeclarationName and the correspnding source/type location info. |
453 | struct DeclarationNameInfo { |
454 | private: |
455 | /// Name - The declaration name, also encoding name kind. |
456 | DeclarationName Name; |
457 | |
458 | /// Loc - The main source location for the declaration name. |
459 | SourceLocation NameLoc; |
460 | |
461 | /// Info - Further source/type location info for special kinds of names. |
462 | DeclarationNameLoc LocInfo; |
463 | |
464 | public: |
465 | // FIXME: remove it. |
466 | DeclarationNameInfo() = default; |
467 | |
468 | DeclarationNameInfo(DeclarationName Name, SourceLocation NameLoc) |
469 | : Name(Name), NameLoc(NameLoc), LocInfo(Name) {} |
470 | |
471 | DeclarationNameInfo(DeclarationName Name, SourceLocation NameLoc, |
472 | DeclarationNameLoc LocInfo) |
473 | : Name(Name), NameLoc(NameLoc), LocInfo(LocInfo) {} |
474 | |
475 | /// getName - Returns the embedded declaration name. |
476 | DeclarationName getName() const { return Name; } |
477 | |
478 | /// setName - Sets the embedded declaration name. |
479 | void setName(DeclarationName N) { Name = N; } |
480 | |
481 | /// getLoc - Returns the main location of the declaration name. |
482 | SourceLocation getLoc() const { return NameLoc; } |
483 | |
484 | /// setLoc - Sets the main location of the declaration name. |
485 | void setLoc(SourceLocation L) { NameLoc = L; } |
486 | |
487 | const DeclarationNameLoc &getInfo() const { return LocInfo; } |
488 | DeclarationNameLoc &getInfo() { return LocInfo; } |
489 | void setInfo(const DeclarationNameLoc &Info) { LocInfo = Info; } |
490 | |
491 | /// getNamedTypeInfo - Returns the source type info associated to |
492 | /// the name. Assumes it is a constructor, destructor or conversion. |
493 | TypeSourceInfo *getNamedTypeInfo() const { |
494 | assert(Name.getNameKind() == DeclarationName::CXXConstructorName ||(static_cast <bool> (Name.getNameKind() == DeclarationName ::CXXConstructorName || Name.getNameKind() == DeclarationName ::CXXDestructorName || Name.getNameKind() == DeclarationName:: CXXConversionFunctionName) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::CXXConstructorName || Name.getNameKind() == DeclarationName::CXXDestructorName || Name.getNameKind() == DeclarationName::CXXConversionFunctionName" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 496, __extension__ __PRETTY_FUNCTION__)) |
495 | Name.getNameKind() == DeclarationName::CXXDestructorName ||(static_cast <bool> (Name.getNameKind() == DeclarationName ::CXXConstructorName || Name.getNameKind() == DeclarationName ::CXXDestructorName || Name.getNameKind() == DeclarationName:: CXXConversionFunctionName) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::CXXConstructorName || Name.getNameKind() == DeclarationName::CXXDestructorName || Name.getNameKind() == DeclarationName::CXXConversionFunctionName" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 496, __extension__ __PRETTY_FUNCTION__)) |
496 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName)(static_cast <bool> (Name.getNameKind() == DeclarationName ::CXXConstructorName || Name.getNameKind() == DeclarationName ::CXXDestructorName || Name.getNameKind() == DeclarationName:: CXXConversionFunctionName) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::CXXConstructorName || Name.getNameKind() == DeclarationName::CXXDestructorName || Name.getNameKind() == DeclarationName::CXXConversionFunctionName" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 496, __extension__ __PRETTY_FUNCTION__)); |
497 | return LocInfo.NamedType.TInfo; |
498 | } |
499 | |
500 | /// setNamedTypeInfo - Sets the source type info associated to |
501 | /// the name. Assumes it is a constructor, destructor or conversion. |
502 | void setNamedTypeInfo(TypeSourceInfo *TInfo) { |
503 | assert(Name.getNameKind() == DeclarationName::CXXConstructorName ||(static_cast <bool> (Name.getNameKind() == DeclarationName ::CXXConstructorName || Name.getNameKind() == DeclarationName ::CXXDestructorName || Name.getNameKind() == DeclarationName:: CXXConversionFunctionName) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::CXXConstructorName || Name.getNameKind() == DeclarationName::CXXDestructorName || Name.getNameKind() == DeclarationName::CXXConversionFunctionName" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 505, __extension__ __PRETTY_FUNCTION__)) |
504 | Name.getNameKind() == DeclarationName::CXXDestructorName ||(static_cast <bool> (Name.getNameKind() == DeclarationName ::CXXConstructorName || Name.getNameKind() == DeclarationName ::CXXDestructorName || Name.getNameKind() == DeclarationName:: CXXConversionFunctionName) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::CXXConstructorName || Name.getNameKind() == DeclarationName::CXXDestructorName || Name.getNameKind() == DeclarationName::CXXConversionFunctionName" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 505, __extension__ __PRETTY_FUNCTION__)) |
505 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName)(static_cast <bool> (Name.getNameKind() == DeclarationName ::CXXConstructorName || Name.getNameKind() == DeclarationName ::CXXDestructorName || Name.getNameKind() == DeclarationName:: CXXConversionFunctionName) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::CXXConstructorName || Name.getNameKind() == DeclarationName::CXXDestructorName || Name.getNameKind() == DeclarationName::CXXConversionFunctionName" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 505, __extension__ __PRETTY_FUNCTION__)); |
506 | LocInfo.NamedType.TInfo = TInfo; |
507 | } |
508 | |
509 | /// getCXXOperatorNameRange - Gets the range of the operator name |
510 | /// (without the operator keyword). Assumes it is a (non-literal) operator. |
511 | SourceRange getCXXOperatorNameRange() const { |
512 | assert(Name.getNameKind() == DeclarationName::CXXOperatorName)(static_cast <bool> (Name.getNameKind() == DeclarationName ::CXXOperatorName) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::CXXOperatorName" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 512, __extension__ __PRETTY_FUNCTION__)); |
513 | return SourceRange( |
514 | SourceLocation::getFromRawEncoding(LocInfo.CXXOperatorName.BeginOpNameLoc), |
515 | SourceLocation::getFromRawEncoding(LocInfo.CXXOperatorName.EndOpNameLoc) |
516 | ); |
517 | } |
518 | |
519 | /// setCXXOperatorNameRange - Sets the range of the operator name |
520 | /// (without the operator keyword). Assumes it is a C++ operator. |
521 | void setCXXOperatorNameRange(SourceRange R) { |
522 | assert(Name.getNameKind() == DeclarationName::CXXOperatorName)(static_cast <bool> (Name.getNameKind() == DeclarationName ::CXXOperatorName) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::CXXOperatorName" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 522, __extension__ __PRETTY_FUNCTION__)); |
523 | LocInfo.CXXOperatorName.BeginOpNameLoc = R.getBegin().getRawEncoding(); |
524 | LocInfo.CXXOperatorName.EndOpNameLoc = R.getEnd().getRawEncoding(); |
525 | } |
526 | |
527 | /// getCXXLiteralOperatorNameLoc - Returns the location of the literal |
528 | /// operator name (not the operator keyword). |
529 | /// Assumes it is a literal operator. |
530 | SourceLocation getCXXLiteralOperatorNameLoc() const { |
531 | assert(Name.getNameKind() == DeclarationName::CXXLiteralOperatorName)(static_cast <bool> (Name.getNameKind() == DeclarationName ::CXXLiteralOperatorName) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::CXXLiteralOperatorName" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 531, __extension__ __PRETTY_FUNCTION__)); |
532 | return SourceLocation:: |
533 | getFromRawEncoding(LocInfo.CXXLiteralOperatorName.OpNameLoc); |
534 | } |
535 | |
536 | /// setCXXLiteralOperatorNameLoc - Sets the location of the literal |
537 | /// operator name (not the operator keyword). |
538 | /// Assumes it is a literal operator. |
539 | void setCXXLiteralOperatorNameLoc(SourceLocation Loc) { |
540 | assert(Name.getNameKind() == DeclarationName::CXXLiteralOperatorName)(static_cast <bool> (Name.getNameKind() == DeclarationName ::CXXLiteralOperatorName) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::CXXLiteralOperatorName" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/DeclarationName.h" , 540, __extension__ __PRETTY_FUNCTION__)); |
541 | LocInfo.CXXLiteralOperatorName.OpNameLoc = Loc.getRawEncoding(); |
542 | } |
543 | |
544 | /// \brief Determine whether this name involves a template parameter. |
545 | bool isInstantiationDependent() const; |
546 | |
547 | /// \brief Determine whether this name contains an unexpanded |
548 | /// parameter pack. |
549 | bool containsUnexpandedParameterPack() const; |
550 | |
551 | /// getAsString - Retrieve the human-readable string for this name. |
552 | std::string getAsString() const; |
553 | |
554 | /// printName - Print the human-readable name to a stream. |
555 | void printName(raw_ostream &OS) const; |
556 | |
557 | /// getBeginLoc - Retrieve the location of the first token. |
558 | SourceLocation getBeginLoc() const { return NameLoc; } |
559 | |
560 | /// getEndLoc - Retrieve the location of the last token. |
561 | SourceLocation getEndLoc() const; |
562 | |
563 | /// getSourceRange - The range of the declaration name. |
564 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { |
565 | return SourceRange(getLocStart(), getLocEnd()); |
566 | } |
567 | |
568 | SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { |
569 | return getBeginLoc(); |
570 | } |
571 | |
572 | SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { |
573 | SourceLocation EndLoc = getEndLoc(); |
574 | return EndLoc.isValid() ? EndLoc : getLocStart(); |
575 | } |
576 | }; |
577 | |
578 | /// Insertion operator for diagnostics. This allows sending DeclarationName's |
579 | /// into a diagnostic with <<. |
580 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
581 | DeclarationName N) { |
582 | DB.AddTaggedVal(N.getAsOpaqueInteger(), |
583 | DiagnosticsEngine::ak_declarationname); |
584 | return DB; |
585 | } |
586 | |
587 | /// Insertion operator for partial diagnostics. This allows binding |
588 | /// DeclarationName's into a partial diagnostic with <<. |
589 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
590 | DeclarationName N) { |
591 | PD.AddTaggedVal(N.getAsOpaqueInteger(), |
592 | DiagnosticsEngine::ak_declarationname); |
593 | return PD; |
594 | } |
595 | |
596 | inline raw_ostream &operator<<(raw_ostream &OS, |
597 | DeclarationNameInfo DNInfo) { |
598 | DNInfo.printName(OS); |
599 | return OS; |
600 | } |
601 | |
602 | } // namespace clang |
603 | |
604 | namespace llvm { |
605 | |
606 | /// Define DenseMapInfo so that DeclarationNames can be used as keys |
607 | /// in DenseMap and DenseSets. |
608 | template<> |
609 | struct DenseMapInfo<clang::DeclarationName> { |
610 | static inline clang::DeclarationName getEmptyKey() { |
611 | return clang::DeclarationName::getEmptyMarker(); |
612 | } |
613 | |
614 | static inline clang::DeclarationName getTombstoneKey() { |
615 | return clang::DeclarationName::getTombstoneMarker(); |
616 | } |
617 | |
618 | static unsigned getHashValue(clang::DeclarationName Name) { |
619 | return DenseMapInfo<void*>::getHashValue(Name.getAsOpaquePtr()); |
620 | } |
621 | |
622 | static inline bool |
623 | isEqual(clang::DeclarationName LHS, clang::DeclarationName RHS) { |
624 | return LHS == RHS; |
625 | } |
626 | }; |
627 | |
628 | template <> |
629 | struct isPodLike<clang::DeclarationName> { static const bool value = true; }; |
630 | |
631 | } // namespace llvm |
632 | |
633 | #endif // LLVM_CLANG_AST_DECLARATIONNAME_H |
1 | //===- PartialDiagnostic.h - Diagnostic "closures" --------------*- C++ -*-===// | |||
2 | // | |||
3 | // The LLVM Compiler Infrastructure | |||
4 | // | |||
5 | // This file is distributed under the University of Illinois Open Source | |||
6 | // License. See LICENSE.TXT for details. | |||
7 | // | |||
8 | //===----------------------------------------------------------------------===// | |||
9 | // | |||
10 | /// \file | |||
11 | /// \brief Implements a partial diagnostic that can be emitted anwyhere | |||
12 | /// in a DiagnosticBuilder stream. | |||
13 | // | |||
14 | //===----------------------------------------------------------------------===// | |||
15 | ||||
16 | #ifndef LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H | |||
17 | #define LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H | |||
18 | ||||
19 | #include "clang/Basic/Diagnostic.h" | |||
20 | #include "clang/Basic/LLVM.h" | |||
21 | #include "clang/Basic/SourceLocation.h" | |||
22 | #include "llvm/ADT/SmallVector.h" | |||
23 | #include "llvm/ADT/StringRef.h" | |||
24 | #include <cassert> | |||
25 | #include <cstdint> | |||
26 | #include <string> | |||
27 | #include <type_traits> | |||
28 | #include <utility> | |||
29 | ||||
30 | namespace clang { | |||
31 | ||||
32 | class DeclContext; | |||
33 | class IdentifierInfo; | |||
34 | ||||
35 | class PartialDiagnostic { | |||
36 | public: | |||
37 | enum { | |||
38 | // The MaxArguments and MaxFixItHints member enum values from | |||
39 | // DiagnosticsEngine are private but DiagnosticsEngine declares | |||
40 | // PartialDiagnostic a friend. These enum values are redeclared | |||
41 | // here so that the nested Storage class below can access them. | |||
42 | MaxArguments = DiagnosticsEngine::MaxArguments | |||
43 | }; | |||
44 | ||||
45 | struct Storage { | |||
46 | enum { | |||
47 | /// \brief The maximum number of arguments we can hold. We | |||
48 | /// currently only support up to 10 arguments (%0-%9). | |||
49 | /// | |||
50 | /// A single diagnostic with more than that almost certainly has to | |||
51 | /// be simplified anyway. | |||
52 | MaxArguments = PartialDiagnostic::MaxArguments | |||
53 | }; | |||
54 | ||||
55 | /// \brief The number of entries in Arguments. | |||
56 | unsigned char NumDiagArgs = 0; | |||
57 | ||||
58 | /// \brief Specifies for each argument whether it is in DiagArgumentsStr | |||
59 | /// or in DiagArguments. | |||
60 | unsigned char DiagArgumentsKind[MaxArguments]; | |||
61 | ||||
62 | /// \brief The values for the various substitution positions. | |||
63 | /// | |||
64 | /// This is used when the argument is not an std::string. The specific value | |||
65 | /// is mangled into an intptr_t and the interpretation depends on exactly | |||
66 | /// what sort of argument kind it is. | |||
67 | intptr_t DiagArgumentsVal[MaxArguments]; | |||
68 | ||||
69 | /// \brief The values for the various substitution positions that have | |||
70 | /// string arguments. | |||
71 | std::string DiagArgumentsStr[MaxArguments]; | |||
72 | ||||
73 | /// \brief The list of ranges added to this diagnostic. | |||
74 | SmallVector<CharSourceRange, 8> DiagRanges; | |||
75 | ||||
76 | /// \brief If valid, provides a hint with some code to insert, remove, or | |||
77 | /// modify at a particular position. | |||
78 | SmallVector<FixItHint, 6> FixItHints; | |||
79 | ||||
80 | Storage() = default; | |||
81 | }; | |||
82 | ||||
83 | /// \brief An allocator for Storage objects, which uses a small cache to | |||
84 | /// objects, used to reduce malloc()/free() traffic for partial diagnostics. | |||
85 | class StorageAllocator { | |||
86 | static const unsigned NumCached = 16; | |||
87 | Storage Cached[NumCached]; | |||
88 | Storage *FreeList[NumCached]; | |||
89 | unsigned NumFreeListEntries; | |||
90 | ||||
91 | public: | |||
92 | StorageAllocator(); | |||
93 | ~StorageAllocator(); | |||
94 | ||||
95 | /// \brief Allocate new storage. | |||
96 | Storage *Allocate() { | |||
97 | if (NumFreeListEntries == 0) | |||
98 | return new Storage; | |||
99 | ||||
100 | Storage *Result = FreeList[--NumFreeListEntries]; | |||
101 | Result->NumDiagArgs = 0; | |||
102 | Result->DiagRanges.clear(); | |||
103 | Result->FixItHints.clear(); | |||
104 | return Result; | |||
105 | } | |||
106 | ||||
107 | /// \brief Free the given storage object. | |||
108 | void Deallocate(Storage *S) { | |||
109 | if (S >= Cached && S <= Cached + NumCached) { | |||
110 | FreeList[NumFreeListEntries++] = S; | |||
111 | return; | |||
112 | } | |||
113 | ||||
114 | delete S; | |||
115 | } | |||
116 | }; | |||
117 | ||||
118 | private: | |||
119 | // NOTE: Sema assumes that PartialDiagnostic is location-invariant | |||
120 | // in the sense that its bits can be safely memcpy'ed and destructed | |||
121 | // in the new location. | |||
122 | ||||
123 | /// \brief The diagnostic ID. | |||
124 | mutable unsigned DiagID = 0; | |||
125 | ||||
126 | /// \brief Storage for args and ranges. | |||
127 | mutable Storage *DiagStorage = nullptr; | |||
128 | ||||
129 | /// \brief Allocator used to allocate storage for this diagnostic. | |||
130 | StorageAllocator *Allocator = nullptr; | |||
131 | ||||
132 | /// \brief Retrieve storage for this particular diagnostic. | |||
133 | Storage *getStorage() const { | |||
134 | if (DiagStorage) | |||
135 | return DiagStorage; | |||
136 | ||||
137 | if (Allocator) | |||
138 | DiagStorage = Allocator->Allocate(); | |||
139 | else { | |||
140 | assert(Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0)))(static_cast <bool> (Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0))) ? void (0) : __assert_fail ("Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0))" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 140, __extension__ __PRETTY_FUNCTION__)); | |||
141 | DiagStorage = new Storage; | |||
142 | } | |||
143 | return DiagStorage; | |||
144 | } | |||
145 | ||||
146 | void freeStorage() { | |||
147 | if (!DiagStorage) | |||
148 | return; | |||
149 | ||||
150 | // The hot path for PartialDiagnostic is when we just used it to wrap an ID | |||
151 | // (typically so we have the flexibility of passing a more complex | |||
152 | // diagnostic into the callee, but that does not commonly occur). | |||
153 | // | |||
154 | // Split this out into a slow function for silly compilers (*cough*) which | |||
155 | // can't do decent partial inlining. | |||
156 | freeStorageSlow(); | |||
157 | } | |||
158 | ||||
159 | void freeStorageSlow() { | |||
160 | if (Allocator) | |||
161 | Allocator->Deallocate(DiagStorage); | |||
162 | else if (Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0))) | |||
163 | delete DiagStorage; | |||
164 | DiagStorage = nullptr; | |||
165 | } | |||
166 | ||||
167 | void AddSourceRange(const CharSourceRange &R) const { | |||
168 | if (!DiagStorage) | |||
169 | DiagStorage = getStorage(); | |||
170 | ||||
171 | DiagStorage->DiagRanges.push_back(R); | |||
172 | } | |||
173 | ||||
174 | void AddFixItHint(const FixItHint &Hint) const { | |||
175 | if (Hint.isNull()) | |||
176 | return; | |||
177 | ||||
178 | if (!DiagStorage) | |||
179 | DiagStorage = getStorage(); | |||
180 | ||||
181 | DiagStorage->FixItHints.push_back(Hint); | |||
182 | } | |||
183 | ||||
184 | public: | |||
185 | struct NullDiagnostic {}; | |||
186 | ||||
187 | /// \brief Create a null partial diagnostic, which cannot carry a payload, | |||
188 | /// and only exists to be swapped with a real partial diagnostic. | |||
189 | PartialDiagnostic(NullDiagnostic) {} | |||
190 | ||||
191 | PartialDiagnostic(unsigned DiagID, StorageAllocator &Allocator) | |||
192 | : DiagID(DiagID), Allocator(&Allocator) {} | |||
193 | ||||
194 | PartialDiagnostic(const PartialDiagnostic &Other) | |||
195 | : DiagID(Other.DiagID), Allocator(Other.Allocator) { | |||
196 | if (Other.DiagStorage) { | |||
197 | DiagStorage = getStorage(); | |||
198 | *DiagStorage = *Other.DiagStorage; | |||
199 | } | |||
200 | } | |||
201 | ||||
202 | PartialDiagnostic(PartialDiagnostic &&Other) | |||
203 | : DiagID(Other.DiagID), DiagStorage(Other.DiagStorage), | |||
204 | Allocator(Other.Allocator) { | |||
| ||||
205 | Other.DiagStorage = nullptr; | |||
206 | } | |||
207 | ||||
208 | PartialDiagnostic(const PartialDiagnostic &Other, Storage *DiagStorage) | |||
209 | : DiagID(Other.DiagID), DiagStorage(DiagStorage), | |||
210 | Allocator(reinterpret_cast<StorageAllocator *>(~uintptr_t(0))) { | |||
211 | if (Other.DiagStorage) | |||
212 | *this->DiagStorage = *Other.DiagStorage; | |||
213 | } | |||
214 | ||||
215 | PartialDiagnostic(const Diagnostic &Other, StorageAllocator &Allocator) | |||
216 | : DiagID(Other.getID()), Allocator(&Allocator) { | |||
217 | // Copy arguments. | |||
218 | for (unsigned I = 0, N = Other.getNumArgs(); I != N; ++I) { | |||
219 | if (Other.getArgKind(I) == DiagnosticsEngine::ak_std_string) | |||
220 | AddString(Other.getArgStdStr(I)); | |||
221 | else | |||
222 | AddTaggedVal(Other.getRawArg(I), Other.getArgKind(I)); | |||
223 | } | |||
224 | ||||
225 | // Copy source ranges. | |||
226 | for (unsigned I = 0, N = Other.getNumRanges(); I != N; ++I) | |||
227 | AddSourceRange(Other.getRange(I)); | |||
228 | ||||
229 | // Copy fix-its. | |||
230 | for (unsigned I = 0, N = Other.getNumFixItHints(); I != N; ++I) | |||
231 | AddFixItHint(Other.getFixItHint(I)); | |||
232 | } | |||
233 | ||||
234 | PartialDiagnostic &operator=(const PartialDiagnostic &Other) { | |||
235 | DiagID = Other.DiagID; | |||
236 | if (Other.DiagStorage) { | |||
237 | if (!DiagStorage) | |||
238 | DiagStorage = getStorage(); | |||
239 | ||||
240 | *DiagStorage = *Other.DiagStorage; | |||
241 | } else { | |||
242 | freeStorage(); | |||
243 | } | |||
244 | ||||
245 | return *this; | |||
246 | } | |||
247 | ||||
248 | PartialDiagnostic &operator=(PartialDiagnostic &&Other) { | |||
249 | freeStorage(); | |||
250 | ||||
251 | DiagID = Other.DiagID; | |||
252 | DiagStorage = Other.DiagStorage; | |||
253 | Allocator = Other.Allocator; | |||
254 | ||||
255 | Other.DiagStorage = nullptr; | |||
256 | return *this; | |||
257 | } | |||
258 | ||||
259 | ~PartialDiagnostic() { | |||
260 | freeStorage(); | |||
261 | } | |||
262 | ||||
263 | void swap(PartialDiagnostic &PD) { | |||
264 | std::swap(DiagID, PD.DiagID); | |||
265 | std::swap(DiagStorage, PD.DiagStorage); | |||
266 | std::swap(Allocator, PD.Allocator); | |||
267 | } | |||
268 | ||||
269 | unsigned getDiagID() const { return DiagID; } | |||
270 | ||||
271 | void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const { | |||
272 | if (!DiagStorage) | |||
273 | DiagStorage = getStorage(); | |||
274 | ||||
275 | assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < Storage ::MaxArguments && "Too many arguments to diagnostic!" ) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 276, __extension__ __PRETTY_FUNCTION__)) | |||
276 | "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < Storage ::MaxArguments && "Too many arguments to diagnostic!" ) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 276, __extension__ __PRETTY_FUNCTION__)); | |||
277 | DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] = Kind; | |||
278 | DiagStorage->DiagArgumentsVal[DiagStorage->NumDiagArgs++] = V; | |||
279 | } | |||
280 | ||||
281 | void AddString(StringRef V) const { | |||
282 | if (!DiagStorage) | |||
283 | DiagStorage = getStorage(); | |||
284 | ||||
285 | assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < Storage ::MaxArguments && "Too many arguments to diagnostic!" ) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 286, __extension__ __PRETTY_FUNCTION__)) | |||
286 | "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < Storage ::MaxArguments && "Too many arguments to diagnostic!" ) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 286, __extension__ __PRETTY_FUNCTION__)); | |||
287 | DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] | |||
288 | = DiagnosticsEngine::ak_std_string; | |||
289 | DiagStorage->DiagArgumentsStr[DiagStorage->NumDiagArgs++] = V; | |||
290 | } | |||
291 | ||||
292 | void Emit(const DiagnosticBuilder &DB) const { | |||
293 | if (!DiagStorage) | |||
294 | return; | |||
295 | ||||
296 | // Add all arguments. | |||
297 | for (unsigned i = 0, e = DiagStorage->NumDiagArgs; i != e; ++i) { | |||
298 | if ((DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKind[i] | |||
299 | == DiagnosticsEngine::ak_std_string) | |||
300 | DB.AddString(DiagStorage->DiagArgumentsStr[i]); | |||
301 | else | |||
302 | DB.AddTaggedVal(DiagStorage->DiagArgumentsVal[i], | |||
303 | (DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKind[i]); | |||
304 | } | |||
305 | ||||
306 | // Add all ranges. | |||
307 | for (const CharSourceRange &Range : DiagStorage->DiagRanges) | |||
308 | DB.AddSourceRange(Range); | |||
309 | ||||
310 | // Add all fix-its. | |||
311 | for (const FixItHint &Fix : DiagStorage->FixItHints) | |||
312 | DB.AddFixItHint(Fix); | |||
313 | } | |||
314 | ||||
315 | void EmitToString(DiagnosticsEngine &Diags, | |||
316 | SmallVectorImpl<char> &Buf) const { | |||
317 | // FIXME: It should be possible to render a diagnostic to a string without | |||
318 | // messing with the state of the diagnostics engine. | |||
319 | DiagnosticBuilder DB(Diags.Report(getDiagID())); | |||
320 | Emit(DB); | |||
321 | DB.FlushCounts(); | |||
322 | Diagnostic(&Diags).FormatDiagnostic(Buf); | |||
323 | DB.Clear(); | |||
324 | Diags.Clear(); | |||
325 | } | |||
326 | ||||
327 | /// \brief Clear out this partial diagnostic, giving it a new diagnostic ID | |||
328 | /// and removing all of its arguments, ranges, and fix-it hints. | |||
329 | void Reset(unsigned DiagID = 0) { | |||
330 | this->DiagID = DiagID; | |||
331 | freeStorage(); | |||
332 | } | |||
333 | ||||
334 | bool hasStorage() const { return DiagStorage != nullptr; } | |||
335 | ||||
336 | /// Retrieve the string argument at the given index. | |||
337 | StringRef getStringArg(unsigned I) { | |||
338 | assert(DiagStorage && "No diagnostic storage?")(static_cast <bool> (DiagStorage && "No diagnostic storage?" ) ? void (0) : __assert_fail ("DiagStorage && \"No diagnostic storage?\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 338, __extension__ __PRETTY_FUNCTION__)); | |||
339 | assert(I < DiagStorage->NumDiagArgs && "Not enough diagnostic args")(static_cast <bool> (I < DiagStorage->NumDiagArgs && "Not enough diagnostic args") ? void (0) : __assert_fail ("I < DiagStorage->NumDiagArgs && \"Not enough diagnostic args\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 339, __extension__ __PRETTY_FUNCTION__)); | |||
340 | assert(DiagStorage->DiagArgumentsKind[I](static_cast <bool> (DiagStorage->DiagArgumentsKind[ I] == DiagnosticsEngine::ak_std_string && "Not a string arg" ) ? void (0) : __assert_fail ("DiagStorage->DiagArgumentsKind[I] == DiagnosticsEngine::ak_std_string && \"Not a string arg\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 341, __extension__ __PRETTY_FUNCTION__)) | |||
341 | == DiagnosticsEngine::ak_std_string && "Not a string arg")(static_cast <bool> (DiagStorage->DiagArgumentsKind[ I] == DiagnosticsEngine::ak_std_string && "Not a string arg" ) ? void (0) : __assert_fail ("DiagStorage->DiagArgumentsKind[I] == DiagnosticsEngine::ak_std_string && \"Not a string arg\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 341, __extension__ __PRETTY_FUNCTION__)); | |||
342 | return DiagStorage->DiagArgumentsStr[I]; | |||
343 | } | |||
344 | ||||
345 | friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, | |||
346 | unsigned I) { | |||
347 | PD.AddTaggedVal(I, DiagnosticsEngine::ak_uint); | |||
348 | return PD; | |||
349 | } | |||
350 | ||||
351 | friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, | |||
352 | int I) { | |||
353 | PD.AddTaggedVal(I, DiagnosticsEngine::ak_sint); | |||
354 | return PD; | |||
355 | } | |||
356 | ||||
357 | friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, | |||
358 | const char *S) { | |||
359 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(S), | |||
360 | DiagnosticsEngine::ak_c_string); | |||
361 | return PD; | |||
362 | } | |||
363 | ||||
364 | friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, | |||
365 | StringRef S) { | |||
366 | ||||
367 | PD.AddString(S); | |||
368 | return PD; | |||
369 | } | |||
370 | ||||
371 | friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, | |||
372 | const IdentifierInfo *II) { | |||
373 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(II), | |||
374 | DiagnosticsEngine::ak_identifierinfo); | |||
375 | return PD; | |||
376 | } | |||
377 | ||||
378 | // Adds a DeclContext to the diagnostic. The enable_if template magic is here | |||
379 | // so that we only match those arguments that are (statically) DeclContexts; | |||
380 | // other arguments that derive from DeclContext (e.g., RecordDecls) will not | |||
381 | // match. | |||
382 | template<typename T> | |||
383 | friend inline | |||
384 | typename std::enable_if<std::is_same<T, DeclContext>::value, | |||
385 | const PartialDiagnostic &>::type | |||
386 | operator<<(const PartialDiagnostic &PD, T *DC) { | |||
387 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(DC), | |||
388 | DiagnosticsEngine::ak_declcontext); | |||
389 | return PD; | |||
390 | } | |||
391 | ||||
392 | friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, | |||
393 | SourceRange R) { | |||
394 | PD.AddSourceRange(CharSourceRange::getTokenRange(R)); | |||
395 | return PD; | |||
396 | } | |||
397 | ||||
398 | friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, | |||
399 | const CharSourceRange &R) { | |||
400 | PD.AddSourceRange(R); | |||
401 | return PD; | |||
402 | } | |||
403 | ||||
404 | friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, | |||
405 | const FixItHint &Hint) { | |||
406 | PD.AddFixItHint(Hint); | |||
407 | return PD; | |||
408 | } | |||
409 | }; | |||
410 | ||||
411 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, | |||
412 | const PartialDiagnostic &PD) { | |||
413 | PD.Emit(DB); | |||
414 | return DB; | |||
415 | } | |||
416 | ||||
417 | /// \brief A partial diagnostic along with the source location where this | |||
418 | /// diagnostic occurs. | |||
419 | using PartialDiagnosticAt = std::pair<SourceLocation, PartialDiagnostic>; | |||
420 | ||||
421 | } // namespace clang | |||
422 | ||||
423 | #endif // LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H |
1 | //===--- SemaInternal.h - Internal Sema Interfaces --------------*- C++ -*-===// |
2 | // |
3 | // The LLVM Compiler Infrastructure |
4 | // |
5 | // This file is distributed under the University of Illinois Open Source |
6 | // License. See LICENSE.TXT for details. |
7 | // |
8 | //===----------------------------------------------------------------------===// |
9 | // |
10 | // This file provides common API and #includes for the internal |
11 | // implementation of Sema. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_CLANG_SEMA_SEMAINTERNAL_H |
16 | #define LLVM_CLANG_SEMA_SEMAINTERNAL_H |
17 | |
18 | #include "clang/AST/ASTContext.h" |
19 | #include "clang/Sema/Lookup.h" |
20 | #include "clang/Sema/Sema.h" |
21 | #include "clang/Sema/SemaDiagnostic.h" |
22 | |
23 | namespace clang { |
24 | |
25 | inline PartialDiagnostic Sema::PDiag(unsigned DiagID) { |
26 | return PartialDiagnostic(DiagID, Context.getDiagAllocator()); |
27 | } |
28 | |
29 | inline bool |
30 | FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI) { |
31 | return FTI.NumParams == 1 && !FTI.isVariadic && |
32 | FTI.Params[0].Ident == nullptr && FTI.Params[0].Param && |
33 | cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType(); |
34 | } |
35 | |
36 | inline bool |
37 | FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI) { |
38 | // Assume FTI is well-formed. |
39 | return FTI.NumParams && !FTIHasSingleVoidParameter(FTI); |
40 | } |
41 | |
42 | // This requires the variable to be non-dependent and the initializer |
43 | // to not be value dependent. |
44 | inline bool IsVariableAConstantExpression(VarDecl *Var, ASTContext &Context) { |
45 | const VarDecl *DefVD = nullptr; |
46 | return !isa<ParmVarDecl>(Var) && |
47 | Var->isUsableInConstantExpressions(Context) && |
48 | Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE(); |
49 | } |
50 | |
51 | // Helper function to check whether D's attributes match current CUDA mode. |
52 | // Decls with mismatched attributes and related diagnostics may have to be |
53 | // ignored during this CUDA compilation pass. |
54 | inline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D) { |
55 | if (!LangOpts.CUDA || !D) |
56 | return true; |
57 | bool isDeviceSideDecl = D->hasAttr<CUDADeviceAttr>() || |
58 | D->hasAttr<CUDASharedAttr>() || |
59 | D->hasAttr<CUDAGlobalAttr>(); |
60 | return isDeviceSideDecl == LangOpts.CUDAIsDevice; |
61 | } |
62 | |
63 | // Directly mark a variable odr-used. Given a choice, prefer to use |
64 | // MarkVariableReferenced since it does additional checks and then |
65 | // calls MarkVarDeclODRUsed. |
66 | // If the variable must be captured: |
67 | // - if FunctionScopeIndexToStopAt is null, capture it in the CurContext |
68 | // - else capture it in the DeclContext that maps to the |
69 | // *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. |
70 | inline void MarkVarDeclODRUsed(VarDecl *Var, |
71 | SourceLocation Loc, Sema &SemaRef, |
72 | const unsigned *const FunctionScopeIndexToStopAt) { |
73 | // Keep track of used but undefined variables. |
74 | // FIXME: We shouldn't suppress this warning for static data members. |
75 | if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && |
76 | (!Var->isExternallyVisible() || Var->isInline() || |
77 | SemaRef.isExternalWithNoLinkageType(Var)) && |
78 | !(Var->isStaticDataMember() && Var->hasInit())) { |
79 | SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; |
80 | if (old.isInvalid()) |
81 | old = Loc; |
82 | } |
83 | QualType CaptureType, DeclRefType; |
84 | SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, |
85 | /*EllipsisLoc*/ SourceLocation(), |
86 | /*BuildAndDiagnose*/ true, |
87 | CaptureType, DeclRefType, |
88 | FunctionScopeIndexToStopAt); |
89 | |
90 | Var->markUsed(SemaRef.Context); |
91 | } |
92 | |
93 | /// Return a DLL attribute from the declaration. |
94 | inline InheritableAttr *getDLLAttr(Decl *D) { |
95 | assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&(static_cast <bool> (!(D->hasAttr<DLLImportAttr> () && D->hasAttr<DLLExportAttr>()) && "A declaration cannot be both dllimport and dllexport.") ? void (0) : __assert_fail ("!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) && \"A declaration cannot be both dllimport and dllexport.\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/SemaInternal.h" , 96, __extension__ __PRETTY_FUNCTION__)) |
96 | "A declaration cannot be both dllimport and dllexport.")(static_cast <bool> (!(D->hasAttr<DLLImportAttr> () && D->hasAttr<DLLExportAttr>()) && "A declaration cannot be both dllimport and dllexport.") ? void (0) : __assert_fail ("!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) && \"A declaration cannot be both dllimport and dllexport.\"" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/SemaInternal.h" , 96, __extension__ __PRETTY_FUNCTION__)); |
97 | if (auto *Import = D->getAttr<DLLImportAttr>()) |
98 | return Import; |
99 | if (auto *Export = D->getAttr<DLLExportAttr>()) |
100 | return Export; |
101 | return nullptr; |
102 | } |
103 | |
104 | class TypoCorrectionConsumer : public VisibleDeclConsumer { |
105 | typedef SmallVector<TypoCorrection, 1> TypoResultList; |
106 | typedef llvm::StringMap<TypoResultList> TypoResultsMap; |
107 | typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap; |
108 | |
109 | public: |
110 | TypoCorrectionConsumer(Sema &SemaRef, |
111 | const DeclarationNameInfo &TypoName, |
112 | Sema::LookupNameKind LookupKind, |
113 | Scope *S, CXXScopeSpec *SS, |
114 | std::unique_ptr<CorrectionCandidateCallback> CCC, |
115 | DeclContext *MemberContext, |
116 | bool EnteringContext) |
117 | : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0), |
118 | SavedTCIndex(0), SemaRef(SemaRef), S(S), |
119 | SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr), |
120 | CorrectionValidator(std::move(CCC)), MemberContext(MemberContext), |
121 | Result(SemaRef, TypoName, LookupKind), |
122 | Namespaces(SemaRef.Context, SemaRef.CurContext, SS), |
123 | EnteringContext(EnteringContext), SearchNamespaces(false) { |
124 | Result.suppressDiagnostics(); |
125 | // Arrange for ValidatedCorrections[0] to always be an empty correction. |
126 | ValidatedCorrections.push_back(TypoCorrection()); |
127 | } |
128 | |
129 | bool includeHiddenDecls() const override { return true; } |
130 | |
131 | // Methods for adding potential corrections to the consumer. |
132 | void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, |
133 | bool InBaseClass) override; |
134 | void FoundName(StringRef Name); |
135 | void addKeywordResult(StringRef Keyword); |
136 | void addCorrection(TypoCorrection Correction); |
137 | |
138 | bool empty() const { |
139 | return CorrectionResults.empty() && ValidatedCorrections.size() == 1; |
140 | } |
141 | |
142 | /// \brief Return the list of TypoCorrections for the given identifier from |
143 | /// the set of corrections that have the closest edit distance, if any. |
144 | TypoResultList &operator[](StringRef Name) { |
145 | return CorrectionResults.begin()->second[Name]; |
146 | } |
147 | |
148 | /// \brief Return the edit distance of the corrections that have the |
149 | /// closest/best edit distance from the original typop. |
150 | unsigned getBestEditDistance(bool Normalized) { |
151 | if (CorrectionResults.empty()) |
152 | return (std::numeric_limits<unsigned>::max)(); |
153 | |
154 | unsigned BestED = CorrectionResults.begin()->first; |
155 | return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED; |
156 | } |
157 | |
158 | /// \brief Set-up method to add to the consumer the set of namespaces to use |
159 | /// in performing corrections to nested name specifiers. This method also |
160 | /// implicitly adds all of the known classes in the current AST context to the |
161 | /// to the consumer for correcting nested name specifiers. |
162 | void |
163 | addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces); |
164 | |
165 | /// \brief Return the next typo correction that passes all internal filters |
166 | /// and is deemed valid by the consumer's CorrectionCandidateCallback, |
167 | /// starting with the corrections that have the closest edit distance. An |
168 | /// empty TypoCorrection is returned once no more viable corrections remain |
169 | /// in the consumer. |
170 | const TypoCorrection &getNextCorrection(); |
171 | |
172 | /// \brief Get the last correction returned by getNextCorrection(). |
173 | const TypoCorrection &getCurrentCorrection() { |
174 | return CurrentTCIndex < ValidatedCorrections.size() |
175 | ? ValidatedCorrections[CurrentTCIndex] |
176 | : ValidatedCorrections[0]; // The empty correction. |
177 | } |
178 | |
179 | /// \brief Return the next typo correction like getNextCorrection, but keep |
180 | /// the internal state pointed to the current correction (i.e. the next time |
181 | /// getNextCorrection is called, it will return the same correction returned |
182 | /// by peekNextcorrection). |
183 | const TypoCorrection &peekNextCorrection() { |
184 | auto Current = CurrentTCIndex; |
185 | const TypoCorrection &TC = getNextCorrection(); |
186 | CurrentTCIndex = Current; |
187 | return TC; |
188 | } |
189 | |
190 | /// \brief Reset the consumer's position in the stream of viable corrections |
191 | /// (i.e. getNextCorrection() will return each of the previously returned |
192 | /// corrections in order before returning any new corrections). |
193 | void resetCorrectionStream() { |
194 | CurrentTCIndex = 0; |
195 | } |
196 | |
197 | /// \brief Return whether the end of the stream of corrections has been |
198 | /// reached. |
199 | bool finished() { |
200 | return CorrectionResults.empty() && |
201 | CurrentTCIndex >= ValidatedCorrections.size(); |
202 | } |
203 | |
204 | /// \brief Save the current position in the correction stream (overwriting any |
205 | /// previously saved position). |
206 | void saveCurrentPosition() { |
207 | SavedTCIndex = CurrentTCIndex; |
208 | } |
209 | |
210 | /// \brief Restore the saved position in the correction stream. |
211 | void restoreSavedPosition() { |
212 | CurrentTCIndex = SavedTCIndex; |
213 | } |
214 | |
215 | ASTContext &getContext() const { return SemaRef.Context; } |
216 | const LookupResult &getLookupResult() const { return Result; } |
217 | |
218 | bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; } |
219 | const CXXScopeSpec *getSS() const { return SS.get(); } |
220 | Scope *getScope() const { return S; } |
221 | CorrectionCandidateCallback *getCorrectionValidator() const { |
222 | return CorrectionValidator.get(); |
223 | } |
224 | |
225 | private: |
226 | class NamespaceSpecifierSet { |
227 | struct SpecifierInfo { |
228 | DeclContext* DeclCtx; |
229 | NestedNameSpecifier* NameSpecifier; |
230 | unsigned EditDistance; |
231 | }; |
232 | |
233 | typedef SmallVector<DeclContext*, 4> DeclContextList; |
234 | typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList; |
235 | |
236 | ASTContext &Context; |
237 | DeclContextList CurContextChain; |
238 | std::string CurNameSpecifier; |
239 | SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers; |
240 | SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers; |
241 | |
242 | std::map<unsigned, SpecifierInfoList> DistanceMap; |
243 | |
244 | /// \brief Helper for building the list of DeclContexts between the current |
245 | /// context and the top of the translation unit |
246 | static DeclContextList buildContextChain(DeclContext *Start); |
247 | |
248 | unsigned buildNestedNameSpecifier(DeclContextList &DeclChain, |
249 | NestedNameSpecifier *&NNS); |
250 | |
251 | public: |
252 | NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext, |
253 | CXXScopeSpec *CurScopeSpec); |
254 | |
255 | /// \brief Add the DeclContext (a namespace or record) to the set, computing |
256 | /// the corresponding NestedNameSpecifier and its distance in the process. |
257 | void addNameSpecifier(DeclContext *Ctx); |
258 | |
259 | /// \brief Provides flat iteration over specifiers, sorted by distance. |
260 | class iterator |
261 | : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag, |
262 | SpecifierInfo> { |
263 | /// Always points to the last element in the distance map. |
264 | const std::map<unsigned, SpecifierInfoList>::iterator OuterBack; |
265 | /// Iterator on the distance map. |
266 | std::map<unsigned, SpecifierInfoList>::iterator Outer; |
267 | /// Iterator on an element in the distance map. |
268 | SpecifierInfoList::iterator Inner; |
269 | |
270 | public: |
271 | iterator(NamespaceSpecifierSet &Set, bool IsAtEnd) |
272 | : OuterBack(std::prev(Set.DistanceMap.end())), |
273 | Outer(Set.DistanceMap.begin()), |
274 | Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) { |
275 | assert(!Set.DistanceMap.empty())(static_cast <bool> (!Set.DistanceMap.empty()) ? void ( 0) : __assert_fail ("!Set.DistanceMap.empty()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/SemaInternal.h" , 275, __extension__ __PRETTY_FUNCTION__)); |
276 | } |
277 | |
278 | iterator &operator++() { |
279 | ++Inner; |
280 | if (Inner == Outer->second.end() && Outer != OuterBack) { |
281 | ++Outer; |
282 | Inner = Outer->second.begin(); |
283 | } |
284 | return *this; |
285 | } |
286 | |
287 | SpecifierInfo &operator*() { return *Inner; } |
288 | bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; } |
289 | }; |
290 | |
291 | iterator begin() { return iterator(*this, /*IsAtEnd=*/false); } |
292 | iterator end() { return iterator(*this, /*IsAtEnd=*/true); } |
293 | }; |
294 | |
295 | void addName(StringRef Name, NamedDecl *ND, |
296 | NestedNameSpecifier *NNS = nullptr, bool isKeyword = false); |
297 | |
298 | /// \brief Find any visible decls for the given typo correction candidate. |
299 | /// If none are found, it to the set of candidates for which qualified lookups |
300 | /// will be performed to find possible nested name specifier changes. |
301 | bool resolveCorrection(TypoCorrection &Candidate); |
302 | |
303 | /// \brief Perform qualified lookups on the queued set of typo correction |
304 | /// candidates and add the nested name specifier changes to each candidate if |
305 | /// a lookup succeeds (at which point the candidate will be returned to the |
306 | /// main pool of potential corrections). |
307 | void performQualifiedLookups(); |
308 | |
309 | /// \brief The name written that is a typo in the source. |
310 | IdentifierInfo *Typo; |
311 | |
312 | /// \brief The results found that have the smallest edit distance |
313 | /// found (so far) with the typo name. |
314 | /// |
315 | /// The pointer value being set to the current DeclContext indicates |
316 | /// whether there is a keyword with this name. |
317 | TypoEditDistanceMap CorrectionResults; |
318 | |
319 | SmallVector<TypoCorrection, 4> ValidatedCorrections; |
320 | size_t CurrentTCIndex; |
321 | size_t SavedTCIndex; |
322 | |
323 | Sema &SemaRef; |
324 | Scope *S; |
325 | std::unique_ptr<CXXScopeSpec> SS; |
326 | std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator; |
327 | DeclContext *MemberContext; |
328 | LookupResult Result; |
329 | NamespaceSpecifierSet Namespaces; |
330 | SmallVector<TypoCorrection, 2> QualifiedResults; |
331 | bool EnteringContext; |
332 | bool SearchNamespaces; |
333 | }; |
334 | |
335 | inline Sema::TypoExprState::TypoExprState() {} |
336 | |
337 | inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) noexcept { |
338 | *this = std::move(other); |
339 | } |
340 | |
341 | inline Sema::TypoExprState &Sema::TypoExprState:: |
342 | operator=(Sema::TypoExprState &&other) noexcept { |
343 | Consumer = std::move(other.Consumer); |
344 | DiagHandler = std::move(other.DiagHandler); |
345 | RecoveryHandler = std::move(other.RecoveryHandler); |
346 | return *this; |
347 | } |
348 | |
349 | } // end namespace clang |
350 | |
351 | #endif |