xref: /aosp_15_r20/external/clang/lib/Sema/SemaExpr.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li //  This file implements semantic analysis for expressions.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li 
14*67e74705SXin Li #include "clang/Sema/SemaInternal.h"
15*67e74705SXin Li #include "TreeTransform.h"
16*67e74705SXin Li #include "clang/AST/ASTConsumer.h"
17*67e74705SXin Li #include "clang/AST/ASTContext.h"
18*67e74705SXin Li #include "clang/AST/ASTLambda.h"
19*67e74705SXin Li #include "clang/AST/ASTMutationListener.h"
20*67e74705SXin Li #include "clang/AST/CXXInheritance.h"
21*67e74705SXin Li #include "clang/AST/DeclObjC.h"
22*67e74705SXin Li #include "clang/AST/DeclTemplate.h"
23*67e74705SXin Li #include "clang/AST/EvaluatedExprVisitor.h"
24*67e74705SXin Li #include "clang/AST/Expr.h"
25*67e74705SXin Li #include "clang/AST/ExprCXX.h"
26*67e74705SXin Li #include "clang/AST/ExprObjC.h"
27*67e74705SXin Li #include "clang/AST/ExprOpenMP.h"
28*67e74705SXin Li #include "clang/AST/RecursiveASTVisitor.h"
29*67e74705SXin Li #include "clang/AST/TypeLoc.h"
30*67e74705SXin Li #include "clang/Basic/PartialDiagnostic.h"
31*67e74705SXin Li #include "clang/Basic/SourceManager.h"
32*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
33*67e74705SXin Li #include "clang/Lex/LiteralSupport.h"
34*67e74705SXin Li #include "clang/Lex/Preprocessor.h"
35*67e74705SXin Li #include "clang/Sema/AnalysisBasedWarnings.h"
36*67e74705SXin Li #include "clang/Sema/DeclSpec.h"
37*67e74705SXin Li #include "clang/Sema/DelayedDiagnostic.h"
38*67e74705SXin Li #include "clang/Sema/Designator.h"
39*67e74705SXin Li #include "clang/Sema/Initialization.h"
40*67e74705SXin Li #include "clang/Sema/Lookup.h"
41*67e74705SXin Li #include "clang/Sema/ParsedTemplate.h"
42*67e74705SXin Li #include "clang/Sema/Scope.h"
43*67e74705SXin Li #include "clang/Sema/ScopeInfo.h"
44*67e74705SXin Li #include "clang/Sema/SemaFixItUtils.h"
45*67e74705SXin Li #include "clang/Sema/Template.h"
46*67e74705SXin Li #include "llvm/Support/ConvertUTF.h"
47*67e74705SXin Li using namespace clang;
48*67e74705SXin Li using namespace sema;
49*67e74705SXin Li 
50*67e74705SXin Li /// \brief Determine whether the use of this declaration is valid, without
51*67e74705SXin Li /// emitting diagnostics.
CanUseDecl(NamedDecl * D,bool TreatUnavailableAsInvalid)52*67e74705SXin Li bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53*67e74705SXin Li   // See if this is an auto-typed variable whose initializer we are parsing.
54*67e74705SXin Li   if (ParsingInitForAutoVars.count(D))
55*67e74705SXin Li     return false;
56*67e74705SXin Li 
57*67e74705SXin Li   // See if this is a deleted function.
58*67e74705SXin Li   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59*67e74705SXin Li     if (FD->isDeleted())
60*67e74705SXin Li       return false;
61*67e74705SXin Li 
62*67e74705SXin Li     // If the function has a deduced return type, and we can't deduce it,
63*67e74705SXin Li     // then we can't use it either.
64*67e74705SXin Li     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65*67e74705SXin Li         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66*67e74705SXin Li       return false;
67*67e74705SXin Li   }
68*67e74705SXin Li 
69*67e74705SXin Li   // See if this function is unavailable.
70*67e74705SXin Li   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71*67e74705SXin Li       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72*67e74705SXin Li     return false;
73*67e74705SXin Li 
74*67e74705SXin Li   return true;
75*67e74705SXin Li }
76*67e74705SXin Li 
DiagnoseUnusedOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc)77*67e74705SXin Li static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78*67e74705SXin Li   // Warn if this is used but marked unused.
79*67e74705SXin Li   if (const auto *A = D->getAttr<UnusedAttr>()) {
80*67e74705SXin Li     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81*67e74705SXin Li     // should diagnose them.
82*67e74705SXin Li     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83*67e74705SXin Li       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84*67e74705SXin Li       if (DC && !DC->hasAttr<UnusedAttr>())
85*67e74705SXin Li         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86*67e74705SXin Li     }
87*67e74705SXin Li   }
88*67e74705SXin Li }
89*67e74705SXin Li 
HasRedeclarationWithoutAvailabilityInCategory(const Decl * D)90*67e74705SXin Li static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91*67e74705SXin Li   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
92*67e74705SXin Li   if (!OMD)
93*67e74705SXin Li     return false;
94*67e74705SXin Li   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
95*67e74705SXin Li   if (!OID)
96*67e74705SXin Li     return false;
97*67e74705SXin Li 
98*67e74705SXin Li   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99*67e74705SXin Li     if (ObjCMethodDecl *CatMeth =
100*67e74705SXin Li             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101*67e74705SXin Li       if (!CatMeth->hasAttr<AvailabilityAttr>())
102*67e74705SXin Li         return true;
103*67e74705SXin Li   return false;
104*67e74705SXin Li }
105*67e74705SXin Li 
106*67e74705SXin Li static AvailabilityResult
DiagnoseAvailabilityOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess)107*67e74705SXin Li DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
108*67e74705SXin Li                            const ObjCInterfaceDecl *UnknownObjCClass,
109*67e74705SXin Li                            bool ObjCPropertyAccess) {
110*67e74705SXin Li   // See if this declaration is unavailable or deprecated.
111*67e74705SXin Li   std::string Message;
112*67e74705SXin Li   AvailabilityResult Result = D->getAvailability(&Message);
113*67e74705SXin Li 
114*67e74705SXin Li   // For typedefs, if the typedef declaration appears available look
115*67e74705SXin Li   // to the underlying type to see if it is more restrictive.
116*67e74705SXin Li   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
117*67e74705SXin Li     if (Result == AR_Available) {
118*67e74705SXin Li       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
119*67e74705SXin Li         D = TT->getDecl();
120*67e74705SXin Li         Result = D->getAvailability(&Message);
121*67e74705SXin Li         continue;
122*67e74705SXin Li       }
123*67e74705SXin Li     }
124*67e74705SXin Li     break;
125*67e74705SXin Li   }
126*67e74705SXin Li 
127*67e74705SXin Li   // Forward class declarations get their attributes from their definition.
128*67e74705SXin Li   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
129*67e74705SXin Li     if (IDecl->getDefinition()) {
130*67e74705SXin Li       D = IDecl->getDefinition();
131*67e74705SXin Li       Result = D->getAvailability(&Message);
132*67e74705SXin Li     }
133*67e74705SXin Li   }
134*67e74705SXin Li 
135*67e74705SXin Li   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
136*67e74705SXin Li     if (Result == AR_Available) {
137*67e74705SXin Li       const DeclContext *DC = ECD->getDeclContext();
138*67e74705SXin Li       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
139*67e74705SXin Li         Result = TheEnumDecl->getAvailability(&Message);
140*67e74705SXin Li     }
141*67e74705SXin Li 
142*67e74705SXin Li   const ObjCPropertyDecl *ObjCPDecl = nullptr;
143*67e74705SXin Li   if (Result == AR_Deprecated || Result == AR_Unavailable ||
144*67e74705SXin Li       Result == AR_NotYetIntroduced) {
145*67e74705SXin Li     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
146*67e74705SXin Li       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
147*67e74705SXin Li         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
148*67e74705SXin Li         if (PDeclResult == Result)
149*67e74705SXin Li           ObjCPDecl = PD;
150*67e74705SXin Li       }
151*67e74705SXin Li     }
152*67e74705SXin Li   }
153*67e74705SXin Li 
154*67e74705SXin Li   switch (Result) {
155*67e74705SXin Li     case AR_Available:
156*67e74705SXin Li       break;
157*67e74705SXin Li 
158*67e74705SXin Li     case AR_Deprecated:
159*67e74705SXin Li       if (S.getCurContextAvailability() != AR_Deprecated)
160*67e74705SXin Li         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
161*67e74705SXin Li                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
162*67e74705SXin Li                                   ObjCPropertyAccess);
163*67e74705SXin Li       break;
164*67e74705SXin Li 
165*67e74705SXin Li     case AR_NotYetIntroduced: {
166*67e74705SXin Li       // Don't do this for enums, they can't be redeclared.
167*67e74705SXin Li       if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
168*67e74705SXin Li         break;
169*67e74705SXin Li 
170*67e74705SXin Li       bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
171*67e74705SXin Li       // Objective-C method declarations in categories are not modelled as
172*67e74705SXin Li       // redeclarations, so manually look for a redeclaration in a category
173*67e74705SXin Li       // if necessary.
174*67e74705SXin Li       if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
175*67e74705SXin Li         Warn = false;
176*67e74705SXin Li       // In general, D will point to the most recent redeclaration. However,
177*67e74705SXin Li       // for `@class A;` decls, this isn't true -- manually go through the
178*67e74705SXin Li       // redecl chain in that case.
179*67e74705SXin Li       if (Warn && isa<ObjCInterfaceDecl>(D))
180*67e74705SXin Li         for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
181*67e74705SXin Li              Redecl = Redecl->getPreviousDecl())
182*67e74705SXin Li           if (!Redecl->hasAttr<AvailabilityAttr>() ||
183*67e74705SXin Li               Redecl->getAttr<AvailabilityAttr>()->isInherited())
184*67e74705SXin Li             Warn = false;
185*67e74705SXin Li 
186*67e74705SXin Li       if (Warn)
187*67e74705SXin Li         S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
188*67e74705SXin Li                                   UnknownObjCClass, ObjCPDecl,
189*67e74705SXin Li                                   ObjCPropertyAccess);
190*67e74705SXin Li       break;
191*67e74705SXin Li     }
192*67e74705SXin Li 
193*67e74705SXin Li     case AR_Unavailable:
194*67e74705SXin Li       if (S.getCurContextAvailability() != AR_Unavailable)
195*67e74705SXin Li         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
196*67e74705SXin Li                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
197*67e74705SXin Li                                   ObjCPropertyAccess);
198*67e74705SXin Li       break;
199*67e74705SXin Li 
200*67e74705SXin Li     }
201*67e74705SXin Li     return Result;
202*67e74705SXin Li }
203*67e74705SXin Li 
204*67e74705SXin Li /// \brief Emit a note explaining that this function is deleted.
NoteDeletedFunction(FunctionDecl * Decl)205*67e74705SXin Li void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
206*67e74705SXin Li   assert(Decl->isDeleted());
207*67e74705SXin Li 
208*67e74705SXin Li   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
209*67e74705SXin Li 
210*67e74705SXin Li   if (Method && Method->isDeleted() && Method->isDefaulted()) {
211*67e74705SXin Li     // If the method was explicitly defaulted, point at that declaration.
212*67e74705SXin Li     if (!Method->isImplicit())
213*67e74705SXin Li       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
214*67e74705SXin Li 
215*67e74705SXin Li     // Try to diagnose why this special member function was implicitly
216*67e74705SXin Li     // deleted. This might fail, if that reason no longer applies.
217*67e74705SXin Li     CXXSpecialMember CSM = getSpecialMember(Method);
218*67e74705SXin Li     if (CSM != CXXInvalid)
219*67e74705SXin Li       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
220*67e74705SXin Li 
221*67e74705SXin Li     return;
222*67e74705SXin Li   }
223*67e74705SXin Li 
224*67e74705SXin Li   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
225*67e74705SXin Li   if (Ctor && Ctor->isInheritingConstructor())
226*67e74705SXin Li     return NoteDeletedInheritingConstructor(Ctor);
227*67e74705SXin Li 
228*67e74705SXin Li   Diag(Decl->getLocation(), diag::note_availability_specified_here)
229*67e74705SXin Li     << Decl << true;
230*67e74705SXin Li }
231*67e74705SXin Li 
232*67e74705SXin Li /// \brief Determine whether a FunctionDecl was ever declared with an
233*67e74705SXin Li /// explicit storage class.
hasAnyExplicitStorageClass(const FunctionDecl * D)234*67e74705SXin Li static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
235*67e74705SXin Li   for (auto I : D->redecls()) {
236*67e74705SXin Li     if (I->getStorageClass() != SC_None)
237*67e74705SXin Li       return true;
238*67e74705SXin Li   }
239*67e74705SXin Li   return false;
240*67e74705SXin Li }
241*67e74705SXin Li 
242*67e74705SXin Li /// \brief Check whether we're in an extern inline function and referring to a
243*67e74705SXin Li /// variable or function with internal linkage (C11 6.7.4p3).
244*67e74705SXin Li ///
245*67e74705SXin Li /// This is only a warning because we used to silently accept this code, but
246*67e74705SXin Li /// in many cases it will not behave correctly. This is not enabled in C++ mode
247*67e74705SXin Li /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
248*67e74705SXin Li /// and so while there may still be user mistakes, most of the time we can't
249*67e74705SXin Li /// prove that there are errors.
diagnoseUseOfInternalDeclInInlineFunction(Sema & S,const NamedDecl * D,SourceLocation Loc)250*67e74705SXin Li static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
251*67e74705SXin Li                                                       const NamedDecl *D,
252*67e74705SXin Li                                                       SourceLocation Loc) {
253*67e74705SXin Li   // This is disabled under C++; there are too many ways for this to fire in
254*67e74705SXin Li   // contexts where the warning is a false positive, or where it is technically
255*67e74705SXin Li   // correct but benign.
256*67e74705SXin Li   if (S.getLangOpts().CPlusPlus)
257*67e74705SXin Li     return;
258*67e74705SXin Li 
259*67e74705SXin Li   // Check if this is an inlined function or method.
260*67e74705SXin Li   FunctionDecl *Current = S.getCurFunctionDecl();
261*67e74705SXin Li   if (!Current)
262*67e74705SXin Li     return;
263*67e74705SXin Li   if (!Current->isInlined())
264*67e74705SXin Li     return;
265*67e74705SXin Li   if (!Current->isExternallyVisible())
266*67e74705SXin Li     return;
267*67e74705SXin Li 
268*67e74705SXin Li   // Check if the decl has internal linkage.
269*67e74705SXin Li   if (D->getFormalLinkage() != InternalLinkage)
270*67e74705SXin Li     return;
271*67e74705SXin Li 
272*67e74705SXin Li   // Downgrade from ExtWarn to Extension if
273*67e74705SXin Li   //  (1) the supposedly external inline function is in the main file,
274*67e74705SXin Li   //      and probably won't be included anywhere else.
275*67e74705SXin Li   //  (2) the thing we're referencing is a pure function.
276*67e74705SXin Li   //  (3) the thing we're referencing is another inline function.
277*67e74705SXin Li   // This last can give us false negatives, but it's better than warning on
278*67e74705SXin Li   // wrappers for simple C library functions.
279*67e74705SXin Li   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
280*67e74705SXin Li   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
281*67e74705SXin Li   if (!DowngradeWarning && UsedFn)
282*67e74705SXin Li     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
283*67e74705SXin Li 
284*67e74705SXin Li   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
285*67e74705SXin Li                                : diag::ext_internal_in_extern_inline)
286*67e74705SXin Li     << /*IsVar=*/!UsedFn << D;
287*67e74705SXin Li 
288*67e74705SXin Li   S.MaybeSuggestAddingStaticToDecl(Current);
289*67e74705SXin Li 
290*67e74705SXin Li   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
291*67e74705SXin Li       << D;
292*67e74705SXin Li }
293*67e74705SXin Li 
MaybeSuggestAddingStaticToDecl(const FunctionDecl * Cur)294*67e74705SXin Li void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
295*67e74705SXin Li   const FunctionDecl *First = Cur->getFirstDecl();
296*67e74705SXin Li 
297*67e74705SXin Li   // Suggest "static" on the function, if possible.
298*67e74705SXin Li   if (!hasAnyExplicitStorageClass(First)) {
299*67e74705SXin Li     SourceLocation DeclBegin = First->getSourceRange().getBegin();
300*67e74705SXin Li     Diag(DeclBegin, diag::note_convert_inline_to_static)
301*67e74705SXin Li       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
302*67e74705SXin Li   }
303*67e74705SXin Li }
304*67e74705SXin Li 
305*67e74705SXin Li /// \brief Determine whether the use of this declaration is valid, and
306*67e74705SXin Li /// emit any corresponding diagnostics.
307*67e74705SXin Li ///
308*67e74705SXin Li /// This routine diagnoses various problems with referencing
309*67e74705SXin Li /// declarations that can occur when using a declaration. For example,
310*67e74705SXin Li /// it might warn if a deprecated or unavailable declaration is being
311*67e74705SXin Li /// used, or produce an error (and return true) if a C++0x deleted
312*67e74705SXin Li /// function is being used.
313*67e74705SXin Li ///
314*67e74705SXin Li /// \returns true if there was an error (this declaration cannot be
315*67e74705SXin Li /// referenced), false otherwise.
316*67e74705SXin Li ///
DiagnoseUseOfDecl(NamedDecl * D,SourceLocation Loc,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess)317*67e74705SXin Li bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
318*67e74705SXin Li                              const ObjCInterfaceDecl *UnknownObjCClass,
319*67e74705SXin Li                              bool ObjCPropertyAccess) {
320*67e74705SXin Li   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
321*67e74705SXin Li     // If there were any diagnostics suppressed by template argument deduction,
322*67e74705SXin Li     // emit them now.
323*67e74705SXin Li     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
324*67e74705SXin Li     if (Pos != SuppressedDiagnostics.end()) {
325*67e74705SXin Li       for (const PartialDiagnosticAt &Suppressed : Pos->second)
326*67e74705SXin Li         Diag(Suppressed.first, Suppressed.second);
327*67e74705SXin Li 
328*67e74705SXin Li       // Clear out the list of suppressed diagnostics, so that we don't emit
329*67e74705SXin Li       // them again for this specialization. However, we don't obsolete this
330*67e74705SXin Li       // entry from the table, because we want to avoid ever emitting these
331*67e74705SXin Li       // diagnostics again.
332*67e74705SXin Li       Pos->second.clear();
333*67e74705SXin Li     }
334*67e74705SXin Li 
335*67e74705SXin Li     // C++ [basic.start.main]p3:
336*67e74705SXin Li     //   The function 'main' shall not be used within a program.
337*67e74705SXin Li     if (cast<FunctionDecl>(D)->isMain())
338*67e74705SXin Li       Diag(Loc, diag::ext_main_used);
339*67e74705SXin Li   }
340*67e74705SXin Li 
341*67e74705SXin Li   // See if this is an auto-typed variable whose initializer we are parsing.
342*67e74705SXin Li   if (ParsingInitForAutoVars.count(D)) {
343*67e74705SXin Li     const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
344*67e74705SXin Li 
345*67e74705SXin Li     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
346*67e74705SXin Li       << D->getDeclName() << (unsigned)AT->getKeyword();
347*67e74705SXin Li     return true;
348*67e74705SXin Li   }
349*67e74705SXin Li 
350*67e74705SXin Li   // See if this is a deleted function.
351*67e74705SXin Li   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
352*67e74705SXin Li     if (FD->isDeleted()) {
353*67e74705SXin Li       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
354*67e74705SXin Li       if (Ctor && Ctor->isInheritingConstructor())
355*67e74705SXin Li         Diag(Loc, diag::err_deleted_inherited_ctor_use)
356*67e74705SXin Li             << Ctor->getParent()
357*67e74705SXin Li             << Ctor->getInheritedConstructor().getConstructor()->getParent();
358*67e74705SXin Li       else
359*67e74705SXin Li         Diag(Loc, diag::err_deleted_function_use);
360*67e74705SXin Li       NoteDeletedFunction(FD);
361*67e74705SXin Li       return true;
362*67e74705SXin Li     }
363*67e74705SXin Li 
364*67e74705SXin Li     // If the function has a deduced return type, and we can't deduce it,
365*67e74705SXin Li     // then we can't use it either.
366*67e74705SXin Li     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
367*67e74705SXin Li         DeduceReturnType(FD, Loc))
368*67e74705SXin Li       return true;
369*67e74705SXin Li   }
370*67e74705SXin Li 
371*67e74705SXin Li   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
372*67e74705SXin Li   // Only the variables omp_in and omp_out are allowed in the combiner.
373*67e74705SXin Li   // Only the variables omp_priv and omp_orig are allowed in the
374*67e74705SXin Li   // initializer-clause.
375*67e74705SXin Li   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
376*67e74705SXin Li   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
377*67e74705SXin Li       isa<VarDecl>(D)) {
378*67e74705SXin Li     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
379*67e74705SXin Li         << getCurFunction()->HasOMPDeclareReductionCombiner;
380*67e74705SXin Li     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
381*67e74705SXin Li     return true;
382*67e74705SXin Li   }
383*67e74705SXin Li   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
384*67e74705SXin Li                              ObjCPropertyAccess);
385*67e74705SXin Li 
386*67e74705SXin Li   DiagnoseUnusedOfDecl(*this, D, Loc);
387*67e74705SXin Li 
388*67e74705SXin Li   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
389*67e74705SXin Li 
390*67e74705SXin Li   return false;
391*67e74705SXin Li }
392*67e74705SXin Li 
393*67e74705SXin Li /// \brief Retrieve the message suffix that should be added to a
394*67e74705SXin Li /// diagnostic complaining about the given function being deleted or
395*67e74705SXin Li /// unavailable.
getDeletedOrUnavailableSuffix(const FunctionDecl * FD)396*67e74705SXin Li std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
397*67e74705SXin Li   std::string Message;
398*67e74705SXin Li   if (FD->getAvailability(&Message))
399*67e74705SXin Li     return ": " + Message;
400*67e74705SXin Li 
401*67e74705SXin Li   return std::string();
402*67e74705SXin Li }
403*67e74705SXin Li 
404*67e74705SXin Li /// DiagnoseSentinelCalls - This routine checks whether a call or
405*67e74705SXin Li /// message-send is to a declaration with the sentinel attribute, and
406*67e74705SXin Li /// if so, it checks that the requirements of the sentinel are
407*67e74705SXin Li /// satisfied.
DiagnoseSentinelCalls(NamedDecl * D,SourceLocation Loc,ArrayRef<Expr * > Args)408*67e74705SXin Li void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
409*67e74705SXin Li                                  ArrayRef<Expr *> Args) {
410*67e74705SXin Li   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
411*67e74705SXin Li   if (!attr)
412*67e74705SXin Li     return;
413*67e74705SXin Li 
414*67e74705SXin Li   // The number of formal parameters of the declaration.
415*67e74705SXin Li   unsigned numFormalParams;
416*67e74705SXin Li 
417*67e74705SXin Li   // The kind of declaration.  This is also an index into a %select in
418*67e74705SXin Li   // the diagnostic.
419*67e74705SXin Li   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
420*67e74705SXin Li 
421*67e74705SXin Li   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
422*67e74705SXin Li     numFormalParams = MD->param_size();
423*67e74705SXin Li     calleeType = CT_Method;
424*67e74705SXin Li   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
425*67e74705SXin Li     numFormalParams = FD->param_size();
426*67e74705SXin Li     calleeType = CT_Function;
427*67e74705SXin Li   } else if (isa<VarDecl>(D)) {
428*67e74705SXin Li     QualType type = cast<ValueDecl>(D)->getType();
429*67e74705SXin Li     const FunctionType *fn = nullptr;
430*67e74705SXin Li     if (const PointerType *ptr = type->getAs<PointerType>()) {
431*67e74705SXin Li       fn = ptr->getPointeeType()->getAs<FunctionType>();
432*67e74705SXin Li       if (!fn) return;
433*67e74705SXin Li       calleeType = CT_Function;
434*67e74705SXin Li     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
435*67e74705SXin Li       fn = ptr->getPointeeType()->castAs<FunctionType>();
436*67e74705SXin Li       calleeType = CT_Block;
437*67e74705SXin Li     } else {
438*67e74705SXin Li       return;
439*67e74705SXin Li     }
440*67e74705SXin Li 
441*67e74705SXin Li     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
442*67e74705SXin Li       numFormalParams = proto->getNumParams();
443*67e74705SXin Li     } else {
444*67e74705SXin Li       numFormalParams = 0;
445*67e74705SXin Li     }
446*67e74705SXin Li   } else {
447*67e74705SXin Li     return;
448*67e74705SXin Li   }
449*67e74705SXin Li 
450*67e74705SXin Li   // "nullPos" is the number of formal parameters at the end which
451*67e74705SXin Li   // effectively count as part of the variadic arguments.  This is
452*67e74705SXin Li   // useful if you would prefer to not have *any* formal parameters,
453*67e74705SXin Li   // but the language forces you to have at least one.
454*67e74705SXin Li   unsigned nullPos = attr->getNullPos();
455*67e74705SXin Li   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
456*67e74705SXin Li   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
457*67e74705SXin Li 
458*67e74705SXin Li   // The number of arguments which should follow the sentinel.
459*67e74705SXin Li   unsigned numArgsAfterSentinel = attr->getSentinel();
460*67e74705SXin Li 
461*67e74705SXin Li   // If there aren't enough arguments for all the formal parameters,
462*67e74705SXin Li   // the sentinel, and the args after the sentinel, complain.
463*67e74705SXin Li   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
464*67e74705SXin Li     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
465*67e74705SXin Li     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
466*67e74705SXin Li     return;
467*67e74705SXin Li   }
468*67e74705SXin Li 
469*67e74705SXin Li   // Otherwise, find the sentinel expression.
470*67e74705SXin Li   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
471*67e74705SXin Li   if (!sentinelExpr) return;
472*67e74705SXin Li   if (sentinelExpr->isValueDependent()) return;
473*67e74705SXin Li   if (Context.isSentinelNullExpr(sentinelExpr)) return;
474*67e74705SXin Li 
475*67e74705SXin Li   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
476*67e74705SXin Li   // or 'NULL' if those are actually defined in the context.  Only use
477*67e74705SXin Li   // 'nil' for ObjC methods, where it's much more likely that the
478*67e74705SXin Li   // variadic arguments form a list of object pointers.
479*67e74705SXin Li   SourceLocation MissingNilLoc
480*67e74705SXin Li     = getLocForEndOfToken(sentinelExpr->getLocEnd());
481*67e74705SXin Li   std::string NullValue;
482*67e74705SXin Li   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
483*67e74705SXin Li     NullValue = "nil";
484*67e74705SXin Li   else if (getLangOpts().CPlusPlus11)
485*67e74705SXin Li     NullValue = "nullptr";
486*67e74705SXin Li   else if (PP.isMacroDefined("NULL"))
487*67e74705SXin Li     NullValue = "NULL";
488*67e74705SXin Li   else
489*67e74705SXin Li     NullValue = "(void*) 0";
490*67e74705SXin Li 
491*67e74705SXin Li   if (MissingNilLoc.isInvalid())
492*67e74705SXin Li     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
493*67e74705SXin Li   else
494*67e74705SXin Li     Diag(MissingNilLoc, diag::warn_missing_sentinel)
495*67e74705SXin Li       << int(calleeType)
496*67e74705SXin Li       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
497*67e74705SXin Li   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
498*67e74705SXin Li }
499*67e74705SXin Li 
getExprRange(Expr * E) const500*67e74705SXin Li SourceRange Sema::getExprRange(Expr *E) const {
501*67e74705SXin Li   return E ? E->getSourceRange() : SourceRange();
502*67e74705SXin Li }
503*67e74705SXin Li 
504*67e74705SXin Li //===----------------------------------------------------------------------===//
505*67e74705SXin Li //  Standard Promotions and Conversions
506*67e74705SXin Li //===----------------------------------------------------------------------===//
507*67e74705SXin Li 
508*67e74705SXin Li /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
DefaultFunctionArrayConversion(Expr * E,bool Diagnose)509*67e74705SXin Li ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
510*67e74705SXin Li   // Handle any placeholder expressions which made it here.
511*67e74705SXin Li   if (E->getType()->isPlaceholderType()) {
512*67e74705SXin Li     ExprResult result = CheckPlaceholderExpr(E);
513*67e74705SXin Li     if (result.isInvalid()) return ExprError();
514*67e74705SXin Li     E = result.get();
515*67e74705SXin Li   }
516*67e74705SXin Li 
517*67e74705SXin Li   QualType Ty = E->getType();
518*67e74705SXin Li   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
519*67e74705SXin Li 
520*67e74705SXin Li   if (Ty->isFunctionType()) {
521*67e74705SXin Li     // If we are here, we are not calling a function but taking
522*67e74705SXin Li     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
523*67e74705SXin Li     if (getLangOpts().OpenCL) {
524*67e74705SXin Li       if (Diagnose)
525*67e74705SXin Li         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
526*67e74705SXin Li       return ExprError();
527*67e74705SXin Li     }
528*67e74705SXin Li 
529*67e74705SXin Li     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
530*67e74705SXin Li       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
531*67e74705SXin Li         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
532*67e74705SXin Li           return ExprError();
533*67e74705SXin Li 
534*67e74705SXin Li     E = ImpCastExprToType(E, Context.getPointerType(Ty),
535*67e74705SXin Li                           CK_FunctionToPointerDecay).get();
536*67e74705SXin Li   } else if (Ty->isArrayType()) {
537*67e74705SXin Li     // In C90 mode, arrays only promote to pointers if the array expression is
538*67e74705SXin Li     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
539*67e74705SXin Li     // type 'array of type' is converted to an expression that has type 'pointer
540*67e74705SXin Li     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
541*67e74705SXin Li     // that has type 'array of type' ...".  The relevant change is "an lvalue"
542*67e74705SXin Li     // (C90) to "an expression" (C99).
543*67e74705SXin Li     //
544*67e74705SXin Li     // C++ 4.2p1:
545*67e74705SXin Li     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
546*67e74705SXin Li     // T" can be converted to an rvalue of type "pointer to T".
547*67e74705SXin Li     //
548*67e74705SXin Li     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
549*67e74705SXin Li       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
550*67e74705SXin Li                             CK_ArrayToPointerDecay).get();
551*67e74705SXin Li   }
552*67e74705SXin Li   return E;
553*67e74705SXin Li }
554*67e74705SXin Li 
CheckForNullPointerDereference(Sema & S,Expr * E)555*67e74705SXin Li static void CheckForNullPointerDereference(Sema &S, Expr *E) {
556*67e74705SXin Li   // Check to see if we are dereferencing a null pointer.  If so,
557*67e74705SXin Li   // and if not volatile-qualified, this is undefined behavior that the
558*67e74705SXin Li   // optimizer will delete, so warn about it.  People sometimes try to use this
559*67e74705SXin Li   // to get a deterministic trap and are surprised by clang's behavior.  This
560*67e74705SXin Li   // only handles the pattern "*null", which is a very syntactic check.
561*67e74705SXin Li   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
562*67e74705SXin Li     if (UO->getOpcode() == UO_Deref &&
563*67e74705SXin Li         UO->getSubExpr()->IgnoreParenCasts()->
564*67e74705SXin Li           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
565*67e74705SXin Li         !UO->getType().isVolatileQualified()) {
566*67e74705SXin Li     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
567*67e74705SXin Li                           S.PDiag(diag::warn_indirection_through_null)
568*67e74705SXin Li                             << UO->getSubExpr()->getSourceRange());
569*67e74705SXin Li     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
570*67e74705SXin Li                         S.PDiag(diag::note_indirection_through_null));
571*67e74705SXin Li   }
572*67e74705SXin Li }
573*67e74705SXin Li 
DiagnoseDirectIsaAccess(Sema & S,const ObjCIvarRefExpr * OIRE,SourceLocation AssignLoc,const Expr * RHS)574*67e74705SXin Li static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
575*67e74705SXin Li                                     SourceLocation AssignLoc,
576*67e74705SXin Li                                     const Expr* RHS) {
577*67e74705SXin Li   const ObjCIvarDecl *IV = OIRE->getDecl();
578*67e74705SXin Li   if (!IV)
579*67e74705SXin Li     return;
580*67e74705SXin Li 
581*67e74705SXin Li   DeclarationName MemberName = IV->getDeclName();
582*67e74705SXin Li   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
583*67e74705SXin Li   if (!Member || !Member->isStr("isa"))
584*67e74705SXin Li     return;
585*67e74705SXin Li 
586*67e74705SXin Li   const Expr *Base = OIRE->getBase();
587*67e74705SXin Li   QualType BaseType = Base->getType();
588*67e74705SXin Li   if (OIRE->isArrow())
589*67e74705SXin Li     BaseType = BaseType->getPointeeType();
590*67e74705SXin Li   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
591*67e74705SXin Li     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
592*67e74705SXin Li       ObjCInterfaceDecl *ClassDeclared = nullptr;
593*67e74705SXin Li       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
594*67e74705SXin Li       if (!ClassDeclared->getSuperClass()
595*67e74705SXin Li           && (*ClassDeclared->ivar_begin()) == IV) {
596*67e74705SXin Li         if (RHS) {
597*67e74705SXin Li           NamedDecl *ObjectSetClass =
598*67e74705SXin Li             S.LookupSingleName(S.TUScope,
599*67e74705SXin Li                                &S.Context.Idents.get("object_setClass"),
600*67e74705SXin Li                                SourceLocation(), S.LookupOrdinaryName);
601*67e74705SXin Li           if (ObjectSetClass) {
602*67e74705SXin Li             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
603*67e74705SXin Li             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
604*67e74705SXin Li             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
605*67e74705SXin Li             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
606*67e74705SXin Li                                                      AssignLoc), ",") <<
607*67e74705SXin Li             FixItHint::CreateInsertion(RHSLocEnd, ")");
608*67e74705SXin Li           }
609*67e74705SXin Li           else
610*67e74705SXin Li             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
611*67e74705SXin Li         } else {
612*67e74705SXin Li           NamedDecl *ObjectGetClass =
613*67e74705SXin Li             S.LookupSingleName(S.TUScope,
614*67e74705SXin Li                                &S.Context.Idents.get("object_getClass"),
615*67e74705SXin Li                                SourceLocation(), S.LookupOrdinaryName);
616*67e74705SXin Li           if (ObjectGetClass)
617*67e74705SXin Li             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
618*67e74705SXin Li             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
619*67e74705SXin Li             FixItHint::CreateReplacement(
620*67e74705SXin Li                                          SourceRange(OIRE->getOpLoc(),
621*67e74705SXin Li                                                      OIRE->getLocEnd()), ")");
622*67e74705SXin Li           else
623*67e74705SXin Li             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
624*67e74705SXin Li         }
625*67e74705SXin Li         S.Diag(IV->getLocation(), diag::note_ivar_decl);
626*67e74705SXin Li       }
627*67e74705SXin Li     }
628*67e74705SXin Li }
629*67e74705SXin Li 
DefaultLvalueConversion(Expr * E)630*67e74705SXin Li ExprResult Sema::DefaultLvalueConversion(Expr *E) {
631*67e74705SXin Li   // Handle any placeholder expressions which made it here.
632*67e74705SXin Li   if (E->getType()->isPlaceholderType()) {
633*67e74705SXin Li     ExprResult result = CheckPlaceholderExpr(E);
634*67e74705SXin Li     if (result.isInvalid()) return ExprError();
635*67e74705SXin Li     E = result.get();
636*67e74705SXin Li   }
637*67e74705SXin Li 
638*67e74705SXin Li   // C++ [conv.lval]p1:
639*67e74705SXin Li   //   A glvalue of a non-function, non-array type T can be
640*67e74705SXin Li   //   converted to a prvalue.
641*67e74705SXin Li   if (!E->isGLValue()) return E;
642*67e74705SXin Li 
643*67e74705SXin Li   QualType T = E->getType();
644*67e74705SXin Li   assert(!T.isNull() && "r-value conversion on typeless expression?");
645*67e74705SXin Li 
646*67e74705SXin Li   // We don't want to throw lvalue-to-rvalue casts on top of
647*67e74705SXin Li   // expressions of certain types in C++.
648*67e74705SXin Li   if (getLangOpts().CPlusPlus &&
649*67e74705SXin Li       (E->getType() == Context.OverloadTy ||
650*67e74705SXin Li        T->isDependentType() ||
651*67e74705SXin Li        T->isRecordType()))
652*67e74705SXin Li     return E;
653*67e74705SXin Li 
654*67e74705SXin Li   // The C standard is actually really unclear on this point, and
655*67e74705SXin Li   // DR106 tells us what the result should be but not why.  It's
656*67e74705SXin Li   // generally best to say that void types just doesn't undergo
657*67e74705SXin Li   // lvalue-to-rvalue at all.  Note that expressions of unqualified
658*67e74705SXin Li   // 'void' type are never l-values, but qualified void can be.
659*67e74705SXin Li   if (T->isVoidType())
660*67e74705SXin Li     return E;
661*67e74705SXin Li 
662*67e74705SXin Li   // OpenCL usually rejects direct accesses to values of 'half' type.
663*67e74705SXin Li   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
664*67e74705SXin Li       T->isHalfType()) {
665*67e74705SXin Li     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
666*67e74705SXin Li       << 0 << T;
667*67e74705SXin Li     return ExprError();
668*67e74705SXin Li   }
669*67e74705SXin Li 
670*67e74705SXin Li   CheckForNullPointerDereference(*this, E);
671*67e74705SXin Li   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
672*67e74705SXin Li     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
673*67e74705SXin Li                                      &Context.Idents.get("object_getClass"),
674*67e74705SXin Li                                      SourceLocation(), LookupOrdinaryName);
675*67e74705SXin Li     if (ObjectGetClass)
676*67e74705SXin Li       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
677*67e74705SXin Li         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
678*67e74705SXin Li         FixItHint::CreateReplacement(
679*67e74705SXin Li                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
680*67e74705SXin Li     else
681*67e74705SXin Li       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
682*67e74705SXin Li   }
683*67e74705SXin Li   else if (const ObjCIvarRefExpr *OIRE =
684*67e74705SXin Li             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
685*67e74705SXin Li     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
686*67e74705SXin Li 
687*67e74705SXin Li   // C++ [conv.lval]p1:
688*67e74705SXin Li   //   [...] If T is a non-class type, the type of the prvalue is the
689*67e74705SXin Li   //   cv-unqualified version of T. Otherwise, the type of the
690*67e74705SXin Li   //   rvalue is T.
691*67e74705SXin Li   //
692*67e74705SXin Li   // C99 6.3.2.1p2:
693*67e74705SXin Li   //   If the lvalue has qualified type, the value has the unqualified
694*67e74705SXin Li   //   version of the type of the lvalue; otherwise, the value has the
695*67e74705SXin Li   //   type of the lvalue.
696*67e74705SXin Li   if (T.hasQualifiers())
697*67e74705SXin Li     T = T.getUnqualifiedType();
698*67e74705SXin Li 
699*67e74705SXin Li   // Under the MS ABI, lock down the inheritance model now.
700*67e74705SXin Li   if (T->isMemberPointerType() &&
701*67e74705SXin Li       Context.getTargetInfo().getCXXABI().isMicrosoft())
702*67e74705SXin Li     (void)isCompleteType(E->getExprLoc(), T);
703*67e74705SXin Li 
704*67e74705SXin Li   UpdateMarkingForLValueToRValue(E);
705*67e74705SXin Li 
706*67e74705SXin Li   // Loading a __weak object implicitly retains the value, so we need a cleanup to
707*67e74705SXin Li   // balance that.
708*67e74705SXin Li   if (getLangOpts().ObjCAutoRefCount &&
709*67e74705SXin Li       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
710*67e74705SXin Li     Cleanup.setExprNeedsCleanups(true);
711*67e74705SXin Li 
712*67e74705SXin Li   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
713*67e74705SXin Li                                             nullptr, VK_RValue);
714*67e74705SXin Li 
715*67e74705SXin Li   // C11 6.3.2.1p2:
716*67e74705SXin Li   //   ... if the lvalue has atomic type, the value has the non-atomic version
717*67e74705SXin Li   //   of the type of the lvalue ...
718*67e74705SXin Li   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
719*67e74705SXin Li     T = Atomic->getValueType().getUnqualifiedType();
720*67e74705SXin Li     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
721*67e74705SXin Li                                    nullptr, VK_RValue);
722*67e74705SXin Li   }
723*67e74705SXin Li 
724*67e74705SXin Li   return Res;
725*67e74705SXin Li }
726*67e74705SXin Li 
DefaultFunctionArrayLvalueConversion(Expr * E,bool Diagnose)727*67e74705SXin Li ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
728*67e74705SXin Li   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
729*67e74705SXin Li   if (Res.isInvalid())
730*67e74705SXin Li     return ExprError();
731*67e74705SXin Li   Res = DefaultLvalueConversion(Res.get());
732*67e74705SXin Li   if (Res.isInvalid())
733*67e74705SXin Li     return ExprError();
734*67e74705SXin Li   return Res;
735*67e74705SXin Li }
736*67e74705SXin Li 
737*67e74705SXin Li /// CallExprUnaryConversions - a special case of an unary conversion
738*67e74705SXin Li /// performed on a function designator of a call expression.
CallExprUnaryConversions(Expr * E)739*67e74705SXin Li ExprResult Sema::CallExprUnaryConversions(Expr *E) {
740*67e74705SXin Li   QualType Ty = E->getType();
741*67e74705SXin Li   ExprResult Res = E;
742*67e74705SXin Li   // Only do implicit cast for a function type, but not for a pointer
743*67e74705SXin Li   // to function type.
744*67e74705SXin Li   if (Ty->isFunctionType()) {
745*67e74705SXin Li     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
746*67e74705SXin Li                             CK_FunctionToPointerDecay).get();
747*67e74705SXin Li     if (Res.isInvalid())
748*67e74705SXin Li       return ExprError();
749*67e74705SXin Li   }
750*67e74705SXin Li   Res = DefaultLvalueConversion(Res.get());
751*67e74705SXin Li   if (Res.isInvalid())
752*67e74705SXin Li     return ExprError();
753*67e74705SXin Li   return Res.get();
754*67e74705SXin Li }
755*67e74705SXin Li 
756*67e74705SXin Li /// UsualUnaryConversions - Performs various conversions that are common to most
757*67e74705SXin Li /// operators (C99 6.3). The conversions of array and function types are
758*67e74705SXin Li /// sometimes suppressed. For example, the array->pointer conversion doesn't
759*67e74705SXin Li /// apply if the array is an argument to the sizeof or address (&) operators.
760*67e74705SXin Li /// In these instances, this routine should *not* be called.
UsualUnaryConversions(Expr * E)761*67e74705SXin Li ExprResult Sema::UsualUnaryConversions(Expr *E) {
762*67e74705SXin Li   // First, convert to an r-value.
763*67e74705SXin Li   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
764*67e74705SXin Li   if (Res.isInvalid())
765*67e74705SXin Li     return ExprError();
766*67e74705SXin Li   E = Res.get();
767*67e74705SXin Li 
768*67e74705SXin Li   QualType Ty = E->getType();
769*67e74705SXin Li   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
770*67e74705SXin Li 
771*67e74705SXin Li   // Half FP have to be promoted to float unless it is natively supported
772*67e74705SXin Li   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
773*67e74705SXin Li     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
774*67e74705SXin Li 
775*67e74705SXin Li   // Try to perform integral promotions if the object has a theoretically
776*67e74705SXin Li   // promotable type.
777*67e74705SXin Li   if (Ty->isIntegralOrUnscopedEnumerationType()) {
778*67e74705SXin Li     // C99 6.3.1.1p2:
779*67e74705SXin Li     //
780*67e74705SXin Li     //   The following may be used in an expression wherever an int or
781*67e74705SXin Li     //   unsigned int may be used:
782*67e74705SXin Li     //     - an object or expression with an integer type whose integer
783*67e74705SXin Li     //       conversion rank is less than or equal to the rank of int
784*67e74705SXin Li     //       and unsigned int.
785*67e74705SXin Li     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
786*67e74705SXin Li     //
787*67e74705SXin Li     //   If an int can represent all values of the original type, the
788*67e74705SXin Li     //   value is converted to an int; otherwise, it is converted to an
789*67e74705SXin Li     //   unsigned int. These are called the integer promotions. All
790*67e74705SXin Li     //   other types are unchanged by the integer promotions.
791*67e74705SXin Li 
792*67e74705SXin Li     QualType PTy = Context.isPromotableBitField(E);
793*67e74705SXin Li     if (!PTy.isNull()) {
794*67e74705SXin Li       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
795*67e74705SXin Li       return E;
796*67e74705SXin Li     }
797*67e74705SXin Li     if (Ty->isPromotableIntegerType()) {
798*67e74705SXin Li       QualType PT = Context.getPromotedIntegerType(Ty);
799*67e74705SXin Li       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
800*67e74705SXin Li       return E;
801*67e74705SXin Li     }
802*67e74705SXin Li   }
803*67e74705SXin Li   return E;
804*67e74705SXin Li }
805*67e74705SXin Li 
806*67e74705SXin Li /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
807*67e74705SXin Li /// do not have a prototype. Arguments that have type float or __fp16
808*67e74705SXin Li /// are promoted to double. All other argument types are converted by
809*67e74705SXin Li /// UsualUnaryConversions().
DefaultArgumentPromotion(Expr * E)810*67e74705SXin Li ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
811*67e74705SXin Li   QualType Ty = E->getType();
812*67e74705SXin Li   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
813*67e74705SXin Li 
814*67e74705SXin Li   ExprResult Res = UsualUnaryConversions(E);
815*67e74705SXin Li   if (Res.isInvalid())
816*67e74705SXin Li     return ExprError();
817*67e74705SXin Li   E = Res.get();
818*67e74705SXin Li 
819*67e74705SXin Li   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
820*67e74705SXin Li   // double.
821*67e74705SXin Li   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
822*67e74705SXin Li   if (BTy && (BTy->getKind() == BuiltinType::Half ||
823*67e74705SXin Li               BTy->getKind() == BuiltinType::Float))
824*67e74705SXin Li     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
825*67e74705SXin Li 
826*67e74705SXin Li   // C++ performs lvalue-to-rvalue conversion as a default argument
827*67e74705SXin Li   // promotion, even on class types, but note:
828*67e74705SXin Li   //   C++11 [conv.lval]p2:
829*67e74705SXin Li   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
830*67e74705SXin Li   //     operand or a subexpression thereof the value contained in the
831*67e74705SXin Li   //     referenced object is not accessed. Otherwise, if the glvalue
832*67e74705SXin Li   //     has a class type, the conversion copy-initializes a temporary
833*67e74705SXin Li   //     of type T from the glvalue and the result of the conversion
834*67e74705SXin Li   //     is a prvalue for the temporary.
835*67e74705SXin Li   // FIXME: add some way to gate this entire thing for correctness in
836*67e74705SXin Li   // potentially potentially evaluated contexts.
837*67e74705SXin Li   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
838*67e74705SXin Li     ExprResult Temp = PerformCopyInitialization(
839*67e74705SXin Li                        InitializedEntity::InitializeTemporary(E->getType()),
840*67e74705SXin Li                                                 E->getExprLoc(), E);
841*67e74705SXin Li     if (Temp.isInvalid())
842*67e74705SXin Li       return ExprError();
843*67e74705SXin Li     E = Temp.get();
844*67e74705SXin Li   }
845*67e74705SXin Li 
846*67e74705SXin Li   return E;
847*67e74705SXin Li }
848*67e74705SXin Li 
849*67e74705SXin Li /// Determine the degree of POD-ness for an expression.
850*67e74705SXin Li /// Incomplete types are considered POD, since this check can be performed
851*67e74705SXin Li /// when we're in an unevaluated context.
isValidVarArgType(const QualType & Ty)852*67e74705SXin Li Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
853*67e74705SXin Li   if (Ty->isIncompleteType()) {
854*67e74705SXin Li     // C++11 [expr.call]p7:
855*67e74705SXin Li     //   After these conversions, if the argument does not have arithmetic,
856*67e74705SXin Li     //   enumeration, pointer, pointer to member, or class type, the program
857*67e74705SXin Li     //   is ill-formed.
858*67e74705SXin Li     //
859*67e74705SXin Li     // Since we've already performed array-to-pointer and function-to-pointer
860*67e74705SXin Li     // decay, the only such type in C++ is cv void. This also handles
861*67e74705SXin Li     // initializer lists as variadic arguments.
862*67e74705SXin Li     if (Ty->isVoidType())
863*67e74705SXin Li       return VAK_Invalid;
864*67e74705SXin Li 
865*67e74705SXin Li     if (Ty->isObjCObjectType())
866*67e74705SXin Li       return VAK_Invalid;
867*67e74705SXin Li     return VAK_Valid;
868*67e74705SXin Li   }
869*67e74705SXin Li 
870*67e74705SXin Li   if (Ty.isCXX98PODType(Context))
871*67e74705SXin Li     return VAK_Valid;
872*67e74705SXin Li 
873*67e74705SXin Li   // C++11 [expr.call]p7:
874*67e74705SXin Li   //   Passing a potentially-evaluated argument of class type (Clause 9)
875*67e74705SXin Li   //   having a non-trivial copy constructor, a non-trivial move constructor,
876*67e74705SXin Li   //   or a non-trivial destructor, with no corresponding parameter,
877*67e74705SXin Li   //   is conditionally-supported with implementation-defined semantics.
878*67e74705SXin Li   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
879*67e74705SXin Li     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
880*67e74705SXin Li       if (!Record->hasNonTrivialCopyConstructor() &&
881*67e74705SXin Li           !Record->hasNonTrivialMoveConstructor() &&
882*67e74705SXin Li           !Record->hasNonTrivialDestructor())
883*67e74705SXin Li         return VAK_ValidInCXX11;
884*67e74705SXin Li 
885*67e74705SXin Li   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
886*67e74705SXin Li     return VAK_Valid;
887*67e74705SXin Li 
888*67e74705SXin Li   if (Ty->isObjCObjectType())
889*67e74705SXin Li     return VAK_Invalid;
890*67e74705SXin Li 
891*67e74705SXin Li   if (getLangOpts().MSVCCompat)
892*67e74705SXin Li     return VAK_MSVCUndefined;
893*67e74705SXin Li 
894*67e74705SXin Li   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
895*67e74705SXin Li   // permitted to reject them. We should consider doing so.
896*67e74705SXin Li   return VAK_Undefined;
897*67e74705SXin Li }
898*67e74705SXin Li 
checkVariadicArgument(const Expr * E,VariadicCallType CT)899*67e74705SXin Li void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
900*67e74705SXin Li   // Don't allow one to pass an Objective-C interface to a vararg.
901*67e74705SXin Li   const QualType &Ty = E->getType();
902*67e74705SXin Li   VarArgKind VAK = isValidVarArgType(Ty);
903*67e74705SXin Li 
904*67e74705SXin Li   // Complain about passing non-POD types through varargs.
905*67e74705SXin Li   switch (VAK) {
906*67e74705SXin Li   case VAK_ValidInCXX11:
907*67e74705SXin Li     DiagRuntimeBehavior(
908*67e74705SXin Li         E->getLocStart(), nullptr,
909*67e74705SXin Li         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
910*67e74705SXin Li           << Ty << CT);
911*67e74705SXin Li     // Fall through.
912*67e74705SXin Li   case VAK_Valid:
913*67e74705SXin Li     if (Ty->isRecordType()) {
914*67e74705SXin Li       // This is unlikely to be what the user intended. If the class has a
915*67e74705SXin Li       // 'c_str' member function, the user probably meant to call that.
916*67e74705SXin Li       DiagRuntimeBehavior(E->getLocStart(), nullptr,
917*67e74705SXin Li                           PDiag(diag::warn_pass_class_arg_to_vararg)
918*67e74705SXin Li                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
919*67e74705SXin Li     }
920*67e74705SXin Li     break;
921*67e74705SXin Li 
922*67e74705SXin Li   case VAK_Undefined:
923*67e74705SXin Li   case VAK_MSVCUndefined:
924*67e74705SXin Li     DiagRuntimeBehavior(
925*67e74705SXin Li         E->getLocStart(), nullptr,
926*67e74705SXin Li         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
927*67e74705SXin Li           << getLangOpts().CPlusPlus11 << Ty << CT);
928*67e74705SXin Li     break;
929*67e74705SXin Li 
930*67e74705SXin Li   case VAK_Invalid:
931*67e74705SXin Li     if (Ty->isObjCObjectType())
932*67e74705SXin Li       DiagRuntimeBehavior(
933*67e74705SXin Li           E->getLocStart(), nullptr,
934*67e74705SXin Li           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
935*67e74705SXin Li             << Ty << CT);
936*67e74705SXin Li     else
937*67e74705SXin Li       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
938*67e74705SXin Li         << isa<InitListExpr>(E) << Ty << CT;
939*67e74705SXin Li     break;
940*67e74705SXin Li   }
941*67e74705SXin Li }
942*67e74705SXin Li 
943*67e74705SXin Li /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
944*67e74705SXin Li /// will create a trap if the resulting type is not a POD type.
DefaultVariadicArgumentPromotion(Expr * E,VariadicCallType CT,FunctionDecl * FDecl)945*67e74705SXin Li ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
946*67e74705SXin Li                                                   FunctionDecl *FDecl) {
947*67e74705SXin Li   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
948*67e74705SXin Li     // Strip the unbridged-cast placeholder expression off, if applicable.
949*67e74705SXin Li     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
950*67e74705SXin Li         (CT == VariadicMethod ||
951*67e74705SXin Li          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
952*67e74705SXin Li       E = stripARCUnbridgedCast(E);
953*67e74705SXin Li 
954*67e74705SXin Li     // Otherwise, do normal placeholder checking.
955*67e74705SXin Li     } else {
956*67e74705SXin Li       ExprResult ExprRes = CheckPlaceholderExpr(E);
957*67e74705SXin Li       if (ExprRes.isInvalid())
958*67e74705SXin Li         return ExprError();
959*67e74705SXin Li       E = ExprRes.get();
960*67e74705SXin Li     }
961*67e74705SXin Li   }
962*67e74705SXin Li 
963*67e74705SXin Li   ExprResult ExprRes = DefaultArgumentPromotion(E);
964*67e74705SXin Li   if (ExprRes.isInvalid())
965*67e74705SXin Li     return ExprError();
966*67e74705SXin Li   E = ExprRes.get();
967*67e74705SXin Li 
968*67e74705SXin Li   // Diagnostics regarding non-POD argument types are
969*67e74705SXin Li   // emitted along with format string checking in Sema::CheckFunctionCall().
970*67e74705SXin Li   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
971*67e74705SXin Li     // Turn this into a trap.
972*67e74705SXin Li     CXXScopeSpec SS;
973*67e74705SXin Li     SourceLocation TemplateKWLoc;
974*67e74705SXin Li     UnqualifiedId Name;
975*67e74705SXin Li     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
976*67e74705SXin Li                        E->getLocStart());
977*67e74705SXin Li     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
978*67e74705SXin Li                                           Name, true, false);
979*67e74705SXin Li     if (TrapFn.isInvalid())
980*67e74705SXin Li       return ExprError();
981*67e74705SXin Li 
982*67e74705SXin Li     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
983*67e74705SXin Li                                     E->getLocStart(), None,
984*67e74705SXin Li                                     E->getLocEnd());
985*67e74705SXin Li     if (Call.isInvalid())
986*67e74705SXin Li       return ExprError();
987*67e74705SXin Li 
988*67e74705SXin Li     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
989*67e74705SXin Li                                   Call.get(), E);
990*67e74705SXin Li     if (Comma.isInvalid())
991*67e74705SXin Li       return ExprError();
992*67e74705SXin Li     return Comma.get();
993*67e74705SXin Li   }
994*67e74705SXin Li 
995*67e74705SXin Li   if (!getLangOpts().CPlusPlus &&
996*67e74705SXin Li       RequireCompleteType(E->getExprLoc(), E->getType(),
997*67e74705SXin Li                           diag::err_call_incomplete_argument))
998*67e74705SXin Li     return ExprError();
999*67e74705SXin Li 
1000*67e74705SXin Li   return E;
1001*67e74705SXin Li }
1002*67e74705SXin Li 
1003*67e74705SXin Li /// \brief Converts an integer to complex float type.  Helper function of
1004*67e74705SXin Li /// UsualArithmeticConversions()
1005*67e74705SXin Li ///
1006*67e74705SXin Li /// \return false if the integer expression is an integer type and is
1007*67e74705SXin Li /// successfully converted to the complex type.
handleIntegerToComplexFloatConversion(Sema & S,ExprResult & IntExpr,ExprResult & ComplexExpr,QualType IntTy,QualType ComplexTy,bool SkipCast)1008*67e74705SXin Li static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1009*67e74705SXin Li                                                   ExprResult &ComplexExpr,
1010*67e74705SXin Li                                                   QualType IntTy,
1011*67e74705SXin Li                                                   QualType ComplexTy,
1012*67e74705SXin Li                                                   bool SkipCast) {
1013*67e74705SXin Li   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1014*67e74705SXin Li   if (SkipCast) return false;
1015*67e74705SXin Li   if (IntTy->isIntegerType()) {
1016*67e74705SXin Li     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1017*67e74705SXin Li     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1018*67e74705SXin Li     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1019*67e74705SXin Li                                   CK_FloatingRealToComplex);
1020*67e74705SXin Li   } else {
1021*67e74705SXin Li     assert(IntTy->isComplexIntegerType());
1022*67e74705SXin Li     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1023*67e74705SXin Li                                   CK_IntegralComplexToFloatingComplex);
1024*67e74705SXin Li   }
1025*67e74705SXin Li   return false;
1026*67e74705SXin Li }
1027*67e74705SXin Li 
1028*67e74705SXin Li /// \brief Handle arithmetic conversion with complex types.  Helper function of
1029*67e74705SXin Li /// UsualArithmeticConversions()
handleComplexFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1030*67e74705SXin Li static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1031*67e74705SXin Li                                              ExprResult &RHS, QualType LHSType,
1032*67e74705SXin Li                                              QualType RHSType,
1033*67e74705SXin Li                                              bool IsCompAssign) {
1034*67e74705SXin Li   // if we have an integer operand, the result is the complex type.
1035*67e74705SXin Li   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1036*67e74705SXin Li                                              /*skipCast*/false))
1037*67e74705SXin Li     return LHSType;
1038*67e74705SXin Li   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1039*67e74705SXin Li                                              /*skipCast*/IsCompAssign))
1040*67e74705SXin Li     return RHSType;
1041*67e74705SXin Li 
1042*67e74705SXin Li   // This handles complex/complex, complex/float, or float/complex.
1043*67e74705SXin Li   // When both operands are complex, the shorter operand is converted to the
1044*67e74705SXin Li   // type of the longer, and that is the type of the result. This corresponds
1045*67e74705SXin Li   // to what is done when combining two real floating-point operands.
1046*67e74705SXin Li   // The fun begins when size promotion occur across type domains.
1047*67e74705SXin Li   // From H&S 6.3.4: When one operand is complex and the other is a real
1048*67e74705SXin Li   // floating-point type, the less precise type is converted, within it's
1049*67e74705SXin Li   // real or complex domain, to the precision of the other type. For example,
1050*67e74705SXin Li   // when combining a "long double" with a "double _Complex", the
1051*67e74705SXin Li   // "double _Complex" is promoted to "long double _Complex".
1052*67e74705SXin Li 
1053*67e74705SXin Li   // Compute the rank of the two types, regardless of whether they are complex.
1054*67e74705SXin Li   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1055*67e74705SXin Li 
1056*67e74705SXin Li   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1057*67e74705SXin Li   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1058*67e74705SXin Li   QualType LHSElementType =
1059*67e74705SXin Li       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1060*67e74705SXin Li   QualType RHSElementType =
1061*67e74705SXin Li       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1062*67e74705SXin Li 
1063*67e74705SXin Li   QualType ResultType = S.Context.getComplexType(LHSElementType);
1064*67e74705SXin Li   if (Order < 0) {
1065*67e74705SXin Li     // Promote the precision of the LHS if not an assignment.
1066*67e74705SXin Li     ResultType = S.Context.getComplexType(RHSElementType);
1067*67e74705SXin Li     if (!IsCompAssign) {
1068*67e74705SXin Li       if (LHSComplexType)
1069*67e74705SXin Li         LHS =
1070*67e74705SXin Li             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1071*67e74705SXin Li       else
1072*67e74705SXin Li         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1073*67e74705SXin Li     }
1074*67e74705SXin Li   } else if (Order > 0) {
1075*67e74705SXin Li     // Promote the precision of the RHS.
1076*67e74705SXin Li     if (RHSComplexType)
1077*67e74705SXin Li       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1078*67e74705SXin Li     else
1079*67e74705SXin Li       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1080*67e74705SXin Li   }
1081*67e74705SXin Li   return ResultType;
1082*67e74705SXin Li }
1083*67e74705SXin Li 
1084*67e74705SXin Li /// \brief Hande arithmetic conversion from integer to float.  Helper function
1085*67e74705SXin Li /// of UsualArithmeticConversions()
handleIntToFloatConversion(Sema & S,ExprResult & FloatExpr,ExprResult & IntExpr,QualType FloatTy,QualType IntTy,bool ConvertFloat,bool ConvertInt)1086*67e74705SXin Li static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1087*67e74705SXin Li                                            ExprResult &IntExpr,
1088*67e74705SXin Li                                            QualType FloatTy, QualType IntTy,
1089*67e74705SXin Li                                            bool ConvertFloat, bool ConvertInt) {
1090*67e74705SXin Li   if (IntTy->isIntegerType()) {
1091*67e74705SXin Li     if (ConvertInt)
1092*67e74705SXin Li       // Convert intExpr to the lhs floating point type.
1093*67e74705SXin Li       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1094*67e74705SXin Li                                     CK_IntegralToFloating);
1095*67e74705SXin Li     return FloatTy;
1096*67e74705SXin Li   }
1097*67e74705SXin Li 
1098*67e74705SXin Li   // Convert both sides to the appropriate complex float.
1099*67e74705SXin Li   assert(IntTy->isComplexIntegerType());
1100*67e74705SXin Li   QualType result = S.Context.getComplexType(FloatTy);
1101*67e74705SXin Li 
1102*67e74705SXin Li   // _Complex int -> _Complex float
1103*67e74705SXin Li   if (ConvertInt)
1104*67e74705SXin Li     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1105*67e74705SXin Li                                   CK_IntegralComplexToFloatingComplex);
1106*67e74705SXin Li 
1107*67e74705SXin Li   // float -> _Complex float
1108*67e74705SXin Li   if (ConvertFloat)
1109*67e74705SXin Li     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1110*67e74705SXin Li                                     CK_FloatingRealToComplex);
1111*67e74705SXin Li 
1112*67e74705SXin Li   return result;
1113*67e74705SXin Li }
1114*67e74705SXin Li 
1115*67e74705SXin Li /// \brief Handle arithmethic conversion with floating point types.  Helper
1116*67e74705SXin Li /// function of UsualArithmeticConversions()
handleFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1117*67e74705SXin Li static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1118*67e74705SXin Li                                       ExprResult &RHS, QualType LHSType,
1119*67e74705SXin Li                                       QualType RHSType, bool IsCompAssign) {
1120*67e74705SXin Li   bool LHSFloat = LHSType->isRealFloatingType();
1121*67e74705SXin Li   bool RHSFloat = RHSType->isRealFloatingType();
1122*67e74705SXin Li 
1123*67e74705SXin Li   // If we have two real floating types, convert the smaller operand
1124*67e74705SXin Li   // to the bigger result.
1125*67e74705SXin Li   if (LHSFloat && RHSFloat) {
1126*67e74705SXin Li     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1127*67e74705SXin Li     if (order > 0) {
1128*67e74705SXin Li       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1129*67e74705SXin Li       return LHSType;
1130*67e74705SXin Li     }
1131*67e74705SXin Li 
1132*67e74705SXin Li     assert(order < 0 && "illegal float comparison");
1133*67e74705SXin Li     if (!IsCompAssign)
1134*67e74705SXin Li       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1135*67e74705SXin Li     return RHSType;
1136*67e74705SXin Li   }
1137*67e74705SXin Li 
1138*67e74705SXin Li   if (LHSFloat) {
1139*67e74705SXin Li     // Half FP has to be promoted to float unless it is natively supported
1140*67e74705SXin Li     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1141*67e74705SXin Li       LHSType = S.Context.FloatTy;
1142*67e74705SXin Li 
1143*67e74705SXin Li     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1144*67e74705SXin Li                                       /*convertFloat=*/!IsCompAssign,
1145*67e74705SXin Li                                       /*convertInt=*/ true);
1146*67e74705SXin Li   }
1147*67e74705SXin Li   assert(RHSFloat);
1148*67e74705SXin Li   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1149*67e74705SXin Li                                     /*convertInt=*/ true,
1150*67e74705SXin Li                                     /*convertFloat=*/!IsCompAssign);
1151*67e74705SXin Li }
1152*67e74705SXin Li 
1153*67e74705SXin Li /// \brief Diagnose attempts to convert between __float128 and long double if
1154*67e74705SXin Li /// there is no support for such conversion. Helper function of
1155*67e74705SXin Li /// UsualArithmeticConversions().
unsupportedTypeConversion(const Sema & S,QualType LHSType,QualType RHSType)1156*67e74705SXin Li static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1157*67e74705SXin Li                                       QualType RHSType) {
1158*67e74705SXin Li   /*  No issue converting if at least one of the types is not a floating point
1159*67e74705SXin Li       type or the two types have the same rank.
1160*67e74705SXin Li   */
1161*67e74705SXin Li   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1162*67e74705SXin Li       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1163*67e74705SXin Li     return false;
1164*67e74705SXin Li 
1165*67e74705SXin Li   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1166*67e74705SXin Li          "The remaining types must be floating point types.");
1167*67e74705SXin Li 
1168*67e74705SXin Li   auto *LHSComplex = LHSType->getAs<ComplexType>();
1169*67e74705SXin Li   auto *RHSComplex = RHSType->getAs<ComplexType>();
1170*67e74705SXin Li 
1171*67e74705SXin Li   QualType LHSElemType = LHSComplex ?
1172*67e74705SXin Li     LHSComplex->getElementType() : LHSType;
1173*67e74705SXin Li   QualType RHSElemType = RHSComplex ?
1174*67e74705SXin Li     RHSComplex->getElementType() : RHSType;
1175*67e74705SXin Li 
1176*67e74705SXin Li   // No issue if the two types have the same representation
1177*67e74705SXin Li   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1178*67e74705SXin Li       &S.Context.getFloatTypeSemantics(RHSElemType))
1179*67e74705SXin Li     return false;
1180*67e74705SXin Li 
1181*67e74705SXin Li   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1182*67e74705SXin Li                                 RHSElemType == S.Context.LongDoubleTy);
1183*67e74705SXin Li   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1184*67e74705SXin Li                             RHSElemType == S.Context.Float128Ty);
1185*67e74705SXin Li 
1186*67e74705SXin Li   /* We've handled the situation where __float128 and long double have the same
1187*67e74705SXin Li      representation. The only other allowable conversion is if long double is
1188*67e74705SXin Li      really just double.
1189*67e74705SXin Li   */
1190*67e74705SXin Li   return Float128AndLongDouble &&
1191*67e74705SXin Li     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1192*67e74705SXin Li      &llvm::APFloat::IEEEdouble);
1193*67e74705SXin Li }
1194*67e74705SXin Li 
1195*67e74705SXin Li typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1196*67e74705SXin Li 
1197*67e74705SXin Li namespace {
1198*67e74705SXin Li /// These helper callbacks are placed in an anonymous namespace to
1199*67e74705SXin Li /// permit their use as function template parameters.
doIntegralCast(Sema & S,Expr * op,QualType toType)1200*67e74705SXin Li ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1201*67e74705SXin Li   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1202*67e74705SXin Li }
1203*67e74705SXin Li 
doComplexIntegralCast(Sema & S,Expr * op,QualType toType)1204*67e74705SXin Li ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1205*67e74705SXin Li   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1206*67e74705SXin Li                              CK_IntegralComplexCast);
1207*67e74705SXin Li }
1208*67e74705SXin Li }
1209*67e74705SXin Li 
1210*67e74705SXin Li /// \brief Handle integer arithmetic conversions.  Helper function of
1211*67e74705SXin Li /// UsualArithmeticConversions()
1212*67e74705SXin Li template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
handleIntegerConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1213*67e74705SXin Li static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1214*67e74705SXin Li                                         ExprResult &RHS, QualType LHSType,
1215*67e74705SXin Li                                         QualType RHSType, bool IsCompAssign) {
1216*67e74705SXin Li   // The rules for this case are in C99 6.3.1.8
1217*67e74705SXin Li   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1218*67e74705SXin Li   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1219*67e74705SXin Li   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1220*67e74705SXin Li   if (LHSSigned == RHSSigned) {
1221*67e74705SXin Li     // Same signedness; use the higher-ranked type
1222*67e74705SXin Li     if (order >= 0) {
1223*67e74705SXin Li       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1224*67e74705SXin Li       return LHSType;
1225*67e74705SXin Li     } else if (!IsCompAssign)
1226*67e74705SXin Li       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1227*67e74705SXin Li     return RHSType;
1228*67e74705SXin Li   } else if (order != (LHSSigned ? 1 : -1)) {
1229*67e74705SXin Li     // The unsigned type has greater than or equal rank to the
1230*67e74705SXin Li     // signed type, so use the unsigned type
1231*67e74705SXin Li     if (RHSSigned) {
1232*67e74705SXin Li       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1233*67e74705SXin Li       return LHSType;
1234*67e74705SXin Li     } else if (!IsCompAssign)
1235*67e74705SXin Li       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1236*67e74705SXin Li     return RHSType;
1237*67e74705SXin Li   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1238*67e74705SXin Li     // The two types are different widths; if we are here, that
1239*67e74705SXin Li     // means the signed type is larger than the unsigned type, so
1240*67e74705SXin Li     // use the signed type.
1241*67e74705SXin Li     if (LHSSigned) {
1242*67e74705SXin Li       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1243*67e74705SXin Li       return LHSType;
1244*67e74705SXin Li     } else if (!IsCompAssign)
1245*67e74705SXin Li       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1246*67e74705SXin Li     return RHSType;
1247*67e74705SXin Li   } else {
1248*67e74705SXin Li     // The signed type is higher-ranked than the unsigned type,
1249*67e74705SXin Li     // but isn't actually any bigger (like unsigned int and long
1250*67e74705SXin Li     // on most 32-bit systems).  Use the unsigned type corresponding
1251*67e74705SXin Li     // to the signed type.
1252*67e74705SXin Li     QualType result =
1253*67e74705SXin Li       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1254*67e74705SXin Li     RHS = (*doRHSCast)(S, RHS.get(), result);
1255*67e74705SXin Li     if (!IsCompAssign)
1256*67e74705SXin Li       LHS = (*doLHSCast)(S, LHS.get(), result);
1257*67e74705SXin Li     return result;
1258*67e74705SXin Li   }
1259*67e74705SXin Li }
1260*67e74705SXin Li 
1261*67e74705SXin Li /// \brief Handle conversions with GCC complex int extension.  Helper function
1262*67e74705SXin Li /// of UsualArithmeticConversions()
handleComplexIntConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1263*67e74705SXin Li static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1264*67e74705SXin Li                                            ExprResult &RHS, QualType LHSType,
1265*67e74705SXin Li                                            QualType RHSType,
1266*67e74705SXin Li                                            bool IsCompAssign) {
1267*67e74705SXin Li   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1268*67e74705SXin Li   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1269*67e74705SXin Li 
1270*67e74705SXin Li   if (LHSComplexInt && RHSComplexInt) {
1271*67e74705SXin Li     QualType LHSEltType = LHSComplexInt->getElementType();
1272*67e74705SXin Li     QualType RHSEltType = RHSComplexInt->getElementType();
1273*67e74705SXin Li     QualType ScalarType =
1274*67e74705SXin Li       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1275*67e74705SXin Li         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1276*67e74705SXin Li 
1277*67e74705SXin Li     return S.Context.getComplexType(ScalarType);
1278*67e74705SXin Li   }
1279*67e74705SXin Li 
1280*67e74705SXin Li   if (LHSComplexInt) {
1281*67e74705SXin Li     QualType LHSEltType = LHSComplexInt->getElementType();
1282*67e74705SXin Li     QualType ScalarType =
1283*67e74705SXin Li       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1284*67e74705SXin Li         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1285*67e74705SXin Li     QualType ComplexType = S.Context.getComplexType(ScalarType);
1286*67e74705SXin Li     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1287*67e74705SXin Li                               CK_IntegralRealToComplex);
1288*67e74705SXin Li 
1289*67e74705SXin Li     return ComplexType;
1290*67e74705SXin Li   }
1291*67e74705SXin Li 
1292*67e74705SXin Li   assert(RHSComplexInt);
1293*67e74705SXin Li 
1294*67e74705SXin Li   QualType RHSEltType = RHSComplexInt->getElementType();
1295*67e74705SXin Li   QualType ScalarType =
1296*67e74705SXin Li     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1297*67e74705SXin Li       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1298*67e74705SXin Li   QualType ComplexType = S.Context.getComplexType(ScalarType);
1299*67e74705SXin Li 
1300*67e74705SXin Li   if (!IsCompAssign)
1301*67e74705SXin Li     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1302*67e74705SXin Li                               CK_IntegralRealToComplex);
1303*67e74705SXin Li   return ComplexType;
1304*67e74705SXin Li }
1305*67e74705SXin Li 
1306*67e74705SXin Li /// UsualArithmeticConversions - Performs various conversions that are common to
1307*67e74705SXin Li /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1308*67e74705SXin Li /// routine returns the first non-arithmetic type found. The client is
1309*67e74705SXin Li /// responsible for emitting appropriate error diagnostics.
UsualArithmeticConversions(ExprResult & LHS,ExprResult & RHS,bool IsCompAssign)1310*67e74705SXin Li QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1311*67e74705SXin Li                                           bool IsCompAssign) {
1312*67e74705SXin Li   if (!IsCompAssign) {
1313*67e74705SXin Li     LHS = UsualUnaryConversions(LHS.get());
1314*67e74705SXin Li     if (LHS.isInvalid())
1315*67e74705SXin Li       return QualType();
1316*67e74705SXin Li   }
1317*67e74705SXin Li 
1318*67e74705SXin Li   RHS = UsualUnaryConversions(RHS.get());
1319*67e74705SXin Li   if (RHS.isInvalid())
1320*67e74705SXin Li     return QualType();
1321*67e74705SXin Li 
1322*67e74705SXin Li   // For conversion purposes, we ignore any qualifiers.
1323*67e74705SXin Li   // For example, "const float" and "float" are equivalent.
1324*67e74705SXin Li   QualType LHSType =
1325*67e74705SXin Li     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1326*67e74705SXin Li   QualType RHSType =
1327*67e74705SXin Li     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1328*67e74705SXin Li 
1329*67e74705SXin Li   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1330*67e74705SXin Li   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1331*67e74705SXin Li     LHSType = AtomicLHS->getValueType();
1332*67e74705SXin Li 
1333*67e74705SXin Li   // If both types are identical, no conversion is needed.
1334*67e74705SXin Li   if (LHSType == RHSType)
1335*67e74705SXin Li     return LHSType;
1336*67e74705SXin Li 
1337*67e74705SXin Li   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1338*67e74705SXin Li   // The caller can deal with this (e.g. pointer + int).
1339*67e74705SXin Li   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1340*67e74705SXin Li     return QualType();
1341*67e74705SXin Li 
1342*67e74705SXin Li   // Apply unary and bitfield promotions to the LHS's type.
1343*67e74705SXin Li   QualType LHSUnpromotedType = LHSType;
1344*67e74705SXin Li   if (LHSType->isPromotableIntegerType())
1345*67e74705SXin Li     LHSType = Context.getPromotedIntegerType(LHSType);
1346*67e74705SXin Li   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1347*67e74705SXin Li   if (!LHSBitfieldPromoteTy.isNull())
1348*67e74705SXin Li     LHSType = LHSBitfieldPromoteTy;
1349*67e74705SXin Li   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1350*67e74705SXin Li     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1351*67e74705SXin Li 
1352*67e74705SXin Li   // If both types are identical, no conversion is needed.
1353*67e74705SXin Li   if (LHSType == RHSType)
1354*67e74705SXin Li     return LHSType;
1355*67e74705SXin Li 
1356*67e74705SXin Li   // At this point, we have two different arithmetic types.
1357*67e74705SXin Li 
1358*67e74705SXin Li   // Diagnose attempts to convert between __float128 and long double where
1359*67e74705SXin Li   // such conversions currently can't be handled.
1360*67e74705SXin Li   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1361*67e74705SXin Li     return QualType();
1362*67e74705SXin Li 
1363*67e74705SXin Li   // Handle complex types first (C99 6.3.1.8p1).
1364*67e74705SXin Li   if (LHSType->isComplexType() || RHSType->isComplexType())
1365*67e74705SXin Li     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1366*67e74705SXin Li                                         IsCompAssign);
1367*67e74705SXin Li 
1368*67e74705SXin Li   // Now handle "real" floating types (i.e. float, double, long double).
1369*67e74705SXin Li   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1370*67e74705SXin Li     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1371*67e74705SXin Li                                  IsCompAssign);
1372*67e74705SXin Li 
1373*67e74705SXin Li   // Handle GCC complex int extension.
1374*67e74705SXin Li   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1375*67e74705SXin Li     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1376*67e74705SXin Li                                       IsCompAssign);
1377*67e74705SXin Li 
1378*67e74705SXin Li   // Finally, we have two differing integer types.
1379*67e74705SXin Li   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1380*67e74705SXin Li            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1381*67e74705SXin Li }
1382*67e74705SXin Li 
1383*67e74705SXin Li 
1384*67e74705SXin Li //===----------------------------------------------------------------------===//
1385*67e74705SXin Li //  Semantic Analysis for various Expression Types
1386*67e74705SXin Li //===----------------------------------------------------------------------===//
1387*67e74705SXin Li 
1388*67e74705SXin Li 
1389*67e74705SXin Li ExprResult
ActOnGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<ParsedType> ArgTypes,ArrayRef<Expr * > ArgExprs)1390*67e74705SXin Li Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1391*67e74705SXin Li                                 SourceLocation DefaultLoc,
1392*67e74705SXin Li                                 SourceLocation RParenLoc,
1393*67e74705SXin Li                                 Expr *ControllingExpr,
1394*67e74705SXin Li                                 ArrayRef<ParsedType> ArgTypes,
1395*67e74705SXin Li                                 ArrayRef<Expr *> ArgExprs) {
1396*67e74705SXin Li   unsigned NumAssocs = ArgTypes.size();
1397*67e74705SXin Li   assert(NumAssocs == ArgExprs.size());
1398*67e74705SXin Li 
1399*67e74705SXin Li   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1400*67e74705SXin Li   for (unsigned i = 0; i < NumAssocs; ++i) {
1401*67e74705SXin Li     if (ArgTypes[i])
1402*67e74705SXin Li       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1403*67e74705SXin Li     else
1404*67e74705SXin Li       Types[i] = nullptr;
1405*67e74705SXin Li   }
1406*67e74705SXin Li 
1407*67e74705SXin Li   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1408*67e74705SXin Li                                              ControllingExpr,
1409*67e74705SXin Li                                              llvm::makeArrayRef(Types, NumAssocs),
1410*67e74705SXin Li                                              ArgExprs);
1411*67e74705SXin Li   delete [] Types;
1412*67e74705SXin Li   return ER;
1413*67e74705SXin Li }
1414*67e74705SXin Li 
1415*67e74705SXin Li ExprResult
CreateGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > Types,ArrayRef<Expr * > Exprs)1416*67e74705SXin Li Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1417*67e74705SXin Li                                  SourceLocation DefaultLoc,
1418*67e74705SXin Li                                  SourceLocation RParenLoc,
1419*67e74705SXin Li                                  Expr *ControllingExpr,
1420*67e74705SXin Li                                  ArrayRef<TypeSourceInfo *> Types,
1421*67e74705SXin Li                                  ArrayRef<Expr *> Exprs) {
1422*67e74705SXin Li   unsigned NumAssocs = Types.size();
1423*67e74705SXin Li   assert(NumAssocs == Exprs.size());
1424*67e74705SXin Li 
1425*67e74705SXin Li   // Decay and strip qualifiers for the controlling expression type, and handle
1426*67e74705SXin Li   // placeholder type replacement. See committee discussion from WG14 DR423.
1427*67e74705SXin Li   {
1428*67e74705SXin Li     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1429*67e74705SXin Li     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1430*67e74705SXin Li     if (R.isInvalid())
1431*67e74705SXin Li       return ExprError();
1432*67e74705SXin Li     ControllingExpr = R.get();
1433*67e74705SXin Li   }
1434*67e74705SXin Li 
1435*67e74705SXin Li   // The controlling expression is an unevaluated operand, so side effects are
1436*67e74705SXin Li   // likely unintended.
1437*67e74705SXin Li   if (ActiveTemplateInstantiations.empty() &&
1438*67e74705SXin Li       ControllingExpr->HasSideEffects(Context, false))
1439*67e74705SXin Li     Diag(ControllingExpr->getExprLoc(),
1440*67e74705SXin Li          diag::warn_side_effects_unevaluated_context);
1441*67e74705SXin Li 
1442*67e74705SXin Li   bool TypeErrorFound = false,
1443*67e74705SXin Li        IsResultDependent = ControllingExpr->isTypeDependent(),
1444*67e74705SXin Li        ContainsUnexpandedParameterPack
1445*67e74705SXin Li          = ControllingExpr->containsUnexpandedParameterPack();
1446*67e74705SXin Li 
1447*67e74705SXin Li   for (unsigned i = 0; i < NumAssocs; ++i) {
1448*67e74705SXin Li     if (Exprs[i]->containsUnexpandedParameterPack())
1449*67e74705SXin Li       ContainsUnexpandedParameterPack = true;
1450*67e74705SXin Li 
1451*67e74705SXin Li     if (Types[i]) {
1452*67e74705SXin Li       if (Types[i]->getType()->containsUnexpandedParameterPack())
1453*67e74705SXin Li         ContainsUnexpandedParameterPack = true;
1454*67e74705SXin Li 
1455*67e74705SXin Li       if (Types[i]->getType()->isDependentType()) {
1456*67e74705SXin Li         IsResultDependent = true;
1457*67e74705SXin Li       } else {
1458*67e74705SXin Li         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1459*67e74705SXin Li         // complete object type other than a variably modified type."
1460*67e74705SXin Li         unsigned D = 0;
1461*67e74705SXin Li         if (Types[i]->getType()->isIncompleteType())
1462*67e74705SXin Li           D = diag::err_assoc_type_incomplete;
1463*67e74705SXin Li         else if (!Types[i]->getType()->isObjectType())
1464*67e74705SXin Li           D = diag::err_assoc_type_nonobject;
1465*67e74705SXin Li         else if (Types[i]->getType()->isVariablyModifiedType())
1466*67e74705SXin Li           D = diag::err_assoc_type_variably_modified;
1467*67e74705SXin Li 
1468*67e74705SXin Li         if (D != 0) {
1469*67e74705SXin Li           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1470*67e74705SXin Li             << Types[i]->getTypeLoc().getSourceRange()
1471*67e74705SXin Li             << Types[i]->getType();
1472*67e74705SXin Li           TypeErrorFound = true;
1473*67e74705SXin Li         }
1474*67e74705SXin Li 
1475*67e74705SXin Li         // C11 6.5.1.1p2 "No two generic associations in the same generic
1476*67e74705SXin Li         // selection shall specify compatible types."
1477*67e74705SXin Li         for (unsigned j = i+1; j < NumAssocs; ++j)
1478*67e74705SXin Li           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1479*67e74705SXin Li               Context.typesAreCompatible(Types[i]->getType(),
1480*67e74705SXin Li                                          Types[j]->getType())) {
1481*67e74705SXin Li             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1482*67e74705SXin Li                  diag::err_assoc_compatible_types)
1483*67e74705SXin Li               << Types[j]->getTypeLoc().getSourceRange()
1484*67e74705SXin Li               << Types[j]->getType()
1485*67e74705SXin Li               << Types[i]->getType();
1486*67e74705SXin Li             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1487*67e74705SXin Li                  diag::note_compat_assoc)
1488*67e74705SXin Li               << Types[i]->getTypeLoc().getSourceRange()
1489*67e74705SXin Li               << Types[i]->getType();
1490*67e74705SXin Li             TypeErrorFound = true;
1491*67e74705SXin Li           }
1492*67e74705SXin Li       }
1493*67e74705SXin Li     }
1494*67e74705SXin Li   }
1495*67e74705SXin Li   if (TypeErrorFound)
1496*67e74705SXin Li     return ExprError();
1497*67e74705SXin Li 
1498*67e74705SXin Li   // If we determined that the generic selection is result-dependent, don't
1499*67e74705SXin Li   // try to compute the result expression.
1500*67e74705SXin Li   if (IsResultDependent)
1501*67e74705SXin Li     return new (Context) GenericSelectionExpr(
1502*67e74705SXin Li         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1503*67e74705SXin Li         ContainsUnexpandedParameterPack);
1504*67e74705SXin Li 
1505*67e74705SXin Li   SmallVector<unsigned, 1> CompatIndices;
1506*67e74705SXin Li   unsigned DefaultIndex = -1U;
1507*67e74705SXin Li   for (unsigned i = 0; i < NumAssocs; ++i) {
1508*67e74705SXin Li     if (!Types[i])
1509*67e74705SXin Li       DefaultIndex = i;
1510*67e74705SXin Li     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1511*67e74705SXin Li                                         Types[i]->getType()))
1512*67e74705SXin Li       CompatIndices.push_back(i);
1513*67e74705SXin Li   }
1514*67e74705SXin Li 
1515*67e74705SXin Li   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1516*67e74705SXin Li   // type compatible with at most one of the types named in its generic
1517*67e74705SXin Li   // association list."
1518*67e74705SXin Li   if (CompatIndices.size() > 1) {
1519*67e74705SXin Li     // We strip parens here because the controlling expression is typically
1520*67e74705SXin Li     // parenthesized in macro definitions.
1521*67e74705SXin Li     ControllingExpr = ControllingExpr->IgnoreParens();
1522*67e74705SXin Li     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1523*67e74705SXin Li       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1524*67e74705SXin Li       << (unsigned) CompatIndices.size();
1525*67e74705SXin Li     for (unsigned I : CompatIndices) {
1526*67e74705SXin Li       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1527*67e74705SXin Li            diag::note_compat_assoc)
1528*67e74705SXin Li         << Types[I]->getTypeLoc().getSourceRange()
1529*67e74705SXin Li         << Types[I]->getType();
1530*67e74705SXin Li     }
1531*67e74705SXin Li     return ExprError();
1532*67e74705SXin Li   }
1533*67e74705SXin Li 
1534*67e74705SXin Li   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1535*67e74705SXin Li   // its controlling expression shall have type compatible with exactly one of
1536*67e74705SXin Li   // the types named in its generic association list."
1537*67e74705SXin Li   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1538*67e74705SXin Li     // We strip parens here because the controlling expression is typically
1539*67e74705SXin Li     // parenthesized in macro definitions.
1540*67e74705SXin Li     ControllingExpr = ControllingExpr->IgnoreParens();
1541*67e74705SXin Li     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1542*67e74705SXin Li       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1543*67e74705SXin Li     return ExprError();
1544*67e74705SXin Li   }
1545*67e74705SXin Li 
1546*67e74705SXin Li   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1547*67e74705SXin Li   // type name that is compatible with the type of the controlling expression,
1548*67e74705SXin Li   // then the result expression of the generic selection is the expression
1549*67e74705SXin Li   // in that generic association. Otherwise, the result expression of the
1550*67e74705SXin Li   // generic selection is the expression in the default generic association."
1551*67e74705SXin Li   unsigned ResultIndex =
1552*67e74705SXin Li     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1553*67e74705SXin Li 
1554*67e74705SXin Li   return new (Context) GenericSelectionExpr(
1555*67e74705SXin Li       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1556*67e74705SXin Li       ContainsUnexpandedParameterPack, ResultIndex);
1557*67e74705SXin Li }
1558*67e74705SXin Li 
1559*67e74705SXin Li /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1560*67e74705SXin Li /// location of the token and the offset of the ud-suffix within it.
getUDSuffixLoc(Sema & S,SourceLocation TokLoc,unsigned Offset)1561*67e74705SXin Li static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1562*67e74705SXin Li                                      unsigned Offset) {
1563*67e74705SXin Li   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1564*67e74705SXin Li                                         S.getLangOpts());
1565*67e74705SXin Li }
1566*67e74705SXin Li 
1567*67e74705SXin Li /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1568*67e74705SXin Li /// the corresponding cooked (non-raw) literal operator, and build a call to it.
BuildCookedLiteralOperatorCall(Sema & S,Scope * Scope,IdentifierInfo * UDSuffix,SourceLocation UDSuffixLoc,ArrayRef<Expr * > Args,SourceLocation LitEndLoc)1569*67e74705SXin Li static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1570*67e74705SXin Li                                                  IdentifierInfo *UDSuffix,
1571*67e74705SXin Li                                                  SourceLocation UDSuffixLoc,
1572*67e74705SXin Li                                                  ArrayRef<Expr*> Args,
1573*67e74705SXin Li                                                  SourceLocation LitEndLoc) {
1574*67e74705SXin Li   assert(Args.size() <= 2 && "too many arguments for literal operator");
1575*67e74705SXin Li 
1576*67e74705SXin Li   QualType ArgTy[2];
1577*67e74705SXin Li   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1578*67e74705SXin Li     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1579*67e74705SXin Li     if (ArgTy[ArgIdx]->isArrayType())
1580*67e74705SXin Li       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1581*67e74705SXin Li   }
1582*67e74705SXin Li 
1583*67e74705SXin Li   DeclarationName OpName =
1584*67e74705SXin Li     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1585*67e74705SXin Li   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1586*67e74705SXin Li   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1587*67e74705SXin Li 
1588*67e74705SXin Li   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1589*67e74705SXin Li   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1590*67e74705SXin Li                               /*AllowRaw*/false, /*AllowTemplate*/false,
1591*67e74705SXin Li                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1592*67e74705SXin Li     return ExprError();
1593*67e74705SXin Li 
1594*67e74705SXin Li   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1595*67e74705SXin Li }
1596*67e74705SXin Li 
1597*67e74705SXin Li /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1598*67e74705SXin Li /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1599*67e74705SXin Li /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1600*67e74705SXin Li /// multiple tokens.  However, the common case is that StringToks points to one
1601*67e74705SXin Li /// string.
1602*67e74705SXin Li ///
1603*67e74705SXin Li ExprResult
ActOnStringLiteral(ArrayRef<Token> StringToks,Scope * UDLScope)1604*67e74705SXin Li Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1605*67e74705SXin Li   assert(!StringToks.empty() && "Must have at least one string!");
1606*67e74705SXin Li 
1607*67e74705SXin Li   StringLiteralParser Literal(StringToks, PP);
1608*67e74705SXin Li   if (Literal.hadError)
1609*67e74705SXin Li     return ExprError();
1610*67e74705SXin Li 
1611*67e74705SXin Li   SmallVector<SourceLocation, 4> StringTokLocs;
1612*67e74705SXin Li   for (const Token &Tok : StringToks)
1613*67e74705SXin Li     StringTokLocs.push_back(Tok.getLocation());
1614*67e74705SXin Li 
1615*67e74705SXin Li   QualType CharTy = Context.CharTy;
1616*67e74705SXin Li   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1617*67e74705SXin Li   if (Literal.isWide()) {
1618*67e74705SXin Li     CharTy = Context.getWideCharType();
1619*67e74705SXin Li     Kind = StringLiteral::Wide;
1620*67e74705SXin Li   } else if (Literal.isUTF8()) {
1621*67e74705SXin Li     Kind = StringLiteral::UTF8;
1622*67e74705SXin Li   } else if (Literal.isUTF16()) {
1623*67e74705SXin Li     CharTy = Context.Char16Ty;
1624*67e74705SXin Li     Kind = StringLiteral::UTF16;
1625*67e74705SXin Li   } else if (Literal.isUTF32()) {
1626*67e74705SXin Li     CharTy = Context.Char32Ty;
1627*67e74705SXin Li     Kind = StringLiteral::UTF32;
1628*67e74705SXin Li   } else if (Literal.isPascal()) {
1629*67e74705SXin Li     CharTy = Context.UnsignedCharTy;
1630*67e74705SXin Li   }
1631*67e74705SXin Li 
1632*67e74705SXin Li   QualType CharTyConst = CharTy;
1633*67e74705SXin Li   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1634*67e74705SXin Li   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1635*67e74705SXin Li     CharTyConst.addConst();
1636*67e74705SXin Li 
1637*67e74705SXin Li   // Get an array type for the string, according to C99 6.4.5.  This includes
1638*67e74705SXin Li   // the nul terminator character as well as the string length for pascal
1639*67e74705SXin Li   // strings.
1640*67e74705SXin Li   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1641*67e74705SXin Li                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1642*67e74705SXin Li                                  ArrayType::Normal, 0);
1643*67e74705SXin Li 
1644*67e74705SXin Li   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1645*67e74705SXin Li   if (getLangOpts().OpenCL) {
1646*67e74705SXin Li     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1647*67e74705SXin Li   }
1648*67e74705SXin Li 
1649*67e74705SXin Li   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1650*67e74705SXin Li   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1651*67e74705SXin Li                                              Kind, Literal.Pascal, StrTy,
1652*67e74705SXin Li                                              &StringTokLocs[0],
1653*67e74705SXin Li                                              StringTokLocs.size());
1654*67e74705SXin Li   if (Literal.getUDSuffix().empty())
1655*67e74705SXin Li     return Lit;
1656*67e74705SXin Li 
1657*67e74705SXin Li   // We're building a user-defined literal.
1658*67e74705SXin Li   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1659*67e74705SXin Li   SourceLocation UDSuffixLoc =
1660*67e74705SXin Li     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1661*67e74705SXin Li                    Literal.getUDSuffixOffset());
1662*67e74705SXin Li 
1663*67e74705SXin Li   // Make sure we're allowed user-defined literals here.
1664*67e74705SXin Li   if (!UDLScope)
1665*67e74705SXin Li     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1666*67e74705SXin Li 
1667*67e74705SXin Li   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1668*67e74705SXin Li   //   operator "" X (str, len)
1669*67e74705SXin Li   QualType SizeType = Context.getSizeType();
1670*67e74705SXin Li 
1671*67e74705SXin Li   DeclarationName OpName =
1672*67e74705SXin Li     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1673*67e74705SXin Li   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1674*67e74705SXin Li   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1675*67e74705SXin Li 
1676*67e74705SXin Li   QualType ArgTy[] = {
1677*67e74705SXin Li     Context.getArrayDecayedType(StrTy), SizeType
1678*67e74705SXin Li   };
1679*67e74705SXin Li 
1680*67e74705SXin Li   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1681*67e74705SXin Li   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1682*67e74705SXin Li                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1683*67e74705SXin Li                                 /*AllowStringTemplate*/true)) {
1684*67e74705SXin Li 
1685*67e74705SXin Li   case LOLR_Cooked: {
1686*67e74705SXin Li     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1687*67e74705SXin Li     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1688*67e74705SXin Li                                                     StringTokLocs[0]);
1689*67e74705SXin Li     Expr *Args[] = { Lit, LenArg };
1690*67e74705SXin Li 
1691*67e74705SXin Li     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1692*67e74705SXin Li   }
1693*67e74705SXin Li 
1694*67e74705SXin Li   case LOLR_StringTemplate: {
1695*67e74705SXin Li     TemplateArgumentListInfo ExplicitArgs;
1696*67e74705SXin Li 
1697*67e74705SXin Li     unsigned CharBits = Context.getIntWidth(CharTy);
1698*67e74705SXin Li     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1699*67e74705SXin Li     llvm::APSInt Value(CharBits, CharIsUnsigned);
1700*67e74705SXin Li 
1701*67e74705SXin Li     TemplateArgument TypeArg(CharTy);
1702*67e74705SXin Li     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1703*67e74705SXin Li     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1704*67e74705SXin Li 
1705*67e74705SXin Li     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1706*67e74705SXin Li       Value = Lit->getCodeUnit(I);
1707*67e74705SXin Li       TemplateArgument Arg(Context, Value, CharTy);
1708*67e74705SXin Li       TemplateArgumentLocInfo ArgInfo;
1709*67e74705SXin Li       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1710*67e74705SXin Li     }
1711*67e74705SXin Li     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1712*67e74705SXin Li                                     &ExplicitArgs);
1713*67e74705SXin Li   }
1714*67e74705SXin Li   case LOLR_Raw:
1715*67e74705SXin Li   case LOLR_Template:
1716*67e74705SXin Li     llvm_unreachable("unexpected literal operator lookup result");
1717*67e74705SXin Li   case LOLR_Error:
1718*67e74705SXin Li     return ExprError();
1719*67e74705SXin Li   }
1720*67e74705SXin Li   llvm_unreachable("unexpected literal operator lookup result");
1721*67e74705SXin Li }
1722*67e74705SXin Li 
1723*67e74705SXin Li ExprResult
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,SourceLocation Loc,const CXXScopeSpec * SS)1724*67e74705SXin Li Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1725*67e74705SXin Li                        SourceLocation Loc,
1726*67e74705SXin Li                        const CXXScopeSpec *SS) {
1727*67e74705SXin Li   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1728*67e74705SXin Li   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1729*67e74705SXin Li }
1730*67e74705SXin Li 
1731*67e74705SXin Li /// BuildDeclRefExpr - Build an expression that references a
1732*67e74705SXin Li /// declaration that does not require a closure capture.
1733*67e74705SXin Li ExprResult
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,const DeclarationNameInfo & NameInfo,const CXXScopeSpec * SS,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs)1734*67e74705SXin Li Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1735*67e74705SXin Li                        const DeclarationNameInfo &NameInfo,
1736*67e74705SXin Li                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1737*67e74705SXin Li                        const TemplateArgumentListInfo *TemplateArgs) {
1738*67e74705SXin Li   if (getLangOpts().CUDA)
1739*67e74705SXin Li     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1740*67e74705SXin Li       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1741*67e74705SXin Li         if (CheckCUDATarget(Caller, Callee)) {
1742*67e74705SXin Li           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1743*67e74705SXin Li             << IdentifyCUDATarget(Callee) << D->getIdentifier()
1744*67e74705SXin Li             << IdentifyCUDATarget(Caller);
1745*67e74705SXin Li           Diag(D->getLocation(), diag::note_previous_decl)
1746*67e74705SXin Li             << D->getIdentifier();
1747*67e74705SXin Li           return ExprError();
1748*67e74705SXin Li         }
1749*67e74705SXin Li       }
1750*67e74705SXin Li 
1751*67e74705SXin Li   bool RefersToCapturedVariable =
1752*67e74705SXin Li       isa<VarDecl>(D) &&
1753*67e74705SXin Li       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1754*67e74705SXin Li 
1755*67e74705SXin Li   DeclRefExpr *E;
1756*67e74705SXin Li   if (isa<VarTemplateSpecializationDecl>(D)) {
1757*67e74705SXin Li     VarTemplateSpecializationDecl *VarSpec =
1758*67e74705SXin Li         cast<VarTemplateSpecializationDecl>(D);
1759*67e74705SXin Li 
1760*67e74705SXin Li     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1761*67e74705SXin Li                                         : NestedNameSpecifierLoc(),
1762*67e74705SXin Li                             VarSpec->getTemplateKeywordLoc(), D,
1763*67e74705SXin Li                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1764*67e74705SXin Li                             FoundD, TemplateArgs);
1765*67e74705SXin Li   } else {
1766*67e74705SXin Li     assert(!TemplateArgs && "No template arguments for non-variable"
1767*67e74705SXin Li                             " template specialization references");
1768*67e74705SXin Li     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1769*67e74705SXin Li                                         : NestedNameSpecifierLoc(),
1770*67e74705SXin Li                             SourceLocation(), D, RefersToCapturedVariable,
1771*67e74705SXin Li                             NameInfo, Ty, VK, FoundD);
1772*67e74705SXin Li   }
1773*67e74705SXin Li 
1774*67e74705SXin Li   MarkDeclRefReferenced(E);
1775*67e74705SXin Li 
1776*67e74705SXin Li   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1777*67e74705SXin Li       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1778*67e74705SXin Li       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1779*67e74705SXin Li       recordUseOfEvaluatedWeak(E);
1780*67e74705SXin Li 
1781*67e74705SXin Li   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1782*67e74705SXin Li     UnusedPrivateFields.remove(FD);
1783*67e74705SXin Li     // Just in case we're building an illegal pointer-to-member.
1784*67e74705SXin Li     if (FD->isBitField())
1785*67e74705SXin Li       E->setObjectKind(OK_BitField);
1786*67e74705SXin Li   }
1787*67e74705SXin Li 
1788*67e74705SXin Li   return E;
1789*67e74705SXin Li }
1790*67e74705SXin Li 
1791*67e74705SXin Li /// Decomposes the given name into a DeclarationNameInfo, its location, and
1792*67e74705SXin Li /// possibly a list of template arguments.
1793*67e74705SXin Li ///
1794*67e74705SXin Li /// If this produces template arguments, it is permitted to call
1795*67e74705SXin Li /// DecomposeTemplateName.
1796*67e74705SXin Li ///
1797*67e74705SXin Li /// This actually loses a lot of source location information for
1798*67e74705SXin Li /// non-standard name kinds; we should consider preserving that in
1799*67e74705SXin Li /// some way.
1800*67e74705SXin Li void
DecomposeUnqualifiedId(const UnqualifiedId & Id,TemplateArgumentListInfo & Buffer,DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * & TemplateArgs)1801*67e74705SXin Li Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1802*67e74705SXin Li                              TemplateArgumentListInfo &Buffer,
1803*67e74705SXin Li                              DeclarationNameInfo &NameInfo,
1804*67e74705SXin Li                              const TemplateArgumentListInfo *&TemplateArgs) {
1805*67e74705SXin Li   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1806*67e74705SXin Li     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1807*67e74705SXin Li     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1808*67e74705SXin Li 
1809*67e74705SXin Li     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1810*67e74705SXin Li                                        Id.TemplateId->NumArgs);
1811*67e74705SXin Li     translateTemplateArguments(TemplateArgsPtr, Buffer);
1812*67e74705SXin Li 
1813*67e74705SXin Li     TemplateName TName = Id.TemplateId->Template.get();
1814*67e74705SXin Li     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1815*67e74705SXin Li     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1816*67e74705SXin Li     TemplateArgs = &Buffer;
1817*67e74705SXin Li   } else {
1818*67e74705SXin Li     NameInfo = GetNameFromUnqualifiedId(Id);
1819*67e74705SXin Li     TemplateArgs = nullptr;
1820*67e74705SXin Li   }
1821*67e74705SXin Li }
1822*67e74705SXin Li 
emitEmptyLookupTypoDiagnostic(const TypoCorrection & TC,Sema & SemaRef,const CXXScopeSpec & SS,DeclarationName Typo,SourceLocation TypoLoc,ArrayRef<Expr * > Args,unsigned DiagnosticID,unsigned DiagnosticSuggestID)1823*67e74705SXin Li static void emitEmptyLookupTypoDiagnostic(
1824*67e74705SXin Li     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1825*67e74705SXin Li     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1826*67e74705SXin Li     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1827*67e74705SXin Li   DeclContext *Ctx =
1828*67e74705SXin Li       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1829*67e74705SXin Li   if (!TC) {
1830*67e74705SXin Li     // Emit a special diagnostic for failed member lookups.
1831*67e74705SXin Li     // FIXME: computing the declaration context might fail here (?)
1832*67e74705SXin Li     if (Ctx)
1833*67e74705SXin Li       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1834*67e74705SXin Li                                                  << SS.getRange();
1835*67e74705SXin Li     else
1836*67e74705SXin Li       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1837*67e74705SXin Li     return;
1838*67e74705SXin Li   }
1839*67e74705SXin Li 
1840*67e74705SXin Li   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1841*67e74705SXin Li   bool DroppedSpecifier =
1842*67e74705SXin Li       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1843*67e74705SXin Li   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1844*67e74705SXin Li                         ? diag::note_implicit_param_decl
1845*67e74705SXin Li                         : diag::note_previous_decl;
1846*67e74705SXin Li   if (!Ctx)
1847*67e74705SXin Li     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1848*67e74705SXin Li                          SemaRef.PDiag(NoteID));
1849*67e74705SXin Li   else
1850*67e74705SXin Li     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1851*67e74705SXin Li                                  << Typo << Ctx << DroppedSpecifier
1852*67e74705SXin Li                                  << SS.getRange(),
1853*67e74705SXin Li                          SemaRef.PDiag(NoteID));
1854*67e74705SXin Li }
1855*67e74705SXin Li 
1856*67e74705SXin Li /// Diagnose an empty lookup.
1857*67e74705SXin Li ///
1858*67e74705SXin Li /// \return false if new lookup candidates were found
1859*67e74705SXin Li bool
DiagnoseEmptyLookup(Scope * S,CXXScopeSpec & SS,LookupResult & R,std::unique_ptr<CorrectionCandidateCallback> CCC,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,TypoExpr ** Out)1860*67e74705SXin Li Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1861*67e74705SXin Li                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1862*67e74705SXin Li                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1863*67e74705SXin Li                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1864*67e74705SXin Li   DeclarationName Name = R.getLookupName();
1865*67e74705SXin Li 
1866*67e74705SXin Li   unsigned diagnostic = diag::err_undeclared_var_use;
1867*67e74705SXin Li   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1868*67e74705SXin Li   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1869*67e74705SXin Li       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1870*67e74705SXin Li       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1871*67e74705SXin Li     diagnostic = diag::err_undeclared_use;
1872*67e74705SXin Li     diagnostic_suggest = diag::err_undeclared_use_suggest;
1873*67e74705SXin Li   }
1874*67e74705SXin Li 
1875*67e74705SXin Li   // If the original lookup was an unqualified lookup, fake an
1876*67e74705SXin Li   // unqualified lookup.  This is useful when (for example) the
1877*67e74705SXin Li   // original lookup would not have found something because it was a
1878*67e74705SXin Li   // dependent name.
1879*67e74705SXin Li   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1880*67e74705SXin Li   while (DC) {
1881*67e74705SXin Li     if (isa<CXXRecordDecl>(DC)) {
1882*67e74705SXin Li       LookupQualifiedName(R, DC);
1883*67e74705SXin Li 
1884*67e74705SXin Li       if (!R.empty()) {
1885*67e74705SXin Li         // Don't give errors about ambiguities in this lookup.
1886*67e74705SXin Li         R.suppressDiagnostics();
1887*67e74705SXin Li 
1888*67e74705SXin Li         // During a default argument instantiation the CurContext points
1889*67e74705SXin Li         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1890*67e74705SXin Li         // function parameter list, hence add an explicit check.
1891*67e74705SXin Li         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1892*67e74705SXin Li                               ActiveTemplateInstantiations.back().Kind ==
1893*67e74705SXin Li             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1894*67e74705SXin Li         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1895*67e74705SXin Li         bool isInstance = CurMethod &&
1896*67e74705SXin Li                           CurMethod->isInstance() &&
1897*67e74705SXin Li                           DC == CurMethod->getParent() && !isDefaultArgument;
1898*67e74705SXin Li 
1899*67e74705SXin Li         // Give a code modification hint to insert 'this->'.
1900*67e74705SXin Li         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1901*67e74705SXin Li         // Actually quite difficult!
1902*67e74705SXin Li         if (getLangOpts().MSVCCompat)
1903*67e74705SXin Li           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1904*67e74705SXin Li         if (isInstance) {
1905*67e74705SXin Li           Diag(R.getNameLoc(), diagnostic) << Name
1906*67e74705SXin Li             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1907*67e74705SXin Li           CheckCXXThisCapture(R.getNameLoc());
1908*67e74705SXin Li         } else {
1909*67e74705SXin Li           Diag(R.getNameLoc(), diagnostic) << Name;
1910*67e74705SXin Li         }
1911*67e74705SXin Li 
1912*67e74705SXin Li         // Do we really want to note all of these?
1913*67e74705SXin Li         for (NamedDecl *D : R)
1914*67e74705SXin Li           Diag(D->getLocation(), diag::note_dependent_var_use);
1915*67e74705SXin Li 
1916*67e74705SXin Li         // Return true if we are inside a default argument instantiation
1917*67e74705SXin Li         // and the found name refers to an instance member function, otherwise
1918*67e74705SXin Li         // the function calling DiagnoseEmptyLookup will try to create an
1919*67e74705SXin Li         // implicit member call and this is wrong for default argument.
1920*67e74705SXin Li         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1921*67e74705SXin Li           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1922*67e74705SXin Li           return true;
1923*67e74705SXin Li         }
1924*67e74705SXin Li 
1925*67e74705SXin Li         // Tell the callee to try to recover.
1926*67e74705SXin Li         return false;
1927*67e74705SXin Li       }
1928*67e74705SXin Li 
1929*67e74705SXin Li       R.clear();
1930*67e74705SXin Li     }
1931*67e74705SXin Li 
1932*67e74705SXin Li     // In Microsoft mode, if we are performing lookup from within a friend
1933*67e74705SXin Li     // function definition declared at class scope then we must set
1934*67e74705SXin Li     // DC to the lexical parent to be able to search into the parent
1935*67e74705SXin Li     // class.
1936*67e74705SXin Li     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1937*67e74705SXin Li         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1938*67e74705SXin Li         DC->getLexicalParent()->isRecord())
1939*67e74705SXin Li       DC = DC->getLexicalParent();
1940*67e74705SXin Li     else
1941*67e74705SXin Li       DC = DC->getParent();
1942*67e74705SXin Li   }
1943*67e74705SXin Li 
1944*67e74705SXin Li   // We didn't find anything, so try to correct for a typo.
1945*67e74705SXin Li   TypoCorrection Corrected;
1946*67e74705SXin Li   if (S && Out) {
1947*67e74705SXin Li     SourceLocation TypoLoc = R.getNameLoc();
1948*67e74705SXin Li     assert(!ExplicitTemplateArgs &&
1949*67e74705SXin Li            "Diagnosing an empty lookup with explicit template args!");
1950*67e74705SXin Li     *Out = CorrectTypoDelayed(
1951*67e74705SXin Li         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1952*67e74705SXin Li         [=](const TypoCorrection &TC) {
1953*67e74705SXin Li           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1954*67e74705SXin Li                                         diagnostic, diagnostic_suggest);
1955*67e74705SXin Li         },
1956*67e74705SXin Li         nullptr, CTK_ErrorRecovery);
1957*67e74705SXin Li     if (*Out)
1958*67e74705SXin Li       return true;
1959*67e74705SXin Li   } else if (S && (Corrected =
1960*67e74705SXin Li                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1961*67e74705SXin Li                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1962*67e74705SXin Li     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1963*67e74705SXin Li     bool DroppedSpecifier =
1964*67e74705SXin Li         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1965*67e74705SXin Li     R.setLookupName(Corrected.getCorrection());
1966*67e74705SXin Li 
1967*67e74705SXin Li     bool AcceptableWithRecovery = false;
1968*67e74705SXin Li     bool AcceptableWithoutRecovery = false;
1969*67e74705SXin Li     NamedDecl *ND = Corrected.getFoundDecl();
1970*67e74705SXin Li     if (ND) {
1971*67e74705SXin Li       if (Corrected.isOverloaded()) {
1972*67e74705SXin Li         OverloadCandidateSet OCS(R.getNameLoc(),
1973*67e74705SXin Li                                  OverloadCandidateSet::CSK_Normal);
1974*67e74705SXin Li         OverloadCandidateSet::iterator Best;
1975*67e74705SXin Li         for (NamedDecl *CD : Corrected) {
1976*67e74705SXin Li           if (FunctionTemplateDecl *FTD =
1977*67e74705SXin Li                    dyn_cast<FunctionTemplateDecl>(CD))
1978*67e74705SXin Li             AddTemplateOverloadCandidate(
1979*67e74705SXin Li                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1980*67e74705SXin Li                 Args, OCS);
1981*67e74705SXin Li           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1982*67e74705SXin Li             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1983*67e74705SXin Li               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1984*67e74705SXin Li                                    Args, OCS);
1985*67e74705SXin Li         }
1986*67e74705SXin Li         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1987*67e74705SXin Li         case OR_Success:
1988*67e74705SXin Li           ND = Best->FoundDecl;
1989*67e74705SXin Li           Corrected.setCorrectionDecl(ND);
1990*67e74705SXin Li           break;
1991*67e74705SXin Li         default:
1992*67e74705SXin Li           // FIXME: Arbitrarily pick the first declaration for the note.
1993*67e74705SXin Li           Corrected.setCorrectionDecl(ND);
1994*67e74705SXin Li           break;
1995*67e74705SXin Li         }
1996*67e74705SXin Li       }
1997*67e74705SXin Li       R.addDecl(ND);
1998*67e74705SXin Li       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1999*67e74705SXin Li         CXXRecordDecl *Record = nullptr;
2000*67e74705SXin Li         if (Corrected.getCorrectionSpecifier()) {
2001*67e74705SXin Li           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2002*67e74705SXin Li           Record = Ty->getAsCXXRecordDecl();
2003*67e74705SXin Li         }
2004*67e74705SXin Li         if (!Record)
2005*67e74705SXin Li           Record = cast<CXXRecordDecl>(
2006*67e74705SXin Li               ND->getDeclContext()->getRedeclContext());
2007*67e74705SXin Li         R.setNamingClass(Record);
2008*67e74705SXin Li       }
2009*67e74705SXin Li 
2010*67e74705SXin Li       auto *UnderlyingND = ND->getUnderlyingDecl();
2011*67e74705SXin Li       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2012*67e74705SXin Li                                isa<FunctionTemplateDecl>(UnderlyingND);
2013*67e74705SXin Li       // FIXME: If we ended up with a typo for a type name or
2014*67e74705SXin Li       // Objective-C class name, we're in trouble because the parser
2015*67e74705SXin Li       // is in the wrong place to recover. Suggest the typo
2016*67e74705SXin Li       // correction, but don't make it a fix-it since we're not going
2017*67e74705SXin Li       // to recover well anyway.
2018*67e74705SXin Li       AcceptableWithoutRecovery =
2019*67e74705SXin Li           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2020*67e74705SXin Li     } else {
2021*67e74705SXin Li       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2022*67e74705SXin Li       // because we aren't able to recover.
2023*67e74705SXin Li       AcceptableWithoutRecovery = true;
2024*67e74705SXin Li     }
2025*67e74705SXin Li 
2026*67e74705SXin Li     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2027*67e74705SXin Li       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2028*67e74705SXin Li                             ? diag::note_implicit_param_decl
2029*67e74705SXin Li                             : diag::note_previous_decl;
2030*67e74705SXin Li       if (SS.isEmpty())
2031*67e74705SXin Li         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2032*67e74705SXin Li                      PDiag(NoteID), AcceptableWithRecovery);
2033*67e74705SXin Li       else
2034*67e74705SXin Li         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2035*67e74705SXin Li                                   << Name << computeDeclContext(SS, false)
2036*67e74705SXin Li                                   << DroppedSpecifier << SS.getRange(),
2037*67e74705SXin Li                      PDiag(NoteID), AcceptableWithRecovery);
2038*67e74705SXin Li 
2039*67e74705SXin Li       // Tell the callee whether to try to recover.
2040*67e74705SXin Li       return !AcceptableWithRecovery;
2041*67e74705SXin Li     }
2042*67e74705SXin Li   }
2043*67e74705SXin Li   R.clear();
2044*67e74705SXin Li 
2045*67e74705SXin Li   // Emit a special diagnostic for failed member lookups.
2046*67e74705SXin Li   // FIXME: computing the declaration context might fail here (?)
2047*67e74705SXin Li   if (!SS.isEmpty()) {
2048*67e74705SXin Li     Diag(R.getNameLoc(), diag::err_no_member)
2049*67e74705SXin Li       << Name << computeDeclContext(SS, false)
2050*67e74705SXin Li       << SS.getRange();
2051*67e74705SXin Li     return true;
2052*67e74705SXin Li   }
2053*67e74705SXin Li 
2054*67e74705SXin Li   // Give up, we can't recover.
2055*67e74705SXin Li   Diag(R.getNameLoc(), diagnostic) << Name;
2056*67e74705SXin Li   return true;
2057*67e74705SXin Li }
2058*67e74705SXin Li 
2059*67e74705SXin Li /// In Microsoft mode, if we are inside a template class whose parent class has
2060*67e74705SXin Li /// dependent base classes, and we can't resolve an unqualified identifier, then
2061*67e74705SXin Li /// assume the identifier is a member of a dependent base class.  We can only
2062*67e74705SXin Li /// recover successfully in static methods, instance methods, and other contexts
2063*67e74705SXin Li /// where 'this' is available.  This doesn't precisely match MSVC's
2064*67e74705SXin Li /// instantiation model, but it's close enough.
2065*67e74705SXin Li static Expr *
recoverFromMSUnqualifiedLookup(Sema & S,ASTContext & Context,DeclarationNameInfo & NameInfo,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)2066*67e74705SXin Li recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2067*67e74705SXin Li                                DeclarationNameInfo &NameInfo,
2068*67e74705SXin Li                                SourceLocation TemplateKWLoc,
2069*67e74705SXin Li                                const TemplateArgumentListInfo *TemplateArgs) {
2070*67e74705SXin Li   // Only try to recover from lookup into dependent bases in static methods or
2071*67e74705SXin Li   // contexts where 'this' is available.
2072*67e74705SXin Li   QualType ThisType = S.getCurrentThisType();
2073*67e74705SXin Li   const CXXRecordDecl *RD = nullptr;
2074*67e74705SXin Li   if (!ThisType.isNull())
2075*67e74705SXin Li     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2076*67e74705SXin Li   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2077*67e74705SXin Li     RD = MD->getParent();
2078*67e74705SXin Li   if (!RD || !RD->hasAnyDependentBases())
2079*67e74705SXin Li     return nullptr;
2080*67e74705SXin Li 
2081*67e74705SXin Li   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2082*67e74705SXin Li   // is available, suggest inserting 'this->' as a fixit.
2083*67e74705SXin Li   SourceLocation Loc = NameInfo.getLoc();
2084*67e74705SXin Li   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2085*67e74705SXin Li   DB << NameInfo.getName() << RD;
2086*67e74705SXin Li 
2087*67e74705SXin Li   if (!ThisType.isNull()) {
2088*67e74705SXin Li     DB << FixItHint::CreateInsertion(Loc, "this->");
2089*67e74705SXin Li     return CXXDependentScopeMemberExpr::Create(
2090*67e74705SXin Li         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2091*67e74705SXin Li         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2092*67e74705SXin Li         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2093*67e74705SXin Li   }
2094*67e74705SXin Li 
2095*67e74705SXin Li   // Synthesize a fake NNS that points to the derived class.  This will
2096*67e74705SXin Li   // perform name lookup during template instantiation.
2097*67e74705SXin Li   CXXScopeSpec SS;
2098*67e74705SXin Li   auto *NNS =
2099*67e74705SXin Li       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2100*67e74705SXin Li   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2101*67e74705SXin Li   return DependentScopeDeclRefExpr::Create(
2102*67e74705SXin Li       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2103*67e74705SXin Li       TemplateArgs);
2104*67e74705SXin Li }
2105*67e74705SXin Li 
2106*67e74705SXin Li ExprResult
ActOnIdExpression(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Id,bool HasTrailingLParen,bool IsAddressOfOperand,std::unique_ptr<CorrectionCandidateCallback> CCC,bool IsInlineAsmIdentifier,Token * KeywordReplacement)2107*67e74705SXin Li Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2108*67e74705SXin Li                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2109*67e74705SXin Li                         bool HasTrailingLParen, bool IsAddressOfOperand,
2110*67e74705SXin Li                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2111*67e74705SXin Li                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2112*67e74705SXin Li   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2113*67e74705SXin Li          "cannot be direct & operand and have a trailing lparen");
2114*67e74705SXin Li   if (SS.isInvalid())
2115*67e74705SXin Li     return ExprError();
2116*67e74705SXin Li 
2117*67e74705SXin Li   TemplateArgumentListInfo TemplateArgsBuffer;
2118*67e74705SXin Li 
2119*67e74705SXin Li   // Decompose the UnqualifiedId into the following data.
2120*67e74705SXin Li   DeclarationNameInfo NameInfo;
2121*67e74705SXin Li   const TemplateArgumentListInfo *TemplateArgs;
2122*67e74705SXin Li   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2123*67e74705SXin Li 
2124*67e74705SXin Li   DeclarationName Name = NameInfo.getName();
2125*67e74705SXin Li   IdentifierInfo *II = Name.getAsIdentifierInfo();
2126*67e74705SXin Li   SourceLocation NameLoc = NameInfo.getLoc();
2127*67e74705SXin Li 
2128*67e74705SXin Li   // C++ [temp.dep.expr]p3:
2129*67e74705SXin Li   //   An id-expression is type-dependent if it contains:
2130*67e74705SXin Li   //     -- an identifier that was declared with a dependent type,
2131*67e74705SXin Li   //        (note: handled after lookup)
2132*67e74705SXin Li   //     -- a template-id that is dependent,
2133*67e74705SXin Li   //        (note: handled in BuildTemplateIdExpr)
2134*67e74705SXin Li   //     -- a conversion-function-id that specifies a dependent type,
2135*67e74705SXin Li   //     -- a nested-name-specifier that contains a class-name that
2136*67e74705SXin Li   //        names a dependent type.
2137*67e74705SXin Li   // Determine whether this is a member of an unknown specialization;
2138*67e74705SXin Li   // we need to handle these differently.
2139*67e74705SXin Li   bool DependentID = false;
2140*67e74705SXin Li   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2141*67e74705SXin Li       Name.getCXXNameType()->isDependentType()) {
2142*67e74705SXin Li     DependentID = true;
2143*67e74705SXin Li   } else if (SS.isSet()) {
2144*67e74705SXin Li     if (DeclContext *DC = computeDeclContext(SS, false)) {
2145*67e74705SXin Li       if (RequireCompleteDeclContext(SS, DC))
2146*67e74705SXin Li         return ExprError();
2147*67e74705SXin Li     } else {
2148*67e74705SXin Li       DependentID = true;
2149*67e74705SXin Li     }
2150*67e74705SXin Li   }
2151*67e74705SXin Li 
2152*67e74705SXin Li   if (DependentID)
2153*67e74705SXin Li     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2154*67e74705SXin Li                                       IsAddressOfOperand, TemplateArgs);
2155*67e74705SXin Li 
2156*67e74705SXin Li   // Perform the required lookup.
2157*67e74705SXin Li   LookupResult R(*this, NameInfo,
2158*67e74705SXin Li                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2159*67e74705SXin Li                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2160*67e74705SXin Li   if (TemplateArgs) {
2161*67e74705SXin Li     // Lookup the template name again to correctly establish the context in
2162*67e74705SXin Li     // which it was found. This is really unfortunate as we already did the
2163*67e74705SXin Li     // lookup to determine that it was a template name in the first place. If
2164*67e74705SXin Li     // this becomes a performance hit, we can work harder to preserve those
2165*67e74705SXin Li     // results until we get here but it's likely not worth it.
2166*67e74705SXin Li     bool MemberOfUnknownSpecialization;
2167*67e74705SXin Li     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2168*67e74705SXin Li                        MemberOfUnknownSpecialization);
2169*67e74705SXin Li 
2170*67e74705SXin Li     if (MemberOfUnknownSpecialization ||
2171*67e74705SXin Li         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2172*67e74705SXin Li       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2173*67e74705SXin Li                                         IsAddressOfOperand, TemplateArgs);
2174*67e74705SXin Li   } else {
2175*67e74705SXin Li     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2176*67e74705SXin Li     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2177*67e74705SXin Li 
2178*67e74705SXin Li     // If the result might be in a dependent base class, this is a dependent
2179*67e74705SXin Li     // id-expression.
2180*67e74705SXin Li     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2181*67e74705SXin Li       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2182*67e74705SXin Li                                         IsAddressOfOperand, TemplateArgs);
2183*67e74705SXin Li 
2184*67e74705SXin Li     // If this reference is in an Objective-C method, then we need to do
2185*67e74705SXin Li     // some special Objective-C lookup, too.
2186*67e74705SXin Li     if (IvarLookupFollowUp) {
2187*67e74705SXin Li       ExprResult E(LookupInObjCMethod(R, S, II, true));
2188*67e74705SXin Li       if (E.isInvalid())
2189*67e74705SXin Li         return ExprError();
2190*67e74705SXin Li 
2191*67e74705SXin Li       if (Expr *Ex = E.getAs<Expr>())
2192*67e74705SXin Li         return Ex;
2193*67e74705SXin Li     }
2194*67e74705SXin Li   }
2195*67e74705SXin Li 
2196*67e74705SXin Li   if (R.isAmbiguous())
2197*67e74705SXin Li     return ExprError();
2198*67e74705SXin Li 
2199*67e74705SXin Li   // This could be an implicitly declared function reference (legal in C90,
2200*67e74705SXin Li   // extension in C99, forbidden in C++).
2201*67e74705SXin Li   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2202*67e74705SXin Li     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2203*67e74705SXin Li     if (D) R.addDecl(D);
2204*67e74705SXin Li   }
2205*67e74705SXin Li 
2206*67e74705SXin Li   // Determine whether this name might be a candidate for
2207*67e74705SXin Li   // argument-dependent lookup.
2208*67e74705SXin Li   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2209*67e74705SXin Li 
2210*67e74705SXin Li   if (R.empty() && !ADL) {
2211*67e74705SXin Li     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2212*67e74705SXin Li       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2213*67e74705SXin Li                                                    TemplateKWLoc, TemplateArgs))
2214*67e74705SXin Li         return E;
2215*67e74705SXin Li     }
2216*67e74705SXin Li 
2217*67e74705SXin Li     // Don't diagnose an empty lookup for inline assembly.
2218*67e74705SXin Li     if (IsInlineAsmIdentifier)
2219*67e74705SXin Li       return ExprError();
2220*67e74705SXin Li 
2221*67e74705SXin Li     // If this name wasn't predeclared and if this is not a function
2222*67e74705SXin Li     // call, diagnose the problem.
2223*67e74705SXin Li     TypoExpr *TE = nullptr;
2224*67e74705SXin Li     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2225*67e74705SXin Li         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2226*67e74705SXin Li     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2227*67e74705SXin Li     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2228*67e74705SXin Li            "Typo correction callback misconfigured");
2229*67e74705SXin Li     if (CCC) {
2230*67e74705SXin Li       // Make sure the callback knows what the typo being diagnosed is.
2231*67e74705SXin Li       CCC->setTypoName(II);
2232*67e74705SXin Li       if (SS.isValid())
2233*67e74705SXin Li         CCC->setTypoNNS(SS.getScopeRep());
2234*67e74705SXin Li     }
2235*67e74705SXin Li     if (DiagnoseEmptyLookup(S, SS, R,
2236*67e74705SXin Li                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2237*67e74705SXin Li                             nullptr, None, &TE)) {
2238*67e74705SXin Li       if (TE && KeywordReplacement) {
2239*67e74705SXin Li         auto &State = getTypoExprState(TE);
2240*67e74705SXin Li         auto BestTC = State.Consumer->getNextCorrection();
2241*67e74705SXin Li         if (BestTC.isKeyword()) {
2242*67e74705SXin Li           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2243*67e74705SXin Li           if (State.DiagHandler)
2244*67e74705SXin Li             State.DiagHandler(BestTC);
2245*67e74705SXin Li           KeywordReplacement->startToken();
2246*67e74705SXin Li           KeywordReplacement->setKind(II->getTokenID());
2247*67e74705SXin Li           KeywordReplacement->setIdentifierInfo(II);
2248*67e74705SXin Li           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2249*67e74705SXin Li           // Clean up the state associated with the TypoExpr, since it has
2250*67e74705SXin Li           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2251*67e74705SXin Li           clearDelayedTypo(TE);
2252*67e74705SXin Li           // Signal that a correction to a keyword was performed by returning a
2253*67e74705SXin Li           // valid-but-null ExprResult.
2254*67e74705SXin Li           return (Expr*)nullptr;
2255*67e74705SXin Li         }
2256*67e74705SXin Li         State.Consumer->resetCorrectionStream();
2257*67e74705SXin Li       }
2258*67e74705SXin Li       return TE ? TE : ExprError();
2259*67e74705SXin Li     }
2260*67e74705SXin Li 
2261*67e74705SXin Li     assert(!R.empty() &&
2262*67e74705SXin Li            "DiagnoseEmptyLookup returned false but added no results");
2263*67e74705SXin Li 
2264*67e74705SXin Li     // If we found an Objective-C instance variable, let
2265*67e74705SXin Li     // LookupInObjCMethod build the appropriate expression to
2266*67e74705SXin Li     // reference the ivar.
2267*67e74705SXin Li     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2268*67e74705SXin Li       R.clear();
2269*67e74705SXin Li       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2270*67e74705SXin Li       // In a hopelessly buggy code, Objective-C instance variable
2271*67e74705SXin Li       // lookup fails and no expression will be built to reference it.
2272*67e74705SXin Li       if (!E.isInvalid() && !E.get())
2273*67e74705SXin Li         return ExprError();
2274*67e74705SXin Li       return E;
2275*67e74705SXin Li     }
2276*67e74705SXin Li   }
2277*67e74705SXin Li 
2278*67e74705SXin Li   // This is guaranteed from this point on.
2279*67e74705SXin Li   assert(!R.empty() || ADL);
2280*67e74705SXin Li 
2281*67e74705SXin Li   // Check whether this might be a C++ implicit instance member access.
2282*67e74705SXin Li   // C++ [class.mfct.non-static]p3:
2283*67e74705SXin Li   //   When an id-expression that is not part of a class member access
2284*67e74705SXin Li   //   syntax and not used to form a pointer to member is used in the
2285*67e74705SXin Li   //   body of a non-static member function of class X, if name lookup
2286*67e74705SXin Li   //   resolves the name in the id-expression to a non-static non-type
2287*67e74705SXin Li   //   member of some class C, the id-expression is transformed into a
2288*67e74705SXin Li   //   class member access expression using (*this) as the
2289*67e74705SXin Li   //   postfix-expression to the left of the . operator.
2290*67e74705SXin Li   //
2291*67e74705SXin Li   // But we don't actually need to do this for '&' operands if R
2292*67e74705SXin Li   // resolved to a function or overloaded function set, because the
2293*67e74705SXin Li   // expression is ill-formed if it actually works out to be a
2294*67e74705SXin Li   // non-static member function:
2295*67e74705SXin Li   //
2296*67e74705SXin Li   // C++ [expr.ref]p4:
2297*67e74705SXin Li   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2298*67e74705SXin Li   //   [t]he expression can be used only as the left-hand operand of a
2299*67e74705SXin Li   //   member function call.
2300*67e74705SXin Li   //
2301*67e74705SXin Li   // There are other safeguards against such uses, but it's important
2302*67e74705SXin Li   // to get this right here so that we don't end up making a
2303*67e74705SXin Li   // spuriously dependent expression if we're inside a dependent
2304*67e74705SXin Li   // instance method.
2305*67e74705SXin Li   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2306*67e74705SXin Li     bool MightBeImplicitMember;
2307*67e74705SXin Li     if (!IsAddressOfOperand)
2308*67e74705SXin Li       MightBeImplicitMember = true;
2309*67e74705SXin Li     else if (!SS.isEmpty())
2310*67e74705SXin Li       MightBeImplicitMember = false;
2311*67e74705SXin Li     else if (R.isOverloadedResult())
2312*67e74705SXin Li       MightBeImplicitMember = false;
2313*67e74705SXin Li     else if (R.isUnresolvableResult())
2314*67e74705SXin Li       MightBeImplicitMember = true;
2315*67e74705SXin Li     else
2316*67e74705SXin Li       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2317*67e74705SXin Li                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2318*67e74705SXin Li                               isa<MSPropertyDecl>(R.getFoundDecl());
2319*67e74705SXin Li 
2320*67e74705SXin Li     if (MightBeImplicitMember)
2321*67e74705SXin Li       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2322*67e74705SXin Li                                              R, TemplateArgs, S);
2323*67e74705SXin Li   }
2324*67e74705SXin Li 
2325*67e74705SXin Li   if (TemplateArgs || TemplateKWLoc.isValid()) {
2326*67e74705SXin Li 
2327*67e74705SXin Li     // In C++1y, if this is a variable template id, then check it
2328*67e74705SXin Li     // in BuildTemplateIdExpr().
2329*67e74705SXin Li     // The single lookup result must be a variable template declaration.
2330*67e74705SXin Li     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2331*67e74705SXin Li         Id.TemplateId->Kind == TNK_Var_template) {
2332*67e74705SXin Li       assert(R.getAsSingle<VarTemplateDecl>() &&
2333*67e74705SXin Li              "There should only be one declaration found.");
2334*67e74705SXin Li     }
2335*67e74705SXin Li 
2336*67e74705SXin Li     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2337*67e74705SXin Li   }
2338*67e74705SXin Li 
2339*67e74705SXin Li   return BuildDeclarationNameExpr(SS, R, ADL);
2340*67e74705SXin Li }
2341*67e74705SXin Li 
2342*67e74705SXin Li /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2343*67e74705SXin Li /// declaration name, generally during template instantiation.
2344*67e74705SXin Li /// There's a large number of things which don't need to be done along
2345*67e74705SXin Li /// this path.
BuildQualifiedDeclarationNameExpr(CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,bool IsAddressOfOperand,const Scope * S,TypeSourceInfo ** RecoveryTSI)2346*67e74705SXin Li ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2347*67e74705SXin Li     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2348*67e74705SXin Li     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2349*67e74705SXin Li   DeclContext *DC = computeDeclContext(SS, false);
2350*67e74705SXin Li   if (!DC)
2351*67e74705SXin Li     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2352*67e74705SXin Li                                      NameInfo, /*TemplateArgs=*/nullptr);
2353*67e74705SXin Li 
2354*67e74705SXin Li   if (RequireCompleteDeclContext(SS, DC))
2355*67e74705SXin Li     return ExprError();
2356*67e74705SXin Li 
2357*67e74705SXin Li   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2358*67e74705SXin Li   LookupQualifiedName(R, DC);
2359*67e74705SXin Li 
2360*67e74705SXin Li   if (R.isAmbiguous())
2361*67e74705SXin Li     return ExprError();
2362*67e74705SXin Li 
2363*67e74705SXin Li   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2364*67e74705SXin Li     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2365*67e74705SXin Li                                      NameInfo, /*TemplateArgs=*/nullptr);
2366*67e74705SXin Li 
2367*67e74705SXin Li   if (R.empty()) {
2368*67e74705SXin Li     Diag(NameInfo.getLoc(), diag::err_no_member)
2369*67e74705SXin Li       << NameInfo.getName() << DC << SS.getRange();
2370*67e74705SXin Li     return ExprError();
2371*67e74705SXin Li   }
2372*67e74705SXin Li 
2373*67e74705SXin Li   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2374*67e74705SXin Li     // Diagnose a missing typename if this resolved unambiguously to a type in
2375*67e74705SXin Li     // a dependent context.  If we can recover with a type, downgrade this to
2376*67e74705SXin Li     // a warning in Microsoft compatibility mode.
2377*67e74705SXin Li     unsigned DiagID = diag::err_typename_missing;
2378*67e74705SXin Li     if (RecoveryTSI && getLangOpts().MSVCCompat)
2379*67e74705SXin Li       DiagID = diag::ext_typename_missing;
2380*67e74705SXin Li     SourceLocation Loc = SS.getBeginLoc();
2381*67e74705SXin Li     auto D = Diag(Loc, DiagID);
2382*67e74705SXin Li     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2383*67e74705SXin Li       << SourceRange(Loc, NameInfo.getEndLoc());
2384*67e74705SXin Li 
2385*67e74705SXin Li     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2386*67e74705SXin Li     // context.
2387*67e74705SXin Li     if (!RecoveryTSI)
2388*67e74705SXin Li       return ExprError();
2389*67e74705SXin Li 
2390*67e74705SXin Li     // Only issue the fixit if we're prepared to recover.
2391*67e74705SXin Li     D << FixItHint::CreateInsertion(Loc, "typename ");
2392*67e74705SXin Li 
2393*67e74705SXin Li     // Recover by pretending this was an elaborated type.
2394*67e74705SXin Li     QualType Ty = Context.getTypeDeclType(TD);
2395*67e74705SXin Li     TypeLocBuilder TLB;
2396*67e74705SXin Li     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2397*67e74705SXin Li 
2398*67e74705SXin Li     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2399*67e74705SXin Li     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2400*67e74705SXin Li     QTL.setElaboratedKeywordLoc(SourceLocation());
2401*67e74705SXin Li     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2402*67e74705SXin Li 
2403*67e74705SXin Li     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2404*67e74705SXin Li 
2405*67e74705SXin Li     return ExprEmpty();
2406*67e74705SXin Li   }
2407*67e74705SXin Li 
2408*67e74705SXin Li   // Defend against this resolving to an implicit member access. We usually
2409*67e74705SXin Li   // won't get here if this might be a legitimate a class member (we end up in
2410*67e74705SXin Li   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2411*67e74705SXin Li   // a pointer-to-member or in an unevaluated context in C++11.
2412*67e74705SXin Li   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2413*67e74705SXin Li     return BuildPossibleImplicitMemberExpr(SS,
2414*67e74705SXin Li                                            /*TemplateKWLoc=*/SourceLocation(),
2415*67e74705SXin Li                                            R, /*TemplateArgs=*/nullptr, S);
2416*67e74705SXin Li 
2417*67e74705SXin Li   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2418*67e74705SXin Li }
2419*67e74705SXin Li 
2420*67e74705SXin Li /// LookupInObjCMethod - The parser has read a name in, and Sema has
2421*67e74705SXin Li /// detected that we're currently inside an ObjC method.  Perform some
2422*67e74705SXin Li /// additional lookup.
2423*67e74705SXin Li ///
2424*67e74705SXin Li /// Ideally, most of this would be done by lookup, but there's
2425*67e74705SXin Li /// actually quite a lot of extra work involved.
2426*67e74705SXin Li ///
2427*67e74705SXin Li /// Returns a null sentinel to indicate trivial success.
2428*67e74705SXin Li ExprResult
LookupInObjCMethod(LookupResult & Lookup,Scope * S,IdentifierInfo * II,bool AllowBuiltinCreation)2429*67e74705SXin Li Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2430*67e74705SXin Li                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2431*67e74705SXin Li   SourceLocation Loc = Lookup.getNameLoc();
2432*67e74705SXin Li   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2433*67e74705SXin Li 
2434*67e74705SXin Li   // Check for error condition which is already reported.
2435*67e74705SXin Li   if (!CurMethod)
2436*67e74705SXin Li     return ExprError();
2437*67e74705SXin Li 
2438*67e74705SXin Li   // There are two cases to handle here.  1) scoped lookup could have failed,
2439*67e74705SXin Li   // in which case we should look for an ivar.  2) scoped lookup could have
2440*67e74705SXin Li   // found a decl, but that decl is outside the current instance method (i.e.
2441*67e74705SXin Li   // a global variable).  In these two cases, we do a lookup for an ivar with
2442*67e74705SXin Li   // this name, if the lookup sucedes, we replace it our current decl.
2443*67e74705SXin Li 
2444*67e74705SXin Li   // If we're in a class method, we don't normally want to look for
2445*67e74705SXin Li   // ivars.  But if we don't find anything else, and there's an
2446*67e74705SXin Li   // ivar, that's an error.
2447*67e74705SXin Li   bool IsClassMethod = CurMethod->isClassMethod();
2448*67e74705SXin Li 
2449*67e74705SXin Li   bool LookForIvars;
2450*67e74705SXin Li   if (Lookup.empty())
2451*67e74705SXin Li     LookForIvars = true;
2452*67e74705SXin Li   else if (IsClassMethod)
2453*67e74705SXin Li     LookForIvars = false;
2454*67e74705SXin Li   else
2455*67e74705SXin Li     LookForIvars = (Lookup.isSingleResult() &&
2456*67e74705SXin Li                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2457*67e74705SXin Li   ObjCInterfaceDecl *IFace = nullptr;
2458*67e74705SXin Li   if (LookForIvars) {
2459*67e74705SXin Li     IFace = CurMethod->getClassInterface();
2460*67e74705SXin Li     ObjCInterfaceDecl *ClassDeclared;
2461*67e74705SXin Li     ObjCIvarDecl *IV = nullptr;
2462*67e74705SXin Li     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2463*67e74705SXin Li       // Diagnose using an ivar in a class method.
2464*67e74705SXin Li       if (IsClassMethod)
2465*67e74705SXin Li         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2466*67e74705SXin Li                          << IV->getDeclName());
2467*67e74705SXin Li 
2468*67e74705SXin Li       // If we're referencing an invalid decl, just return this as a silent
2469*67e74705SXin Li       // error node.  The error diagnostic was already emitted on the decl.
2470*67e74705SXin Li       if (IV->isInvalidDecl())
2471*67e74705SXin Li         return ExprError();
2472*67e74705SXin Li 
2473*67e74705SXin Li       // Check if referencing a field with __attribute__((deprecated)).
2474*67e74705SXin Li       if (DiagnoseUseOfDecl(IV, Loc))
2475*67e74705SXin Li         return ExprError();
2476*67e74705SXin Li 
2477*67e74705SXin Li       // Diagnose the use of an ivar outside of the declaring class.
2478*67e74705SXin Li       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2479*67e74705SXin Li           !declaresSameEntity(ClassDeclared, IFace) &&
2480*67e74705SXin Li           !getLangOpts().DebuggerSupport)
2481*67e74705SXin Li         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2482*67e74705SXin Li 
2483*67e74705SXin Li       // FIXME: This should use a new expr for a direct reference, don't
2484*67e74705SXin Li       // turn this into Self->ivar, just return a BareIVarExpr or something.
2485*67e74705SXin Li       IdentifierInfo &II = Context.Idents.get("self");
2486*67e74705SXin Li       UnqualifiedId SelfName;
2487*67e74705SXin Li       SelfName.setIdentifier(&II, SourceLocation());
2488*67e74705SXin Li       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2489*67e74705SXin Li       CXXScopeSpec SelfScopeSpec;
2490*67e74705SXin Li       SourceLocation TemplateKWLoc;
2491*67e74705SXin Li       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2492*67e74705SXin Li                                               SelfName, false, false);
2493*67e74705SXin Li       if (SelfExpr.isInvalid())
2494*67e74705SXin Li         return ExprError();
2495*67e74705SXin Li 
2496*67e74705SXin Li       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2497*67e74705SXin Li       if (SelfExpr.isInvalid())
2498*67e74705SXin Li         return ExprError();
2499*67e74705SXin Li 
2500*67e74705SXin Li       MarkAnyDeclReferenced(Loc, IV, true);
2501*67e74705SXin Li 
2502*67e74705SXin Li       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2503*67e74705SXin Li       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2504*67e74705SXin Li           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2505*67e74705SXin Li         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2506*67e74705SXin Li 
2507*67e74705SXin Li       ObjCIvarRefExpr *Result = new (Context)
2508*67e74705SXin Li           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2509*67e74705SXin Li                           IV->getLocation(), SelfExpr.get(), true, true);
2510*67e74705SXin Li 
2511*67e74705SXin Li       if (getLangOpts().ObjCAutoRefCount) {
2512*67e74705SXin Li         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2513*67e74705SXin Li           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2514*67e74705SXin Li             recordUseOfEvaluatedWeak(Result);
2515*67e74705SXin Li         }
2516*67e74705SXin Li         if (CurContext->isClosure())
2517*67e74705SXin Li           Diag(Loc, diag::warn_implicitly_retains_self)
2518*67e74705SXin Li             << FixItHint::CreateInsertion(Loc, "self->");
2519*67e74705SXin Li       }
2520*67e74705SXin Li 
2521*67e74705SXin Li       return Result;
2522*67e74705SXin Li     }
2523*67e74705SXin Li   } else if (CurMethod->isInstanceMethod()) {
2524*67e74705SXin Li     // We should warn if a local variable hides an ivar.
2525*67e74705SXin Li     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2526*67e74705SXin Li       ObjCInterfaceDecl *ClassDeclared;
2527*67e74705SXin Li       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2528*67e74705SXin Li         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2529*67e74705SXin Li             declaresSameEntity(IFace, ClassDeclared))
2530*67e74705SXin Li           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2531*67e74705SXin Li       }
2532*67e74705SXin Li     }
2533*67e74705SXin Li   } else if (Lookup.isSingleResult() &&
2534*67e74705SXin Li              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2535*67e74705SXin Li     // If accessing a stand-alone ivar in a class method, this is an error.
2536*67e74705SXin Li     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2537*67e74705SXin Li       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2538*67e74705SXin Li                        << IV->getDeclName());
2539*67e74705SXin Li   }
2540*67e74705SXin Li 
2541*67e74705SXin Li   if (Lookup.empty() && II && AllowBuiltinCreation) {
2542*67e74705SXin Li     // FIXME. Consolidate this with similar code in LookupName.
2543*67e74705SXin Li     if (unsigned BuiltinID = II->getBuiltinID()) {
2544*67e74705SXin Li       if (!(getLangOpts().CPlusPlus &&
2545*67e74705SXin Li             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2546*67e74705SXin Li         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2547*67e74705SXin Li                                            S, Lookup.isForRedeclaration(),
2548*67e74705SXin Li                                            Lookup.getNameLoc());
2549*67e74705SXin Li         if (D) Lookup.addDecl(D);
2550*67e74705SXin Li       }
2551*67e74705SXin Li     }
2552*67e74705SXin Li   }
2553*67e74705SXin Li   // Sentinel value saying that we didn't do anything special.
2554*67e74705SXin Li   return ExprResult((Expr *)nullptr);
2555*67e74705SXin Li }
2556*67e74705SXin Li 
2557*67e74705SXin Li /// \brief Cast a base object to a member's actual type.
2558*67e74705SXin Li ///
2559*67e74705SXin Li /// Logically this happens in three phases:
2560*67e74705SXin Li ///
2561*67e74705SXin Li /// * First we cast from the base type to the naming class.
2562*67e74705SXin Li ///   The naming class is the class into which we were looking
2563*67e74705SXin Li ///   when we found the member;  it's the qualifier type if a
2564*67e74705SXin Li ///   qualifier was provided, and otherwise it's the base type.
2565*67e74705SXin Li ///
2566*67e74705SXin Li /// * Next we cast from the naming class to the declaring class.
2567*67e74705SXin Li ///   If the member we found was brought into a class's scope by
2568*67e74705SXin Li ///   a using declaration, this is that class;  otherwise it's
2569*67e74705SXin Li ///   the class declaring the member.
2570*67e74705SXin Li ///
2571*67e74705SXin Li /// * Finally we cast from the declaring class to the "true"
2572*67e74705SXin Li ///   declaring class of the member.  This conversion does not
2573*67e74705SXin Li ///   obey access control.
2574*67e74705SXin Li ExprResult
PerformObjectMemberConversion(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,NamedDecl * Member)2575*67e74705SXin Li Sema::PerformObjectMemberConversion(Expr *From,
2576*67e74705SXin Li                                     NestedNameSpecifier *Qualifier,
2577*67e74705SXin Li                                     NamedDecl *FoundDecl,
2578*67e74705SXin Li                                     NamedDecl *Member) {
2579*67e74705SXin Li   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2580*67e74705SXin Li   if (!RD)
2581*67e74705SXin Li     return From;
2582*67e74705SXin Li 
2583*67e74705SXin Li   QualType DestRecordType;
2584*67e74705SXin Li   QualType DestType;
2585*67e74705SXin Li   QualType FromRecordType;
2586*67e74705SXin Li   QualType FromType = From->getType();
2587*67e74705SXin Li   bool PointerConversions = false;
2588*67e74705SXin Li   if (isa<FieldDecl>(Member)) {
2589*67e74705SXin Li     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2590*67e74705SXin Li 
2591*67e74705SXin Li     if (FromType->getAs<PointerType>()) {
2592*67e74705SXin Li       DestType = Context.getPointerType(DestRecordType);
2593*67e74705SXin Li       FromRecordType = FromType->getPointeeType();
2594*67e74705SXin Li       PointerConversions = true;
2595*67e74705SXin Li     } else {
2596*67e74705SXin Li       DestType = DestRecordType;
2597*67e74705SXin Li       FromRecordType = FromType;
2598*67e74705SXin Li     }
2599*67e74705SXin Li   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2600*67e74705SXin Li     if (Method->isStatic())
2601*67e74705SXin Li       return From;
2602*67e74705SXin Li 
2603*67e74705SXin Li     DestType = Method->getThisType(Context);
2604*67e74705SXin Li     DestRecordType = DestType->getPointeeType();
2605*67e74705SXin Li 
2606*67e74705SXin Li     if (FromType->getAs<PointerType>()) {
2607*67e74705SXin Li       FromRecordType = FromType->getPointeeType();
2608*67e74705SXin Li       PointerConversions = true;
2609*67e74705SXin Li     } else {
2610*67e74705SXin Li       FromRecordType = FromType;
2611*67e74705SXin Li       DestType = DestRecordType;
2612*67e74705SXin Li     }
2613*67e74705SXin Li   } else {
2614*67e74705SXin Li     // No conversion necessary.
2615*67e74705SXin Li     return From;
2616*67e74705SXin Li   }
2617*67e74705SXin Li 
2618*67e74705SXin Li   if (DestType->isDependentType() || FromType->isDependentType())
2619*67e74705SXin Li     return From;
2620*67e74705SXin Li 
2621*67e74705SXin Li   // If the unqualified types are the same, no conversion is necessary.
2622*67e74705SXin Li   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2623*67e74705SXin Li     return From;
2624*67e74705SXin Li 
2625*67e74705SXin Li   SourceRange FromRange = From->getSourceRange();
2626*67e74705SXin Li   SourceLocation FromLoc = FromRange.getBegin();
2627*67e74705SXin Li 
2628*67e74705SXin Li   ExprValueKind VK = From->getValueKind();
2629*67e74705SXin Li 
2630*67e74705SXin Li   // C++ [class.member.lookup]p8:
2631*67e74705SXin Li   //   [...] Ambiguities can often be resolved by qualifying a name with its
2632*67e74705SXin Li   //   class name.
2633*67e74705SXin Li   //
2634*67e74705SXin Li   // If the member was a qualified name and the qualified referred to a
2635*67e74705SXin Li   // specific base subobject type, we'll cast to that intermediate type
2636*67e74705SXin Li   // first and then to the object in which the member is declared. That allows
2637*67e74705SXin Li   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2638*67e74705SXin Li   //
2639*67e74705SXin Li   //   class Base { public: int x; };
2640*67e74705SXin Li   //   class Derived1 : public Base { };
2641*67e74705SXin Li   //   class Derived2 : public Base { };
2642*67e74705SXin Li   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2643*67e74705SXin Li   //
2644*67e74705SXin Li   //   void VeryDerived::f() {
2645*67e74705SXin Li   //     x = 17; // error: ambiguous base subobjects
2646*67e74705SXin Li   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2647*67e74705SXin Li   //   }
2648*67e74705SXin Li   if (Qualifier && Qualifier->getAsType()) {
2649*67e74705SXin Li     QualType QType = QualType(Qualifier->getAsType(), 0);
2650*67e74705SXin Li     assert(QType->isRecordType() && "lookup done with non-record type");
2651*67e74705SXin Li 
2652*67e74705SXin Li     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2653*67e74705SXin Li 
2654*67e74705SXin Li     // In C++98, the qualifier type doesn't actually have to be a base
2655*67e74705SXin Li     // type of the object type, in which case we just ignore it.
2656*67e74705SXin Li     // Otherwise build the appropriate casts.
2657*67e74705SXin Li     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2658*67e74705SXin Li       CXXCastPath BasePath;
2659*67e74705SXin Li       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2660*67e74705SXin Li                                        FromLoc, FromRange, &BasePath))
2661*67e74705SXin Li         return ExprError();
2662*67e74705SXin Li 
2663*67e74705SXin Li       if (PointerConversions)
2664*67e74705SXin Li         QType = Context.getPointerType(QType);
2665*67e74705SXin Li       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2666*67e74705SXin Li                                VK, &BasePath).get();
2667*67e74705SXin Li 
2668*67e74705SXin Li       FromType = QType;
2669*67e74705SXin Li       FromRecordType = QRecordType;
2670*67e74705SXin Li 
2671*67e74705SXin Li       // If the qualifier type was the same as the destination type,
2672*67e74705SXin Li       // we're done.
2673*67e74705SXin Li       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2674*67e74705SXin Li         return From;
2675*67e74705SXin Li     }
2676*67e74705SXin Li   }
2677*67e74705SXin Li 
2678*67e74705SXin Li   bool IgnoreAccess = false;
2679*67e74705SXin Li 
2680*67e74705SXin Li   // If we actually found the member through a using declaration, cast
2681*67e74705SXin Li   // down to the using declaration's type.
2682*67e74705SXin Li   //
2683*67e74705SXin Li   // Pointer equality is fine here because only one declaration of a
2684*67e74705SXin Li   // class ever has member declarations.
2685*67e74705SXin Li   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2686*67e74705SXin Li     assert(isa<UsingShadowDecl>(FoundDecl));
2687*67e74705SXin Li     QualType URecordType = Context.getTypeDeclType(
2688*67e74705SXin Li                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2689*67e74705SXin Li 
2690*67e74705SXin Li     // We only need to do this if the naming-class to declaring-class
2691*67e74705SXin Li     // conversion is non-trivial.
2692*67e74705SXin Li     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2693*67e74705SXin Li       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2694*67e74705SXin Li       CXXCastPath BasePath;
2695*67e74705SXin Li       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2696*67e74705SXin Li                                        FromLoc, FromRange, &BasePath))
2697*67e74705SXin Li         return ExprError();
2698*67e74705SXin Li 
2699*67e74705SXin Li       QualType UType = URecordType;
2700*67e74705SXin Li       if (PointerConversions)
2701*67e74705SXin Li         UType = Context.getPointerType(UType);
2702*67e74705SXin Li       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2703*67e74705SXin Li                                VK, &BasePath).get();
2704*67e74705SXin Li       FromType = UType;
2705*67e74705SXin Li       FromRecordType = URecordType;
2706*67e74705SXin Li     }
2707*67e74705SXin Li 
2708*67e74705SXin Li     // We don't do access control for the conversion from the
2709*67e74705SXin Li     // declaring class to the true declaring class.
2710*67e74705SXin Li     IgnoreAccess = true;
2711*67e74705SXin Li   }
2712*67e74705SXin Li 
2713*67e74705SXin Li   CXXCastPath BasePath;
2714*67e74705SXin Li   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2715*67e74705SXin Li                                    FromLoc, FromRange, &BasePath,
2716*67e74705SXin Li                                    IgnoreAccess))
2717*67e74705SXin Li     return ExprError();
2718*67e74705SXin Li 
2719*67e74705SXin Li   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2720*67e74705SXin Li                            VK, &BasePath);
2721*67e74705SXin Li }
2722*67e74705SXin Li 
UseArgumentDependentLookup(const CXXScopeSpec & SS,const LookupResult & R,bool HasTrailingLParen)2723*67e74705SXin Li bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2724*67e74705SXin Li                                       const LookupResult &R,
2725*67e74705SXin Li                                       bool HasTrailingLParen) {
2726*67e74705SXin Li   // Only when used directly as the postfix-expression of a call.
2727*67e74705SXin Li   if (!HasTrailingLParen)
2728*67e74705SXin Li     return false;
2729*67e74705SXin Li 
2730*67e74705SXin Li   // Never if a scope specifier was provided.
2731*67e74705SXin Li   if (SS.isSet())
2732*67e74705SXin Li     return false;
2733*67e74705SXin Li 
2734*67e74705SXin Li   // Only in C++ or ObjC++.
2735*67e74705SXin Li   if (!getLangOpts().CPlusPlus)
2736*67e74705SXin Li     return false;
2737*67e74705SXin Li 
2738*67e74705SXin Li   // Turn off ADL when we find certain kinds of declarations during
2739*67e74705SXin Li   // normal lookup:
2740*67e74705SXin Li   for (NamedDecl *D : R) {
2741*67e74705SXin Li     // C++0x [basic.lookup.argdep]p3:
2742*67e74705SXin Li     //     -- a declaration of a class member
2743*67e74705SXin Li     // Since using decls preserve this property, we check this on the
2744*67e74705SXin Li     // original decl.
2745*67e74705SXin Li     if (D->isCXXClassMember())
2746*67e74705SXin Li       return false;
2747*67e74705SXin Li 
2748*67e74705SXin Li     // C++0x [basic.lookup.argdep]p3:
2749*67e74705SXin Li     //     -- a block-scope function declaration that is not a
2750*67e74705SXin Li     //        using-declaration
2751*67e74705SXin Li     // NOTE: we also trigger this for function templates (in fact, we
2752*67e74705SXin Li     // don't check the decl type at all, since all other decl types
2753*67e74705SXin Li     // turn off ADL anyway).
2754*67e74705SXin Li     if (isa<UsingShadowDecl>(D))
2755*67e74705SXin Li       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2756*67e74705SXin Li     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2757*67e74705SXin Li       return false;
2758*67e74705SXin Li 
2759*67e74705SXin Li     // C++0x [basic.lookup.argdep]p3:
2760*67e74705SXin Li     //     -- a declaration that is neither a function or a function
2761*67e74705SXin Li     //        template
2762*67e74705SXin Li     // And also for builtin functions.
2763*67e74705SXin Li     if (isa<FunctionDecl>(D)) {
2764*67e74705SXin Li       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2765*67e74705SXin Li 
2766*67e74705SXin Li       // But also builtin functions.
2767*67e74705SXin Li       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2768*67e74705SXin Li         return false;
2769*67e74705SXin Li     } else if (!isa<FunctionTemplateDecl>(D))
2770*67e74705SXin Li       return false;
2771*67e74705SXin Li   }
2772*67e74705SXin Li 
2773*67e74705SXin Li   return true;
2774*67e74705SXin Li }
2775*67e74705SXin Li 
2776*67e74705SXin Li 
2777*67e74705SXin Li /// Diagnoses obvious problems with the use of the given declaration
2778*67e74705SXin Li /// as an expression.  This is only actually called for lookups that
2779*67e74705SXin Li /// were not overloaded, and it doesn't promise that the declaration
2780*67e74705SXin Li /// will in fact be used.
CheckDeclInExpr(Sema & S,SourceLocation Loc,NamedDecl * D)2781*67e74705SXin Li static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2782*67e74705SXin Li   if (isa<TypedefNameDecl>(D)) {
2783*67e74705SXin Li     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2784*67e74705SXin Li     return true;
2785*67e74705SXin Li   }
2786*67e74705SXin Li 
2787*67e74705SXin Li   if (isa<ObjCInterfaceDecl>(D)) {
2788*67e74705SXin Li     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2789*67e74705SXin Li     return true;
2790*67e74705SXin Li   }
2791*67e74705SXin Li 
2792*67e74705SXin Li   if (isa<NamespaceDecl>(D)) {
2793*67e74705SXin Li     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2794*67e74705SXin Li     return true;
2795*67e74705SXin Li   }
2796*67e74705SXin Li 
2797*67e74705SXin Li   return false;
2798*67e74705SXin Li }
2799*67e74705SXin Li 
BuildDeclarationNameExpr(const CXXScopeSpec & SS,LookupResult & R,bool NeedsADL,bool AcceptInvalidDecl)2800*67e74705SXin Li ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2801*67e74705SXin Li                                           LookupResult &R, bool NeedsADL,
2802*67e74705SXin Li                                           bool AcceptInvalidDecl) {
2803*67e74705SXin Li   // If this is a single, fully-resolved result and we don't need ADL,
2804*67e74705SXin Li   // just build an ordinary singleton decl ref.
2805*67e74705SXin Li   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2806*67e74705SXin Li     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2807*67e74705SXin Li                                     R.getRepresentativeDecl(), nullptr,
2808*67e74705SXin Li                                     AcceptInvalidDecl);
2809*67e74705SXin Li 
2810*67e74705SXin Li   // We only need to check the declaration if there's exactly one
2811*67e74705SXin Li   // result, because in the overloaded case the results can only be
2812*67e74705SXin Li   // functions and function templates.
2813*67e74705SXin Li   if (R.isSingleResult() &&
2814*67e74705SXin Li       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2815*67e74705SXin Li     return ExprError();
2816*67e74705SXin Li 
2817*67e74705SXin Li   // Otherwise, just build an unresolved lookup expression.  Suppress
2818*67e74705SXin Li   // any lookup-related diagnostics; we'll hash these out later, when
2819*67e74705SXin Li   // we've picked a target.
2820*67e74705SXin Li   R.suppressDiagnostics();
2821*67e74705SXin Li 
2822*67e74705SXin Li   UnresolvedLookupExpr *ULE
2823*67e74705SXin Li     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2824*67e74705SXin Li                                    SS.getWithLocInContext(Context),
2825*67e74705SXin Li                                    R.getLookupNameInfo(),
2826*67e74705SXin Li                                    NeedsADL, R.isOverloadedResult(),
2827*67e74705SXin Li                                    R.begin(), R.end());
2828*67e74705SXin Li 
2829*67e74705SXin Li   return ULE;
2830*67e74705SXin Li }
2831*67e74705SXin Li 
2832*67e74705SXin Li /// \brief Complete semantic analysis for a reference to the given declaration.
BuildDeclarationNameExpr(const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,NamedDecl * D,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs,bool AcceptInvalidDecl)2833*67e74705SXin Li ExprResult Sema::BuildDeclarationNameExpr(
2834*67e74705SXin Li     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2835*67e74705SXin Li     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2836*67e74705SXin Li     bool AcceptInvalidDecl) {
2837*67e74705SXin Li   assert(D && "Cannot refer to a NULL declaration");
2838*67e74705SXin Li   assert(!isa<FunctionTemplateDecl>(D) &&
2839*67e74705SXin Li          "Cannot refer unambiguously to a function template");
2840*67e74705SXin Li 
2841*67e74705SXin Li   SourceLocation Loc = NameInfo.getLoc();
2842*67e74705SXin Li   if (CheckDeclInExpr(*this, Loc, D))
2843*67e74705SXin Li     return ExprError();
2844*67e74705SXin Li 
2845*67e74705SXin Li   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2846*67e74705SXin Li     // Specifically diagnose references to class templates that are missing
2847*67e74705SXin Li     // a template argument list.
2848*67e74705SXin Li     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2849*67e74705SXin Li                                            << Template << SS.getRange();
2850*67e74705SXin Li     Diag(Template->getLocation(), diag::note_template_decl_here);
2851*67e74705SXin Li     return ExprError();
2852*67e74705SXin Li   }
2853*67e74705SXin Li 
2854*67e74705SXin Li   // Make sure that we're referring to a value.
2855*67e74705SXin Li   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2856*67e74705SXin Li   if (!VD) {
2857*67e74705SXin Li     Diag(Loc, diag::err_ref_non_value)
2858*67e74705SXin Li       << D << SS.getRange();
2859*67e74705SXin Li     Diag(D->getLocation(), diag::note_declared_at);
2860*67e74705SXin Li     return ExprError();
2861*67e74705SXin Li   }
2862*67e74705SXin Li 
2863*67e74705SXin Li   // Check whether this declaration can be used. Note that we suppress
2864*67e74705SXin Li   // this check when we're going to perform argument-dependent lookup
2865*67e74705SXin Li   // on this function name, because this might not be the function
2866*67e74705SXin Li   // that overload resolution actually selects.
2867*67e74705SXin Li   if (DiagnoseUseOfDecl(VD, Loc))
2868*67e74705SXin Li     return ExprError();
2869*67e74705SXin Li 
2870*67e74705SXin Li   // Only create DeclRefExpr's for valid Decl's.
2871*67e74705SXin Li   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2872*67e74705SXin Li     return ExprError();
2873*67e74705SXin Li 
2874*67e74705SXin Li   // Handle members of anonymous structs and unions.  If we got here,
2875*67e74705SXin Li   // and the reference is to a class member indirect field, then this
2876*67e74705SXin Li   // must be the subject of a pointer-to-member expression.
2877*67e74705SXin Li   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2878*67e74705SXin Li     if (!indirectField->isCXXClassMember())
2879*67e74705SXin Li       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2880*67e74705SXin Li                                                       indirectField);
2881*67e74705SXin Li 
2882*67e74705SXin Li   {
2883*67e74705SXin Li     QualType type = VD->getType();
2884*67e74705SXin Li     ExprValueKind valueKind = VK_RValue;
2885*67e74705SXin Li 
2886*67e74705SXin Li     switch (D->getKind()) {
2887*67e74705SXin Li     // Ignore all the non-ValueDecl kinds.
2888*67e74705SXin Li #define ABSTRACT_DECL(kind)
2889*67e74705SXin Li #define VALUE(type, base)
2890*67e74705SXin Li #define DECL(type, base) \
2891*67e74705SXin Li     case Decl::type:
2892*67e74705SXin Li #include "clang/AST/DeclNodes.inc"
2893*67e74705SXin Li       llvm_unreachable("invalid value decl kind");
2894*67e74705SXin Li 
2895*67e74705SXin Li     // These shouldn't make it here.
2896*67e74705SXin Li     case Decl::ObjCAtDefsField:
2897*67e74705SXin Li     case Decl::ObjCIvar:
2898*67e74705SXin Li       llvm_unreachable("forming non-member reference to ivar?");
2899*67e74705SXin Li 
2900*67e74705SXin Li     // Enum constants are always r-values and never references.
2901*67e74705SXin Li     // Unresolved using declarations are dependent.
2902*67e74705SXin Li     case Decl::EnumConstant:
2903*67e74705SXin Li     case Decl::UnresolvedUsingValue:
2904*67e74705SXin Li     case Decl::OMPDeclareReduction:
2905*67e74705SXin Li       valueKind = VK_RValue;
2906*67e74705SXin Li       break;
2907*67e74705SXin Li 
2908*67e74705SXin Li     // Fields and indirect fields that got here must be for
2909*67e74705SXin Li     // pointer-to-member expressions; we just call them l-values for
2910*67e74705SXin Li     // internal consistency, because this subexpression doesn't really
2911*67e74705SXin Li     // exist in the high-level semantics.
2912*67e74705SXin Li     case Decl::Field:
2913*67e74705SXin Li     case Decl::IndirectField:
2914*67e74705SXin Li       assert(getLangOpts().CPlusPlus &&
2915*67e74705SXin Li              "building reference to field in C?");
2916*67e74705SXin Li 
2917*67e74705SXin Li       // These can't have reference type in well-formed programs, but
2918*67e74705SXin Li       // for internal consistency we do this anyway.
2919*67e74705SXin Li       type = type.getNonReferenceType();
2920*67e74705SXin Li       valueKind = VK_LValue;
2921*67e74705SXin Li       break;
2922*67e74705SXin Li 
2923*67e74705SXin Li     // Non-type template parameters are either l-values or r-values
2924*67e74705SXin Li     // depending on the type.
2925*67e74705SXin Li     case Decl::NonTypeTemplateParm: {
2926*67e74705SXin Li       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2927*67e74705SXin Li         type = reftype->getPointeeType();
2928*67e74705SXin Li         valueKind = VK_LValue; // even if the parameter is an r-value reference
2929*67e74705SXin Li         break;
2930*67e74705SXin Li       }
2931*67e74705SXin Li 
2932*67e74705SXin Li       // For non-references, we need to strip qualifiers just in case
2933*67e74705SXin Li       // the template parameter was declared as 'const int' or whatever.
2934*67e74705SXin Li       valueKind = VK_RValue;
2935*67e74705SXin Li       type = type.getUnqualifiedType();
2936*67e74705SXin Li       break;
2937*67e74705SXin Li     }
2938*67e74705SXin Li 
2939*67e74705SXin Li     case Decl::Var:
2940*67e74705SXin Li     case Decl::VarTemplateSpecialization:
2941*67e74705SXin Li     case Decl::VarTemplatePartialSpecialization:
2942*67e74705SXin Li     case Decl::OMPCapturedExpr:
2943*67e74705SXin Li       // In C, "extern void blah;" is valid and is an r-value.
2944*67e74705SXin Li       if (!getLangOpts().CPlusPlus &&
2945*67e74705SXin Li           !type.hasQualifiers() &&
2946*67e74705SXin Li           type->isVoidType()) {
2947*67e74705SXin Li         valueKind = VK_RValue;
2948*67e74705SXin Li         break;
2949*67e74705SXin Li       }
2950*67e74705SXin Li       // fallthrough
2951*67e74705SXin Li 
2952*67e74705SXin Li     case Decl::ImplicitParam:
2953*67e74705SXin Li     case Decl::ParmVar: {
2954*67e74705SXin Li       // These are always l-values.
2955*67e74705SXin Li       valueKind = VK_LValue;
2956*67e74705SXin Li       type = type.getNonReferenceType();
2957*67e74705SXin Li 
2958*67e74705SXin Li       // FIXME: Does the addition of const really only apply in
2959*67e74705SXin Li       // potentially-evaluated contexts? Since the variable isn't actually
2960*67e74705SXin Li       // captured in an unevaluated context, it seems that the answer is no.
2961*67e74705SXin Li       if (!isUnevaluatedContext()) {
2962*67e74705SXin Li         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2963*67e74705SXin Li         if (!CapturedType.isNull())
2964*67e74705SXin Li           type = CapturedType;
2965*67e74705SXin Li       }
2966*67e74705SXin Li 
2967*67e74705SXin Li       break;
2968*67e74705SXin Li     }
2969*67e74705SXin Li 
2970*67e74705SXin Li     case Decl::Function: {
2971*67e74705SXin Li       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2972*67e74705SXin Li         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2973*67e74705SXin Li           type = Context.BuiltinFnTy;
2974*67e74705SXin Li           valueKind = VK_RValue;
2975*67e74705SXin Li           break;
2976*67e74705SXin Li         }
2977*67e74705SXin Li       }
2978*67e74705SXin Li 
2979*67e74705SXin Li       const FunctionType *fty = type->castAs<FunctionType>();
2980*67e74705SXin Li 
2981*67e74705SXin Li       // If we're referring to a function with an __unknown_anytype
2982*67e74705SXin Li       // result type, make the entire expression __unknown_anytype.
2983*67e74705SXin Li       if (fty->getReturnType() == Context.UnknownAnyTy) {
2984*67e74705SXin Li         type = Context.UnknownAnyTy;
2985*67e74705SXin Li         valueKind = VK_RValue;
2986*67e74705SXin Li         break;
2987*67e74705SXin Li       }
2988*67e74705SXin Li 
2989*67e74705SXin Li       // Functions are l-values in C++.
2990*67e74705SXin Li       if (getLangOpts().CPlusPlus) {
2991*67e74705SXin Li         valueKind = VK_LValue;
2992*67e74705SXin Li         break;
2993*67e74705SXin Li       }
2994*67e74705SXin Li 
2995*67e74705SXin Li       // C99 DR 316 says that, if a function type comes from a
2996*67e74705SXin Li       // function definition (without a prototype), that type is only
2997*67e74705SXin Li       // used for checking compatibility. Therefore, when referencing
2998*67e74705SXin Li       // the function, we pretend that we don't have the full function
2999*67e74705SXin Li       // type.
3000*67e74705SXin Li       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3001*67e74705SXin Li           isa<FunctionProtoType>(fty))
3002*67e74705SXin Li         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3003*67e74705SXin Li                                               fty->getExtInfo());
3004*67e74705SXin Li 
3005*67e74705SXin Li       // Functions are r-values in C.
3006*67e74705SXin Li       valueKind = VK_RValue;
3007*67e74705SXin Li       break;
3008*67e74705SXin Li     }
3009*67e74705SXin Li 
3010*67e74705SXin Li     case Decl::MSProperty:
3011*67e74705SXin Li       valueKind = VK_LValue;
3012*67e74705SXin Li       break;
3013*67e74705SXin Li 
3014*67e74705SXin Li     case Decl::CXXMethod:
3015*67e74705SXin Li       // If we're referring to a method with an __unknown_anytype
3016*67e74705SXin Li       // result type, make the entire expression __unknown_anytype.
3017*67e74705SXin Li       // This should only be possible with a type written directly.
3018*67e74705SXin Li       if (const FunctionProtoType *proto
3019*67e74705SXin Li             = dyn_cast<FunctionProtoType>(VD->getType()))
3020*67e74705SXin Li         if (proto->getReturnType() == Context.UnknownAnyTy) {
3021*67e74705SXin Li           type = Context.UnknownAnyTy;
3022*67e74705SXin Li           valueKind = VK_RValue;
3023*67e74705SXin Li           break;
3024*67e74705SXin Li         }
3025*67e74705SXin Li 
3026*67e74705SXin Li       // C++ methods are l-values if static, r-values if non-static.
3027*67e74705SXin Li       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3028*67e74705SXin Li         valueKind = VK_LValue;
3029*67e74705SXin Li         break;
3030*67e74705SXin Li       }
3031*67e74705SXin Li       // fallthrough
3032*67e74705SXin Li 
3033*67e74705SXin Li     case Decl::CXXConversion:
3034*67e74705SXin Li     case Decl::CXXDestructor:
3035*67e74705SXin Li     case Decl::CXXConstructor:
3036*67e74705SXin Li       valueKind = VK_RValue;
3037*67e74705SXin Li       break;
3038*67e74705SXin Li     }
3039*67e74705SXin Li 
3040*67e74705SXin Li     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3041*67e74705SXin Li                             TemplateArgs);
3042*67e74705SXin Li   }
3043*67e74705SXin Li }
3044*67e74705SXin Li 
ConvertUTF8ToWideString(unsigned CharByteWidth,StringRef Source,SmallString<32> & Target)3045*67e74705SXin Li static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3046*67e74705SXin Li                                     SmallString<32> &Target) {
3047*67e74705SXin Li   Target.resize(CharByteWidth * (Source.size() + 1));
3048*67e74705SXin Li   char *ResultPtr = &Target[0];
3049*67e74705SXin Li   const UTF8 *ErrorPtr;
3050*67e74705SXin Li   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3051*67e74705SXin Li   (void)success;
3052*67e74705SXin Li   assert(success);
3053*67e74705SXin Li   Target.resize(ResultPtr - &Target[0]);
3054*67e74705SXin Li }
3055*67e74705SXin Li 
BuildPredefinedExpr(SourceLocation Loc,PredefinedExpr::IdentType IT)3056*67e74705SXin Li ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3057*67e74705SXin Li                                      PredefinedExpr::IdentType IT) {
3058*67e74705SXin Li   // Pick the current block, lambda, captured statement or function.
3059*67e74705SXin Li   Decl *currentDecl = nullptr;
3060*67e74705SXin Li   if (const BlockScopeInfo *BSI = getCurBlock())
3061*67e74705SXin Li     currentDecl = BSI->TheDecl;
3062*67e74705SXin Li   else if (const LambdaScopeInfo *LSI = getCurLambda())
3063*67e74705SXin Li     currentDecl = LSI->CallOperator;
3064*67e74705SXin Li   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3065*67e74705SXin Li     currentDecl = CSI->TheCapturedDecl;
3066*67e74705SXin Li   else
3067*67e74705SXin Li     currentDecl = getCurFunctionOrMethodDecl();
3068*67e74705SXin Li 
3069*67e74705SXin Li   if (!currentDecl) {
3070*67e74705SXin Li     Diag(Loc, diag::ext_predef_outside_function);
3071*67e74705SXin Li     currentDecl = Context.getTranslationUnitDecl();
3072*67e74705SXin Li   }
3073*67e74705SXin Li 
3074*67e74705SXin Li   QualType ResTy;
3075*67e74705SXin Li   StringLiteral *SL = nullptr;
3076*67e74705SXin Li   if (cast<DeclContext>(currentDecl)->isDependentContext())
3077*67e74705SXin Li     ResTy = Context.DependentTy;
3078*67e74705SXin Li   else {
3079*67e74705SXin Li     // Pre-defined identifiers are of type char[x], where x is the length of
3080*67e74705SXin Li     // the string.
3081*67e74705SXin Li     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3082*67e74705SXin Li     unsigned Length = Str.length();
3083*67e74705SXin Li 
3084*67e74705SXin Li     llvm::APInt LengthI(32, Length + 1);
3085*67e74705SXin Li     if (IT == PredefinedExpr::LFunction) {
3086*67e74705SXin Li       ResTy = Context.WideCharTy.withConst();
3087*67e74705SXin Li       SmallString<32> RawChars;
3088*67e74705SXin Li       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3089*67e74705SXin Li                               Str, RawChars);
3090*67e74705SXin Li       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3091*67e74705SXin Li                                            /*IndexTypeQuals*/ 0);
3092*67e74705SXin Li       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3093*67e74705SXin Li                                  /*Pascal*/ false, ResTy, Loc);
3094*67e74705SXin Li     } else {
3095*67e74705SXin Li       ResTy = Context.CharTy.withConst();
3096*67e74705SXin Li       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3097*67e74705SXin Li                                            /*IndexTypeQuals*/ 0);
3098*67e74705SXin Li       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3099*67e74705SXin Li                                  /*Pascal*/ false, ResTy, Loc);
3100*67e74705SXin Li     }
3101*67e74705SXin Li   }
3102*67e74705SXin Li 
3103*67e74705SXin Li   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3104*67e74705SXin Li }
3105*67e74705SXin Li 
ActOnPredefinedExpr(SourceLocation Loc,tok::TokenKind Kind)3106*67e74705SXin Li ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3107*67e74705SXin Li   PredefinedExpr::IdentType IT;
3108*67e74705SXin Li 
3109*67e74705SXin Li   switch (Kind) {
3110*67e74705SXin Li   default: llvm_unreachable("Unknown simple primary expr!");
3111*67e74705SXin Li   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3112*67e74705SXin Li   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3113*67e74705SXin Li   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3114*67e74705SXin Li   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3115*67e74705SXin Li   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3116*67e74705SXin Li   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3117*67e74705SXin Li   }
3118*67e74705SXin Li 
3119*67e74705SXin Li   return BuildPredefinedExpr(Loc, IT);
3120*67e74705SXin Li }
3121*67e74705SXin Li 
ActOnCharacterConstant(const Token & Tok,Scope * UDLScope)3122*67e74705SXin Li ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3123*67e74705SXin Li   SmallString<16> CharBuffer;
3124*67e74705SXin Li   bool Invalid = false;
3125*67e74705SXin Li   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3126*67e74705SXin Li   if (Invalid)
3127*67e74705SXin Li     return ExprError();
3128*67e74705SXin Li 
3129*67e74705SXin Li   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3130*67e74705SXin Li                             PP, Tok.getKind());
3131*67e74705SXin Li   if (Literal.hadError())
3132*67e74705SXin Li     return ExprError();
3133*67e74705SXin Li 
3134*67e74705SXin Li   QualType Ty;
3135*67e74705SXin Li   if (Literal.isWide())
3136*67e74705SXin Li     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3137*67e74705SXin Li   else if (Literal.isUTF16())
3138*67e74705SXin Li     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3139*67e74705SXin Li   else if (Literal.isUTF32())
3140*67e74705SXin Li     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3141*67e74705SXin Li   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3142*67e74705SXin Li     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3143*67e74705SXin Li   else
3144*67e74705SXin Li     Ty = Context.CharTy;  // 'x' -> char in C++
3145*67e74705SXin Li 
3146*67e74705SXin Li   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3147*67e74705SXin Li   if (Literal.isWide())
3148*67e74705SXin Li     Kind = CharacterLiteral::Wide;
3149*67e74705SXin Li   else if (Literal.isUTF16())
3150*67e74705SXin Li     Kind = CharacterLiteral::UTF16;
3151*67e74705SXin Li   else if (Literal.isUTF32())
3152*67e74705SXin Li     Kind = CharacterLiteral::UTF32;
3153*67e74705SXin Li   else if (Literal.isUTF8())
3154*67e74705SXin Li     Kind = CharacterLiteral::UTF8;
3155*67e74705SXin Li 
3156*67e74705SXin Li   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3157*67e74705SXin Li                                              Tok.getLocation());
3158*67e74705SXin Li 
3159*67e74705SXin Li   if (Literal.getUDSuffix().empty())
3160*67e74705SXin Li     return Lit;
3161*67e74705SXin Li 
3162*67e74705SXin Li   // We're building a user-defined literal.
3163*67e74705SXin Li   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3164*67e74705SXin Li   SourceLocation UDSuffixLoc =
3165*67e74705SXin Li     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3166*67e74705SXin Li 
3167*67e74705SXin Li   // Make sure we're allowed user-defined literals here.
3168*67e74705SXin Li   if (!UDLScope)
3169*67e74705SXin Li     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3170*67e74705SXin Li 
3171*67e74705SXin Li   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3172*67e74705SXin Li   //   operator "" X (ch)
3173*67e74705SXin Li   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3174*67e74705SXin Li                                         Lit, Tok.getLocation());
3175*67e74705SXin Li }
3176*67e74705SXin Li 
ActOnIntegerConstant(SourceLocation Loc,uint64_t Val)3177*67e74705SXin Li ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3178*67e74705SXin Li   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3179*67e74705SXin Li   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3180*67e74705SXin Li                                 Context.IntTy, Loc);
3181*67e74705SXin Li }
3182*67e74705SXin Li 
BuildFloatingLiteral(Sema & S,NumericLiteralParser & Literal,QualType Ty,SourceLocation Loc)3183*67e74705SXin Li static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3184*67e74705SXin Li                                   QualType Ty, SourceLocation Loc) {
3185*67e74705SXin Li   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3186*67e74705SXin Li 
3187*67e74705SXin Li   using llvm::APFloat;
3188*67e74705SXin Li   APFloat Val(Format);
3189*67e74705SXin Li 
3190*67e74705SXin Li   APFloat::opStatus result = Literal.GetFloatValue(Val);
3191*67e74705SXin Li 
3192*67e74705SXin Li   // Overflow is always an error, but underflow is only an error if
3193*67e74705SXin Li   // we underflowed to zero (APFloat reports denormals as underflow).
3194*67e74705SXin Li   if ((result & APFloat::opOverflow) ||
3195*67e74705SXin Li       ((result & APFloat::opUnderflow) && Val.isZero())) {
3196*67e74705SXin Li     unsigned diagnostic;
3197*67e74705SXin Li     SmallString<20> buffer;
3198*67e74705SXin Li     if (result & APFloat::opOverflow) {
3199*67e74705SXin Li       diagnostic = diag::warn_float_overflow;
3200*67e74705SXin Li       APFloat::getLargest(Format).toString(buffer);
3201*67e74705SXin Li     } else {
3202*67e74705SXin Li       diagnostic = diag::warn_float_underflow;
3203*67e74705SXin Li       APFloat::getSmallest(Format).toString(buffer);
3204*67e74705SXin Li     }
3205*67e74705SXin Li 
3206*67e74705SXin Li     S.Diag(Loc, diagnostic)
3207*67e74705SXin Li       << Ty
3208*67e74705SXin Li       << StringRef(buffer.data(), buffer.size());
3209*67e74705SXin Li   }
3210*67e74705SXin Li 
3211*67e74705SXin Li   bool isExact = (result == APFloat::opOK);
3212*67e74705SXin Li   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3213*67e74705SXin Li }
3214*67e74705SXin Li 
CheckLoopHintExpr(Expr * E,SourceLocation Loc)3215*67e74705SXin Li bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3216*67e74705SXin Li   assert(E && "Invalid expression");
3217*67e74705SXin Li 
3218*67e74705SXin Li   if (E->isValueDependent())
3219*67e74705SXin Li     return false;
3220*67e74705SXin Li 
3221*67e74705SXin Li   QualType QT = E->getType();
3222*67e74705SXin Li   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3223*67e74705SXin Li     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3224*67e74705SXin Li     return true;
3225*67e74705SXin Li   }
3226*67e74705SXin Li 
3227*67e74705SXin Li   llvm::APSInt ValueAPS;
3228*67e74705SXin Li   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3229*67e74705SXin Li 
3230*67e74705SXin Li   if (R.isInvalid())
3231*67e74705SXin Li     return true;
3232*67e74705SXin Li 
3233*67e74705SXin Li   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3234*67e74705SXin Li   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3235*67e74705SXin Li     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3236*67e74705SXin Li         << ValueAPS.toString(10) << ValueIsPositive;
3237*67e74705SXin Li     return true;
3238*67e74705SXin Li   }
3239*67e74705SXin Li 
3240*67e74705SXin Li   return false;
3241*67e74705SXin Li }
3242*67e74705SXin Li 
ActOnNumericConstant(const Token & Tok,Scope * UDLScope)3243*67e74705SXin Li ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3244*67e74705SXin Li   // Fast path for a single digit (which is quite common).  A single digit
3245*67e74705SXin Li   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3246*67e74705SXin Li   if (Tok.getLength() == 1) {
3247*67e74705SXin Li     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3248*67e74705SXin Li     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3249*67e74705SXin Li   }
3250*67e74705SXin Li 
3251*67e74705SXin Li   SmallString<128> SpellingBuffer;
3252*67e74705SXin Li   // NumericLiteralParser wants to overread by one character.  Add padding to
3253*67e74705SXin Li   // the buffer in case the token is copied to the buffer.  If getSpelling()
3254*67e74705SXin Li   // returns a StringRef to the memory buffer, it should have a null char at
3255*67e74705SXin Li   // the EOF, so it is also safe.
3256*67e74705SXin Li   SpellingBuffer.resize(Tok.getLength() + 1);
3257*67e74705SXin Li 
3258*67e74705SXin Li   // Get the spelling of the token, which eliminates trigraphs, etc.
3259*67e74705SXin Li   bool Invalid = false;
3260*67e74705SXin Li   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3261*67e74705SXin Li   if (Invalid)
3262*67e74705SXin Li     return ExprError();
3263*67e74705SXin Li 
3264*67e74705SXin Li   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3265*67e74705SXin Li   if (Literal.hadError)
3266*67e74705SXin Li     return ExprError();
3267*67e74705SXin Li 
3268*67e74705SXin Li   if (Literal.hasUDSuffix()) {
3269*67e74705SXin Li     // We're building a user-defined literal.
3270*67e74705SXin Li     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3271*67e74705SXin Li     SourceLocation UDSuffixLoc =
3272*67e74705SXin Li       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3273*67e74705SXin Li 
3274*67e74705SXin Li     // Make sure we're allowed user-defined literals here.
3275*67e74705SXin Li     if (!UDLScope)
3276*67e74705SXin Li       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3277*67e74705SXin Li 
3278*67e74705SXin Li     QualType CookedTy;
3279*67e74705SXin Li     if (Literal.isFloatingLiteral()) {
3280*67e74705SXin Li       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3281*67e74705SXin Li       // long double, the literal is treated as a call of the form
3282*67e74705SXin Li       //   operator "" X (f L)
3283*67e74705SXin Li       CookedTy = Context.LongDoubleTy;
3284*67e74705SXin Li     } else {
3285*67e74705SXin Li       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3286*67e74705SXin Li       // unsigned long long, the literal is treated as a call of the form
3287*67e74705SXin Li       //   operator "" X (n ULL)
3288*67e74705SXin Li       CookedTy = Context.UnsignedLongLongTy;
3289*67e74705SXin Li     }
3290*67e74705SXin Li 
3291*67e74705SXin Li     DeclarationName OpName =
3292*67e74705SXin Li       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3293*67e74705SXin Li     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3294*67e74705SXin Li     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3295*67e74705SXin Li 
3296*67e74705SXin Li     SourceLocation TokLoc = Tok.getLocation();
3297*67e74705SXin Li 
3298*67e74705SXin Li     // Perform literal operator lookup to determine if we're building a raw
3299*67e74705SXin Li     // literal or a cooked one.
3300*67e74705SXin Li     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3301*67e74705SXin Li     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3302*67e74705SXin Li                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3303*67e74705SXin Li                                   /*AllowStringTemplate*/false)) {
3304*67e74705SXin Li     case LOLR_Error:
3305*67e74705SXin Li       return ExprError();
3306*67e74705SXin Li 
3307*67e74705SXin Li     case LOLR_Cooked: {
3308*67e74705SXin Li       Expr *Lit;
3309*67e74705SXin Li       if (Literal.isFloatingLiteral()) {
3310*67e74705SXin Li         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3311*67e74705SXin Li       } else {
3312*67e74705SXin Li         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3313*67e74705SXin Li         if (Literal.GetIntegerValue(ResultVal))
3314*67e74705SXin Li           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3315*67e74705SXin Li               << /* Unsigned */ 1;
3316*67e74705SXin Li         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3317*67e74705SXin Li                                      Tok.getLocation());
3318*67e74705SXin Li       }
3319*67e74705SXin Li       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3320*67e74705SXin Li     }
3321*67e74705SXin Li 
3322*67e74705SXin Li     case LOLR_Raw: {
3323*67e74705SXin Li       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3324*67e74705SXin Li       // literal is treated as a call of the form
3325*67e74705SXin Li       //   operator "" X ("n")
3326*67e74705SXin Li       unsigned Length = Literal.getUDSuffixOffset();
3327*67e74705SXin Li       QualType StrTy = Context.getConstantArrayType(
3328*67e74705SXin Li           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3329*67e74705SXin Li           ArrayType::Normal, 0);
3330*67e74705SXin Li       Expr *Lit = StringLiteral::Create(
3331*67e74705SXin Li           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3332*67e74705SXin Li           /*Pascal*/false, StrTy, &TokLoc, 1);
3333*67e74705SXin Li       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3334*67e74705SXin Li     }
3335*67e74705SXin Li 
3336*67e74705SXin Li     case LOLR_Template: {
3337*67e74705SXin Li       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3338*67e74705SXin Li       // template), L is treated as a call fo the form
3339*67e74705SXin Li       //   operator "" X <'c1', 'c2', ... 'ck'>()
3340*67e74705SXin Li       // where n is the source character sequence c1 c2 ... ck.
3341*67e74705SXin Li       TemplateArgumentListInfo ExplicitArgs;
3342*67e74705SXin Li       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3343*67e74705SXin Li       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3344*67e74705SXin Li       llvm::APSInt Value(CharBits, CharIsUnsigned);
3345*67e74705SXin Li       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3346*67e74705SXin Li         Value = TokSpelling[I];
3347*67e74705SXin Li         TemplateArgument Arg(Context, Value, Context.CharTy);
3348*67e74705SXin Li         TemplateArgumentLocInfo ArgInfo;
3349*67e74705SXin Li         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3350*67e74705SXin Li       }
3351*67e74705SXin Li       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3352*67e74705SXin Li                                       &ExplicitArgs);
3353*67e74705SXin Li     }
3354*67e74705SXin Li     case LOLR_StringTemplate:
3355*67e74705SXin Li       llvm_unreachable("unexpected literal operator lookup result");
3356*67e74705SXin Li     }
3357*67e74705SXin Li   }
3358*67e74705SXin Li 
3359*67e74705SXin Li   Expr *Res;
3360*67e74705SXin Li 
3361*67e74705SXin Li   if (Literal.isFloatingLiteral()) {
3362*67e74705SXin Li     QualType Ty;
3363*67e74705SXin Li     if (Literal.isHalf){
3364*67e74705SXin Li       if (getOpenCLOptions().cl_khr_fp16)
3365*67e74705SXin Li         Ty = Context.HalfTy;
3366*67e74705SXin Li       else {
3367*67e74705SXin Li         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3368*67e74705SXin Li         return ExprError();
3369*67e74705SXin Li       }
3370*67e74705SXin Li     } else if (Literal.isFloat)
3371*67e74705SXin Li       Ty = Context.FloatTy;
3372*67e74705SXin Li     else if (Literal.isLong)
3373*67e74705SXin Li       Ty = Context.LongDoubleTy;
3374*67e74705SXin Li     else if (Literal.isFloat128)
3375*67e74705SXin Li       Ty = Context.Float128Ty;
3376*67e74705SXin Li     else
3377*67e74705SXin Li       Ty = Context.DoubleTy;
3378*67e74705SXin Li 
3379*67e74705SXin Li     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3380*67e74705SXin Li 
3381*67e74705SXin Li     if (Ty == Context.DoubleTy) {
3382*67e74705SXin Li       if (getLangOpts().SinglePrecisionConstants) {
3383*67e74705SXin Li         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3384*67e74705SXin Li       } else if (getLangOpts().OpenCL &&
3385*67e74705SXin Li                  !((getLangOpts().OpenCLVersion >= 120) ||
3386*67e74705SXin Li                    getOpenCLOptions().cl_khr_fp64)) {
3387*67e74705SXin Li         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3388*67e74705SXin Li         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3389*67e74705SXin Li       }
3390*67e74705SXin Li     }
3391*67e74705SXin Li   } else if (!Literal.isIntegerLiteral()) {
3392*67e74705SXin Li     return ExprError();
3393*67e74705SXin Li   } else {
3394*67e74705SXin Li     QualType Ty;
3395*67e74705SXin Li 
3396*67e74705SXin Li     // 'long long' is a C99 or C++11 feature.
3397*67e74705SXin Li     if (!getLangOpts().C99 && Literal.isLongLong) {
3398*67e74705SXin Li       if (getLangOpts().CPlusPlus)
3399*67e74705SXin Li         Diag(Tok.getLocation(),
3400*67e74705SXin Li              getLangOpts().CPlusPlus11 ?
3401*67e74705SXin Li              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3402*67e74705SXin Li       else
3403*67e74705SXin Li         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3404*67e74705SXin Li     }
3405*67e74705SXin Li 
3406*67e74705SXin Li     // Get the value in the widest-possible width.
3407*67e74705SXin Li     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3408*67e74705SXin Li     llvm::APInt ResultVal(MaxWidth, 0);
3409*67e74705SXin Li 
3410*67e74705SXin Li     if (Literal.GetIntegerValue(ResultVal)) {
3411*67e74705SXin Li       // If this value didn't fit into uintmax_t, error and force to ull.
3412*67e74705SXin Li       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3413*67e74705SXin Li           << /* Unsigned */ 1;
3414*67e74705SXin Li       Ty = Context.UnsignedLongLongTy;
3415*67e74705SXin Li       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3416*67e74705SXin Li              "long long is not intmax_t?");
3417*67e74705SXin Li     } else {
3418*67e74705SXin Li       // If this value fits into a ULL, try to figure out what else it fits into
3419*67e74705SXin Li       // according to the rules of C99 6.4.4.1p5.
3420*67e74705SXin Li 
3421*67e74705SXin Li       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3422*67e74705SXin Li       // be an unsigned int.
3423*67e74705SXin Li       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3424*67e74705SXin Li 
3425*67e74705SXin Li       // Check from smallest to largest, picking the smallest type we can.
3426*67e74705SXin Li       unsigned Width = 0;
3427*67e74705SXin Li 
3428*67e74705SXin Li       // Microsoft specific integer suffixes are explicitly sized.
3429*67e74705SXin Li       if (Literal.MicrosoftInteger) {
3430*67e74705SXin Li         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3431*67e74705SXin Li           Width = 8;
3432*67e74705SXin Li           Ty = Context.CharTy;
3433*67e74705SXin Li         } else {
3434*67e74705SXin Li           Width = Literal.MicrosoftInteger;
3435*67e74705SXin Li           Ty = Context.getIntTypeForBitwidth(Width,
3436*67e74705SXin Li                                              /*Signed=*/!Literal.isUnsigned);
3437*67e74705SXin Li         }
3438*67e74705SXin Li       }
3439*67e74705SXin Li 
3440*67e74705SXin Li       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3441*67e74705SXin Li         // Are int/unsigned possibilities?
3442*67e74705SXin Li         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3443*67e74705SXin Li 
3444*67e74705SXin Li         // Does it fit in a unsigned int?
3445*67e74705SXin Li         if (ResultVal.isIntN(IntSize)) {
3446*67e74705SXin Li           // Does it fit in a signed int?
3447*67e74705SXin Li           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3448*67e74705SXin Li             Ty = Context.IntTy;
3449*67e74705SXin Li           else if (AllowUnsigned)
3450*67e74705SXin Li             Ty = Context.UnsignedIntTy;
3451*67e74705SXin Li           Width = IntSize;
3452*67e74705SXin Li         }
3453*67e74705SXin Li       }
3454*67e74705SXin Li 
3455*67e74705SXin Li       // Are long/unsigned long possibilities?
3456*67e74705SXin Li       if (Ty.isNull() && !Literal.isLongLong) {
3457*67e74705SXin Li         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3458*67e74705SXin Li 
3459*67e74705SXin Li         // Does it fit in a unsigned long?
3460*67e74705SXin Li         if (ResultVal.isIntN(LongSize)) {
3461*67e74705SXin Li           // Does it fit in a signed long?
3462*67e74705SXin Li           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3463*67e74705SXin Li             Ty = Context.LongTy;
3464*67e74705SXin Li           else if (AllowUnsigned)
3465*67e74705SXin Li             Ty = Context.UnsignedLongTy;
3466*67e74705SXin Li           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3467*67e74705SXin Li           // is compatible.
3468*67e74705SXin Li           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3469*67e74705SXin Li             const unsigned LongLongSize =
3470*67e74705SXin Li                 Context.getTargetInfo().getLongLongWidth();
3471*67e74705SXin Li             Diag(Tok.getLocation(),
3472*67e74705SXin Li                  getLangOpts().CPlusPlus
3473*67e74705SXin Li                      ? Literal.isLong
3474*67e74705SXin Li                            ? diag::warn_old_implicitly_unsigned_long_cxx
3475*67e74705SXin Li                            : /*C++98 UB*/ diag::
3476*67e74705SXin Li                                  ext_old_implicitly_unsigned_long_cxx
3477*67e74705SXin Li                      : diag::warn_old_implicitly_unsigned_long)
3478*67e74705SXin Li                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3479*67e74705SXin Li                                             : /*will be ill-formed*/ 1);
3480*67e74705SXin Li             Ty = Context.UnsignedLongTy;
3481*67e74705SXin Li           }
3482*67e74705SXin Li           Width = LongSize;
3483*67e74705SXin Li         }
3484*67e74705SXin Li       }
3485*67e74705SXin Li 
3486*67e74705SXin Li       // Check long long if needed.
3487*67e74705SXin Li       if (Ty.isNull()) {
3488*67e74705SXin Li         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3489*67e74705SXin Li 
3490*67e74705SXin Li         // Does it fit in a unsigned long long?
3491*67e74705SXin Li         if (ResultVal.isIntN(LongLongSize)) {
3492*67e74705SXin Li           // Does it fit in a signed long long?
3493*67e74705SXin Li           // To be compatible with MSVC, hex integer literals ending with the
3494*67e74705SXin Li           // LL or i64 suffix are always signed in Microsoft mode.
3495*67e74705SXin Li           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3496*67e74705SXin Li               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3497*67e74705SXin Li             Ty = Context.LongLongTy;
3498*67e74705SXin Li           else if (AllowUnsigned)
3499*67e74705SXin Li             Ty = Context.UnsignedLongLongTy;
3500*67e74705SXin Li           Width = LongLongSize;
3501*67e74705SXin Li         }
3502*67e74705SXin Li       }
3503*67e74705SXin Li 
3504*67e74705SXin Li       // If we still couldn't decide a type, we probably have something that
3505*67e74705SXin Li       // does not fit in a signed long long, but has no U suffix.
3506*67e74705SXin Li       if (Ty.isNull()) {
3507*67e74705SXin Li         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3508*67e74705SXin Li         Ty = Context.UnsignedLongLongTy;
3509*67e74705SXin Li         Width = Context.getTargetInfo().getLongLongWidth();
3510*67e74705SXin Li       }
3511*67e74705SXin Li 
3512*67e74705SXin Li       if (ResultVal.getBitWidth() != Width)
3513*67e74705SXin Li         ResultVal = ResultVal.trunc(Width);
3514*67e74705SXin Li     }
3515*67e74705SXin Li     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3516*67e74705SXin Li   }
3517*67e74705SXin Li 
3518*67e74705SXin Li   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3519*67e74705SXin Li   if (Literal.isImaginary)
3520*67e74705SXin Li     Res = new (Context) ImaginaryLiteral(Res,
3521*67e74705SXin Li                                         Context.getComplexType(Res->getType()));
3522*67e74705SXin Li 
3523*67e74705SXin Li   return Res;
3524*67e74705SXin Li }
3525*67e74705SXin Li 
ActOnParenExpr(SourceLocation L,SourceLocation R,Expr * E)3526*67e74705SXin Li ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3527*67e74705SXin Li   assert(E && "ActOnParenExpr() missing expr");
3528*67e74705SXin Li   return new (Context) ParenExpr(L, R, E);
3529*67e74705SXin Li }
3530*67e74705SXin Li 
CheckVecStepTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange)3531*67e74705SXin Li static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3532*67e74705SXin Li                                          SourceLocation Loc,
3533*67e74705SXin Li                                          SourceRange ArgRange) {
3534*67e74705SXin Li   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3535*67e74705SXin Li   // scalar or vector data type argument..."
3536*67e74705SXin Li   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3537*67e74705SXin Li   // type (C99 6.2.5p18) or void.
3538*67e74705SXin Li   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3539*67e74705SXin Li     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3540*67e74705SXin Li       << T << ArgRange;
3541*67e74705SXin Li     return true;
3542*67e74705SXin Li   }
3543*67e74705SXin Li 
3544*67e74705SXin Li   assert((T->isVoidType() || !T->isIncompleteType()) &&
3545*67e74705SXin Li          "Scalar types should always be complete");
3546*67e74705SXin Li   return false;
3547*67e74705SXin Li }
3548*67e74705SXin Li 
CheckExtensionTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)3549*67e74705SXin Li static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3550*67e74705SXin Li                                            SourceLocation Loc,
3551*67e74705SXin Li                                            SourceRange ArgRange,
3552*67e74705SXin Li                                            UnaryExprOrTypeTrait TraitKind) {
3553*67e74705SXin Li   // Invalid types must be hard errors for SFINAE in C++.
3554*67e74705SXin Li   if (S.LangOpts.CPlusPlus)
3555*67e74705SXin Li     return true;
3556*67e74705SXin Li 
3557*67e74705SXin Li   // C99 6.5.3.4p1:
3558*67e74705SXin Li   if (T->isFunctionType() &&
3559*67e74705SXin Li       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3560*67e74705SXin Li     // sizeof(function)/alignof(function) is allowed as an extension.
3561*67e74705SXin Li     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3562*67e74705SXin Li       << TraitKind << ArgRange;
3563*67e74705SXin Li     return false;
3564*67e74705SXin Li   }
3565*67e74705SXin Li 
3566*67e74705SXin Li   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3567*67e74705SXin Li   // this is an error (OpenCL v1.1 s6.3.k)
3568*67e74705SXin Li   if (T->isVoidType()) {
3569*67e74705SXin Li     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3570*67e74705SXin Li                                         : diag::ext_sizeof_alignof_void_type;
3571*67e74705SXin Li     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3572*67e74705SXin Li     return false;
3573*67e74705SXin Li   }
3574*67e74705SXin Li 
3575*67e74705SXin Li   return true;
3576*67e74705SXin Li }
3577*67e74705SXin Li 
CheckObjCTraitOperandConstraints(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)3578*67e74705SXin Li static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3579*67e74705SXin Li                                              SourceLocation Loc,
3580*67e74705SXin Li                                              SourceRange ArgRange,
3581*67e74705SXin Li                                              UnaryExprOrTypeTrait TraitKind) {
3582*67e74705SXin Li   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3583*67e74705SXin Li   // runtime doesn't allow it.
3584*67e74705SXin Li   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3585*67e74705SXin Li     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3586*67e74705SXin Li       << T << (TraitKind == UETT_SizeOf)
3587*67e74705SXin Li       << ArgRange;
3588*67e74705SXin Li     return true;
3589*67e74705SXin Li   }
3590*67e74705SXin Li 
3591*67e74705SXin Li   return false;
3592*67e74705SXin Li }
3593*67e74705SXin Li 
3594*67e74705SXin Li /// \brief Check whether E is a pointer from a decayed array type (the decayed
3595*67e74705SXin Li /// pointer type is equal to T) and emit a warning if it is.
warnOnSizeofOnArrayDecay(Sema & S,SourceLocation Loc,QualType T,Expr * E)3596*67e74705SXin Li static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3597*67e74705SXin Li                                      Expr *E) {
3598*67e74705SXin Li   // Don't warn if the operation changed the type.
3599*67e74705SXin Li   if (T != E->getType())
3600*67e74705SXin Li     return;
3601*67e74705SXin Li 
3602*67e74705SXin Li   // Now look for array decays.
3603*67e74705SXin Li   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3604*67e74705SXin Li   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3605*67e74705SXin Li     return;
3606*67e74705SXin Li 
3607*67e74705SXin Li   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3608*67e74705SXin Li                                              << ICE->getType()
3609*67e74705SXin Li                                              << ICE->getSubExpr()->getType();
3610*67e74705SXin Li }
3611*67e74705SXin Li 
3612*67e74705SXin Li /// \brief Check the constraints on expression operands to unary type expression
3613*67e74705SXin Li /// and type traits.
3614*67e74705SXin Li ///
3615*67e74705SXin Li /// Completes any types necessary and validates the constraints on the operand
3616*67e74705SXin Li /// expression. The logic mostly mirrors the type-based overload, but may modify
3617*67e74705SXin Li /// the expression as it completes the type for that expression through template
3618*67e74705SXin Li /// instantiation, etc.
CheckUnaryExprOrTypeTraitOperand(Expr * E,UnaryExprOrTypeTrait ExprKind)3619*67e74705SXin Li bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3620*67e74705SXin Li                                             UnaryExprOrTypeTrait ExprKind) {
3621*67e74705SXin Li   QualType ExprTy = E->getType();
3622*67e74705SXin Li   assert(!ExprTy->isReferenceType());
3623*67e74705SXin Li 
3624*67e74705SXin Li   if (ExprKind == UETT_VecStep)
3625*67e74705SXin Li     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3626*67e74705SXin Li                                         E->getSourceRange());
3627*67e74705SXin Li 
3628*67e74705SXin Li   // Whitelist some types as extensions
3629*67e74705SXin Li   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3630*67e74705SXin Li                                       E->getSourceRange(), ExprKind))
3631*67e74705SXin Li     return false;
3632*67e74705SXin Li 
3633*67e74705SXin Li   // 'alignof' applied to an expression only requires the base element type of
3634*67e74705SXin Li   // the expression to be complete. 'sizeof' requires the expression's type to
3635*67e74705SXin Li   // be complete (and will attempt to complete it if it's an array of unknown
3636*67e74705SXin Li   // bound).
3637*67e74705SXin Li   if (ExprKind == UETT_AlignOf) {
3638*67e74705SXin Li     if (RequireCompleteType(E->getExprLoc(),
3639*67e74705SXin Li                             Context.getBaseElementType(E->getType()),
3640*67e74705SXin Li                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3641*67e74705SXin Li                             E->getSourceRange()))
3642*67e74705SXin Li       return true;
3643*67e74705SXin Li   } else {
3644*67e74705SXin Li     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3645*67e74705SXin Li                                 ExprKind, E->getSourceRange()))
3646*67e74705SXin Li       return true;
3647*67e74705SXin Li   }
3648*67e74705SXin Li 
3649*67e74705SXin Li   // Completing the expression's type may have changed it.
3650*67e74705SXin Li   ExprTy = E->getType();
3651*67e74705SXin Li   assert(!ExprTy->isReferenceType());
3652*67e74705SXin Li 
3653*67e74705SXin Li   if (ExprTy->isFunctionType()) {
3654*67e74705SXin Li     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3655*67e74705SXin Li       << ExprKind << E->getSourceRange();
3656*67e74705SXin Li     return true;
3657*67e74705SXin Li   }
3658*67e74705SXin Li 
3659*67e74705SXin Li   // The operand for sizeof and alignof is in an unevaluated expression context,
3660*67e74705SXin Li   // so side effects could result in unintended consequences.
3661*67e74705SXin Li   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3662*67e74705SXin Li       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3663*67e74705SXin Li     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3664*67e74705SXin Li 
3665*67e74705SXin Li   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3666*67e74705SXin Li                                        E->getSourceRange(), ExprKind))
3667*67e74705SXin Li     return true;
3668*67e74705SXin Li 
3669*67e74705SXin Li   if (ExprKind == UETT_SizeOf) {
3670*67e74705SXin Li     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3671*67e74705SXin Li       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3672*67e74705SXin Li         QualType OType = PVD->getOriginalType();
3673*67e74705SXin Li         QualType Type = PVD->getType();
3674*67e74705SXin Li         if (Type->isPointerType() && OType->isArrayType()) {
3675*67e74705SXin Li           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3676*67e74705SXin Li             << Type << OType;
3677*67e74705SXin Li           Diag(PVD->getLocation(), diag::note_declared_at);
3678*67e74705SXin Li         }
3679*67e74705SXin Li       }
3680*67e74705SXin Li     }
3681*67e74705SXin Li 
3682*67e74705SXin Li     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3683*67e74705SXin Li     // decays into a pointer and returns an unintended result. This is most
3684*67e74705SXin Li     // likely a typo for "sizeof(array) op x".
3685*67e74705SXin Li     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3686*67e74705SXin Li       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3687*67e74705SXin Li                                BO->getLHS());
3688*67e74705SXin Li       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3689*67e74705SXin Li                                BO->getRHS());
3690*67e74705SXin Li     }
3691*67e74705SXin Li   }
3692*67e74705SXin Li 
3693*67e74705SXin Li   return false;
3694*67e74705SXin Li }
3695*67e74705SXin Li 
3696*67e74705SXin Li /// \brief Check the constraints on operands to unary expression and type
3697*67e74705SXin Li /// traits.
3698*67e74705SXin Li ///
3699*67e74705SXin Li /// This will complete any types necessary, and validate the various constraints
3700*67e74705SXin Li /// on those operands.
3701*67e74705SXin Li ///
3702*67e74705SXin Li /// The UsualUnaryConversions() function is *not* called by this routine.
3703*67e74705SXin Li /// C99 6.3.2.1p[2-4] all state:
3704*67e74705SXin Li ///   Except when it is the operand of the sizeof operator ...
3705*67e74705SXin Li ///
3706*67e74705SXin Li /// C++ [expr.sizeof]p4
3707*67e74705SXin Li ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3708*67e74705SXin Li ///   standard conversions are not applied to the operand of sizeof.
3709*67e74705SXin Li ///
3710*67e74705SXin Li /// This policy is followed for all of the unary trait expressions.
CheckUnaryExprOrTypeTraitOperand(QualType ExprType,SourceLocation OpLoc,SourceRange ExprRange,UnaryExprOrTypeTrait ExprKind)3711*67e74705SXin Li bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3712*67e74705SXin Li                                             SourceLocation OpLoc,
3713*67e74705SXin Li                                             SourceRange ExprRange,
3714*67e74705SXin Li                                             UnaryExprOrTypeTrait ExprKind) {
3715*67e74705SXin Li   if (ExprType->isDependentType())
3716*67e74705SXin Li     return false;
3717*67e74705SXin Li 
3718*67e74705SXin Li   // C++ [expr.sizeof]p2:
3719*67e74705SXin Li   //     When applied to a reference or a reference type, the result
3720*67e74705SXin Li   //     is the size of the referenced type.
3721*67e74705SXin Li   // C++11 [expr.alignof]p3:
3722*67e74705SXin Li   //     When alignof is applied to a reference type, the result
3723*67e74705SXin Li   //     shall be the alignment of the referenced type.
3724*67e74705SXin Li   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3725*67e74705SXin Li     ExprType = Ref->getPointeeType();
3726*67e74705SXin Li 
3727*67e74705SXin Li   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3728*67e74705SXin Li   //   When alignof or _Alignof is applied to an array type, the result
3729*67e74705SXin Li   //   is the alignment of the element type.
3730*67e74705SXin Li   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3731*67e74705SXin Li     ExprType = Context.getBaseElementType(ExprType);
3732*67e74705SXin Li 
3733*67e74705SXin Li   if (ExprKind == UETT_VecStep)
3734*67e74705SXin Li     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3735*67e74705SXin Li 
3736*67e74705SXin Li   // Whitelist some types as extensions
3737*67e74705SXin Li   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3738*67e74705SXin Li                                       ExprKind))
3739*67e74705SXin Li     return false;
3740*67e74705SXin Li 
3741*67e74705SXin Li   if (RequireCompleteType(OpLoc, ExprType,
3742*67e74705SXin Li                           diag::err_sizeof_alignof_incomplete_type,
3743*67e74705SXin Li                           ExprKind, ExprRange))
3744*67e74705SXin Li     return true;
3745*67e74705SXin Li 
3746*67e74705SXin Li   if (ExprType->isFunctionType()) {
3747*67e74705SXin Li     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3748*67e74705SXin Li       << ExprKind << ExprRange;
3749*67e74705SXin Li     return true;
3750*67e74705SXin Li   }
3751*67e74705SXin Li 
3752*67e74705SXin Li   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3753*67e74705SXin Li                                        ExprKind))
3754*67e74705SXin Li     return true;
3755*67e74705SXin Li 
3756*67e74705SXin Li   return false;
3757*67e74705SXin Li }
3758*67e74705SXin Li 
CheckAlignOfExpr(Sema & S,Expr * E)3759*67e74705SXin Li static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3760*67e74705SXin Li   E = E->IgnoreParens();
3761*67e74705SXin Li 
3762*67e74705SXin Li   // Cannot know anything else if the expression is dependent.
3763*67e74705SXin Li   if (E->isTypeDependent())
3764*67e74705SXin Li     return false;
3765*67e74705SXin Li 
3766*67e74705SXin Li   if (E->getObjectKind() == OK_BitField) {
3767*67e74705SXin Li     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3768*67e74705SXin Li        << 1 << E->getSourceRange();
3769*67e74705SXin Li     return true;
3770*67e74705SXin Li   }
3771*67e74705SXin Li 
3772*67e74705SXin Li   ValueDecl *D = nullptr;
3773*67e74705SXin Li   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3774*67e74705SXin Li     D = DRE->getDecl();
3775*67e74705SXin Li   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3776*67e74705SXin Li     D = ME->getMemberDecl();
3777*67e74705SXin Li   }
3778*67e74705SXin Li 
3779*67e74705SXin Li   // If it's a field, require the containing struct to have a
3780*67e74705SXin Li   // complete definition so that we can compute the layout.
3781*67e74705SXin Li   //
3782*67e74705SXin Li   // This can happen in C++11 onwards, either by naming the member
3783*67e74705SXin Li   // in a way that is not transformed into a member access expression
3784*67e74705SXin Li   // (in an unevaluated operand, for instance), or by naming the member
3785*67e74705SXin Li   // in a trailing-return-type.
3786*67e74705SXin Li   //
3787*67e74705SXin Li   // For the record, since __alignof__ on expressions is a GCC
3788*67e74705SXin Li   // extension, GCC seems to permit this but always gives the
3789*67e74705SXin Li   // nonsensical answer 0.
3790*67e74705SXin Li   //
3791*67e74705SXin Li   // We don't really need the layout here --- we could instead just
3792*67e74705SXin Li   // directly check for all the appropriate alignment-lowing
3793*67e74705SXin Li   // attributes --- but that would require duplicating a lot of
3794*67e74705SXin Li   // logic that just isn't worth duplicating for such a marginal
3795*67e74705SXin Li   // use-case.
3796*67e74705SXin Li   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3797*67e74705SXin Li     // Fast path this check, since we at least know the record has a
3798*67e74705SXin Li     // definition if we can find a member of it.
3799*67e74705SXin Li     if (!FD->getParent()->isCompleteDefinition()) {
3800*67e74705SXin Li       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3801*67e74705SXin Li         << E->getSourceRange();
3802*67e74705SXin Li       return true;
3803*67e74705SXin Li     }
3804*67e74705SXin Li 
3805*67e74705SXin Li     // Otherwise, if it's a field, and the field doesn't have
3806*67e74705SXin Li     // reference type, then it must have a complete type (or be a
3807*67e74705SXin Li     // flexible array member, which we explicitly want to
3808*67e74705SXin Li     // white-list anyway), which makes the following checks trivial.
3809*67e74705SXin Li     if (!FD->getType()->isReferenceType())
3810*67e74705SXin Li       return false;
3811*67e74705SXin Li   }
3812*67e74705SXin Li 
3813*67e74705SXin Li   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3814*67e74705SXin Li }
3815*67e74705SXin Li 
CheckVecStepExpr(Expr * E)3816*67e74705SXin Li bool Sema::CheckVecStepExpr(Expr *E) {
3817*67e74705SXin Li   E = E->IgnoreParens();
3818*67e74705SXin Li 
3819*67e74705SXin Li   // Cannot know anything else if the expression is dependent.
3820*67e74705SXin Li   if (E->isTypeDependent())
3821*67e74705SXin Li     return false;
3822*67e74705SXin Li 
3823*67e74705SXin Li   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3824*67e74705SXin Li }
3825*67e74705SXin Li 
captureVariablyModifiedType(ASTContext & Context,QualType T,CapturingScopeInfo * CSI)3826*67e74705SXin Li static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3827*67e74705SXin Li                                         CapturingScopeInfo *CSI) {
3828*67e74705SXin Li   assert(T->isVariablyModifiedType());
3829*67e74705SXin Li   assert(CSI != nullptr);
3830*67e74705SXin Li 
3831*67e74705SXin Li   // We're going to walk down into the type and look for VLA expressions.
3832*67e74705SXin Li   do {
3833*67e74705SXin Li     const Type *Ty = T.getTypePtr();
3834*67e74705SXin Li     switch (Ty->getTypeClass()) {
3835*67e74705SXin Li #define TYPE(Class, Base)
3836*67e74705SXin Li #define ABSTRACT_TYPE(Class, Base)
3837*67e74705SXin Li #define NON_CANONICAL_TYPE(Class, Base)
3838*67e74705SXin Li #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3839*67e74705SXin Li #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3840*67e74705SXin Li #include "clang/AST/TypeNodes.def"
3841*67e74705SXin Li       T = QualType();
3842*67e74705SXin Li       break;
3843*67e74705SXin Li     // These types are never variably-modified.
3844*67e74705SXin Li     case Type::Builtin:
3845*67e74705SXin Li     case Type::Complex:
3846*67e74705SXin Li     case Type::Vector:
3847*67e74705SXin Li     case Type::ExtVector:
3848*67e74705SXin Li     case Type::Record:
3849*67e74705SXin Li     case Type::Enum:
3850*67e74705SXin Li     case Type::Elaborated:
3851*67e74705SXin Li     case Type::TemplateSpecialization:
3852*67e74705SXin Li     case Type::ObjCObject:
3853*67e74705SXin Li     case Type::ObjCInterface:
3854*67e74705SXin Li     case Type::ObjCObjectPointer:
3855*67e74705SXin Li     case Type::Pipe:
3856*67e74705SXin Li       llvm_unreachable("type class is never variably-modified!");
3857*67e74705SXin Li     case Type::Adjusted:
3858*67e74705SXin Li       T = cast<AdjustedType>(Ty)->getOriginalType();
3859*67e74705SXin Li       break;
3860*67e74705SXin Li     case Type::Decayed:
3861*67e74705SXin Li       T = cast<DecayedType>(Ty)->getPointeeType();
3862*67e74705SXin Li       break;
3863*67e74705SXin Li     case Type::Pointer:
3864*67e74705SXin Li       T = cast<PointerType>(Ty)->getPointeeType();
3865*67e74705SXin Li       break;
3866*67e74705SXin Li     case Type::BlockPointer:
3867*67e74705SXin Li       T = cast<BlockPointerType>(Ty)->getPointeeType();
3868*67e74705SXin Li       break;
3869*67e74705SXin Li     case Type::LValueReference:
3870*67e74705SXin Li     case Type::RValueReference:
3871*67e74705SXin Li       T = cast<ReferenceType>(Ty)->getPointeeType();
3872*67e74705SXin Li       break;
3873*67e74705SXin Li     case Type::MemberPointer:
3874*67e74705SXin Li       T = cast<MemberPointerType>(Ty)->getPointeeType();
3875*67e74705SXin Li       break;
3876*67e74705SXin Li     case Type::ConstantArray:
3877*67e74705SXin Li     case Type::IncompleteArray:
3878*67e74705SXin Li       // Losing element qualification here is fine.
3879*67e74705SXin Li       T = cast<ArrayType>(Ty)->getElementType();
3880*67e74705SXin Li       break;
3881*67e74705SXin Li     case Type::VariableArray: {
3882*67e74705SXin Li       // Losing element qualification here is fine.
3883*67e74705SXin Li       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3884*67e74705SXin Li 
3885*67e74705SXin Li       // Unknown size indication requires no size computation.
3886*67e74705SXin Li       // Otherwise, evaluate and record it.
3887*67e74705SXin Li       if (auto Size = VAT->getSizeExpr()) {
3888*67e74705SXin Li         if (!CSI->isVLATypeCaptured(VAT)) {
3889*67e74705SXin Li           RecordDecl *CapRecord = nullptr;
3890*67e74705SXin Li           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3891*67e74705SXin Li             CapRecord = LSI->Lambda;
3892*67e74705SXin Li           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3893*67e74705SXin Li             CapRecord = CRSI->TheRecordDecl;
3894*67e74705SXin Li           }
3895*67e74705SXin Li           if (CapRecord) {
3896*67e74705SXin Li             auto ExprLoc = Size->getExprLoc();
3897*67e74705SXin Li             auto SizeType = Context.getSizeType();
3898*67e74705SXin Li             // Build the non-static data member.
3899*67e74705SXin Li             auto Field =
3900*67e74705SXin Li                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3901*67e74705SXin Li                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3902*67e74705SXin Li                                   /*BW*/ nullptr, /*Mutable*/ false,
3903*67e74705SXin Li                                   /*InitStyle*/ ICIS_NoInit);
3904*67e74705SXin Li             Field->setImplicit(true);
3905*67e74705SXin Li             Field->setAccess(AS_private);
3906*67e74705SXin Li             Field->setCapturedVLAType(VAT);
3907*67e74705SXin Li             CapRecord->addDecl(Field);
3908*67e74705SXin Li 
3909*67e74705SXin Li             CSI->addVLATypeCapture(ExprLoc, SizeType);
3910*67e74705SXin Li           }
3911*67e74705SXin Li         }
3912*67e74705SXin Li       }
3913*67e74705SXin Li       T = VAT->getElementType();
3914*67e74705SXin Li       break;
3915*67e74705SXin Li     }
3916*67e74705SXin Li     case Type::FunctionProto:
3917*67e74705SXin Li     case Type::FunctionNoProto:
3918*67e74705SXin Li       T = cast<FunctionType>(Ty)->getReturnType();
3919*67e74705SXin Li       break;
3920*67e74705SXin Li     case Type::Paren:
3921*67e74705SXin Li     case Type::TypeOf:
3922*67e74705SXin Li     case Type::UnaryTransform:
3923*67e74705SXin Li     case Type::Attributed:
3924*67e74705SXin Li     case Type::SubstTemplateTypeParm:
3925*67e74705SXin Li     case Type::PackExpansion:
3926*67e74705SXin Li       // Keep walking after single level desugaring.
3927*67e74705SXin Li       T = T.getSingleStepDesugaredType(Context);
3928*67e74705SXin Li       break;
3929*67e74705SXin Li     case Type::Typedef:
3930*67e74705SXin Li       T = cast<TypedefType>(Ty)->desugar();
3931*67e74705SXin Li       break;
3932*67e74705SXin Li     case Type::Decltype:
3933*67e74705SXin Li       T = cast<DecltypeType>(Ty)->desugar();
3934*67e74705SXin Li       break;
3935*67e74705SXin Li     case Type::Auto:
3936*67e74705SXin Li       T = cast<AutoType>(Ty)->getDeducedType();
3937*67e74705SXin Li       break;
3938*67e74705SXin Li     case Type::TypeOfExpr:
3939*67e74705SXin Li       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3940*67e74705SXin Li       break;
3941*67e74705SXin Li     case Type::Atomic:
3942*67e74705SXin Li       T = cast<AtomicType>(Ty)->getValueType();
3943*67e74705SXin Li       break;
3944*67e74705SXin Li     }
3945*67e74705SXin Li   } while (!T.isNull() && T->isVariablyModifiedType());
3946*67e74705SXin Li }
3947*67e74705SXin Li 
3948*67e74705SXin Li /// \brief Build a sizeof or alignof expression given a type operand.
3949*67e74705SXin Li ExprResult
CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo * TInfo,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,SourceRange R)3950*67e74705SXin Li Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3951*67e74705SXin Li                                      SourceLocation OpLoc,
3952*67e74705SXin Li                                      UnaryExprOrTypeTrait ExprKind,
3953*67e74705SXin Li                                      SourceRange R) {
3954*67e74705SXin Li   if (!TInfo)
3955*67e74705SXin Li     return ExprError();
3956*67e74705SXin Li 
3957*67e74705SXin Li   QualType T = TInfo->getType();
3958*67e74705SXin Li 
3959*67e74705SXin Li   if (!T->isDependentType() &&
3960*67e74705SXin Li       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3961*67e74705SXin Li     return ExprError();
3962*67e74705SXin Li 
3963*67e74705SXin Li   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3964*67e74705SXin Li     if (auto *TT = T->getAs<TypedefType>()) {
3965*67e74705SXin Li       for (auto I = FunctionScopes.rbegin(),
3966*67e74705SXin Li                 E = std::prev(FunctionScopes.rend());
3967*67e74705SXin Li            I != E; ++I) {
3968*67e74705SXin Li         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3969*67e74705SXin Li         if (CSI == nullptr)
3970*67e74705SXin Li           break;
3971*67e74705SXin Li         DeclContext *DC = nullptr;
3972*67e74705SXin Li         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3973*67e74705SXin Li           DC = LSI->CallOperator;
3974*67e74705SXin Li         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3975*67e74705SXin Li           DC = CRSI->TheCapturedDecl;
3976*67e74705SXin Li         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3977*67e74705SXin Li           DC = BSI->TheDecl;
3978*67e74705SXin Li         if (DC) {
3979*67e74705SXin Li           if (DC->containsDecl(TT->getDecl()))
3980*67e74705SXin Li             break;
3981*67e74705SXin Li           captureVariablyModifiedType(Context, T, CSI);
3982*67e74705SXin Li         }
3983*67e74705SXin Li       }
3984*67e74705SXin Li     }
3985*67e74705SXin Li   }
3986*67e74705SXin Li 
3987*67e74705SXin Li   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3988*67e74705SXin Li   return new (Context) UnaryExprOrTypeTraitExpr(
3989*67e74705SXin Li       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3990*67e74705SXin Li }
3991*67e74705SXin Li 
3992*67e74705SXin Li /// \brief Build a sizeof or alignof expression given an expression
3993*67e74705SXin Li /// operand.
3994*67e74705SXin Li ExprResult
CreateUnaryExprOrTypeTraitExpr(Expr * E,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind)3995*67e74705SXin Li Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3996*67e74705SXin Li                                      UnaryExprOrTypeTrait ExprKind) {
3997*67e74705SXin Li   ExprResult PE = CheckPlaceholderExpr(E);
3998*67e74705SXin Li   if (PE.isInvalid())
3999*67e74705SXin Li     return ExprError();
4000*67e74705SXin Li 
4001*67e74705SXin Li   E = PE.get();
4002*67e74705SXin Li 
4003*67e74705SXin Li   // Verify that the operand is valid.
4004*67e74705SXin Li   bool isInvalid = false;
4005*67e74705SXin Li   if (E->isTypeDependent()) {
4006*67e74705SXin Li     // Delay type-checking for type-dependent expressions.
4007*67e74705SXin Li   } else if (ExprKind == UETT_AlignOf) {
4008*67e74705SXin Li     isInvalid = CheckAlignOfExpr(*this, E);
4009*67e74705SXin Li   } else if (ExprKind == UETT_VecStep) {
4010*67e74705SXin Li     isInvalid = CheckVecStepExpr(E);
4011*67e74705SXin Li   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4012*67e74705SXin Li       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4013*67e74705SXin Li       isInvalid = true;
4014*67e74705SXin Li   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4015*67e74705SXin Li     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4016*67e74705SXin Li     isInvalid = true;
4017*67e74705SXin Li   } else {
4018*67e74705SXin Li     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4019*67e74705SXin Li   }
4020*67e74705SXin Li 
4021*67e74705SXin Li   if (isInvalid)
4022*67e74705SXin Li     return ExprError();
4023*67e74705SXin Li 
4024*67e74705SXin Li   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4025*67e74705SXin Li     PE = TransformToPotentiallyEvaluated(E);
4026*67e74705SXin Li     if (PE.isInvalid()) return ExprError();
4027*67e74705SXin Li     E = PE.get();
4028*67e74705SXin Li   }
4029*67e74705SXin Li 
4030*67e74705SXin Li   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4031*67e74705SXin Li   return new (Context) UnaryExprOrTypeTraitExpr(
4032*67e74705SXin Li       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4033*67e74705SXin Li }
4034*67e74705SXin Li 
4035*67e74705SXin Li /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4036*67e74705SXin Li /// expr and the same for @c alignof and @c __alignof
4037*67e74705SXin Li /// Note that the ArgRange is invalid if isType is false.
4038*67e74705SXin Li ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,bool IsType,void * TyOrEx,SourceRange ArgRange)4039*67e74705SXin Li Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4040*67e74705SXin Li                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4041*67e74705SXin Li                                     void *TyOrEx, SourceRange ArgRange) {
4042*67e74705SXin Li   // If error parsing type, ignore.
4043*67e74705SXin Li   if (!TyOrEx) return ExprError();
4044*67e74705SXin Li 
4045*67e74705SXin Li   if (IsType) {
4046*67e74705SXin Li     TypeSourceInfo *TInfo;
4047*67e74705SXin Li     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4048*67e74705SXin Li     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4049*67e74705SXin Li   }
4050*67e74705SXin Li 
4051*67e74705SXin Li   Expr *ArgEx = (Expr *)TyOrEx;
4052*67e74705SXin Li   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4053*67e74705SXin Li   return Result;
4054*67e74705SXin Li }
4055*67e74705SXin Li 
CheckRealImagOperand(Sema & S,ExprResult & V,SourceLocation Loc,bool IsReal)4056*67e74705SXin Li static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4057*67e74705SXin Li                                      bool IsReal) {
4058*67e74705SXin Li   if (V.get()->isTypeDependent())
4059*67e74705SXin Li     return S.Context.DependentTy;
4060*67e74705SXin Li 
4061*67e74705SXin Li   // _Real and _Imag are only l-values for normal l-values.
4062*67e74705SXin Li   if (V.get()->getObjectKind() != OK_Ordinary) {
4063*67e74705SXin Li     V = S.DefaultLvalueConversion(V.get());
4064*67e74705SXin Li     if (V.isInvalid())
4065*67e74705SXin Li       return QualType();
4066*67e74705SXin Li   }
4067*67e74705SXin Li 
4068*67e74705SXin Li   // These operators return the element type of a complex type.
4069*67e74705SXin Li   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4070*67e74705SXin Li     return CT->getElementType();
4071*67e74705SXin Li 
4072*67e74705SXin Li   // Otherwise they pass through real integer and floating point types here.
4073*67e74705SXin Li   if (V.get()->getType()->isArithmeticType())
4074*67e74705SXin Li     return V.get()->getType();
4075*67e74705SXin Li 
4076*67e74705SXin Li   // Test for placeholders.
4077*67e74705SXin Li   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4078*67e74705SXin Li   if (PR.isInvalid()) return QualType();
4079*67e74705SXin Li   if (PR.get() != V.get()) {
4080*67e74705SXin Li     V = PR;
4081*67e74705SXin Li     return CheckRealImagOperand(S, V, Loc, IsReal);
4082*67e74705SXin Li   }
4083*67e74705SXin Li 
4084*67e74705SXin Li   // Reject anything else.
4085*67e74705SXin Li   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4086*67e74705SXin Li     << (IsReal ? "__real" : "__imag");
4087*67e74705SXin Li   return QualType();
4088*67e74705SXin Li }
4089*67e74705SXin Li 
4090*67e74705SXin Li 
4091*67e74705SXin Li 
4092*67e74705SXin Li ExprResult
ActOnPostfixUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Kind,Expr * Input)4093*67e74705SXin Li Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4094*67e74705SXin Li                           tok::TokenKind Kind, Expr *Input) {
4095*67e74705SXin Li   UnaryOperatorKind Opc;
4096*67e74705SXin Li   switch (Kind) {
4097*67e74705SXin Li   default: llvm_unreachable("Unknown unary op!");
4098*67e74705SXin Li   case tok::plusplus:   Opc = UO_PostInc; break;
4099*67e74705SXin Li   case tok::minusminus: Opc = UO_PostDec; break;
4100*67e74705SXin Li   }
4101*67e74705SXin Li 
4102*67e74705SXin Li   // Since this might is a postfix expression, get rid of ParenListExprs.
4103*67e74705SXin Li   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4104*67e74705SXin Li   if (Result.isInvalid()) return ExprError();
4105*67e74705SXin Li   Input = Result.get();
4106*67e74705SXin Li 
4107*67e74705SXin Li   return BuildUnaryOp(S, OpLoc, Opc, Input);
4108*67e74705SXin Li }
4109*67e74705SXin Li 
4110*67e74705SXin Li /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4111*67e74705SXin Li ///
4112*67e74705SXin Li /// \return true on error
checkArithmeticOnObjCPointer(Sema & S,SourceLocation opLoc,Expr * op)4113*67e74705SXin Li static bool checkArithmeticOnObjCPointer(Sema &S,
4114*67e74705SXin Li                                          SourceLocation opLoc,
4115*67e74705SXin Li                                          Expr *op) {
4116*67e74705SXin Li   assert(op->getType()->isObjCObjectPointerType());
4117*67e74705SXin Li   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4118*67e74705SXin Li       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4119*67e74705SXin Li     return false;
4120*67e74705SXin Li 
4121*67e74705SXin Li   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4122*67e74705SXin Li     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4123*67e74705SXin Li     << op->getSourceRange();
4124*67e74705SXin Li   return true;
4125*67e74705SXin Li }
4126*67e74705SXin Li 
isMSPropertySubscriptExpr(Sema & S,Expr * Base)4127*67e74705SXin Li static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4128*67e74705SXin Li   auto *BaseNoParens = Base->IgnoreParens();
4129*67e74705SXin Li   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4130*67e74705SXin Li     return MSProp->getPropertyDecl()->getType()->isArrayType();
4131*67e74705SXin Li   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4132*67e74705SXin Li }
4133*67e74705SXin Li 
4134*67e74705SXin Li ExprResult
ActOnArraySubscriptExpr(Scope * S,Expr * base,SourceLocation lbLoc,Expr * idx,SourceLocation rbLoc)4135*67e74705SXin Li Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4136*67e74705SXin Li                               Expr *idx, SourceLocation rbLoc) {
4137*67e74705SXin Li   if (base && !base->getType().isNull() &&
4138*67e74705SXin Li       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4139*67e74705SXin Li     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4140*67e74705SXin Li                                     /*Length=*/nullptr, rbLoc);
4141*67e74705SXin Li 
4142*67e74705SXin Li   // Since this might be a postfix expression, get rid of ParenListExprs.
4143*67e74705SXin Li   if (isa<ParenListExpr>(base)) {
4144*67e74705SXin Li     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4145*67e74705SXin Li     if (result.isInvalid()) return ExprError();
4146*67e74705SXin Li     base = result.get();
4147*67e74705SXin Li   }
4148*67e74705SXin Li 
4149*67e74705SXin Li   // Handle any non-overload placeholder types in the base and index
4150*67e74705SXin Li   // expressions.  We can't handle overloads here because the other
4151*67e74705SXin Li   // operand might be an overloadable type, in which case the overload
4152*67e74705SXin Li   // resolution for the operator overload should get the first crack
4153*67e74705SXin Li   // at the overload.
4154*67e74705SXin Li   bool IsMSPropertySubscript = false;
4155*67e74705SXin Li   if (base->getType()->isNonOverloadPlaceholderType()) {
4156*67e74705SXin Li     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4157*67e74705SXin Li     if (!IsMSPropertySubscript) {
4158*67e74705SXin Li       ExprResult result = CheckPlaceholderExpr(base);
4159*67e74705SXin Li       if (result.isInvalid())
4160*67e74705SXin Li         return ExprError();
4161*67e74705SXin Li       base = result.get();
4162*67e74705SXin Li     }
4163*67e74705SXin Li   }
4164*67e74705SXin Li   if (idx->getType()->isNonOverloadPlaceholderType()) {
4165*67e74705SXin Li     ExprResult result = CheckPlaceholderExpr(idx);
4166*67e74705SXin Li     if (result.isInvalid()) return ExprError();
4167*67e74705SXin Li     idx = result.get();
4168*67e74705SXin Li   }
4169*67e74705SXin Li 
4170*67e74705SXin Li   // Build an unanalyzed expression if either operand is type-dependent.
4171*67e74705SXin Li   if (getLangOpts().CPlusPlus &&
4172*67e74705SXin Li       (base->isTypeDependent() || idx->isTypeDependent())) {
4173*67e74705SXin Li     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4174*67e74705SXin Li                                             VK_LValue, OK_Ordinary, rbLoc);
4175*67e74705SXin Li   }
4176*67e74705SXin Li 
4177*67e74705SXin Li   // MSDN, property (C++)
4178*67e74705SXin Li   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4179*67e74705SXin Li   // This attribute can also be used in the declaration of an empty array in a
4180*67e74705SXin Li   // class or structure definition. For example:
4181*67e74705SXin Li   // __declspec(property(get=GetX, put=PutX)) int x[];
4182*67e74705SXin Li   // The above statement indicates that x[] can be used with one or more array
4183*67e74705SXin Li   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4184*67e74705SXin Li   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4185*67e74705SXin Li   if (IsMSPropertySubscript) {
4186*67e74705SXin Li     // Build MS property subscript expression if base is MS property reference
4187*67e74705SXin Li     // or MS property subscript.
4188*67e74705SXin Li     return new (Context) MSPropertySubscriptExpr(
4189*67e74705SXin Li         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4190*67e74705SXin Li   }
4191*67e74705SXin Li 
4192*67e74705SXin Li   // Use C++ overloaded-operator rules if either operand has record
4193*67e74705SXin Li   // type.  The spec says to do this if either type is *overloadable*,
4194*67e74705SXin Li   // but enum types can't declare subscript operators or conversion
4195*67e74705SXin Li   // operators, so there's nothing interesting for overload resolution
4196*67e74705SXin Li   // to do if there aren't any record types involved.
4197*67e74705SXin Li   //
4198*67e74705SXin Li   // ObjC pointers have their own subscripting logic that is not tied
4199*67e74705SXin Li   // to overload resolution and so should not take this path.
4200*67e74705SXin Li   if (getLangOpts().CPlusPlus &&
4201*67e74705SXin Li       (base->getType()->isRecordType() ||
4202*67e74705SXin Li        (!base->getType()->isObjCObjectPointerType() &&
4203*67e74705SXin Li         idx->getType()->isRecordType()))) {
4204*67e74705SXin Li     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4205*67e74705SXin Li   }
4206*67e74705SXin Li 
4207*67e74705SXin Li   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4208*67e74705SXin Li }
4209*67e74705SXin Li 
ActOnOMPArraySectionExpr(Expr * Base,SourceLocation LBLoc,Expr * LowerBound,SourceLocation ColonLoc,Expr * Length,SourceLocation RBLoc)4210*67e74705SXin Li ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4211*67e74705SXin Li                                           Expr *LowerBound,
4212*67e74705SXin Li                                           SourceLocation ColonLoc, Expr *Length,
4213*67e74705SXin Li                                           SourceLocation RBLoc) {
4214*67e74705SXin Li   if (Base->getType()->isPlaceholderType() &&
4215*67e74705SXin Li       !Base->getType()->isSpecificPlaceholderType(
4216*67e74705SXin Li           BuiltinType::OMPArraySection)) {
4217*67e74705SXin Li     ExprResult Result = CheckPlaceholderExpr(Base);
4218*67e74705SXin Li     if (Result.isInvalid())
4219*67e74705SXin Li       return ExprError();
4220*67e74705SXin Li     Base = Result.get();
4221*67e74705SXin Li   }
4222*67e74705SXin Li   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4223*67e74705SXin Li     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4224*67e74705SXin Li     if (Result.isInvalid())
4225*67e74705SXin Li       return ExprError();
4226*67e74705SXin Li     Result = DefaultLvalueConversion(Result.get());
4227*67e74705SXin Li     if (Result.isInvalid())
4228*67e74705SXin Li       return ExprError();
4229*67e74705SXin Li     LowerBound = Result.get();
4230*67e74705SXin Li   }
4231*67e74705SXin Li   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4232*67e74705SXin Li     ExprResult Result = CheckPlaceholderExpr(Length);
4233*67e74705SXin Li     if (Result.isInvalid())
4234*67e74705SXin Li       return ExprError();
4235*67e74705SXin Li     Result = DefaultLvalueConversion(Result.get());
4236*67e74705SXin Li     if (Result.isInvalid())
4237*67e74705SXin Li       return ExprError();
4238*67e74705SXin Li     Length = Result.get();
4239*67e74705SXin Li   }
4240*67e74705SXin Li 
4241*67e74705SXin Li   // Build an unanalyzed expression if either operand is type-dependent.
4242*67e74705SXin Li   if (Base->isTypeDependent() ||
4243*67e74705SXin Li       (LowerBound &&
4244*67e74705SXin Li        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4245*67e74705SXin Li       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4246*67e74705SXin Li     return new (Context)
4247*67e74705SXin Li         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4248*67e74705SXin Li                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4249*67e74705SXin Li   }
4250*67e74705SXin Li 
4251*67e74705SXin Li   // Perform default conversions.
4252*67e74705SXin Li   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4253*67e74705SXin Li   QualType ResultTy;
4254*67e74705SXin Li   if (OriginalTy->isAnyPointerType()) {
4255*67e74705SXin Li     ResultTy = OriginalTy->getPointeeType();
4256*67e74705SXin Li   } else if (OriginalTy->isArrayType()) {
4257*67e74705SXin Li     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4258*67e74705SXin Li   } else {
4259*67e74705SXin Li     return ExprError(
4260*67e74705SXin Li         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4261*67e74705SXin Li         << Base->getSourceRange());
4262*67e74705SXin Li   }
4263*67e74705SXin Li   // C99 6.5.2.1p1
4264*67e74705SXin Li   if (LowerBound) {
4265*67e74705SXin Li     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4266*67e74705SXin Li                                                       LowerBound);
4267*67e74705SXin Li     if (Res.isInvalid())
4268*67e74705SXin Li       return ExprError(Diag(LowerBound->getExprLoc(),
4269*67e74705SXin Li                             diag::err_omp_typecheck_section_not_integer)
4270*67e74705SXin Li                        << 0 << LowerBound->getSourceRange());
4271*67e74705SXin Li     LowerBound = Res.get();
4272*67e74705SXin Li 
4273*67e74705SXin Li     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4274*67e74705SXin Li         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4275*67e74705SXin Li       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4276*67e74705SXin Li           << 0 << LowerBound->getSourceRange();
4277*67e74705SXin Li   }
4278*67e74705SXin Li   if (Length) {
4279*67e74705SXin Li     auto Res =
4280*67e74705SXin Li         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4281*67e74705SXin Li     if (Res.isInvalid())
4282*67e74705SXin Li       return ExprError(Diag(Length->getExprLoc(),
4283*67e74705SXin Li                             diag::err_omp_typecheck_section_not_integer)
4284*67e74705SXin Li                        << 1 << Length->getSourceRange());
4285*67e74705SXin Li     Length = Res.get();
4286*67e74705SXin Li 
4287*67e74705SXin Li     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4288*67e74705SXin Li         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4289*67e74705SXin Li       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4290*67e74705SXin Li           << 1 << Length->getSourceRange();
4291*67e74705SXin Li   }
4292*67e74705SXin Li 
4293*67e74705SXin Li   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4294*67e74705SXin Li   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4295*67e74705SXin Li   // type. Note that functions are not objects, and that (in C99 parlance)
4296*67e74705SXin Li   // incomplete types are not object types.
4297*67e74705SXin Li   if (ResultTy->isFunctionType()) {
4298*67e74705SXin Li     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4299*67e74705SXin Li         << ResultTy << Base->getSourceRange();
4300*67e74705SXin Li     return ExprError();
4301*67e74705SXin Li   }
4302*67e74705SXin Li 
4303*67e74705SXin Li   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4304*67e74705SXin Li                           diag::err_omp_section_incomplete_type, Base))
4305*67e74705SXin Li     return ExprError();
4306*67e74705SXin Li 
4307*67e74705SXin Li   if (LowerBound) {
4308*67e74705SXin Li     llvm::APSInt LowerBoundValue;
4309*67e74705SXin Li     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4310*67e74705SXin Li       // OpenMP 4.0, [2.4 Array Sections]
4311*67e74705SXin Li       // The lower-bound and length must evaluate to non-negative integers.
4312*67e74705SXin Li       if (LowerBoundValue.isNegative()) {
4313*67e74705SXin Li         Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative)
4314*67e74705SXin Li             << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true)
4315*67e74705SXin Li             << LowerBound->getSourceRange();
4316*67e74705SXin Li         return ExprError();
4317*67e74705SXin Li       }
4318*67e74705SXin Li     }
4319*67e74705SXin Li   }
4320*67e74705SXin Li 
4321*67e74705SXin Li   if (Length) {
4322*67e74705SXin Li     llvm::APSInt LengthValue;
4323*67e74705SXin Li     if (Length->EvaluateAsInt(LengthValue, Context)) {
4324*67e74705SXin Li       // OpenMP 4.0, [2.4 Array Sections]
4325*67e74705SXin Li       // The lower-bound and length must evaluate to non-negative integers.
4326*67e74705SXin Li       if (LengthValue.isNegative()) {
4327*67e74705SXin Li         Diag(Length->getExprLoc(), diag::err_omp_section_negative)
4328*67e74705SXin Li             << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4329*67e74705SXin Li             << Length->getSourceRange();
4330*67e74705SXin Li         return ExprError();
4331*67e74705SXin Li       }
4332*67e74705SXin Li     }
4333*67e74705SXin Li   } else if (ColonLoc.isValid() &&
4334*67e74705SXin Li              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4335*67e74705SXin Li                                       !OriginalTy->isVariableArrayType()))) {
4336*67e74705SXin Li     // OpenMP 4.0, [2.4 Array Sections]
4337*67e74705SXin Li     // When the size of the array dimension is not known, the length must be
4338*67e74705SXin Li     // specified explicitly.
4339*67e74705SXin Li     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4340*67e74705SXin Li         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4341*67e74705SXin Li     return ExprError();
4342*67e74705SXin Li   }
4343*67e74705SXin Li 
4344*67e74705SXin Li   if (!Base->getType()->isSpecificPlaceholderType(
4345*67e74705SXin Li           BuiltinType::OMPArraySection)) {
4346*67e74705SXin Li     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4347*67e74705SXin Li     if (Result.isInvalid())
4348*67e74705SXin Li       return ExprError();
4349*67e74705SXin Li     Base = Result.get();
4350*67e74705SXin Li   }
4351*67e74705SXin Li   return new (Context)
4352*67e74705SXin Li       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4353*67e74705SXin Li                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4354*67e74705SXin Li }
4355*67e74705SXin Li 
4356*67e74705SXin Li ExprResult
CreateBuiltinArraySubscriptExpr(Expr * Base,SourceLocation LLoc,Expr * Idx,SourceLocation RLoc)4357*67e74705SXin Li Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4358*67e74705SXin Li                                       Expr *Idx, SourceLocation RLoc) {
4359*67e74705SXin Li   Expr *LHSExp = Base;
4360*67e74705SXin Li   Expr *RHSExp = Idx;
4361*67e74705SXin Li 
4362*67e74705SXin Li   // Perform default conversions.
4363*67e74705SXin Li   if (!LHSExp->getType()->getAs<VectorType>()) {
4364*67e74705SXin Li     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4365*67e74705SXin Li     if (Result.isInvalid())
4366*67e74705SXin Li       return ExprError();
4367*67e74705SXin Li     LHSExp = Result.get();
4368*67e74705SXin Li   }
4369*67e74705SXin Li   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4370*67e74705SXin Li   if (Result.isInvalid())
4371*67e74705SXin Li     return ExprError();
4372*67e74705SXin Li   RHSExp = Result.get();
4373*67e74705SXin Li 
4374*67e74705SXin Li   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4375*67e74705SXin Li   ExprValueKind VK = VK_LValue;
4376*67e74705SXin Li   ExprObjectKind OK = OK_Ordinary;
4377*67e74705SXin Li 
4378*67e74705SXin Li   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4379*67e74705SXin Li   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4380*67e74705SXin Li   // in the subscript position. As a result, we need to derive the array base
4381*67e74705SXin Li   // and index from the expression types.
4382*67e74705SXin Li   Expr *BaseExpr, *IndexExpr;
4383*67e74705SXin Li   QualType ResultType;
4384*67e74705SXin Li   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4385*67e74705SXin Li     BaseExpr = LHSExp;
4386*67e74705SXin Li     IndexExpr = RHSExp;
4387*67e74705SXin Li     ResultType = Context.DependentTy;
4388*67e74705SXin Li   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4389*67e74705SXin Li     BaseExpr = LHSExp;
4390*67e74705SXin Li     IndexExpr = RHSExp;
4391*67e74705SXin Li     ResultType = PTy->getPointeeType();
4392*67e74705SXin Li   } else if (const ObjCObjectPointerType *PTy =
4393*67e74705SXin Li                LHSTy->getAs<ObjCObjectPointerType>()) {
4394*67e74705SXin Li     BaseExpr = LHSExp;
4395*67e74705SXin Li     IndexExpr = RHSExp;
4396*67e74705SXin Li 
4397*67e74705SXin Li     // Use custom logic if this should be the pseudo-object subscript
4398*67e74705SXin Li     // expression.
4399*67e74705SXin Li     if (!LangOpts.isSubscriptPointerArithmetic())
4400*67e74705SXin Li       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4401*67e74705SXin Li                                           nullptr);
4402*67e74705SXin Li 
4403*67e74705SXin Li     ResultType = PTy->getPointeeType();
4404*67e74705SXin Li   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4405*67e74705SXin Li      // Handle the uncommon case of "123[Ptr]".
4406*67e74705SXin Li     BaseExpr = RHSExp;
4407*67e74705SXin Li     IndexExpr = LHSExp;
4408*67e74705SXin Li     ResultType = PTy->getPointeeType();
4409*67e74705SXin Li   } else if (const ObjCObjectPointerType *PTy =
4410*67e74705SXin Li                RHSTy->getAs<ObjCObjectPointerType>()) {
4411*67e74705SXin Li      // Handle the uncommon case of "123[Ptr]".
4412*67e74705SXin Li     BaseExpr = RHSExp;
4413*67e74705SXin Li     IndexExpr = LHSExp;
4414*67e74705SXin Li     ResultType = PTy->getPointeeType();
4415*67e74705SXin Li     if (!LangOpts.isSubscriptPointerArithmetic()) {
4416*67e74705SXin Li       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4417*67e74705SXin Li         << ResultType << BaseExpr->getSourceRange();
4418*67e74705SXin Li       return ExprError();
4419*67e74705SXin Li     }
4420*67e74705SXin Li   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4421*67e74705SXin Li     BaseExpr = LHSExp;    // vectors: V[123]
4422*67e74705SXin Li     IndexExpr = RHSExp;
4423*67e74705SXin Li     VK = LHSExp->getValueKind();
4424*67e74705SXin Li     if (VK != VK_RValue)
4425*67e74705SXin Li       OK = OK_VectorComponent;
4426*67e74705SXin Li 
4427*67e74705SXin Li     // FIXME: need to deal with const...
4428*67e74705SXin Li     ResultType = VTy->getElementType();
4429*67e74705SXin Li   } else if (LHSTy->isArrayType()) {
4430*67e74705SXin Li     // If we see an array that wasn't promoted by
4431*67e74705SXin Li     // DefaultFunctionArrayLvalueConversion, it must be an array that
4432*67e74705SXin Li     // wasn't promoted because of the C90 rule that doesn't
4433*67e74705SXin Li     // allow promoting non-lvalue arrays.  Warn, then
4434*67e74705SXin Li     // force the promotion here.
4435*67e74705SXin Li     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4436*67e74705SXin Li         LHSExp->getSourceRange();
4437*67e74705SXin Li     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4438*67e74705SXin Li                                CK_ArrayToPointerDecay).get();
4439*67e74705SXin Li     LHSTy = LHSExp->getType();
4440*67e74705SXin Li 
4441*67e74705SXin Li     BaseExpr = LHSExp;
4442*67e74705SXin Li     IndexExpr = RHSExp;
4443*67e74705SXin Li     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4444*67e74705SXin Li   } else if (RHSTy->isArrayType()) {
4445*67e74705SXin Li     // Same as previous, except for 123[f().a] case
4446*67e74705SXin Li     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4447*67e74705SXin Li         RHSExp->getSourceRange();
4448*67e74705SXin Li     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4449*67e74705SXin Li                                CK_ArrayToPointerDecay).get();
4450*67e74705SXin Li     RHSTy = RHSExp->getType();
4451*67e74705SXin Li 
4452*67e74705SXin Li     BaseExpr = RHSExp;
4453*67e74705SXin Li     IndexExpr = LHSExp;
4454*67e74705SXin Li     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4455*67e74705SXin Li   } else {
4456*67e74705SXin Li     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4457*67e74705SXin Li        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4458*67e74705SXin Li   }
4459*67e74705SXin Li   // C99 6.5.2.1p1
4460*67e74705SXin Li   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4461*67e74705SXin Li     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4462*67e74705SXin Li                      << IndexExpr->getSourceRange());
4463*67e74705SXin Li 
4464*67e74705SXin Li   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4465*67e74705SXin Li        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4466*67e74705SXin Li          && !IndexExpr->isTypeDependent())
4467*67e74705SXin Li     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4468*67e74705SXin Li 
4469*67e74705SXin Li   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4470*67e74705SXin Li   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4471*67e74705SXin Li   // type. Note that Functions are not objects, and that (in C99 parlance)
4472*67e74705SXin Li   // incomplete types are not object types.
4473*67e74705SXin Li   if (ResultType->isFunctionType()) {
4474*67e74705SXin Li     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4475*67e74705SXin Li       << ResultType << BaseExpr->getSourceRange();
4476*67e74705SXin Li     return ExprError();
4477*67e74705SXin Li   }
4478*67e74705SXin Li 
4479*67e74705SXin Li   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4480*67e74705SXin Li     // GNU extension: subscripting on pointer to void
4481*67e74705SXin Li     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4482*67e74705SXin Li       << BaseExpr->getSourceRange();
4483*67e74705SXin Li 
4484*67e74705SXin Li     // C forbids expressions of unqualified void type from being l-values.
4485*67e74705SXin Li     // See IsCForbiddenLValueType.
4486*67e74705SXin Li     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4487*67e74705SXin Li   } else if (!ResultType->isDependentType() &&
4488*67e74705SXin Li       RequireCompleteType(LLoc, ResultType,
4489*67e74705SXin Li                           diag::err_subscript_incomplete_type, BaseExpr))
4490*67e74705SXin Li     return ExprError();
4491*67e74705SXin Li 
4492*67e74705SXin Li   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4493*67e74705SXin Li          !ResultType.isCForbiddenLValueType());
4494*67e74705SXin Li 
4495*67e74705SXin Li   return new (Context)
4496*67e74705SXin Li       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4497*67e74705SXin Li }
4498*67e74705SXin Li 
BuildCXXDefaultArgExpr(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)4499*67e74705SXin Li ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4500*67e74705SXin Li                                         FunctionDecl *FD,
4501*67e74705SXin Li                                         ParmVarDecl *Param) {
4502*67e74705SXin Li   if (Param->hasUnparsedDefaultArg()) {
4503*67e74705SXin Li     Diag(CallLoc,
4504*67e74705SXin Li          diag::err_use_of_default_argument_to_function_declared_later) <<
4505*67e74705SXin Li       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4506*67e74705SXin Li     Diag(UnparsedDefaultArgLocs[Param],
4507*67e74705SXin Li          diag::note_default_argument_declared_here);
4508*67e74705SXin Li     return ExprError();
4509*67e74705SXin Li   }
4510*67e74705SXin Li 
4511*67e74705SXin Li   if (Param->hasUninstantiatedDefaultArg()) {
4512*67e74705SXin Li     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4513*67e74705SXin Li 
4514*67e74705SXin Li     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4515*67e74705SXin Li                                                  Param);
4516*67e74705SXin Li 
4517*67e74705SXin Li     // Instantiate the expression.
4518*67e74705SXin Li     MultiLevelTemplateArgumentList MutiLevelArgList
4519*67e74705SXin Li       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4520*67e74705SXin Li 
4521*67e74705SXin Li     InstantiatingTemplate Inst(*this, CallLoc, Param,
4522*67e74705SXin Li                                MutiLevelArgList.getInnermost());
4523*67e74705SXin Li     if (Inst.isInvalid())
4524*67e74705SXin Li       return ExprError();
4525*67e74705SXin Li 
4526*67e74705SXin Li     ExprResult Result;
4527*67e74705SXin Li     {
4528*67e74705SXin Li       // C++ [dcl.fct.default]p5:
4529*67e74705SXin Li       //   The names in the [default argument] expression are bound, and
4530*67e74705SXin Li       //   the semantic constraints are checked, at the point where the
4531*67e74705SXin Li       //   default argument expression appears.
4532*67e74705SXin Li       ContextRAII SavedContext(*this, FD);
4533*67e74705SXin Li       LocalInstantiationScope Local(*this);
4534*67e74705SXin Li       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4535*67e74705SXin Li     }
4536*67e74705SXin Li     if (Result.isInvalid())
4537*67e74705SXin Li       return ExprError();
4538*67e74705SXin Li 
4539*67e74705SXin Li     // Check the expression as an initializer for the parameter.
4540*67e74705SXin Li     InitializedEntity Entity
4541*67e74705SXin Li       = InitializedEntity::InitializeParameter(Context, Param);
4542*67e74705SXin Li     InitializationKind Kind
4543*67e74705SXin Li       = InitializationKind::CreateCopy(Param->getLocation(),
4544*67e74705SXin Li              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4545*67e74705SXin Li     Expr *ResultE = Result.getAs<Expr>();
4546*67e74705SXin Li 
4547*67e74705SXin Li     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4548*67e74705SXin Li     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4549*67e74705SXin Li     if (Result.isInvalid())
4550*67e74705SXin Li       return ExprError();
4551*67e74705SXin Li 
4552*67e74705SXin Li     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4553*67e74705SXin Li                                  Param->getOuterLocStart());
4554*67e74705SXin Li     if (Result.isInvalid())
4555*67e74705SXin Li       return ExprError();
4556*67e74705SXin Li 
4557*67e74705SXin Li     // Remember the instantiated default argument.
4558*67e74705SXin Li     Param->setDefaultArg(Result.getAs<Expr>());
4559*67e74705SXin Li     if (ASTMutationListener *L = getASTMutationListener()) {
4560*67e74705SXin Li       L->DefaultArgumentInstantiated(Param);
4561*67e74705SXin Li     }
4562*67e74705SXin Li   }
4563*67e74705SXin Li 
4564*67e74705SXin Li   // If the default argument expression is not set yet, we are building it now.
4565*67e74705SXin Li   if (!Param->hasInit()) {
4566*67e74705SXin Li     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4567*67e74705SXin Li     Param->setInvalidDecl();
4568*67e74705SXin Li     return ExprError();
4569*67e74705SXin Li   }
4570*67e74705SXin Li 
4571*67e74705SXin Li   // If the default expression creates temporaries, we need to
4572*67e74705SXin Li   // push them to the current stack of expression temporaries so they'll
4573*67e74705SXin Li   // be properly destroyed.
4574*67e74705SXin Li   // FIXME: We should really be rebuilding the default argument with new
4575*67e74705SXin Li   // bound temporaries; see the comment in PR5810.
4576*67e74705SXin Li   // We don't need to do that with block decls, though, because
4577*67e74705SXin Li   // blocks in default argument expression can never capture anything.
4578*67e74705SXin Li   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4579*67e74705SXin Li     // Set the "needs cleanups" bit regardless of whether there are
4580*67e74705SXin Li     // any explicit objects.
4581*67e74705SXin Li     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4582*67e74705SXin Li 
4583*67e74705SXin Li     // Append all the objects to the cleanup list.  Right now, this
4584*67e74705SXin Li     // should always be a no-op, because blocks in default argument
4585*67e74705SXin Li     // expressions should never be able to capture anything.
4586*67e74705SXin Li     assert(!Init->getNumObjects() &&
4587*67e74705SXin Li            "default argument expression has capturing blocks?");
4588*67e74705SXin Li   }
4589*67e74705SXin Li 
4590*67e74705SXin Li   // We already type-checked the argument, so we know it works.
4591*67e74705SXin Li   // Just mark all of the declarations in this potentially-evaluated expression
4592*67e74705SXin Li   // as being "referenced".
4593*67e74705SXin Li   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4594*67e74705SXin Li                                    /*SkipLocalVariables=*/true);
4595*67e74705SXin Li   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4596*67e74705SXin Li }
4597*67e74705SXin Li 
4598*67e74705SXin Li 
4599*67e74705SXin Li Sema::VariadicCallType
getVariadicCallType(FunctionDecl * FDecl,const FunctionProtoType * Proto,Expr * Fn)4600*67e74705SXin Li Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4601*67e74705SXin Li                           Expr *Fn) {
4602*67e74705SXin Li   if (Proto && Proto->isVariadic()) {
4603*67e74705SXin Li     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4604*67e74705SXin Li       return VariadicConstructor;
4605*67e74705SXin Li     else if (Fn && Fn->getType()->isBlockPointerType())
4606*67e74705SXin Li       return VariadicBlock;
4607*67e74705SXin Li     else if (FDecl) {
4608*67e74705SXin Li       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4609*67e74705SXin Li         if (Method->isInstance())
4610*67e74705SXin Li           return VariadicMethod;
4611*67e74705SXin Li     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4612*67e74705SXin Li       return VariadicMethod;
4613*67e74705SXin Li     return VariadicFunction;
4614*67e74705SXin Li   }
4615*67e74705SXin Li   return VariadicDoesNotApply;
4616*67e74705SXin Li }
4617*67e74705SXin Li 
4618*67e74705SXin Li namespace {
4619*67e74705SXin Li class FunctionCallCCC : public FunctionCallFilterCCC {
4620*67e74705SXin Li public:
FunctionCallCCC(Sema & SemaRef,const IdentifierInfo * FuncName,unsigned NumArgs,MemberExpr * ME)4621*67e74705SXin Li   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4622*67e74705SXin Li                   unsigned NumArgs, MemberExpr *ME)
4623*67e74705SXin Li       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4624*67e74705SXin Li         FunctionName(FuncName) {}
4625*67e74705SXin Li 
ValidateCandidate(const TypoCorrection & candidate)4626*67e74705SXin Li   bool ValidateCandidate(const TypoCorrection &candidate) override {
4627*67e74705SXin Li     if (!candidate.getCorrectionSpecifier() ||
4628*67e74705SXin Li         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4629*67e74705SXin Li       return false;
4630*67e74705SXin Li     }
4631*67e74705SXin Li 
4632*67e74705SXin Li     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4633*67e74705SXin Li   }
4634*67e74705SXin Li 
4635*67e74705SXin Li private:
4636*67e74705SXin Li   const IdentifierInfo *const FunctionName;
4637*67e74705SXin Li };
4638*67e74705SXin Li }
4639*67e74705SXin Li 
TryTypoCorrectionForCall(Sema & S,Expr * Fn,FunctionDecl * FDecl,ArrayRef<Expr * > Args)4640*67e74705SXin Li static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4641*67e74705SXin Li                                                FunctionDecl *FDecl,
4642*67e74705SXin Li                                                ArrayRef<Expr *> Args) {
4643*67e74705SXin Li   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4644*67e74705SXin Li   DeclarationName FuncName = FDecl->getDeclName();
4645*67e74705SXin Li   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4646*67e74705SXin Li 
4647*67e74705SXin Li   if (TypoCorrection Corrected = S.CorrectTypo(
4648*67e74705SXin Li           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4649*67e74705SXin Li           S.getScopeForContext(S.CurContext), nullptr,
4650*67e74705SXin Li           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4651*67e74705SXin Li                                              Args.size(), ME),
4652*67e74705SXin Li           Sema::CTK_ErrorRecovery)) {
4653*67e74705SXin Li     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4654*67e74705SXin Li       if (Corrected.isOverloaded()) {
4655*67e74705SXin Li         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4656*67e74705SXin Li         OverloadCandidateSet::iterator Best;
4657*67e74705SXin Li         for (NamedDecl *CD : Corrected) {
4658*67e74705SXin Li           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4659*67e74705SXin Li             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4660*67e74705SXin Li                                    OCS);
4661*67e74705SXin Li         }
4662*67e74705SXin Li         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4663*67e74705SXin Li         case OR_Success:
4664*67e74705SXin Li           ND = Best->FoundDecl;
4665*67e74705SXin Li           Corrected.setCorrectionDecl(ND);
4666*67e74705SXin Li           break;
4667*67e74705SXin Li         default:
4668*67e74705SXin Li           break;
4669*67e74705SXin Li         }
4670*67e74705SXin Li       }
4671*67e74705SXin Li       ND = ND->getUnderlyingDecl();
4672*67e74705SXin Li       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4673*67e74705SXin Li         return Corrected;
4674*67e74705SXin Li     }
4675*67e74705SXin Li   }
4676*67e74705SXin Li   return TypoCorrection();
4677*67e74705SXin Li }
4678*67e74705SXin Li 
4679*67e74705SXin Li /// ConvertArgumentsForCall - Converts the arguments specified in
4680*67e74705SXin Li /// Args/NumArgs to the parameter types of the function FDecl with
4681*67e74705SXin Li /// function prototype Proto. Call is the call expression itself, and
4682*67e74705SXin Li /// Fn is the function expression. For a C++ member function, this
4683*67e74705SXin Li /// routine does not attempt to convert the object argument. Returns
4684*67e74705SXin Li /// true if the call is ill-formed.
4685*67e74705SXin Li bool
ConvertArgumentsForCall(CallExpr * Call,Expr * Fn,FunctionDecl * FDecl,const FunctionProtoType * Proto,ArrayRef<Expr * > Args,SourceLocation RParenLoc,bool IsExecConfig)4686*67e74705SXin Li Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4687*67e74705SXin Li                               FunctionDecl *FDecl,
4688*67e74705SXin Li                               const FunctionProtoType *Proto,
4689*67e74705SXin Li                               ArrayRef<Expr *> Args,
4690*67e74705SXin Li                               SourceLocation RParenLoc,
4691*67e74705SXin Li                               bool IsExecConfig) {
4692*67e74705SXin Li   // Bail out early if calling a builtin with custom typechecking.
4693*67e74705SXin Li   if (FDecl)
4694*67e74705SXin Li     if (unsigned ID = FDecl->getBuiltinID())
4695*67e74705SXin Li       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4696*67e74705SXin Li         return false;
4697*67e74705SXin Li 
4698*67e74705SXin Li   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4699*67e74705SXin Li   // assignment, to the types of the corresponding parameter, ...
4700*67e74705SXin Li   unsigned NumParams = Proto->getNumParams();
4701*67e74705SXin Li   bool Invalid = false;
4702*67e74705SXin Li   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4703*67e74705SXin Li   unsigned FnKind = Fn->getType()->isBlockPointerType()
4704*67e74705SXin Li                        ? 1 /* block */
4705*67e74705SXin Li                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4706*67e74705SXin Li                                        : 0 /* function */);
4707*67e74705SXin Li 
4708*67e74705SXin Li   // If too few arguments are available (and we don't have default
4709*67e74705SXin Li   // arguments for the remaining parameters), don't make the call.
4710*67e74705SXin Li   if (Args.size() < NumParams) {
4711*67e74705SXin Li     if (Args.size() < MinArgs) {
4712*67e74705SXin Li       TypoCorrection TC;
4713*67e74705SXin Li       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4714*67e74705SXin Li         unsigned diag_id =
4715*67e74705SXin Li             MinArgs == NumParams && !Proto->isVariadic()
4716*67e74705SXin Li                 ? diag::err_typecheck_call_too_few_args_suggest
4717*67e74705SXin Li                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4718*67e74705SXin Li         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4719*67e74705SXin Li                                         << static_cast<unsigned>(Args.size())
4720*67e74705SXin Li                                         << TC.getCorrectionRange());
4721*67e74705SXin Li       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4722*67e74705SXin Li         Diag(RParenLoc,
4723*67e74705SXin Li              MinArgs == NumParams && !Proto->isVariadic()
4724*67e74705SXin Li                  ? diag::err_typecheck_call_too_few_args_one
4725*67e74705SXin Li                  : diag::err_typecheck_call_too_few_args_at_least_one)
4726*67e74705SXin Li             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4727*67e74705SXin Li       else
4728*67e74705SXin Li         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4729*67e74705SXin Li                             ? diag::err_typecheck_call_too_few_args
4730*67e74705SXin Li                             : diag::err_typecheck_call_too_few_args_at_least)
4731*67e74705SXin Li             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4732*67e74705SXin Li             << Fn->getSourceRange();
4733*67e74705SXin Li 
4734*67e74705SXin Li       // Emit the location of the prototype.
4735*67e74705SXin Li       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4736*67e74705SXin Li         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4737*67e74705SXin Li           << FDecl;
4738*67e74705SXin Li 
4739*67e74705SXin Li       return true;
4740*67e74705SXin Li     }
4741*67e74705SXin Li     Call->setNumArgs(Context, NumParams);
4742*67e74705SXin Li   }
4743*67e74705SXin Li 
4744*67e74705SXin Li   // If too many are passed and not variadic, error on the extras and drop
4745*67e74705SXin Li   // them.
4746*67e74705SXin Li   if (Args.size() > NumParams) {
4747*67e74705SXin Li     if (!Proto->isVariadic()) {
4748*67e74705SXin Li       TypoCorrection TC;
4749*67e74705SXin Li       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4750*67e74705SXin Li         unsigned diag_id =
4751*67e74705SXin Li             MinArgs == NumParams && !Proto->isVariadic()
4752*67e74705SXin Li                 ? diag::err_typecheck_call_too_many_args_suggest
4753*67e74705SXin Li                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4754*67e74705SXin Li         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4755*67e74705SXin Li                                         << static_cast<unsigned>(Args.size())
4756*67e74705SXin Li                                         << TC.getCorrectionRange());
4757*67e74705SXin Li       } else if (NumParams == 1 && FDecl &&
4758*67e74705SXin Li                  FDecl->getParamDecl(0)->getDeclName())
4759*67e74705SXin Li         Diag(Args[NumParams]->getLocStart(),
4760*67e74705SXin Li              MinArgs == NumParams
4761*67e74705SXin Li                  ? diag::err_typecheck_call_too_many_args_one
4762*67e74705SXin Li                  : diag::err_typecheck_call_too_many_args_at_most_one)
4763*67e74705SXin Li             << FnKind << FDecl->getParamDecl(0)
4764*67e74705SXin Li             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4765*67e74705SXin Li             << SourceRange(Args[NumParams]->getLocStart(),
4766*67e74705SXin Li                            Args.back()->getLocEnd());
4767*67e74705SXin Li       else
4768*67e74705SXin Li         Diag(Args[NumParams]->getLocStart(),
4769*67e74705SXin Li              MinArgs == NumParams
4770*67e74705SXin Li                  ? diag::err_typecheck_call_too_many_args
4771*67e74705SXin Li                  : diag::err_typecheck_call_too_many_args_at_most)
4772*67e74705SXin Li             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4773*67e74705SXin Li             << Fn->getSourceRange()
4774*67e74705SXin Li             << SourceRange(Args[NumParams]->getLocStart(),
4775*67e74705SXin Li                            Args.back()->getLocEnd());
4776*67e74705SXin Li 
4777*67e74705SXin Li       // Emit the location of the prototype.
4778*67e74705SXin Li       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4779*67e74705SXin Li         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4780*67e74705SXin Li           << FDecl;
4781*67e74705SXin Li 
4782*67e74705SXin Li       // This deletes the extra arguments.
4783*67e74705SXin Li       Call->setNumArgs(Context, NumParams);
4784*67e74705SXin Li       return true;
4785*67e74705SXin Li     }
4786*67e74705SXin Li   }
4787*67e74705SXin Li   SmallVector<Expr *, 8> AllArgs;
4788*67e74705SXin Li   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4789*67e74705SXin Li 
4790*67e74705SXin Li   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4791*67e74705SXin Li                                    Proto, 0, Args, AllArgs, CallType);
4792*67e74705SXin Li   if (Invalid)
4793*67e74705SXin Li     return true;
4794*67e74705SXin Li   unsigned TotalNumArgs = AllArgs.size();
4795*67e74705SXin Li   for (unsigned i = 0; i < TotalNumArgs; ++i)
4796*67e74705SXin Li     Call->setArg(i, AllArgs[i]);
4797*67e74705SXin Li 
4798*67e74705SXin Li   return false;
4799*67e74705SXin Li }
4800*67e74705SXin Li 
GatherArgumentsForCall(SourceLocation CallLoc,FunctionDecl * FDecl,const FunctionProtoType * Proto,unsigned FirstParam,ArrayRef<Expr * > Args,SmallVectorImpl<Expr * > & AllArgs,VariadicCallType CallType,bool AllowExplicit,bool IsListInitialization)4801*67e74705SXin Li bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4802*67e74705SXin Li                                   const FunctionProtoType *Proto,
4803*67e74705SXin Li                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4804*67e74705SXin Li                                   SmallVectorImpl<Expr *> &AllArgs,
4805*67e74705SXin Li                                   VariadicCallType CallType, bool AllowExplicit,
4806*67e74705SXin Li                                   bool IsListInitialization) {
4807*67e74705SXin Li   unsigned NumParams = Proto->getNumParams();
4808*67e74705SXin Li   bool Invalid = false;
4809*67e74705SXin Li   size_t ArgIx = 0;
4810*67e74705SXin Li   // Continue to check argument types (even if we have too few/many args).
4811*67e74705SXin Li   for (unsigned i = FirstParam; i < NumParams; i++) {
4812*67e74705SXin Li     QualType ProtoArgType = Proto->getParamType(i);
4813*67e74705SXin Li 
4814*67e74705SXin Li     Expr *Arg;
4815*67e74705SXin Li     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4816*67e74705SXin Li     if (ArgIx < Args.size()) {
4817*67e74705SXin Li       Arg = Args[ArgIx++];
4818*67e74705SXin Li 
4819*67e74705SXin Li       if (RequireCompleteType(Arg->getLocStart(),
4820*67e74705SXin Li                               ProtoArgType,
4821*67e74705SXin Li                               diag::err_call_incomplete_argument, Arg))
4822*67e74705SXin Li         return true;
4823*67e74705SXin Li 
4824*67e74705SXin Li       // Strip the unbridged-cast placeholder expression off, if applicable.
4825*67e74705SXin Li       bool CFAudited = false;
4826*67e74705SXin Li       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4827*67e74705SXin Li           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4828*67e74705SXin Li           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4829*67e74705SXin Li         Arg = stripARCUnbridgedCast(Arg);
4830*67e74705SXin Li       else if (getLangOpts().ObjCAutoRefCount &&
4831*67e74705SXin Li                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4832*67e74705SXin Li                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4833*67e74705SXin Li         CFAudited = true;
4834*67e74705SXin Li 
4835*67e74705SXin Li       InitializedEntity Entity =
4836*67e74705SXin Li           Param ? InitializedEntity::InitializeParameter(Context, Param,
4837*67e74705SXin Li                                                          ProtoArgType)
4838*67e74705SXin Li                 : InitializedEntity::InitializeParameter(
4839*67e74705SXin Li                       Context, ProtoArgType, Proto->isParamConsumed(i));
4840*67e74705SXin Li 
4841*67e74705SXin Li       // Remember that parameter belongs to a CF audited API.
4842*67e74705SXin Li       if (CFAudited)
4843*67e74705SXin Li         Entity.setParameterCFAudited();
4844*67e74705SXin Li 
4845*67e74705SXin Li       ExprResult ArgE = PerformCopyInitialization(
4846*67e74705SXin Li           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4847*67e74705SXin Li       if (ArgE.isInvalid())
4848*67e74705SXin Li         return true;
4849*67e74705SXin Li 
4850*67e74705SXin Li       Arg = ArgE.getAs<Expr>();
4851*67e74705SXin Li     } else {
4852*67e74705SXin Li       assert(Param && "can't use default arguments without a known callee");
4853*67e74705SXin Li 
4854*67e74705SXin Li       ExprResult ArgExpr =
4855*67e74705SXin Li         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4856*67e74705SXin Li       if (ArgExpr.isInvalid())
4857*67e74705SXin Li         return true;
4858*67e74705SXin Li 
4859*67e74705SXin Li       Arg = ArgExpr.getAs<Expr>();
4860*67e74705SXin Li     }
4861*67e74705SXin Li 
4862*67e74705SXin Li     // Check for array bounds violations for each argument to the call. This
4863*67e74705SXin Li     // check only triggers warnings when the argument isn't a more complex Expr
4864*67e74705SXin Li     // with its own checking, such as a BinaryOperator.
4865*67e74705SXin Li     CheckArrayAccess(Arg);
4866*67e74705SXin Li 
4867*67e74705SXin Li     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4868*67e74705SXin Li     CheckStaticArrayArgument(CallLoc, Param, Arg);
4869*67e74705SXin Li 
4870*67e74705SXin Li     AllArgs.push_back(Arg);
4871*67e74705SXin Li   }
4872*67e74705SXin Li 
4873*67e74705SXin Li   // If this is a variadic call, handle args passed through "...".
4874*67e74705SXin Li   if (CallType != VariadicDoesNotApply) {
4875*67e74705SXin Li     // Assume that extern "C" functions with variadic arguments that
4876*67e74705SXin Li     // return __unknown_anytype aren't *really* variadic.
4877*67e74705SXin Li     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4878*67e74705SXin Li         FDecl->isExternC()) {
4879*67e74705SXin Li       for (Expr *A : Args.slice(ArgIx)) {
4880*67e74705SXin Li         QualType paramType; // ignored
4881*67e74705SXin Li         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4882*67e74705SXin Li         Invalid |= arg.isInvalid();
4883*67e74705SXin Li         AllArgs.push_back(arg.get());
4884*67e74705SXin Li       }
4885*67e74705SXin Li 
4886*67e74705SXin Li     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4887*67e74705SXin Li     } else {
4888*67e74705SXin Li       for (Expr *A : Args.slice(ArgIx)) {
4889*67e74705SXin Li         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4890*67e74705SXin Li         Invalid |= Arg.isInvalid();
4891*67e74705SXin Li         AllArgs.push_back(Arg.get());
4892*67e74705SXin Li       }
4893*67e74705SXin Li     }
4894*67e74705SXin Li 
4895*67e74705SXin Li     // Check for array bounds violations.
4896*67e74705SXin Li     for (Expr *A : Args.slice(ArgIx))
4897*67e74705SXin Li       CheckArrayAccess(A);
4898*67e74705SXin Li   }
4899*67e74705SXin Li   return Invalid;
4900*67e74705SXin Li }
4901*67e74705SXin Li 
DiagnoseCalleeStaticArrayParam(Sema & S,ParmVarDecl * PVD)4902*67e74705SXin Li static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4903*67e74705SXin Li   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4904*67e74705SXin Li   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4905*67e74705SXin Li     TL = DTL.getOriginalLoc();
4906*67e74705SXin Li   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4907*67e74705SXin Li     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4908*67e74705SXin Li       << ATL.getLocalSourceRange();
4909*67e74705SXin Li }
4910*67e74705SXin Li 
4911*67e74705SXin Li /// CheckStaticArrayArgument - If the given argument corresponds to a static
4912*67e74705SXin Li /// array parameter, check that it is non-null, and that if it is formed by
4913*67e74705SXin Li /// array-to-pointer decay, the underlying array is sufficiently large.
4914*67e74705SXin Li ///
4915*67e74705SXin Li /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4916*67e74705SXin Li /// array type derivation, then for each call to the function, the value of the
4917*67e74705SXin Li /// corresponding actual argument shall provide access to the first element of
4918*67e74705SXin Li /// an array with at least as many elements as specified by the size expression.
4919*67e74705SXin Li void
CheckStaticArrayArgument(SourceLocation CallLoc,ParmVarDecl * Param,const Expr * ArgExpr)4920*67e74705SXin Li Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4921*67e74705SXin Li                                ParmVarDecl *Param,
4922*67e74705SXin Li                                const Expr *ArgExpr) {
4923*67e74705SXin Li   // Static array parameters are not supported in C++.
4924*67e74705SXin Li   if (!Param || getLangOpts().CPlusPlus)
4925*67e74705SXin Li     return;
4926*67e74705SXin Li 
4927*67e74705SXin Li   QualType OrigTy = Param->getOriginalType();
4928*67e74705SXin Li 
4929*67e74705SXin Li   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4930*67e74705SXin Li   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4931*67e74705SXin Li     return;
4932*67e74705SXin Li 
4933*67e74705SXin Li   if (ArgExpr->isNullPointerConstant(Context,
4934*67e74705SXin Li                                      Expr::NPC_NeverValueDependent)) {
4935*67e74705SXin Li     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4936*67e74705SXin Li     DiagnoseCalleeStaticArrayParam(*this, Param);
4937*67e74705SXin Li     return;
4938*67e74705SXin Li   }
4939*67e74705SXin Li 
4940*67e74705SXin Li   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4941*67e74705SXin Li   if (!CAT)
4942*67e74705SXin Li     return;
4943*67e74705SXin Li 
4944*67e74705SXin Li   const ConstantArrayType *ArgCAT =
4945*67e74705SXin Li     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4946*67e74705SXin Li   if (!ArgCAT)
4947*67e74705SXin Li     return;
4948*67e74705SXin Li 
4949*67e74705SXin Li   if (ArgCAT->getSize().ult(CAT->getSize())) {
4950*67e74705SXin Li     Diag(CallLoc, diag::warn_static_array_too_small)
4951*67e74705SXin Li       << ArgExpr->getSourceRange()
4952*67e74705SXin Li       << (unsigned) ArgCAT->getSize().getZExtValue()
4953*67e74705SXin Li       << (unsigned) CAT->getSize().getZExtValue();
4954*67e74705SXin Li     DiagnoseCalleeStaticArrayParam(*this, Param);
4955*67e74705SXin Li   }
4956*67e74705SXin Li }
4957*67e74705SXin Li 
4958*67e74705SXin Li /// Given a function expression of unknown-any type, try to rebuild it
4959*67e74705SXin Li /// to have a function type.
4960*67e74705SXin Li static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4961*67e74705SXin Li 
4962*67e74705SXin Li /// Is the given type a placeholder that we need to lower out
4963*67e74705SXin Li /// immediately during argument processing?
isPlaceholderToRemoveAsArg(QualType type)4964*67e74705SXin Li static bool isPlaceholderToRemoveAsArg(QualType type) {
4965*67e74705SXin Li   // Placeholders are never sugared.
4966*67e74705SXin Li   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4967*67e74705SXin Li   if (!placeholder) return false;
4968*67e74705SXin Li 
4969*67e74705SXin Li   switch (placeholder->getKind()) {
4970*67e74705SXin Li   // Ignore all the non-placeholder types.
4971*67e74705SXin Li #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4972*67e74705SXin Li   case BuiltinType::Id:
4973*67e74705SXin Li #include "clang/Basic/OpenCLImageTypes.def"
4974*67e74705SXin Li #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4975*67e74705SXin Li #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4976*67e74705SXin Li #include "clang/AST/BuiltinTypes.def"
4977*67e74705SXin Li     return false;
4978*67e74705SXin Li 
4979*67e74705SXin Li   // We cannot lower out overload sets; they might validly be resolved
4980*67e74705SXin Li   // by the call machinery.
4981*67e74705SXin Li   case BuiltinType::Overload:
4982*67e74705SXin Li     return false;
4983*67e74705SXin Li 
4984*67e74705SXin Li   // Unbridged casts in ARC can be handled in some call positions and
4985*67e74705SXin Li   // should be left in place.
4986*67e74705SXin Li   case BuiltinType::ARCUnbridgedCast:
4987*67e74705SXin Li     return false;
4988*67e74705SXin Li 
4989*67e74705SXin Li   // Pseudo-objects should be converted as soon as possible.
4990*67e74705SXin Li   case BuiltinType::PseudoObject:
4991*67e74705SXin Li     return true;
4992*67e74705SXin Li 
4993*67e74705SXin Li   // The debugger mode could theoretically but currently does not try
4994*67e74705SXin Li   // to resolve unknown-typed arguments based on known parameter types.
4995*67e74705SXin Li   case BuiltinType::UnknownAny:
4996*67e74705SXin Li     return true;
4997*67e74705SXin Li 
4998*67e74705SXin Li   // These are always invalid as call arguments and should be reported.
4999*67e74705SXin Li   case BuiltinType::BoundMember:
5000*67e74705SXin Li   case BuiltinType::BuiltinFn:
5001*67e74705SXin Li   case BuiltinType::OMPArraySection:
5002*67e74705SXin Li     return true;
5003*67e74705SXin Li 
5004*67e74705SXin Li   }
5005*67e74705SXin Li   llvm_unreachable("bad builtin type kind");
5006*67e74705SXin Li }
5007*67e74705SXin Li 
5008*67e74705SXin Li /// Check an argument list for placeholders that we won't try to
5009*67e74705SXin Li /// handle later.
checkArgsForPlaceholders(Sema & S,MultiExprArg args)5010*67e74705SXin Li static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5011*67e74705SXin Li   // Apply this processing to all the arguments at once instead of
5012*67e74705SXin Li   // dying at the first failure.
5013*67e74705SXin Li   bool hasInvalid = false;
5014*67e74705SXin Li   for (size_t i = 0, e = args.size(); i != e; i++) {
5015*67e74705SXin Li     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5016*67e74705SXin Li       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5017*67e74705SXin Li       if (result.isInvalid()) hasInvalid = true;
5018*67e74705SXin Li       else args[i] = result.get();
5019*67e74705SXin Li     } else if (hasInvalid) {
5020*67e74705SXin Li       (void)S.CorrectDelayedTyposInExpr(args[i]);
5021*67e74705SXin Li     }
5022*67e74705SXin Li   }
5023*67e74705SXin Li   return hasInvalid;
5024*67e74705SXin Li }
5025*67e74705SXin Li 
5026*67e74705SXin Li /// If a builtin function has a pointer argument with no explicit address
5027*67e74705SXin Li /// space, then it should be able to accept a pointer to any address
5028*67e74705SXin Li /// space as input.  In order to do this, we need to replace the
5029*67e74705SXin Li /// standard builtin declaration with one that uses the same address space
5030*67e74705SXin Li /// as the call.
5031*67e74705SXin Li ///
5032*67e74705SXin Li /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5033*67e74705SXin Li ///                  it does not contain any pointer arguments without
5034*67e74705SXin Li ///                  an address space qualifer.  Otherwise the rewritten
5035*67e74705SXin Li ///                  FunctionDecl is returned.
5036*67e74705SXin Li /// TODO: Handle pointer return types.
rewriteBuiltinFunctionDecl(Sema * Sema,ASTContext & Context,const FunctionDecl * FDecl,MultiExprArg ArgExprs)5037*67e74705SXin Li static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5038*67e74705SXin Li                                                 const FunctionDecl *FDecl,
5039*67e74705SXin Li                                                 MultiExprArg ArgExprs) {
5040*67e74705SXin Li 
5041*67e74705SXin Li   QualType DeclType = FDecl->getType();
5042*67e74705SXin Li   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5043*67e74705SXin Li 
5044*67e74705SXin Li   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5045*67e74705SXin Li       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5046*67e74705SXin Li     return nullptr;
5047*67e74705SXin Li 
5048*67e74705SXin Li   bool NeedsNewDecl = false;
5049*67e74705SXin Li   unsigned i = 0;
5050*67e74705SXin Li   SmallVector<QualType, 8> OverloadParams;
5051*67e74705SXin Li 
5052*67e74705SXin Li   for (QualType ParamType : FT->param_types()) {
5053*67e74705SXin Li 
5054*67e74705SXin Li     // Convert array arguments to pointer to simplify type lookup.
5055*67e74705SXin Li     Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
5056*67e74705SXin Li     QualType ArgType = Arg->getType();
5057*67e74705SXin Li     if (!ParamType->isPointerType() ||
5058*67e74705SXin Li         ParamType.getQualifiers().hasAddressSpace() ||
5059*67e74705SXin Li         !ArgType->isPointerType() ||
5060*67e74705SXin Li         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5061*67e74705SXin Li       OverloadParams.push_back(ParamType);
5062*67e74705SXin Li       continue;
5063*67e74705SXin Li     }
5064*67e74705SXin Li 
5065*67e74705SXin Li     NeedsNewDecl = true;
5066*67e74705SXin Li     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5067*67e74705SXin Li 
5068*67e74705SXin Li     QualType PointeeType = ParamType->getPointeeType();
5069*67e74705SXin Li     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5070*67e74705SXin Li     OverloadParams.push_back(Context.getPointerType(PointeeType));
5071*67e74705SXin Li   }
5072*67e74705SXin Li 
5073*67e74705SXin Li   if (!NeedsNewDecl)
5074*67e74705SXin Li     return nullptr;
5075*67e74705SXin Li 
5076*67e74705SXin Li   FunctionProtoType::ExtProtoInfo EPI;
5077*67e74705SXin Li   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5078*67e74705SXin Li                                                 OverloadParams, EPI);
5079*67e74705SXin Li   DeclContext *Parent = Context.getTranslationUnitDecl();
5080*67e74705SXin Li   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5081*67e74705SXin Li                                                     FDecl->getLocation(),
5082*67e74705SXin Li                                                     FDecl->getLocation(),
5083*67e74705SXin Li                                                     FDecl->getIdentifier(),
5084*67e74705SXin Li                                                     OverloadTy,
5085*67e74705SXin Li                                                     /*TInfo=*/nullptr,
5086*67e74705SXin Li                                                     SC_Extern, false,
5087*67e74705SXin Li                                                     /*hasPrototype=*/true);
5088*67e74705SXin Li   SmallVector<ParmVarDecl*, 16> Params;
5089*67e74705SXin Li   FT = cast<FunctionProtoType>(OverloadTy);
5090*67e74705SXin Li   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5091*67e74705SXin Li     QualType ParamType = FT->getParamType(i);
5092*67e74705SXin Li     ParmVarDecl *Parm =
5093*67e74705SXin Li         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5094*67e74705SXin Li                                 SourceLocation(), nullptr, ParamType,
5095*67e74705SXin Li                                 /*TInfo=*/nullptr, SC_None, nullptr);
5096*67e74705SXin Li     Parm->setScopeInfo(0, i);
5097*67e74705SXin Li     Params.push_back(Parm);
5098*67e74705SXin Li   }
5099*67e74705SXin Li   OverloadDecl->setParams(Params);
5100*67e74705SXin Li   return OverloadDecl;
5101*67e74705SXin Li }
5102*67e74705SXin Li 
isNumberOfArgsValidForCall(Sema & S,const FunctionDecl * Callee,std::size_t NumArgs)5103*67e74705SXin Li static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5104*67e74705SXin Li                                        std::size_t NumArgs) {
5105*67e74705SXin Li   if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5106*67e74705SXin Li                          /*PartialOverloading=*/false))
5107*67e74705SXin Li     return Callee->isVariadic();
5108*67e74705SXin Li   return Callee->getMinRequiredArguments() <= NumArgs;
5109*67e74705SXin Li }
5110*67e74705SXin Li 
5111*67e74705SXin Li /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5112*67e74705SXin Li /// This provides the location of the left/right parens and a list of comma
5113*67e74705SXin Li /// locations.
5114*67e74705SXin Li ExprResult
ActOnCallExpr(Scope * S,Expr * Fn,SourceLocation LParenLoc,MultiExprArg ArgExprs,SourceLocation RParenLoc,Expr * ExecConfig,bool IsExecConfig)5115*67e74705SXin Li Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5116*67e74705SXin Li                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
5117*67e74705SXin Li                     Expr *ExecConfig, bool IsExecConfig) {
5118*67e74705SXin Li   // Since this might be a postfix expression, get rid of ParenListExprs.
5119*67e74705SXin Li   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
5120*67e74705SXin Li   if (Result.isInvalid()) return ExprError();
5121*67e74705SXin Li   Fn = Result.get();
5122*67e74705SXin Li 
5123*67e74705SXin Li   if (checkArgsForPlaceholders(*this, ArgExprs))
5124*67e74705SXin Li     return ExprError();
5125*67e74705SXin Li 
5126*67e74705SXin Li   if (getLangOpts().CPlusPlus) {
5127*67e74705SXin Li     // If this is a pseudo-destructor expression, build the call immediately.
5128*67e74705SXin Li     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5129*67e74705SXin Li       if (!ArgExprs.empty()) {
5130*67e74705SXin Li         // Pseudo-destructor calls should not have any arguments.
5131*67e74705SXin Li         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5132*67e74705SXin Li           << FixItHint::CreateRemoval(
5133*67e74705SXin Li                                     SourceRange(ArgExprs.front()->getLocStart(),
5134*67e74705SXin Li                                                 ArgExprs.back()->getLocEnd()));
5135*67e74705SXin Li       }
5136*67e74705SXin Li 
5137*67e74705SXin Li       return new (Context)
5138*67e74705SXin Li           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5139*67e74705SXin Li     }
5140*67e74705SXin Li     if (Fn->getType() == Context.PseudoObjectTy) {
5141*67e74705SXin Li       ExprResult result = CheckPlaceholderExpr(Fn);
5142*67e74705SXin Li       if (result.isInvalid()) return ExprError();
5143*67e74705SXin Li       Fn = result.get();
5144*67e74705SXin Li     }
5145*67e74705SXin Li 
5146*67e74705SXin Li     // Determine whether this is a dependent call inside a C++ template,
5147*67e74705SXin Li     // in which case we won't do any semantic analysis now.
5148*67e74705SXin Li     bool Dependent = false;
5149*67e74705SXin Li     if (Fn->isTypeDependent())
5150*67e74705SXin Li       Dependent = true;
5151*67e74705SXin Li     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5152*67e74705SXin Li       Dependent = true;
5153*67e74705SXin Li 
5154*67e74705SXin Li     if (Dependent) {
5155*67e74705SXin Li       if (ExecConfig) {
5156*67e74705SXin Li         return new (Context) CUDAKernelCallExpr(
5157*67e74705SXin Li             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5158*67e74705SXin Li             Context.DependentTy, VK_RValue, RParenLoc);
5159*67e74705SXin Li       } else {
5160*67e74705SXin Li         return new (Context) CallExpr(
5161*67e74705SXin Li             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5162*67e74705SXin Li       }
5163*67e74705SXin Li     }
5164*67e74705SXin Li 
5165*67e74705SXin Li     // Determine whether this is a call to an object (C++ [over.call.object]).
5166*67e74705SXin Li     if (Fn->getType()->isRecordType())
5167*67e74705SXin Li       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
5168*67e74705SXin Li                                           RParenLoc);
5169*67e74705SXin Li 
5170*67e74705SXin Li     if (Fn->getType() == Context.UnknownAnyTy) {
5171*67e74705SXin Li       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5172*67e74705SXin Li       if (result.isInvalid()) return ExprError();
5173*67e74705SXin Li       Fn = result.get();
5174*67e74705SXin Li     }
5175*67e74705SXin Li 
5176*67e74705SXin Li     if (Fn->getType() == Context.BoundMemberTy) {
5177*67e74705SXin Li       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5178*67e74705SXin Li     }
5179*67e74705SXin Li   }
5180*67e74705SXin Li 
5181*67e74705SXin Li   // Check for overloaded calls.  This can happen even in C due to extensions.
5182*67e74705SXin Li   if (Fn->getType() == Context.OverloadTy) {
5183*67e74705SXin Li     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5184*67e74705SXin Li 
5185*67e74705SXin Li     // We aren't supposed to apply this logic for if there's an '&' involved.
5186*67e74705SXin Li     if (!find.HasFormOfMemberPointer) {
5187*67e74705SXin Li       OverloadExpr *ovl = find.Expression;
5188*67e74705SXin Li       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5189*67e74705SXin Li         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
5190*67e74705SXin Li                                        RParenLoc, ExecConfig,
5191*67e74705SXin Li                                        /*AllowTypoCorrection=*/true,
5192*67e74705SXin Li                                        find.IsAddressOfOperand);
5193*67e74705SXin Li       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5194*67e74705SXin Li     }
5195*67e74705SXin Li   }
5196*67e74705SXin Li 
5197*67e74705SXin Li   // If we're directly calling a function, get the appropriate declaration.
5198*67e74705SXin Li   if (Fn->getType() == Context.UnknownAnyTy) {
5199*67e74705SXin Li     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5200*67e74705SXin Li     if (result.isInvalid()) return ExprError();
5201*67e74705SXin Li     Fn = result.get();
5202*67e74705SXin Li   }
5203*67e74705SXin Li 
5204*67e74705SXin Li   Expr *NakedFn = Fn->IgnoreParens();
5205*67e74705SXin Li 
5206*67e74705SXin Li   bool CallingNDeclIndirectly = false;
5207*67e74705SXin Li   NamedDecl *NDecl = nullptr;
5208*67e74705SXin Li   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5209*67e74705SXin Li     if (UnOp->getOpcode() == UO_AddrOf) {
5210*67e74705SXin Li       CallingNDeclIndirectly = true;
5211*67e74705SXin Li       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5212*67e74705SXin Li     }
5213*67e74705SXin Li   }
5214*67e74705SXin Li 
5215*67e74705SXin Li   if (isa<DeclRefExpr>(NakedFn)) {
5216*67e74705SXin Li     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5217*67e74705SXin Li 
5218*67e74705SXin Li     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5219*67e74705SXin Li     if (FDecl && FDecl->getBuiltinID()) {
5220*67e74705SXin Li       // Rewrite the function decl for this builtin by replacing parameters
5221*67e74705SXin Li       // with no explicit address space with the address space of the arguments
5222*67e74705SXin Li       // in ArgExprs.
5223*67e74705SXin Li       if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5224*67e74705SXin Li         NDecl = FDecl;
5225*67e74705SXin Li         Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
5226*67e74705SXin Li                            SourceLocation(), FDecl, false,
5227*67e74705SXin Li                            SourceLocation(), FDecl->getType(),
5228*67e74705SXin Li                            Fn->getValueKind(), FDecl);
5229*67e74705SXin Li       }
5230*67e74705SXin Li     }
5231*67e74705SXin Li   } else if (isa<MemberExpr>(NakedFn))
5232*67e74705SXin Li     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5233*67e74705SXin Li 
5234*67e74705SXin Li   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5235*67e74705SXin Li     if (CallingNDeclIndirectly &&
5236*67e74705SXin Li         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5237*67e74705SXin Li                                            Fn->getLocStart()))
5238*67e74705SXin Li       return ExprError();
5239*67e74705SXin Li 
5240*67e74705SXin Li     // CheckEnableIf assumes that the we're passing in a sane number of args for
5241*67e74705SXin Li     // FD, but that doesn't always hold true here. This is because, in some
5242*67e74705SXin Li     // cases, we'll emit a diag about an ill-formed function call, but then
5243*67e74705SXin Li     // we'll continue on as if the function call wasn't ill-formed. So, if the
5244*67e74705SXin Li     // number of args looks incorrect, don't do enable_if checks; we should've
5245*67e74705SXin Li     // already emitted an error about the bad call.
5246*67e74705SXin Li     if (FD->hasAttr<EnableIfAttr>() &&
5247*67e74705SXin Li         isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
5248*67e74705SXin Li       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5249*67e74705SXin Li         Diag(Fn->getLocStart(),
5250*67e74705SXin Li              isa<CXXMethodDecl>(FD) ?
5251*67e74705SXin Li                  diag::err_ovl_no_viable_member_function_in_call :
5252*67e74705SXin Li                  diag::err_ovl_no_viable_function_in_call)
5253*67e74705SXin Li           << FD << FD->getSourceRange();
5254*67e74705SXin Li         Diag(FD->getLocation(),
5255*67e74705SXin Li              diag::note_ovl_candidate_disabled_by_enable_if_attr)
5256*67e74705SXin Li             << Attr->getCond()->getSourceRange() << Attr->getMessage();
5257*67e74705SXin Li       }
5258*67e74705SXin Li     }
5259*67e74705SXin Li   }
5260*67e74705SXin Li 
5261*67e74705SXin Li   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5262*67e74705SXin Li                                ExecConfig, IsExecConfig);
5263*67e74705SXin Li }
5264*67e74705SXin Li 
5265*67e74705SXin Li /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5266*67e74705SXin Li ///
5267*67e74705SXin Li /// __builtin_astype( value, dst type )
5268*67e74705SXin Li ///
ActOnAsTypeExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)5269*67e74705SXin Li ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5270*67e74705SXin Li                                  SourceLocation BuiltinLoc,
5271*67e74705SXin Li                                  SourceLocation RParenLoc) {
5272*67e74705SXin Li   ExprValueKind VK = VK_RValue;
5273*67e74705SXin Li   ExprObjectKind OK = OK_Ordinary;
5274*67e74705SXin Li   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5275*67e74705SXin Li   QualType SrcTy = E->getType();
5276*67e74705SXin Li   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5277*67e74705SXin Li     return ExprError(Diag(BuiltinLoc,
5278*67e74705SXin Li                           diag::err_invalid_astype_of_different_size)
5279*67e74705SXin Li                      << DstTy
5280*67e74705SXin Li                      << SrcTy
5281*67e74705SXin Li                      << E->getSourceRange());
5282*67e74705SXin Li   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5283*67e74705SXin Li }
5284*67e74705SXin Li 
5285*67e74705SXin Li /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5286*67e74705SXin Li /// provided arguments.
5287*67e74705SXin Li ///
5288*67e74705SXin Li /// __builtin_convertvector( value, dst type )
5289*67e74705SXin Li ///
ActOnConvertVectorExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)5290*67e74705SXin Li ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5291*67e74705SXin Li                                         SourceLocation BuiltinLoc,
5292*67e74705SXin Li                                         SourceLocation RParenLoc) {
5293*67e74705SXin Li   TypeSourceInfo *TInfo;
5294*67e74705SXin Li   GetTypeFromParser(ParsedDestTy, &TInfo);
5295*67e74705SXin Li   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5296*67e74705SXin Li }
5297*67e74705SXin Li 
5298*67e74705SXin Li /// BuildResolvedCallExpr - Build a call to a resolved expression,
5299*67e74705SXin Li /// i.e. an expression not of \p OverloadTy.  The expression should
5300*67e74705SXin Li /// unary-convert to an expression of function-pointer or
5301*67e74705SXin Li /// block-pointer type.
5302*67e74705SXin Li ///
5303*67e74705SXin Li /// \param NDecl the declaration being called, if available
5304*67e74705SXin Li ExprResult
BuildResolvedCallExpr(Expr * Fn,NamedDecl * NDecl,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc,Expr * Config,bool IsExecConfig)5305*67e74705SXin Li Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5306*67e74705SXin Li                             SourceLocation LParenLoc,
5307*67e74705SXin Li                             ArrayRef<Expr *> Args,
5308*67e74705SXin Li                             SourceLocation RParenLoc,
5309*67e74705SXin Li                             Expr *Config, bool IsExecConfig) {
5310*67e74705SXin Li   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5311*67e74705SXin Li   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5312*67e74705SXin Li 
5313*67e74705SXin Li   // Functions with 'interrupt' attribute cannot be called directly.
5314*67e74705SXin Li   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5315*67e74705SXin Li     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5316*67e74705SXin Li     return ExprError();
5317*67e74705SXin Li   }
5318*67e74705SXin Li 
5319*67e74705SXin Li   // Promote the function operand.
5320*67e74705SXin Li   // We special-case function promotion here because we only allow promoting
5321*67e74705SXin Li   // builtin functions to function pointers in the callee of a call.
5322*67e74705SXin Li   ExprResult Result;
5323*67e74705SXin Li   if (BuiltinID &&
5324*67e74705SXin Li       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5325*67e74705SXin Li     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5326*67e74705SXin Li                                CK_BuiltinFnToFnPtr).get();
5327*67e74705SXin Li   } else {
5328*67e74705SXin Li     Result = CallExprUnaryConversions(Fn);
5329*67e74705SXin Li   }
5330*67e74705SXin Li   if (Result.isInvalid())
5331*67e74705SXin Li     return ExprError();
5332*67e74705SXin Li   Fn = Result.get();
5333*67e74705SXin Li 
5334*67e74705SXin Li   // Make the call expr early, before semantic checks.  This guarantees cleanup
5335*67e74705SXin Li   // of arguments and function on error.
5336*67e74705SXin Li   CallExpr *TheCall;
5337*67e74705SXin Li   if (Config)
5338*67e74705SXin Li     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5339*67e74705SXin Li                                                cast<CallExpr>(Config), Args,
5340*67e74705SXin Li                                                Context.BoolTy, VK_RValue,
5341*67e74705SXin Li                                                RParenLoc);
5342*67e74705SXin Li   else
5343*67e74705SXin Li     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5344*67e74705SXin Li                                      VK_RValue, RParenLoc);
5345*67e74705SXin Li 
5346*67e74705SXin Li   if (!getLangOpts().CPlusPlus) {
5347*67e74705SXin Li     // C cannot always handle TypoExpr nodes in builtin calls and direct
5348*67e74705SXin Li     // function calls as their argument checking don't necessarily handle
5349*67e74705SXin Li     // dependent types properly, so make sure any TypoExprs have been
5350*67e74705SXin Li     // dealt with.
5351*67e74705SXin Li     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5352*67e74705SXin Li     if (!Result.isUsable()) return ExprError();
5353*67e74705SXin Li     TheCall = dyn_cast<CallExpr>(Result.get());
5354*67e74705SXin Li     if (!TheCall) return Result;
5355*67e74705SXin Li     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5356*67e74705SXin Li   }
5357*67e74705SXin Li 
5358*67e74705SXin Li   // Bail out early if calling a builtin with custom typechecking.
5359*67e74705SXin Li   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5360*67e74705SXin Li     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5361*67e74705SXin Li 
5362*67e74705SXin Li  retry:
5363*67e74705SXin Li   const FunctionType *FuncT;
5364*67e74705SXin Li   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5365*67e74705SXin Li     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5366*67e74705SXin Li     // have type pointer to function".
5367*67e74705SXin Li     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5368*67e74705SXin Li     if (!FuncT)
5369*67e74705SXin Li       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5370*67e74705SXin Li                          << Fn->getType() << Fn->getSourceRange());
5371*67e74705SXin Li   } else if (const BlockPointerType *BPT =
5372*67e74705SXin Li                Fn->getType()->getAs<BlockPointerType>()) {
5373*67e74705SXin Li     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5374*67e74705SXin Li   } else {
5375*67e74705SXin Li     // Handle calls to expressions of unknown-any type.
5376*67e74705SXin Li     if (Fn->getType() == Context.UnknownAnyTy) {
5377*67e74705SXin Li       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5378*67e74705SXin Li       if (rewrite.isInvalid()) return ExprError();
5379*67e74705SXin Li       Fn = rewrite.get();
5380*67e74705SXin Li       TheCall->setCallee(Fn);
5381*67e74705SXin Li       goto retry;
5382*67e74705SXin Li     }
5383*67e74705SXin Li 
5384*67e74705SXin Li     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5385*67e74705SXin Li       << Fn->getType() << Fn->getSourceRange());
5386*67e74705SXin Li   }
5387*67e74705SXin Li 
5388*67e74705SXin Li   if (getLangOpts().CUDA) {
5389*67e74705SXin Li     if (Config) {
5390*67e74705SXin Li       // CUDA: Kernel calls must be to global functions
5391*67e74705SXin Li       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5392*67e74705SXin Li         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5393*67e74705SXin Li             << FDecl->getName() << Fn->getSourceRange());
5394*67e74705SXin Li 
5395*67e74705SXin Li       // CUDA: Kernel function must have 'void' return type
5396*67e74705SXin Li       if (!FuncT->getReturnType()->isVoidType())
5397*67e74705SXin Li         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5398*67e74705SXin Li             << Fn->getType() << Fn->getSourceRange());
5399*67e74705SXin Li     } else {
5400*67e74705SXin Li       // CUDA: Calls to global functions must be configured
5401*67e74705SXin Li       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5402*67e74705SXin Li         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5403*67e74705SXin Li             << FDecl->getName() << Fn->getSourceRange());
5404*67e74705SXin Li     }
5405*67e74705SXin Li   }
5406*67e74705SXin Li 
5407*67e74705SXin Li   // Check for a valid return type
5408*67e74705SXin Li   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5409*67e74705SXin Li                           FDecl))
5410*67e74705SXin Li     return ExprError();
5411*67e74705SXin Li 
5412*67e74705SXin Li   // We know the result type of the call, set it.
5413*67e74705SXin Li   TheCall->setType(FuncT->getCallResultType(Context));
5414*67e74705SXin Li   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5415*67e74705SXin Li 
5416*67e74705SXin Li   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5417*67e74705SXin Li   if (Proto) {
5418*67e74705SXin Li     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5419*67e74705SXin Li                                 IsExecConfig))
5420*67e74705SXin Li       return ExprError();
5421*67e74705SXin Li   } else {
5422*67e74705SXin Li     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5423*67e74705SXin Li 
5424*67e74705SXin Li     if (FDecl) {
5425*67e74705SXin Li       // Check if we have too few/too many template arguments, based
5426*67e74705SXin Li       // on our knowledge of the function definition.
5427*67e74705SXin Li       const FunctionDecl *Def = nullptr;
5428*67e74705SXin Li       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5429*67e74705SXin Li         Proto = Def->getType()->getAs<FunctionProtoType>();
5430*67e74705SXin Li        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5431*67e74705SXin Li           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5432*67e74705SXin Li           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5433*67e74705SXin Li       }
5434*67e74705SXin Li 
5435*67e74705SXin Li       // If the function we're calling isn't a function prototype, but we have
5436*67e74705SXin Li       // a function prototype from a prior declaratiom, use that prototype.
5437*67e74705SXin Li       if (!FDecl->hasPrototype())
5438*67e74705SXin Li         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5439*67e74705SXin Li     }
5440*67e74705SXin Li 
5441*67e74705SXin Li     // Promote the arguments (C99 6.5.2.2p6).
5442*67e74705SXin Li     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5443*67e74705SXin Li       Expr *Arg = Args[i];
5444*67e74705SXin Li 
5445*67e74705SXin Li       if (Proto && i < Proto->getNumParams()) {
5446*67e74705SXin Li         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5447*67e74705SXin Li             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5448*67e74705SXin Li         ExprResult ArgE =
5449*67e74705SXin Li             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5450*67e74705SXin Li         if (ArgE.isInvalid())
5451*67e74705SXin Li           return true;
5452*67e74705SXin Li 
5453*67e74705SXin Li         Arg = ArgE.getAs<Expr>();
5454*67e74705SXin Li 
5455*67e74705SXin Li       } else {
5456*67e74705SXin Li         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5457*67e74705SXin Li 
5458*67e74705SXin Li         if (ArgE.isInvalid())
5459*67e74705SXin Li           return true;
5460*67e74705SXin Li 
5461*67e74705SXin Li         Arg = ArgE.getAs<Expr>();
5462*67e74705SXin Li       }
5463*67e74705SXin Li 
5464*67e74705SXin Li       if (RequireCompleteType(Arg->getLocStart(),
5465*67e74705SXin Li                               Arg->getType(),
5466*67e74705SXin Li                               diag::err_call_incomplete_argument, Arg))
5467*67e74705SXin Li         return ExprError();
5468*67e74705SXin Li 
5469*67e74705SXin Li       TheCall->setArg(i, Arg);
5470*67e74705SXin Li     }
5471*67e74705SXin Li   }
5472*67e74705SXin Li 
5473*67e74705SXin Li   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5474*67e74705SXin Li     if (!Method->isStatic())
5475*67e74705SXin Li       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5476*67e74705SXin Li         << Fn->getSourceRange());
5477*67e74705SXin Li 
5478*67e74705SXin Li   // Check for sentinels
5479*67e74705SXin Li   if (NDecl)
5480*67e74705SXin Li     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5481*67e74705SXin Li 
5482*67e74705SXin Li   // Do special checking on direct calls to functions.
5483*67e74705SXin Li   if (FDecl) {
5484*67e74705SXin Li     if (CheckFunctionCall(FDecl, TheCall, Proto))
5485*67e74705SXin Li       return ExprError();
5486*67e74705SXin Li 
5487*67e74705SXin Li     if (BuiltinID)
5488*67e74705SXin Li       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5489*67e74705SXin Li   } else if (NDecl) {
5490*67e74705SXin Li     if (CheckPointerCall(NDecl, TheCall, Proto))
5491*67e74705SXin Li       return ExprError();
5492*67e74705SXin Li   } else {
5493*67e74705SXin Li     if (CheckOtherCall(TheCall, Proto))
5494*67e74705SXin Li       return ExprError();
5495*67e74705SXin Li   }
5496*67e74705SXin Li 
5497*67e74705SXin Li   return MaybeBindToTemporary(TheCall);
5498*67e74705SXin Li }
5499*67e74705SXin Li 
5500*67e74705SXin Li ExprResult
ActOnCompoundLiteral(SourceLocation LParenLoc,ParsedType Ty,SourceLocation RParenLoc,Expr * InitExpr)5501*67e74705SXin Li Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5502*67e74705SXin Li                            SourceLocation RParenLoc, Expr *InitExpr) {
5503*67e74705SXin Li   assert(Ty && "ActOnCompoundLiteral(): missing type");
5504*67e74705SXin Li   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5505*67e74705SXin Li 
5506*67e74705SXin Li   TypeSourceInfo *TInfo;
5507*67e74705SXin Li   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5508*67e74705SXin Li   if (!TInfo)
5509*67e74705SXin Li     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5510*67e74705SXin Li 
5511*67e74705SXin Li   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5512*67e74705SXin Li }
5513*67e74705SXin Li 
5514*67e74705SXin Li ExprResult
BuildCompoundLiteralExpr(SourceLocation LParenLoc,TypeSourceInfo * TInfo,SourceLocation RParenLoc,Expr * LiteralExpr)5515*67e74705SXin Li Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5516*67e74705SXin Li                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5517*67e74705SXin Li   QualType literalType = TInfo->getType();
5518*67e74705SXin Li 
5519*67e74705SXin Li   if (literalType->isArrayType()) {
5520*67e74705SXin Li     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5521*67e74705SXin Li           diag::err_illegal_decl_array_incomplete_type,
5522*67e74705SXin Li           SourceRange(LParenLoc,
5523*67e74705SXin Li                       LiteralExpr->getSourceRange().getEnd())))
5524*67e74705SXin Li       return ExprError();
5525*67e74705SXin Li     if (literalType->isVariableArrayType())
5526*67e74705SXin Li       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5527*67e74705SXin Li         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5528*67e74705SXin Li   } else if (!literalType->isDependentType() &&
5529*67e74705SXin Li              RequireCompleteType(LParenLoc, literalType,
5530*67e74705SXin Li                diag::err_typecheck_decl_incomplete_type,
5531*67e74705SXin Li                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5532*67e74705SXin Li     return ExprError();
5533*67e74705SXin Li 
5534*67e74705SXin Li   InitializedEntity Entity
5535*67e74705SXin Li     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5536*67e74705SXin Li   InitializationKind Kind
5537*67e74705SXin Li     = InitializationKind::CreateCStyleCast(LParenLoc,
5538*67e74705SXin Li                                            SourceRange(LParenLoc, RParenLoc),
5539*67e74705SXin Li                                            /*InitList=*/true);
5540*67e74705SXin Li   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5541*67e74705SXin Li   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5542*67e74705SXin Li                                       &literalType);
5543*67e74705SXin Li   if (Result.isInvalid())
5544*67e74705SXin Li     return ExprError();
5545*67e74705SXin Li   LiteralExpr = Result.get();
5546*67e74705SXin Li 
5547*67e74705SXin Li   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5548*67e74705SXin Li   if (isFileScope &&
5549*67e74705SXin Li       !LiteralExpr->isTypeDependent() &&
5550*67e74705SXin Li       !LiteralExpr->isValueDependent() &&
5551*67e74705SXin Li       !literalType->isDependentType()) { // 6.5.2.5p3
5552*67e74705SXin Li     if (CheckForConstantInitializer(LiteralExpr, literalType))
5553*67e74705SXin Li       return ExprError();
5554*67e74705SXin Li   }
5555*67e74705SXin Li 
5556*67e74705SXin Li   // In C, compound literals are l-values for some reason.
5557*67e74705SXin Li   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5558*67e74705SXin Li 
5559*67e74705SXin Li   return MaybeBindToTemporary(
5560*67e74705SXin Li            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5561*67e74705SXin Li                                              VK, LiteralExpr, isFileScope));
5562*67e74705SXin Li }
5563*67e74705SXin Li 
5564*67e74705SXin Li ExprResult
ActOnInitList(SourceLocation LBraceLoc,MultiExprArg InitArgList,SourceLocation RBraceLoc)5565*67e74705SXin Li Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5566*67e74705SXin Li                     SourceLocation RBraceLoc) {
5567*67e74705SXin Li   // Immediately handle non-overload placeholders.  Overloads can be
5568*67e74705SXin Li   // resolved contextually, but everything else here can't.
5569*67e74705SXin Li   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5570*67e74705SXin Li     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5571*67e74705SXin Li       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5572*67e74705SXin Li 
5573*67e74705SXin Li       // Ignore failures; dropping the entire initializer list because
5574*67e74705SXin Li       // of one failure would be terrible for indexing/etc.
5575*67e74705SXin Li       if (result.isInvalid()) continue;
5576*67e74705SXin Li 
5577*67e74705SXin Li       InitArgList[I] = result.get();
5578*67e74705SXin Li     }
5579*67e74705SXin Li   }
5580*67e74705SXin Li 
5581*67e74705SXin Li   // Semantic analysis for initializers is done by ActOnDeclarator() and
5582*67e74705SXin Li   // CheckInitializer() - it requires knowledge of the object being intialized.
5583*67e74705SXin Li 
5584*67e74705SXin Li   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5585*67e74705SXin Li                                                RBraceLoc);
5586*67e74705SXin Li   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5587*67e74705SXin Li   return E;
5588*67e74705SXin Li }
5589*67e74705SXin Li 
5590*67e74705SXin Li /// Do an explicit extend of the given block pointer if we're in ARC.
maybeExtendBlockObject(ExprResult & E)5591*67e74705SXin Li void Sema::maybeExtendBlockObject(ExprResult &E) {
5592*67e74705SXin Li   assert(E.get()->getType()->isBlockPointerType());
5593*67e74705SXin Li   assert(E.get()->isRValue());
5594*67e74705SXin Li 
5595*67e74705SXin Li   // Only do this in an r-value context.
5596*67e74705SXin Li   if (!getLangOpts().ObjCAutoRefCount) return;
5597*67e74705SXin Li 
5598*67e74705SXin Li   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5599*67e74705SXin Li                                CK_ARCExtendBlockObject, E.get(),
5600*67e74705SXin Li                                /*base path*/ nullptr, VK_RValue);
5601*67e74705SXin Li   Cleanup.setExprNeedsCleanups(true);
5602*67e74705SXin Li }
5603*67e74705SXin Li 
5604*67e74705SXin Li /// Prepare a conversion of the given expression to an ObjC object
5605*67e74705SXin Li /// pointer type.
PrepareCastToObjCObjectPointer(ExprResult & E)5606*67e74705SXin Li CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5607*67e74705SXin Li   QualType type = E.get()->getType();
5608*67e74705SXin Li   if (type->isObjCObjectPointerType()) {
5609*67e74705SXin Li     return CK_BitCast;
5610*67e74705SXin Li   } else if (type->isBlockPointerType()) {
5611*67e74705SXin Li     maybeExtendBlockObject(E);
5612*67e74705SXin Li     return CK_BlockPointerToObjCPointerCast;
5613*67e74705SXin Li   } else {
5614*67e74705SXin Li     assert(type->isPointerType());
5615*67e74705SXin Li     return CK_CPointerToObjCPointerCast;
5616*67e74705SXin Li   }
5617*67e74705SXin Li }
5618*67e74705SXin Li 
5619*67e74705SXin Li /// Prepares for a scalar cast, performing all the necessary stages
5620*67e74705SXin Li /// except the final cast and returning the kind required.
PrepareScalarCast(ExprResult & Src,QualType DestTy)5621*67e74705SXin Li CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5622*67e74705SXin Li   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5623*67e74705SXin Li   // Also, callers should have filtered out the invalid cases with
5624*67e74705SXin Li   // pointers.  Everything else should be possible.
5625*67e74705SXin Li 
5626*67e74705SXin Li   QualType SrcTy = Src.get()->getType();
5627*67e74705SXin Li   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5628*67e74705SXin Li     return CK_NoOp;
5629*67e74705SXin Li 
5630*67e74705SXin Li   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5631*67e74705SXin Li   case Type::STK_MemberPointer:
5632*67e74705SXin Li     llvm_unreachable("member pointer type in C");
5633*67e74705SXin Li 
5634*67e74705SXin Li   case Type::STK_CPointer:
5635*67e74705SXin Li   case Type::STK_BlockPointer:
5636*67e74705SXin Li   case Type::STK_ObjCObjectPointer:
5637*67e74705SXin Li     switch (DestTy->getScalarTypeKind()) {
5638*67e74705SXin Li     case Type::STK_CPointer: {
5639*67e74705SXin Li       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5640*67e74705SXin Li       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5641*67e74705SXin Li       if (SrcAS != DestAS)
5642*67e74705SXin Li         return CK_AddressSpaceConversion;
5643*67e74705SXin Li       return CK_BitCast;
5644*67e74705SXin Li     }
5645*67e74705SXin Li     case Type::STK_BlockPointer:
5646*67e74705SXin Li       return (SrcKind == Type::STK_BlockPointer
5647*67e74705SXin Li                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5648*67e74705SXin Li     case Type::STK_ObjCObjectPointer:
5649*67e74705SXin Li       if (SrcKind == Type::STK_ObjCObjectPointer)
5650*67e74705SXin Li         return CK_BitCast;
5651*67e74705SXin Li       if (SrcKind == Type::STK_CPointer)
5652*67e74705SXin Li         return CK_CPointerToObjCPointerCast;
5653*67e74705SXin Li       maybeExtendBlockObject(Src);
5654*67e74705SXin Li       return CK_BlockPointerToObjCPointerCast;
5655*67e74705SXin Li     case Type::STK_Bool:
5656*67e74705SXin Li       return CK_PointerToBoolean;
5657*67e74705SXin Li     case Type::STK_Integral:
5658*67e74705SXin Li       return CK_PointerToIntegral;
5659*67e74705SXin Li     case Type::STK_Floating:
5660*67e74705SXin Li     case Type::STK_FloatingComplex:
5661*67e74705SXin Li     case Type::STK_IntegralComplex:
5662*67e74705SXin Li     case Type::STK_MemberPointer:
5663*67e74705SXin Li       llvm_unreachable("illegal cast from pointer");
5664*67e74705SXin Li     }
5665*67e74705SXin Li     llvm_unreachable("Should have returned before this");
5666*67e74705SXin Li 
5667*67e74705SXin Li   case Type::STK_Bool: // casting from bool is like casting from an integer
5668*67e74705SXin Li   case Type::STK_Integral:
5669*67e74705SXin Li     switch (DestTy->getScalarTypeKind()) {
5670*67e74705SXin Li     case Type::STK_CPointer:
5671*67e74705SXin Li     case Type::STK_ObjCObjectPointer:
5672*67e74705SXin Li     case Type::STK_BlockPointer:
5673*67e74705SXin Li       if (Src.get()->isNullPointerConstant(Context,
5674*67e74705SXin Li                                            Expr::NPC_ValueDependentIsNull))
5675*67e74705SXin Li         return CK_NullToPointer;
5676*67e74705SXin Li       return CK_IntegralToPointer;
5677*67e74705SXin Li     case Type::STK_Bool:
5678*67e74705SXin Li       return CK_IntegralToBoolean;
5679*67e74705SXin Li     case Type::STK_Integral:
5680*67e74705SXin Li       return CK_IntegralCast;
5681*67e74705SXin Li     case Type::STK_Floating:
5682*67e74705SXin Li       return CK_IntegralToFloating;
5683*67e74705SXin Li     case Type::STK_IntegralComplex:
5684*67e74705SXin Li       Src = ImpCastExprToType(Src.get(),
5685*67e74705SXin Li                       DestTy->castAs<ComplexType>()->getElementType(),
5686*67e74705SXin Li                       CK_IntegralCast);
5687*67e74705SXin Li       return CK_IntegralRealToComplex;
5688*67e74705SXin Li     case Type::STK_FloatingComplex:
5689*67e74705SXin Li       Src = ImpCastExprToType(Src.get(),
5690*67e74705SXin Li                       DestTy->castAs<ComplexType>()->getElementType(),
5691*67e74705SXin Li                       CK_IntegralToFloating);
5692*67e74705SXin Li       return CK_FloatingRealToComplex;
5693*67e74705SXin Li     case Type::STK_MemberPointer:
5694*67e74705SXin Li       llvm_unreachable("member pointer type in C");
5695*67e74705SXin Li     }
5696*67e74705SXin Li     llvm_unreachable("Should have returned before this");
5697*67e74705SXin Li 
5698*67e74705SXin Li   case Type::STK_Floating:
5699*67e74705SXin Li     switch (DestTy->getScalarTypeKind()) {
5700*67e74705SXin Li     case Type::STK_Floating:
5701*67e74705SXin Li       return CK_FloatingCast;
5702*67e74705SXin Li     case Type::STK_Bool:
5703*67e74705SXin Li       return CK_FloatingToBoolean;
5704*67e74705SXin Li     case Type::STK_Integral:
5705*67e74705SXin Li       return CK_FloatingToIntegral;
5706*67e74705SXin Li     case Type::STK_FloatingComplex:
5707*67e74705SXin Li       Src = ImpCastExprToType(Src.get(),
5708*67e74705SXin Li                               DestTy->castAs<ComplexType>()->getElementType(),
5709*67e74705SXin Li                               CK_FloatingCast);
5710*67e74705SXin Li       return CK_FloatingRealToComplex;
5711*67e74705SXin Li     case Type::STK_IntegralComplex:
5712*67e74705SXin Li       Src = ImpCastExprToType(Src.get(),
5713*67e74705SXin Li                               DestTy->castAs<ComplexType>()->getElementType(),
5714*67e74705SXin Li                               CK_FloatingToIntegral);
5715*67e74705SXin Li       return CK_IntegralRealToComplex;
5716*67e74705SXin Li     case Type::STK_CPointer:
5717*67e74705SXin Li     case Type::STK_ObjCObjectPointer:
5718*67e74705SXin Li     case Type::STK_BlockPointer:
5719*67e74705SXin Li       llvm_unreachable("valid float->pointer cast?");
5720*67e74705SXin Li     case Type::STK_MemberPointer:
5721*67e74705SXin Li       llvm_unreachable("member pointer type in C");
5722*67e74705SXin Li     }
5723*67e74705SXin Li     llvm_unreachable("Should have returned before this");
5724*67e74705SXin Li 
5725*67e74705SXin Li   case Type::STK_FloatingComplex:
5726*67e74705SXin Li     switch (DestTy->getScalarTypeKind()) {
5727*67e74705SXin Li     case Type::STK_FloatingComplex:
5728*67e74705SXin Li       return CK_FloatingComplexCast;
5729*67e74705SXin Li     case Type::STK_IntegralComplex:
5730*67e74705SXin Li       return CK_FloatingComplexToIntegralComplex;
5731*67e74705SXin Li     case Type::STK_Floating: {
5732*67e74705SXin Li       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5733*67e74705SXin Li       if (Context.hasSameType(ET, DestTy))
5734*67e74705SXin Li         return CK_FloatingComplexToReal;
5735*67e74705SXin Li       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5736*67e74705SXin Li       return CK_FloatingCast;
5737*67e74705SXin Li     }
5738*67e74705SXin Li     case Type::STK_Bool:
5739*67e74705SXin Li       return CK_FloatingComplexToBoolean;
5740*67e74705SXin Li     case Type::STK_Integral:
5741*67e74705SXin Li       Src = ImpCastExprToType(Src.get(),
5742*67e74705SXin Li                               SrcTy->castAs<ComplexType>()->getElementType(),
5743*67e74705SXin Li                               CK_FloatingComplexToReal);
5744*67e74705SXin Li       return CK_FloatingToIntegral;
5745*67e74705SXin Li     case Type::STK_CPointer:
5746*67e74705SXin Li     case Type::STK_ObjCObjectPointer:
5747*67e74705SXin Li     case Type::STK_BlockPointer:
5748*67e74705SXin Li       llvm_unreachable("valid complex float->pointer cast?");
5749*67e74705SXin Li     case Type::STK_MemberPointer:
5750*67e74705SXin Li       llvm_unreachable("member pointer type in C");
5751*67e74705SXin Li     }
5752*67e74705SXin Li     llvm_unreachable("Should have returned before this");
5753*67e74705SXin Li 
5754*67e74705SXin Li   case Type::STK_IntegralComplex:
5755*67e74705SXin Li     switch (DestTy->getScalarTypeKind()) {
5756*67e74705SXin Li     case Type::STK_FloatingComplex:
5757*67e74705SXin Li       return CK_IntegralComplexToFloatingComplex;
5758*67e74705SXin Li     case Type::STK_IntegralComplex:
5759*67e74705SXin Li       return CK_IntegralComplexCast;
5760*67e74705SXin Li     case Type::STK_Integral: {
5761*67e74705SXin Li       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5762*67e74705SXin Li       if (Context.hasSameType(ET, DestTy))
5763*67e74705SXin Li         return CK_IntegralComplexToReal;
5764*67e74705SXin Li       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5765*67e74705SXin Li       return CK_IntegralCast;
5766*67e74705SXin Li     }
5767*67e74705SXin Li     case Type::STK_Bool:
5768*67e74705SXin Li       return CK_IntegralComplexToBoolean;
5769*67e74705SXin Li     case Type::STK_Floating:
5770*67e74705SXin Li       Src = ImpCastExprToType(Src.get(),
5771*67e74705SXin Li                               SrcTy->castAs<ComplexType>()->getElementType(),
5772*67e74705SXin Li                               CK_IntegralComplexToReal);
5773*67e74705SXin Li       return CK_IntegralToFloating;
5774*67e74705SXin Li     case Type::STK_CPointer:
5775*67e74705SXin Li     case Type::STK_ObjCObjectPointer:
5776*67e74705SXin Li     case Type::STK_BlockPointer:
5777*67e74705SXin Li       llvm_unreachable("valid complex int->pointer cast?");
5778*67e74705SXin Li     case Type::STK_MemberPointer:
5779*67e74705SXin Li       llvm_unreachable("member pointer type in C");
5780*67e74705SXin Li     }
5781*67e74705SXin Li     llvm_unreachable("Should have returned before this");
5782*67e74705SXin Li   }
5783*67e74705SXin Li 
5784*67e74705SXin Li   llvm_unreachable("Unhandled scalar cast");
5785*67e74705SXin Li }
5786*67e74705SXin Li 
breakDownVectorType(QualType type,uint64_t & len,QualType & eltType)5787*67e74705SXin Li static bool breakDownVectorType(QualType type, uint64_t &len,
5788*67e74705SXin Li                                 QualType &eltType) {
5789*67e74705SXin Li   // Vectors are simple.
5790*67e74705SXin Li   if (const VectorType *vecType = type->getAs<VectorType>()) {
5791*67e74705SXin Li     len = vecType->getNumElements();
5792*67e74705SXin Li     eltType = vecType->getElementType();
5793*67e74705SXin Li     assert(eltType->isScalarType());
5794*67e74705SXin Li     return true;
5795*67e74705SXin Li   }
5796*67e74705SXin Li 
5797*67e74705SXin Li   // We allow lax conversion to and from non-vector types, but only if
5798*67e74705SXin Li   // they're real types (i.e. non-complex, non-pointer scalar types).
5799*67e74705SXin Li   if (!type->isRealType()) return false;
5800*67e74705SXin Li 
5801*67e74705SXin Li   len = 1;
5802*67e74705SXin Li   eltType = type;
5803*67e74705SXin Li   return true;
5804*67e74705SXin Li }
5805*67e74705SXin Li 
5806*67e74705SXin Li /// Are the two types lax-compatible vector types?  That is, given
5807*67e74705SXin Li /// that one of them is a vector, do they have equal storage sizes,
5808*67e74705SXin Li /// where the storage size is the number of elements times the element
5809*67e74705SXin Li /// size?
5810*67e74705SXin Li ///
5811*67e74705SXin Li /// This will also return false if either of the types is neither a
5812*67e74705SXin Li /// vector nor a real type.
areLaxCompatibleVectorTypes(QualType srcTy,QualType destTy)5813*67e74705SXin Li bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5814*67e74705SXin Li   assert(destTy->isVectorType() || srcTy->isVectorType());
5815*67e74705SXin Li 
5816*67e74705SXin Li   // Disallow lax conversions between scalars and ExtVectors (these
5817*67e74705SXin Li   // conversions are allowed for other vector types because common headers
5818*67e74705SXin Li   // depend on them).  Most scalar OP ExtVector cases are handled by the
5819*67e74705SXin Li   // splat path anyway, which does what we want (convert, not bitcast).
5820*67e74705SXin Li   // What this rules out for ExtVectors is crazy things like char4*float.
5821*67e74705SXin Li   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5822*67e74705SXin Li   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5823*67e74705SXin Li 
5824*67e74705SXin Li   uint64_t srcLen, destLen;
5825*67e74705SXin Li   QualType srcEltTy, destEltTy;
5826*67e74705SXin Li   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5827*67e74705SXin Li   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5828*67e74705SXin Li 
5829*67e74705SXin Li   // ASTContext::getTypeSize will return the size rounded up to a
5830*67e74705SXin Li   // power of 2, so instead of using that, we need to use the raw
5831*67e74705SXin Li   // element size multiplied by the element count.
5832*67e74705SXin Li   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5833*67e74705SXin Li   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5834*67e74705SXin Li 
5835*67e74705SXin Li   return (srcLen * srcEltSize == destLen * destEltSize);
5836*67e74705SXin Li }
5837*67e74705SXin Li 
5838*67e74705SXin Li /// Is this a legal conversion between two types, one of which is
5839*67e74705SXin Li /// known to be a vector type?
isLaxVectorConversion(QualType srcTy,QualType destTy)5840*67e74705SXin Li bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5841*67e74705SXin Li   assert(destTy->isVectorType() || srcTy->isVectorType());
5842*67e74705SXin Li 
5843*67e74705SXin Li   if (!Context.getLangOpts().LaxVectorConversions)
5844*67e74705SXin Li     return false;
5845*67e74705SXin Li   return areLaxCompatibleVectorTypes(srcTy, destTy);
5846*67e74705SXin Li }
5847*67e74705SXin Li 
CheckVectorCast(SourceRange R,QualType VectorTy,QualType Ty,CastKind & Kind)5848*67e74705SXin Li bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5849*67e74705SXin Li                            CastKind &Kind) {
5850*67e74705SXin Li   assert(VectorTy->isVectorType() && "Not a vector type!");
5851*67e74705SXin Li 
5852*67e74705SXin Li   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5853*67e74705SXin Li     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5854*67e74705SXin Li       return Diag(R.getBegin(),
5855*67e74705SXin Li                   Ty->isVectorType() ?
5856*67e74705SXin Li                   diag::err_invalid_conversion_between_vectors :
5857*67e74705SXin Li                   diag::err_invalid_conversion_between_vector_and_integer)
5858*67e74705SXin Li         << VectorTy << Ty << R;
5859*67e74705SXin Li   } else
5860*67e74705SXin Li     return Diag(R.getBegin(),
5861*67e74705SXin Li                 diag::err_invalid_conversion_between_vector_and_scalar)
5862*67e74705SXin Li       << VectorTy << Ty << R;
5863*67e74705SXin Li 
5864*67e74705SXin Li   Kind = CK_BitCast;
5865*67e74705SXin Li   return false;
5866*67e74705SXin Li }
5867*67e74705SXin Li 
prepareVectorSplat(QualType VectorTy,Expr * SplattedExpr)5868*67e74705SXin Li ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5869*67e74705SXin Li   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5870*67e74705SXin Li 
5871*67e74705SXin Li   if (DestElemTy == SplattedExpr->getType())
5872*67e74705SXin Li     return SplattedExpr;
5873*67e74705SXin Li 
5874*67e74705SXin Li   assert(DestElemTy->isFloatingType() ||
5875*67e74705SXin Li          DestElemTy->isIntegralOrEnumerationType());
5876*67e74705SXin Li 
5877*67e74705SXin Li   CastKind CK;
5878*67e74705SXin Li   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5879*67e74705SXin Li     // OpenCL requires that we convert `true` boolean expressions to -1, but
5880*67e74705SXin Li     // only when splatting vectors.
5881*67e74705SXin Li     if (DestElemTy->isFloatingType()) {
5882*67e74705SXin Li       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5883*67e74705SXin Li       // in two steps: boolean to signed integral, then to floating.
5884*67e74705SXin Li       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5885*67e74705SXin Li                                                  CK_BooleanToSignedIntegral);
5886*67e74705SXin Li       SplattedExpr = CastExprRes.get();
5887*67e74705SXin Li       CK = CK_IntegralToFloating;
5888*67e74705SXin Li     } else {
5889*67e74705SXin Li       CK = CK_BooleanToSignedIntegral;
5890*67e74705SXin Li     }
5891*67e74705SXin Li   } else {
5892*67e74705SXin Li     ExprResult CastExprRes = SplattedExpr;
5893*67e74705SXin Li     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5894*67e74705SXin Li     if (CastExprRes.isInvalid())
5895*67e74705SXin Li       return ExprError();
5896*67e74705SXin Li     SplattedExpr = CastExprRes.get();
5897*67e74705SXin Li   }
5898*67e74705SXin Li   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5899*67e74705SXin Li }
5900*67e74705SXin Li 
CheckExtVectorCast(SourceRange R,QualType DestTy,Expr * CastExpr,CastKind & Kind)5901*67e74705SXin Li ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5902*67e74705SXin Li                                     Expr *CastExpr, CastKind &Kind) {
5903*67e74705SXin Li   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5904*67e74705SXin Li 
5905*67e74705SXin Li   QualType SrcTy = CastExpr->getType();
5906*67e74705SXin Li 
5907*67e74705SXin Li   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5908*67e74705SXin Li   // an ExtVectorType.
5909*67e74705SXin Li   // In OpenCL, casts between vectors of different types are not allowed.
5910*67e74705SXin Li   // (See OpenCL 6.2).
5911*67e74705SXin Li   if (SrcTy->isVectorType()) {
5912*67e74705SXin Li     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5913*67e74705SXin Li         || (getLangOpts().OpenCL &&
5914*67e74705SXin Li             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5915*67e74705SXin Li       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5916*67e74705SXin Li         << DestTy << SrcTy << R;
5917*67e74705SXin Li       return ExprError();
5918*67e74705SXin Li     }
5919*67e74705SXin Li     Kind = CK_BitCast;
5920*67e74705SXin Li     return CastExpr;
5921*67e74705SXin Li   }
5922*67e74705SXin Li 
5923*67e74705SXin Li   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5924*67e74705SXin Li   // conversion will take place first from scalar to elt type, and then
5925*67e74705SXin Li   // splat from elt type to vector.
5926*67e74705SXin Li   if (SrcTy->isPointerType())
5927*67e74705SXin Li     return Diag(R.getBegin(),
5928*67e74705SXin Li                 diag::err_invalid_conversion_between_vector_and_scalar)
5929*67e74705SXin Li       << DestTy << SrcTy << R;
5930*67e74705SXin Li 
5931*67e74705SXin Li   Kind = CK_VectorSplat;
5932*67e74705SXin Li   return prepareVectorSplat(DestTy, CastExpr);
5933*67e74705SXin Li }
5934*67e74705SXin Li 
5935*67e74705SXin Li ExprResult
ActOnCastExpr(Scope * S,SourceLocation LParenLoc,Declarator & D,ParsedType & Ty,SourceLocation RParenLoc,Expr * CastExpr)5936*67e74705SXin Li Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5937*67e74705SXin Li                     Declarator &D, ParsedType &Ty,
5938*67e74705SXin Li                     SourceLocation RParenLoc, Expr *CastExpr) {
5939*67e74705SXin Li   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5940*67e74705SXin Li          "ActOnCastExpr(): missing type or expr");
5941*67e74705SXin Li 
5942*67e74705SXin Li   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5943*67e74705SXin Li   if (D.isInvalidType())
5944*67e74705SXin Li     return ExprError();
5945*67e74705SXin Li 
5946*67e74705SXin Li   if (getLangOpts().CPlusPlus) {
5947*67e74705SXin Li     // Check that there are no default arguments (C++ only).
5948*67e74705SXin Li     CheckExtraCXXDefaultArguments(D);
5949*67e74705SXin Li   } else {
5950*67e74705SXin Li     // Make sure any TypoExprs have been dealt with.
5951*67e74705SXin Li     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5952*67e74705SXin Li     if (!Res.isUsable())
5953*67e74705SXin Li       return ExprError();
5954*67e74705SXin Li     CastExpr = Res.get();
5955*67e74705SXin Li   }
5956*67e74705SXin Li 
5957*67e74705SXin Li   checkUnusedDeclAttributes(D);
5958*67e74705SXin Li 
5959*67e74705SXin Li   QualType castType = castTInfo->getType();
5960*67e74705SXin Li   Ty = CreateParsedType(castType, castTInfo);
5961*67e74705SXin Li 
5962*67e74705SXin Li   bool isVectorLiteral = false;
5963*67e74705SXin Li 
5964*67e74705SXin Li   // Check for an altivec or OpenCL literal,
5965*67e74705SXin Li   // i.e. all the elements are integer constants.
5966*67e74705SXin Li   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5967*67e74705SXin Li   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5968*67e74705SXin Li   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
5969*67e74705SXin Li        && castType->isVectorType() && (PE || PLE)) {
5970*67e74705SXin Li     if (PLE && PLE->getNumExprs() == 0) {
5971*67e74705SXin Li       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5972*67e74705SXin Li       return ExprError();
5973*67e74705SXin Li     }
5974*67e74705SXin Li     if (PE || PLE->getNumExprs() == 1) {
5975*67e74705SXin Li       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5976*67e74705SXin Li       if (!E->getType()->isVectorType())
5977*67e74705SXin Li         isVectorLiteral = true;
5978*67e74705SXin Li     }
5979*67e74705SXin Li     else
5980*67e74705SXin Li       isVectorLiteral = true;
5981*67e74705SXin Li   }
5982*67e74705SXin Li 
5983*67e74705SXin Li   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5984*67e74705SXin Li   // then handle it as such.
5985*67e74705SXin Li   if (isVectorLiteral)
5986*67e74705SXin Li     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5987*67e74705SXin Li 
5988*67e74705SXin Li   // If the Expr being casted is a ParenListExpr, handle it specially.
5989*67e74705SXin Li   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5990*67e74705SXin Li   // sequence of BinOp comma operators.
5991*67e74705SXin Li   if (isa<ParenListExpr>(CastExpr)) {
5992*67e74705SXin Li     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5993*67e74705SXin Li     if (Result.isInvalid()) return ExprError();
5994*67e74705SXin Li     CastExpr = Result.get();
5995*67e74705SXin Li   }
5996*67e74705SXin Li 
5997*67e74705SXin Li   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5998*67e74705SXin Li       !getSourceManager().isInSystemMacro(LParenLoc))
5999*67e74705SXin Li     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6000*67e74705SXin Li 
6001*67e74705SXin Li   CheckTollFreeBridgeCast(castType, CastExpr);
6002*67e74705SXin Li 
6003*67e74705SXin Li   CheckObjCBridgeRelatedCast(castType, CastExpr);
6004*67e74705SXin Li 
6005*67e74705SXin Li   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6006*67e74705SXin Li }
6007*67e74705SXin Li 
BuildVectorLiteral(SourceLocation LParenLoc,SourceLocation RParenLoc,Expr * E,TypeSourceInfo * TInfo)6008*67e74705SXin Li ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6009*67e74705SXin Li                                     SourceLocation RParenLoc, Expr *E,
6010*67e74705SXin Li                                     TypeSourceInfo *TInfo) {
6011*67e74705SXin Li   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6012*67e74705SXin Li          "Expected paren or paren list expression");
6013*67e74705SXin Li 
6014*67e74705SXin Li   Expr **exprs;
6015*67e74705SXin Li   unsigned numExprs;
6016*67e74705SXin Li   Expr *subExpr;
6017*67e74705SXin Li   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6018*67e74705SXin Li   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6019*67e74705SXin Li     LiteralLParenLoc = PE->getLParenLoc();
6020*67e74705SXin Li     LiteralRParenLoc = PE->getRParenLoc();
6021*67e74705SXin Li     exprs = PE->getExprs();
6022*67e74705SXin Li     numExprs = PE->getNumExprs();
6023*67e74705SXin Li   } else { // isa<ParenExpr> by assertion at function entrance
6024*67e74705SXin Li     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6025*67e74705SXin Li     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6026*67e74705SXin Li     subExpr = cast<ParenExpr>(E)->getSubExpr();
6027*67e74705SXin Li     exprs = &subExpr;
6028*67e74705SXin Li     numExprs = 1;
6029*67e74705SXin Li   }
6030*67e74705SXin Li 
6031*67e74705SXin Li   QualType Ty = TInfo->getType();
6032*67e74705SXin Li   assert(Ty->isVectorType() && "Expected vector type");
6033*67e74705SXin Li 
6034*67e74705SXin Li   SmallVector<Expr *, 8> initExprs;
6035*67e74705SXin Li   const VectorType *VTy = Ty->getAs<VectorType>();
6036*67e74705SXin Li   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6037*67e74705SXin Li 
6038*67e74705SXin Li   // '(...)' form of vector initialization in AltiVec: the number of
6039*67e74705SXin Li   // initializers must be one or must match the size of the vector.
6040*67e74705SXin Li   // If a single value is specified in the initializer then it will be
6041*67e74705SXin Li   // replicated to all the components of the vector
6042*67e74705SXin Li   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6043*67e74705SXin Li     // The number of initializers must be one or must match the size of the
6044*67e74705SXin Li     // vector. If a single value is specified in the initializer then it will
6045*67e74705SXin Li     // be replicated to all the components of the vector
6046*67e74705SXin Li     if (numExprs == 1) {
6047*67e74705SXin Li       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6048*67e74705SXin Li       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6049*67e74705SXin Li       if (Literal.isInvalid())
6050*67e74705SXin Li         return ExprError();
6051*67e74705SXin Li       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6052*67e74705SXin Li                                   PrepareScalarCast(Literal, ElemTy));
6053*67e74705SXin Li       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6054*67e74705SXin Li     }
6055*67e74705SXin Li     else if (numExprs < numElems) {
6056*67e74705SXin Li       Diag(E->getExprLoc(),
6057*67e74705SXin Li            diag::err_incorrect_number_of_vector_initializers);
6058*67e74705SXin Li       return ExprError();
6059*67e74705SXin Li     }
6060*67e74705SXin Li     else
6061*67e74705SXin Li       initExprs.append(exprs, exprs + numExprs);
6062*67e74705SXin Li   }
6063*67e74705SXin Li   else {
6064*67e74705SXin Li     // For OpenCL, when the number of initializers is a single value,
6065*67e74705SXin Li     // it will be replicated to all components of the vector.
6066*67e74705SXin Li     if (getLangOpts().OpenCL &&
6067*67e74705SXin Li         VTy->getVectorKind() == VectorType::GenericVector &&
6068*67e74705SXin Li         numExprs == 1) {
6069*67e74705SXin Li         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6070*67e74705SXin Li         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6071*67e74705SXin Li         if (Literal.isInvalid())
6072*67e74705SXin Li           return ExprError();
6073*67e74705SXin Li         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6074*67e74705SXin Li                                     PrepareScalarCast(Literal, ElemTy));
6075*67e74705SXin Li         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6076*67e74705SXin Li     }
6077*67e74705SXin Li 
6078*67e74705SXin Li     initExprs.append(exprs, exprs + numExprs);
6079*67e74705SXin Li   }
6080*67e74705SXin Li   // FIXME: This means that pretty-printing the final AST will produce curly
6081*67e74705SXin Li   // braces instead of the original commas.
6082*67e74705SXin Li   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6083*67e74705SXin Li                                                    initExprs, LiteralRParenLoc);
6084*67e74705SXin Li   initE->setType(Ty);
6085*67e74705SXin Li   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6086*67e74705SXin Li }
6087*67e74705SXin Li 
6088*67e74705SXin Li /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6089*67e74705SXin Li /// the ParenListExpr into a sequence of comma binary operators.
6090*67e74705SXin Li ExprResult
MaybeConvertParenListExprToParenExpr(Scope * S,Expr * OrigExpr)6091*67e74705SXin Li Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6092*67e74705SXin Li   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6093*67e74705SXin Li   if (!E)
6094*67e74705SXin Li     return OrigExpr;
6095*67e74705SXin Li 
6096*67e74705SXin Li   ExprResult Result(E->getExpr(0));
6097*67e74705SXin Li 
6098*67e74705SXin Li   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6099*67e74705SXin Li     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6100*67e74705SXin Li                         E->getExpr(i));
6101*67e74705SXin Li 
6102*67e74705SXin Li   if (Result.isInvalid()) return ExprError();
6103*67e74705SXin Li 
6104*67e74705SXin Li   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6105*67e74705SXin Li }
6106*67e74705SXin Li 
ActOnParenListExpr(SourceLocation L,SourceLocation R,MultiExprArg Val)6107*67e74705SXin Li ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6108*67e74705SXin Li                                     SourceLocation R,
6109*67e74705SXin Li                                     MultiExprArg Val) {
6110*67e74705SXin Li   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6111*67e74705SXin Li   return expr;
6112*67e74705SXin Li }
6113*67e74705SXin Li 
6114*67e74705SXin Li /// \brief Emit a specialized diagnostic when one expression is a null pointer
6115*67e74705SXin Li /// constant and the other is not a pointer.  Returns true if a diagnostic is
6116*67e74705SXin Li /// emitted.
DiagnoseConditionalForNull(Expr * LHSExpr,Expr * RHSExpr,SourceLocation QuestionLoc)6117*67e74705SXin Li bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6118*67e74705SXin Li                                       SourceLocation QuestionLoc) {
6119*67e74705SXin Li   Expr *NullExpr = LHSExpr;
6120*67e74705SXin Li   Expr *NonPointerExpr = RHSExpr;
6121*67e74705SXin Li   Expr::NullPointerConstantKind NullKind =
6122*67e74705SXin Li       NullExpr->isNullPointerConstant(Context,
6123*67e74705SXin Li                                       Expr::NPC_ValueDependentIsNotNull);
6124*67e74705SXin Li 
6125*67e74705SXin Li   if (NullKind == Expr::NPCK_NotNull) {
6126*67e74705SXin Li     NullExpr = RHSExpr;
6127*67e74705SXin Li     NonPointerExpr = LHSExpr;
6128*67e74705SXin Li     NullKind =
6129*67e74705SXin Li         NullExpr->isNullPointerConstant(Context,
6130*67e74705SXin Li                                         Expr::NPC_ValueDependentIsNotNull);
6131*67e74705SXin Li   }
6132*67e74705SXin Li 
6133*67e74705SXin Li   if (NullKind == Expr::NPCK_NotNull)
6134*67e74705SXin Li     return false;
6135*67e74705SXin Li 
6136*67e74705SXin Li   if (NullKind == Expr::NPCK_ZeroExpression)
6137*67e74705SXin Li     return false;
6138*67e74705SXin Li 
6139*67e74705SXin Li   if (NullKind == Expr::NPCK_ZeroLiteral) {
6140*67e74705SXin Li     // In this case, check to make sure that we got here from a "NULL"
6141*67e74705SXin Li     // string in the source code.
6142*67e74705SXin Li     NullExpr = NullExpr->IgnoreParenImpCasts();
6143*67e74705SXin Li     SourceLocation loc = NullExpr->getExprLoc();
6144*67e74705SXin Li     if (!findMacroSpelling(loc, "NULL"))
6145*67e74705SXin Li       return false;
6146*67e74705SXin Li   }
6147*67e74705SXin Li 
6148*67e74705SXin Li   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6149*67e74705SXin Li   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6150*67e74705SXin Li       << NonPointerExpr->getType() << DiagType
6151*67e74705SXin Li       << NonPointerExpr->getSourceRange();
6152*67e74705SXin Li   return true;
6153*67e74705SXin Li }
6154*67e74705SXin Li 
6155*67e74705SXin Li /// \brief Return false if the condition expression is valid, true otherwise.
checkCondition(Sema & S,Expr * Cond,SourceLocation QuestionLoc)6156*67e74705SXin Li static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6157*67e74705SXin Li   QualType CondTy = Cond->getType();
6158*67e74705SXin Li 
6159*67e74705SXin Li   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6160*67e74705SXin Li   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6161*67e74705SXin Li     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6162*67e74705SXin Li       << CondTy << Cond->getSourceRange();
6163*67e74705SXin Li     return true;
6164*67e74705SXin Li   }
6165*67e74705SXin Li 
6166*67e74705SXin Li   // C99 6.5.15p2
6167*67e74705SXin Li   if (CondTy->isScalarType()) return false;
6168*67e74705SXin Li 
6169*67e74705SXin Li   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6170*67e74705SXin Li     << CondTy << Cond->getSourceRange();
6171*67e74705SXin Li   return true;
6172*67e74705SXin Li }
6173*67e74705SXin Li 
6174*67e74705SXin Li /// \brief Handle when one or both operands are void type.
checkConditionalVoidType(Sema & S,ExprResult & LHS,ExprResult & RHS)6175*67e74705SXin Li static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6176*67e74705SXin Li                                          ExprResult &RHS) {
6177*67e74705SXin Li     Expr *LHSExpr = LHS.get();
6178*67e74705SXin Li     Expr *RHSExpr = RHS.get();
6179*67e74705SXin Li 
6180*67e74705SXin Li     if (!LHSExpr->getType()->isVoidType())
6181*67e74705SXin Li       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6182*67e74705SXin Li         << RHSExpr->getSourceRange();
6183*67e74705SXin Li     if (!RHSExpr->getType()->isVoidType())
6184*67e74705SXin Li       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6185*67e74705SXin Li         << LHSExpr->getSourceRange();
6186*67e74705SXin Li     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6187*67e74705SXin Li     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6188*67e74705SXin Li     return S.Context.VoidTy;
6189*67e74705SXin Li }
6190*67e74705SXin Li 
6191*67e74705SXin Li /// \brief Return false if the NullExpr can be promoted to PointerTy,
6192*67e74705SXin Li /// true otherwise.
checkConditionalNullPointer(Sema & S,ExprResult & NullExpr,QualType PointerTy)6193*67e74705SXin Li static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6194*67e74705SXin Li                                         QualType PointerTy) {
6195*67e74705SXin Li   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6196*67e74705SXin Li       !NullExpr.get()->isNullPointerConstant(S.Context,
6197*67e74705SXin Li                                             Expr::NPC_ValueDependentIsNull))
6198*67e74705SXin Li     return true;
6199*67e74705SXin Li 
6200*67e74705SXin Li   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6201*67e74705SXin Li   return false;
6202*67e74705SXin Li }
6203*67e74705SXin Li 
6204*67e74705SXin Li /// \brief Checks compatibility between two pointers and return the resulting
6205*67e74705SXin Li /// type.
checkConditionalPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)6206*67e74705SXin Li static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6207*67e74705SXin Li                                                      ExprResult &RHS,
6208*67e74705SXin Li                                                      SourceLocation Loc) {
6209*67e74705SXin Li   QualType LHSTy = LHS.get()->getType();
6210*67e74705SXin Li   QualType RHSTy = RHS.get()->getType();
6211*67e74705SXin Li 
6212*67e74705SXin Li   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6213*67e74705SXin Li     // Two identical pointers types are always compatible.
6214*67e74705SXin Li     return LHSTy;
6215*67e74705SXin Li   }
6216*67e74705SXin Li 
6217*67e74705SXin Li   QualType lhptee, rhptee;
6218*67e74705SXin Li 
6219*67e74705SXin Li   // Get the pointee types.
6220*67e74705SXin Li   bool IsBlockPointer = false;
6221*67e74705SXin Li   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6222*67e74705SXin Li     lhptee = LHSBTy->getPointeeType();
6223*67e74705SXin Li     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6224*67e74705SXin Li     IsBlockPointer = true;
6225*67e74705SXin Li   } else {
6226*67e74705SXin Li     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6227*67e74705SXin Li     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6228*67e74705SXin Li   }
6229*67e74705SXin Li 
6230*67e74705SXin Li   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6231*67e74705SXin Li   // differently qualified versions of compatible types, the result type is
6232*67e74705SXin Li   // a pointer to an appropriately qualified version of the composite
6233*67e74705SXin Li   // type.
6234*67e74705SXin Li 
6235*67e74705SXin Li   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6236*67e74705SXin Li   // clause doesn't make sense for our extensions. E.g. address space 2 should
6237*67e74705SXin Li   // be incompatible with address space 3: they may live on different devices or
6238*67e74705SXin Li   // anything.
6239*67e74705SXin Li   Qualifiers lhQual = lhptee.getQualifiers();
6240*67e74705SXin Li   Qualifiers rhQual = rhptee.getQualifiers();
6241*67e74705SXin Li 
6242*67e74705SXin Li   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6243*67e74705SXin Li   lhQual.removeCVRQualifiers();
6244*67e74705SXin Li   rhQual.removeCVRQualifiers();
6245*67e74705SXin Li 
6246*67e74705SXin Li   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6247*67e74705SXin Li   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6248*67e74705SXin Li 
6249*67e74705SXin Li   // For OpenCL:
6250*67e74705SXin Li   // 1. If LHS and RHS types match exactly and:
6251*67e74705SXin Li   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6252*67e74705SXin Li   //  (b) AS overlap => generate addrspacecast
6253*67e74705SXin Li   //  (c) AS don't overlap => give an error
6254*67e74705SXin Li   // 2. if LHS and RHS types don't match:
6255*67e74705SXin Li   //  (a) AS match => use standard C rules, generate bitcast
6256*67e74705SXin Li   //  (b) AS overlap => generate addrspacecast instead of bitcast
6257*67e74705SXin Li   //  (c) AS don't overlap => give an error
6258*67e74705SXin Li 
6259*67e74705SXin Li   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6260*67e74705SXin Li   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6261*67e74705SXin Li 
6262*67e74705SXin Li   // OpenCL cases 1c, 2a, 2b, and 2c.
6263*67e74705SXin Li   if (CompositeTy.isNull()) {
6264*67e74705SXin Li     // In this situation, we assume void* type. No especially good
6265*67e74705SXin Li     // reason, but this is what gcc does, and we do have to pick
6266*67e74705SXin Li     // to get a consistent AST.
6267*67e74705SXin Li     QualType incompatTy;
6268*67e74705SXin Li     if (S.getLangOpts().OpenCL) {
6269*67e74705SXin Li       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6270*67e74705SXin Li       // spaces is disallowed.
6271*67e74705SXin Li       unsigned ResultAddrSpace;
6272*67e74705SXin Li       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6273*67e74705SXin Li         // Cases 2a and 2b.
6274*67e74705SXin Li         ResultAddrSpace = lhQual.getAddressSpace();
6275*67e74705SXin Li       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6276*67e74705SXin Li         // Cases 2a and 2b.
6277*67e74705SXin Li         ResultAddrSpace = rhQual.getAddressSpace();
6278*67e74705SXin Li       } else {
6279*67e74705SXin Li         // Cases 1c and 2c.
6280*67e74705SXin Li         S.Diag(Loc,
6281*67e74705SXin Li                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6282*67e74705SXin Li             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6283*67e74705SXin Li             << RHS.get()->getSourceRange();
6284*67e74705SXin Li         return QualType();
6285*67e74705SXin Li       }
6286*67e74705SXin Li 
6287*67e74705SXin Li       // Continue handling cases 2a and 2b.
6288*67e74705SXin Li       incompatTy = S.Context.getPointerType(
6289*67e74705SXin Li           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6290*67e74705SXin Li       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6291*67e74705SXin Li                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6292*67e74705SXin Li                                     ? CK_AddressSpaceConversion /* 2b */
6293*67e74705SXin Li                                     : CK_BitCast /* 2a */);
6294*67e74705SXin Li       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6295*67e74705SXin Li                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6296*67e74705SXin Li                                     ? CK_AddressSpaceConversion /* 2b */
6297*67e74705SXin Li                                     : CK_BitCast /* 2a */);
6298*67e74705SXin Li     } else {
6299*67e74705SXin Li       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6300*67e74705SXin Li           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6301*67e74705SXin Li           << RHS.get()->getSourceRange();
6302*67e74705SXin Li       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6303*67e74705SXin Li       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6304*67e74705SXin Li       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6305*67e74705SXin Li     }
6306*67e74705SXin Li     return incompatTy;
6307*67e74705SXin Li   }
6308*67e74705SXin Li 
6309*67e74705SXin Li   // The pointer types are compatible.
6310*67e74705SXin Li   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6311*67e74705SXin Li   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6312*67e74705SXin Li   if (IsBlockPointer)
6313*67e74705SXin Li     ResultTy = S.Context.getBlockPointerType(ResultTy);
6314*67e74705SXin Li   else {
6315*67e74705SXin Li     // Cases 1a and 1b for OpenCL.
6316*67e74705SXin Li     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6317*67e74705SXin Li     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6318*67e74705SXin Li                       ? CK_BitCast /* 1a */
6319*67e74705SXin Li                       : CK_AddressSpaceConversion /* 1b */;
6320*67e74705SXin Li     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6321*67e74705SXin Li                       ? CK_BitCast /* 1a */
6322*67e74705SXin Li                       : CK_AddressSpaceConversion /* 1b */;
6323*67e74705SXin Li     ResultTy = S.Context.getPointerType(ResultTy);
6324*67e74705SXin Li   }
6325*67e74705SXin Li 
6326*67e74705SXin Li   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6327*67e74705SXin Li   // if the target type does not change.
6328*67e74705SXin Li   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6329*67e74705SXin Li   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6330*67e74705SXin Li   return ResultTy;
6331*67e74705SXin Li }
6332*67e74705SXin Li 
6333*67e74705SXin Li /// \brief Return the resulting type when the operands are both block pointers.
checkConditionalBlockPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)6334*67e74705SXin Li static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6335*67e74705SXin Li                                                           ExprResult &LHS,
6336*67e74705SXin Li                                                           ExprResult &RHS,
6337*67e74705SXin Li                                                           SourceLocation Loc) {
6338*67e74705SXin Li   QualType LHSTy = LHS.get()->getType();
6339*67e74705SXin Li   QualType RHSTy = RHS.get()->getType();
6340*67e74705SXin Li 
6341*67e74705SXin Li   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6342*67e74705SXin Li     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6343*67e74705SXin Li       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6344*67e74705SXin Li       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6345*67e74705SXin Li       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6346*67e74705SXin Li       return destType;
6347*67e74705SXin Li     }
6348*67e74705SXin Li     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6349*67e74705SXin Li       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6350*67e74705SXin Li       << RHS.get()->getSourceRange();
6351*67e74705SXin Li     return QualType();
6352*67e74705SXin Li   }
6353*67e74705SXin Li 
6354*67e74705SXin Li   // We have 2 block pointer types.
6355*67e74705SXin Li   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6356*67e74705SXin Li }
6357*67e74705SXin Li 
6358*67e74705SXin Li /// \brief Return the resulting type when the operands are both pointers.
6359*67e74705SXin Li static QualType
checkConditionalObjectPointersCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)6360*67e74705SXin Li checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6361*67e74705SXin Li                                             ExprResult &RHS,
6362*67e74705SXin Li                                             SourceLocation Loc) {
6363*67e74705SXin Li   // get the pointer types
6364*67e74705SXin Li   QualType LHSTy = LHS.get()->getType();
6365*67e74705SXin Li   QualType RHSTy = RHS.get()->getType();
6366*67e74705SXin Li 
6367*67e74705SXin Li   // get the "pointed to" types
6368*67e74705SXin Li   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6369*67e74705SXin Li   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6370*67e74705SXin Li 
6371*67e74705SXin Li   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6372*67e74705SXin Li   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6373*67e74705SXin Li     // Figure out necessary qualifiers (C99 6.5.15p6)
6374*67e74705SXin Li     QualType destPointee
6375*67e74705SXin Li       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6376*67e74705SXin Li     QualType destType = S.Context.getPointerType(destPointee);
6377*67e74705SXin Li     // Add qualifiers if necessary.
6378*67e74705SXin Li     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6379*67e74705SXin Li     // Promote to void*.
6380*67e74705SXin Li     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6381*67e74705SXin Li     return destType;
6382*67e74705SXin Li   }
6383*67e74705SXin Li   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6384*67e74705SXin Li     QualType destPointee
6385*67e74705SXin Li       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6386*67e74705SXin Li     QualType destType = S.Context.getPointerType(destPointee);
6387*67e74705SXin Li     // Add qualifiers if necessary.
6388*67e74705SXin Li     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6389*67e74705SXin Li     // Promote to void*.
6390*67e74705SXin Li     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6391*67e74705SXin Li     return destType;
6392*67e74705SXin Li   }
6393*67e74705SXin Li 
6394*67e74705SXin Li   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6395*67e74705SXin Li }
6396*67e74705SXin Li 
6397*67e74705SXin Li /// \brief Return false if the first expression is not an integer and the second
6398*67e74705SXin Li /// expression is not a pointer, true otherwise.
checkPointerIntegerMismatch(Sema & S,ExprResult & Int,Expr * PointerExpr,SourceLocation Loc,bool IsIntFirstExpr)6399*67e74705SXin Li static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6400*67e74705SXin Li                                         Expr* PointerExpr, SourceLocation Loc,
6401*67e74705SXin Li                                         bool IsIntFirstExpr) {
6402*67e74705SXin Li   if (!PointerExpr->getType()->isPointerType() ||
6403*67e74705SXin Li       !Int.get()->getType()->isIntegerType())
6404*67e74705SXin Li     return false;
6405*67e74705SXin Li 
6406*67e74705SXin Li   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6407*67e74705SXin Li   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6408*67e74705SXin Li 
6409*67e74705SXin Li   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6410*67e74705SXin Li     << Expr1->getType() << Expr2->getType()
6411*67e74705SXin Li     << Expr1->getSourceRange() << Expr2->getSourceRange();
6412*67e74705SXin Li   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6413*67e74705SXin Li                             CK_IntegralToPointer);
6414*67e74705SXin Li   return true;
6415*67e74705SXin Li }
6416*67e74705SXin Li 
6417*67e74705SXin Li /// \brief Simple conversion between integer and floating point types.
6418*67e74705SXin Li ///
6419*67e74705SXin Li /// Used when handling the OpenCL conditional operator where the
6420*67e74705SXin Li /// condition is a vector while the other operands are scalar.
6421*67e74705SXin Li ///
6422*67e74705SXin Li /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6423*67e74705SXin Li /// types are either integer or floating type. Between the two
6424*67e74705SXin Li /// operands, the type with the higher rank is defined as the "result
6425*67e74705SXin Li /// type". The other operand needs to be promoted to the same type. No
6426*67e74705SXin Li /// other type promotion is allowed. We cannot use
6427*67e74705SXin Li /// UsualArithmeticConversions() for this purpose, since it always
6428*67e74705SXin Li /// promotes promotable types.
OpenCLArithmeticConversions(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6429*67e74705SXin Li static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6430*67e74705SXin Li                                             ExprResult &RHS,
6431*67e74705SXin Li                                             SourceLocation QuestionLoc) {
6432*67e74705SXin Li   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6433*67e74705SXin Li   if (LHS.isInvalid())
6434*67e74705SXin Li     return QualType();
6435*67e74705SXin Li   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6436*67e74705SXin Li   if (RHS.isInvalid())
6437*67e74705SXin Li     return QualType();
6438*67e74705SXin Li 
6439*67e74705SXin Li   // For conversion purposes, we ignore any qualifiers.
6440*67e74705SXin Li   // For example, "const float" and "float" are equivalent.
6441*67e74705SXin Li   QualType LHSType =
6442*67e74705SXin Li     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6443*67e74705SXin Li   QualType RHSType =
6444*67e74705SXin Li     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6445*67e74705SXin Li 
6446*67e74705SXin Li   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6447*67e74705SXin Li     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6448*67e74705SXin Li       << LHSType << LHS.get()->getSourceRange();
6449*67e74705SXin Li     return QualType();
6450*67e74705SXin Li   }
6451*67e74705SXin Li 
6452*67e74705SXin Li   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6453*67e74705SXin Li     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6454*67e74705SXin Li       << RHSType << RHS.get()->getSourceRange();
6455*67e74705SXin Li     return QualType();
6456*67e74705SXin Li   }
6457*67e74705SXin Li 
6458*67e74705SXin Li   // If both types are identical, no conversion is needed.
6459*67e74705SXin Li   if (LHSType == RHSType)
6460*67e74705SXin Li     return LHSType;
6461*67e74705SXin Li 
6462*67e74705SXin Li   // Now handle "real" floating types (i.e. float, double, long double).
6463*67e74705SXin Li   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6464*67e74705SXin Li     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6465*67e74705SXin Li                                  /*IsCompAssign = */ false);
6466*67e74705SXin Li 
6467*67e74705SXin Li   // Finally, we have two differing integer types.
6468*67e74705SXin Li   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6469*67e74705SXin Li   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6470*67e74705SXin Li }
6471*67e74705SXin Li 
6472*67e74705SXin Li /// \brief Convert scalar operands to a vector that matches the
6473*67e74705SXin Li ///        condition in length.
6474*67e74705SXin Li ///
6475*67e74705SXin Li /// Used when handling the OpenCL conditional operator where the
6476*67e74705SXin Li /// condition is a vector while the other operands are scalar.
6477*67e74705SXin Li ///
6478*67e74705SXin Li /// We first compute the "result type" for the scalar operands
6479*67e74705SXin Li /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6480*67e74705SXin Li /// into a vector of that type where the length matches the condition
6481*67e74705SXin Li /// vector type. s6.11.6 requires that the element types of the result
6482*67e74705SXin Li /// and the condition must have the same number of bits.
6483*67e74705SXin Li static QualType
OpenCLConvertScalarsToVectors(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType CondTy,SourceLocation QuestionLoc)6484*67e74705SXin Li OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6485*67e74705SXin Li                               QualType CondTy, SourceLocation QuestionLoc) {
6486*67e74705SXin Li   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6487*67e74705SXin Li   if (ResTy.isNull()) return QualType();
6488*67e74705SXin Li 
6489*67e74705SXin Li   const VectorType *CV = CondTy->getAs<VectorType>();
6490*67e74705SXin Li   assert(CV);
6491*67e74705SXin Li 
6492*67e74705SXin Li   // Determine the vector result type
6493*67e74705SXin Li   unsigned NumElements = CV->getNumElements();
6494*67e74705SXin Li   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6495*67e74705SXin Li 
6496*67e74705SXin Li   // Ensure that all types have the same number of bits
6497*67e74705SXin Li   if (S.Context.getTypeSize(CV->getElementType())
6498*67e74705SXin Li       != S.Context.getTypeSize(ResTy)) {
6499*67e74705SXin Li     // Since VectorTy is created internally, it does not pretty print
6500*67e74705SXin Li     // with an OpenCL name. Instead, we just print a description.
6501*67e74705SXin Li     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6502*67e74705SXin Li     SmallString<64> Str;
6503*67e74705SXin Li     llvm::raw_svector_ostream OS(Str);
6504*67e74705SXin Li     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6505*67e74705SXin Li     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6506*67e74705SXin Li       << CondTy << OS.str();
6507*67e74705SXin Li     return QualType();
6508*67e74705SXin Li   }
6509*67e74705SXin Li 
6510*67e74705SXin Li   // Convert operands to the vector result type
6511*67e74705SXin Li   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6512*67e74705SXin Li   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6513*67e74705SXin Li 
6514*67e74705SXin Li   return VectorTy;
6515*67e74705SXin Li }
6516*67e74705SXin Li 
6517*67e74705SXin Li /// \brief Return false if this is a valid OpenCL condition vector
checkOpenCLConditionVector(Sema & S,Expr * Cond,SourceLocation QuestionLoc)6518*67e74705SXin Li static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6519*67e74705SXin Li                                        SourceLocation QuestionLoc) {
6520*67e74705SXin Li   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6521*67e74705SXin Li   // integral type.
6522*67e74705SXin Li   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6523*67e74705SXin Li   assert(CondTy);
6524*67e74705SXin Li   QualType EleTy = CondTy->getElementType();
6525*67e74705SXin Li   if (EleTy->isIntegerType()) return false;
6526*67e74705SXin Li 
6527*67e74705SXin Li   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6528*67e74705SXin Li     << Cond->getType() << Cond->getSourceRange();
6529*67e74705SXin Li   return true;
6530*67e74705SXin Li }
6531*67e74705SXin Li 
6532*67e74705SXin Li /// \brief Return false if the vector condition type and the vector
6533*67e74705SXin Li ///        result type are compatible.
6534*67e74705SXin Li ///
6535*67e74705SXin Li /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6536*67e74705SXin Li /// number of elements, and their element types have the same number
6537*67e74705SXin Li /// of bits.
checkVectorResult(Sema & S,QualType CondTy,QualType VecResTy,SourceLocation QuestionLoc)6538*67e74705SXin Li static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6539*67e74705SXin Li                               SourceLocation QuestionLoc) {
6540*67e74705SXin Li   const VectorType *CV = CondTy->getAs<VectorType>();
6541*67e74705SXin Li   const VectorType *RV = VecResTy->getAs<VectorType>();
6542*67e74705SXin Li   assert(CV && RV);
6543*67e74705SXin Li 
6544*67e74705SXin Li   if (CV->getNumElements() != RV->getNumElements()) {
6545*67e74705SXin Li     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6546*67e74705SXin Li       << CondTy << VecResTy;
6547*67e74705SXin Li     return true;
6548*67e74705SXin Li   }
6549*67e74705SXin Li 
6550*67e74705SXin Li   QualType CVE = CV->getElementType();
6551*67e74705SXin Li   QualType RVE = RV->getElementType();
6552*67e74705SXin Li 
6553*67e74705SXin Li   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6554*67e74705SXin Li     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6555*67e74705SXin Li       << CondTy << VecResTy;
6556*67e74705SXin Li     return true;
6557*67e74705SXin Li   }
6558*67e74705SXin Li 
6559*67e74705SXin Li   return false;
6560*67e74705SXin Li }
6561*67e74705SXin Li 
6562*67e74705SXin Li /// \brief Return the resulting type for the conditional operator in
6563*67e74705SXin Li ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6564*67e74705SXin Li ///        s6.3.i) when the condition is a vector type.
6565*67e74705SXin Li static QualType
OpenCLCheckVectorConditional(Sema & S,ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6566*67e74705SXin Li OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6567*67e74705SXin Li                              ExprResult &LHS, ExprResult &RHS,
6568*67e74705SXin Li                              SourceLocation QuestionLoc) {
6569*67e74705SXin Li   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6570*67e74705SXin Li   if (Cond.isInvalid())
6571*67e74705SXin Li     return QualType();
6572*67e74705SXin Li   QualType CondTy = Cond.get()->getType();
6573*67e74705SXin Li 
6574*67e74705SXin Li   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6575*67e74705SXin Li     return QualType();
6576*67e74705SXin Li 
6577*67e74705SXin Li   // If either operand is a vector then find the vector type of the
6578*67e74705SXin Li   // result as specified in OpenCL v1.1 s6.3.i.
6579*67e74705SXin Li   if (LHS.get()->getType()->isVectorType() ||
6580*67e74705SXin Li       RHS.get()->getType()->isVectorType()) {
6581*67e74705SXin Li     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6582*67e74705SXin Li                                               /*isCompAssign*/false,
6583*67e74705SXin Li                                               /*AllowBothBool*/true,
6584*67e74705SXin Li                                               /*AllowBoolConversions*/false);
6585*67e74705SXin Li     if (VecResTy.isNull()) return QualType();
6586*67e74705SXin Li     // The result type must match the condition type as specified in
6587*67e74705SXin Li     // OpenCL v1.1 s6.11.6.
6588*67e74705SXin Li     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6589*67e74705SXin Li       return QualType();
6590*67e74705SXin Li     return VecResTy;
6591*67e74705SXin Li   }
6592*67e74705SXin Li 
6593*67e74705SXin Li   // Both operands are scalar.
6594*67e74705SXin Li   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6595*67e74705SXin Li }
6596*67e74705SXin Li 
6597*67e74705SXin Li /// \brief Return true if the Expr is block type
checkBlockType(Sema & S,const Expr * E)6598*67e74705SXin Li static bool checkBlockType(Sema &S, const Expr *E) {
6599*67e74705SXin Li   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6600*67e74705SXin Li     QualType Ty = CE->getCallee()->getType();
6601*67e74705SXin Li     if (Ty->isBlockPointerType()) {
6602*67e74705SXin Li       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6603*67e74705SXin Li       return true;
6604*67e74705SXin Li     }
6605*67e74705SXin Li   }
6606*67e74705SXin Li   return false;
6607*67e74705SXin Li }
6608*67e74705SXin Li 
6609*67e74705SXin Li /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6610*67e74705SXin Li /// In that case, LHS = cond.
6611*67e74705SXin Li /// C99 6.5.15
CheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)6612*67e74705SXin Li QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6613*67e74705SXin Li                                         ExprResult &RHS, ExprValueKind &VK,
6614*67e74705SXin Li                                         ExprObjectKind &OK,
6615*67e74705SXin Li                                         SourceLocation QuestionLoc) {
6616*67e74705SXin Li 
6617*67e74705SXin Li   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6618*67e74705SXin Li   if (!LHSResult.isUsable()) return QualType();
6619*67e74705SXin Li   LHS = LHSResult;
6620*67e74705SXin Li 
6621*67e74705SXin Li   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6622*67e74705SXin Li   if (!RHSResult.isUsable()) return QualType();
6623*67e74705SXin Li   RHS = RHSResult;
6624*67e74705SXin Li 
6625*67e74705SXin Li   // C++ is sufficiently different to merit its own checker.
6626*67e74705SXin Li   if (getLangOpts().CPlusPlus)
6627*67e74705SXin Li     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6628*67e74705SXin Li 
6629*67e74705SXin Li   VK = VK_RValue;
6630*67e74705SXin Li   OK = OK_Ordinary;
6631*67e74705SXin Li 
6632*67e74705SXin Li   // The OpenCL operator with a vector condition is sufficiently
6633*67e74705SXin Li   // different to merit its own checker.
6634*67e74705SXin Li   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6635*67e74705SXin Li     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6636*67e74705SXin Li 
6637*67e74705SXin Li   // First, check the condition.
6638*67e74705SXin Li   Cond = UsualUnaryConversions(Cond.get());
6639*67e74705SXin Li   if (Cond.isInvalid())
6640*67e74705SXin Li     return QualType();
6641*67e74705SXin Li   if (checkCondition(*this, Cond.get(), QuestionLoc))
6642*67e74705SXin Li     return QualType();
6643*67e74705SXin Li 
6644*67e74705SXin Li   // Now check the two expressions.
6645*67e74705SXin Li   if (LHS.get()->getType()->isVectorType() ||
6646*67e74705SXin Li       RHS.get()->getType()->isVectorType())
6647*67e74705SXin Li     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6648*67e74705SXin Li                                /*AllowBothBool*/true,
6649*67e74705SXin Li                                /*AllowBoolConversions*/false);
6650*67e74705SXin Li 
6651*67e74705SXin Li   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6652*67e74705SXin Li   if (LHS.isInvalid() || RHS.isInvalid())
6653*67e74705SXin Li     return QualType();
6654*67e74705SXin Li 
6655*67e74705SXin Li   QualType LHSTy = LHS.get()->getType();
6656*67e74705SXin Li   QualType RHSTy = RHS.get()->getType();
6657*67e74705SXin Li 
6658*67e74705SXin Li   // Diagnose attempts to convert between __float128 and long double where
6659*67e74705SXin Li   // such conversions currently can't be handled.
6660*67e74705SXin Li   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6661*67e74705SXin Li     Diag(QuestionLoc,
6662*67e74705SXin Li          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6663*67e74705SXin Li       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6664*67e74705SXin Li     return QualType();
6665*67e74705SXin Li   }
6666*67e74705SXin Li 
6667*67e74705SXin Li   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6668*67e74705SXin Li   // selection operator (?:).
6669*67e74705SXin Li   if (getLangOpts().OpenCL &&
6670*67e74705SXin Li       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6671*67e74705SXin Li     return QualType();
6672*67e74705SXin Li   }
6673*67e74705SXin Li 
6674*67e74705SXin Li   // If both operands have arithmetic type, do the usual arithmetic conversions
6675*67e74705SXin Li   // to find a common type: C99 6.5.15p3,5.
6676*67e74705SXin Li   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6677*67e74705SXin Li     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6678*67e74705SXin Li     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6679*67e74705SXin Li 
6680*67e74705SXin Li     return ResTy;
6681*67e74705SXin Li   }
6682*67e74705SXin Li 
6683*67e74705SXin Li   // If both operands are the same structure or union type, the result is that
6684*67e74705SXin Li   // type.
6685*67e74705SXin Li   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6686*67e74705SXin Li     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6687*67e74705SXin Li       if (LHSRT->getDecl() == RHSRT->getDecl())
6688*67e74705SXin Li         // "If both the operands have structure or union type, the result has
6689*67e74705SXin Li         // that type."  This implies that CV qualifiers are dropped.
6690*67e74705SXin Li         return LHSTy.getUnqualifiedType();
6691*67e74705SXin Li     // FIXME: Type of conditional expression must be complete in C mode.
6692*67e74705SXin Li   }
6693*67e74705SXin Li 
6694*67e74705SXin Li   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6695*67e74705SXin Li   // The following || allows only one side to be void (a GCC-ism).
6696*67e74705SXin Li   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6697*67e74705SXin Li     return checkConditionalVoidType(*this, LHS, RHS);
6698*67e74705SXin Li   }
6699*67e74705SXin Li 
6700*67e74705SXin Li   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6701*67e74705SXin Li   // the type of the other operand."
6702*67e74705SXin Li   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6703*67e74705SXin Li   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6704*67e74705SXin Li 
6705*67e74705SXin Li   // All objective-c pointer type analysis is done here.
6706*67e74705SXin Li   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6707*67e74705SXin Li                                                         QuestionLoc);
6708*67e74705SXin Li   if (LHS.isInvalid() || RHS.isInvalid())
6709*67e74705SXin Li     return QualType();
6710*67e74705SXin Li   if (!compositeType.isNull())
6711*67e74705SXin Li     return compositeType;
6712*67e74705SXin Li 
6713*67e74705SXin Li 
6714*67e74705SXin Li   // Handle block pointer types.
6715*67e74705SXin Li   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6716*67e74705SXin Li     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6717*67e74705SXin Li                                                      QuestionLoc);
6718*67e74705SXin Li 
6719*67e74705SXin Li   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6720*67e74705SXin Li   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6721*67e74705SXin Li     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6722*67e74705SXin Li                                                        QuestionLoc);
6723*67e74705SXin Li 
6724*67e74705SXin Li   // GCC compatibility: soften pointer/integer mismatch.  Note that
6725*67e74705SXin Li   // null pointers have been filtered out by this point.
6726*67e74705SXin Li   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6727*67e74705SXin Li       /*isIntFirstExpr=*/true))
6728*67e74705SXin Li     return RHSTy;
6729*67e74705SXin Li   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6730*67e74705SXin Li       /*isIntFirstExpr=*/false))
6731*67e74705SXin Li     return LHSTy;
6732*67e74705SXin Li 
6733*67e74705SXin Li   // Emit a better diagnostic if one of the expressions is a null pointer
6734*67e74705SXin Li   // constant and the other is not a pointer type. In this case, the user most
6735*67e74705SXin Li   // likely forgot to take the address of the other expression.
6736*67e74705SXin Li   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6737*67e74705SXin Li     return QualType();
6738*67e74705SXin Li 
6739*67e74705SXin Li   // Otherwise, the operands are not compatible.
6740*67e74705SXin Li   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6741*67e74705SXin Li     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6742*67e74705SXin Li     << RHS.get()->getSourceRange();
6743*67e74705SXin Li   return QualType();
6744*67e74705SXin Li }
6745*67e74705SXin Li 
6746*67e74705SXin Li /// FindCompositeObjCPointerType - Helper method to find composite type of
6747*67e74705SXin Li /// two objective-c pointer types of the two input expressions.
FindCompositeObjCPointerType(ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6748*67e74705SXin Li QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6749*67e74705SXin Li                                             SourceLocation QuestionLoc) {
6750*67e74705SXin Li   QualType LHSTy = LHS.get()->getType();
6751*67e74705SXin Li   QualType RHSTy = RHS.get()->getType();
6752*67e74705SXin Li 
6753*67e74705SXin Li   // Handle things like Class and struct objc_class*.  Here we case the result
6754*67e74705SXin Li   // to the pseudo-builtin, because that will be implicitly cast back to the
6755*67e74705SXin Li   // redefinition type if an attempt is made to access its fields.
6756*67e74705SXin Li   if (LHSTy->isObjCClassType() &&
6757*67e74705SXin Li       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6758*67e74705SXin Li     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6759*67e74705SXin Li     return LHSTy;
6760*67e74705SXin Li   }
6761*67e74705SXin Li   if (RHSTy->isObjCClassType() &&
6762*67e74705SXin Li       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6763*67e74705SXin Li     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6764*67e74705SXin Li     return RHSTy;
6765*67e74705SXin Li   }
6766*67e74705SXin Li   // And the same for struct objc_object* / id
6767*67e74705SXin Li   if (LHSTy->isObjCIdType() &&
6768*67e74705SXin Li       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6769*67e74705SXin Li     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6770*67e74705SXin Li     return LHSTy;
6771*67e74705SXin Li   }
6772*67e74705SXin Li   if (RHSTy->isObjCIdType() &&
6773*67e74705SXin Li       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6774*67e74705SXin Li     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6775*67e74705SXin Li     return RHSTy;
6776*67e74705SXin Li   }
6777*67e74705SXin Li   // And the same for struct objc_selector* / SEL
6778*67e74705SXin Li   if (Context.isObjCSelType(LHSTy) &&
6779*67e74705SXin Li       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6780*67e74705SXin Li     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6781*67e74705SXin Li     return LHSTy;
6782*67e74705SXin Li   }
6783*67e74705SXin Li   if (Context.isObjCSelType(RHSTy) &&
6784*67e74705SXin Li       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6785*67e74705SXin Li     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6786*67e74705SXin Li     return RHSTy;
6787*67e74705SXin Li   }
6788*67e74705SXin Li   // Check constraints for Objective-C object pointers types.
6789*67e74705SXin Li   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6790*67e74705SXin Li 
6791*67e74705SXin Li     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6792*67e74705SXin Li       // Two identical object pointer types are always compatible.
6793*67e74705SXin Li       return LHSTy;
6794*67e74705SXin Li     }
6795*67e74705SXin Li     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6796*67e74705SXin Li     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6797*67e74705SXin Li     QualType compositeType = LHSTy;
6798*67e74705SXin Li 
6799*67e74705SXin Li     // If both operands are interfaces and either operand can be
6800*67e74705SXin Li     // assigned to the other, use that type as the composite
6801*67e74705SXin Li     // type. This allows
6802*67e74705SXin Li     //   xxx ? (A*) a : (B*) b
6803*67e74705SXin Li     // where B is a subclass of A.
6804*67e74705SXin Li     //
6805*67e74705SXin Li     // Additionally, as for assignment, if either type is 'id'
6806*67e74705SXin Li     // allow silent coercion. Finally, if the types are
6807*67e74705SXin Li     // incompatible then make sure to use 'id' as the composite
6808*67e74705SXin Li     // type so the result is acceptable for sending messages to.
6809*67e74705SXin Li 
6810*67e74705SXin Li     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6811*67e74705SXin Li     // It could return the composite type.
6812*67e74705SXin Li     if (!(compositeType =
6813*67e74705SXin Li           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6814*67e74705SXin Li       // Nothing more to do.
6815*67e74705SXin Li     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6816*67e74705SXin Li       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6817*67e74705SXin Li     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6818*67e74705SXin Li       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6819*67e74705SXin Li     } else if ((LHSTy->isObjCQualifiedIdType() ||
6820*67e74705SXin Li                 RHSTy->isObjCQualifiedIdType()) &&
6821*67e74705SXin Li                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6822*67e74705SXin Li       // Need to handle "id<xx>" explicitly.
6823*67e74705SXin Li       // GCC allows qualified id and any Objective-C type to devolve to
6824*67e74705SXin Li       // id. Currently localizing to here until clear this should be
6825*67e74705SXin Li       // part of ObjCQualifiedIdTypesAreCompatible.
6826*67e74705SXin Li       compositeType = Context.getObjCIdType();
6827*67e74705SXin Li     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6828*67e74705SXin Li       compositeType = Context.getObjCIdType();
6829*67e74705SXin Li     } else {
6830*67e74705SXin Li       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6831*67e74705SXin Li       << LHSTy << RHSTy
6832*67e74705SXin Li       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6833*67e74705SXin Li       QualType incompatTy = Context.getObjCIdType();
6834*67e74705SXin Li       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6835*67e74705SXin Li       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6836*67e74705SXin Li       return incompatTy;
6837*67e74705SXin Li     }
6838*67e74705SXin Li     // The object pointer types are compatible.
6839*67e74705SXin Li     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6840*67e74705SXin Li     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6841*67e74705SXin Li     return compositeType;
6842*67e74705SXin Li   }
6843*67e74705SXin Li   // Check Objective-C object pointer types and 'void *'
6844*67e74705SXin Li   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6845*67e74705SXin Li     if (getLangOpts().ObjCAutoRefCount) {
6846*67e74705SXin Li       // ARC forbids the implicit conversion of object pointers to 'void *',
6847*67e74705SXin Li       // so these types are not compatible.
6848*67e74705SXin Li       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6849*67e74705SXin Li           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6850*67e74705SXin Li       LHS = RHS = true;
6851*67e74705SXin Li       return QualType();
6852*67e74705SXin Li     }
6853*67e74705SXin Li     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6854*67e74705SXin Li     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6855*67e74705SXin Li     QualType destPointee
6856*67e74705SXin Li     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6857*67e74705SXin Li     QualType destType = Context.getPointerType(destPointee);
6858*67e74705SXin Li     // Add qualifiers if necessary.
6859*67e74705SXin Li     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6860*67e74705SXin Li     // Promote to void*.
6861*67e74705SXin Li     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6862*67e74705SXin Li     return destType;
6863*67e74705SXin Li   }
6864*67e74705SXin Li   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6865*67e74705SXin Li     if (getLangOpts().ObjCAutoRefCount) {
6866*67e74705SXin Li       // ARC forbids the implicit conversion of object pointers to 'void *',
6867*67e74705SXin Li       // so these types are not compatible.
6868*67e74705SXin Li       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6869*67e74705SXin Li           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6870*67e74705SXin Li       LHS = RHS = true;
6871*67e74705SXin Li       return QualType();
6872*67e74705SXin Li     }
6873*67e74705SXin Li     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6874*67e74705SXin Li     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6875*67e74705SXin Li     QualType destPointee
6876*67e74705SXin Li     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6877*67e74705SXin Li     QualType destType = Context.getPointerType(destPointee);
6878*67e74705SXin Li     // Add qualifiers if necessary.
6879*67e74705SXin Li     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6880*67e74705SXin Li     // Promote to void*.
6881*67e74705SXin Li     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6882*67e74705SXin Li     return destType;
6883*67e74705SXin Li   }
6884*67e74705SXin Li   return QualType();
6885*67e74705SXin Li }
6886*67e74705SXin Li 
6887*67e74705SXin Li /// SuggestParentheses - Emit a note with a fixit hint that wraps
6888*67e74705SXin Li /// ParenRange in parentheses.
SuggestParentheses(Sema & Self,SourceLocation Loc,const PartialDiagnostic & Note,SourceRange ParenRange)6889*67e74705SXin Li static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6890*67e74705SXin Li                                const PartialDiagnostic &Note,
6891*67e74705SXin Li                                SourceRange ParenRange) {
6892*67e74705SXin Li   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6893*67e74705SXin Li   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6894*67e74705SXin Li       EndLoc.isValid()) {
6895*67e74705SXin Li     Self.Diag(Loc, Note)
6896*67e74705SXin Li       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6897*67e74705SXin Li       << FixItHint::CreateInsertion(EndLoc, ")");
6898*67e74705SXin Li   } else {
6899*67e74705SXin Li     // We can't display the parentheses, so just show the bare note.
6900*67e74705SXin Li     Self.Diag(Loc, Note) << ParenRange;
6901*67e74705SXin Li   }
6902*67e74705SXin Li }
6903*67e74705SXin Li 
IsArithmeticOp(BinaryOperatorKind Opc)6904*67e74705SXin Li static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6905*67e74705SXin Li   return BinaryOperator::isAdditiveOp(Opc) ||
6906*67e74705SXin Li          BinaryOperator::isMultiplicativeOp(Opc) ||
6907*67e74705SXin Li          BinaryOperator::isShiftOp(Opc);
6908*67e74705SXin Li }
6909*67e74705SXin Li 
6910*67e74705SXin Li /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6911*67e74705SXin Li /// expression, either using a built-in or overloaded operator,
6912*67e74705SXin Li /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6913*67e74705SXin Li /// expression.
IsArithmeticBinaryExpr(Expr * E,BinaryOperatorKind * Opcode,Expr ** RHSExprs)6914*67e74705SXin Li static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6915*67e74705SXin Li                                    Expr **RHSExprs) {
6916*67e74705SXin Li   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6917*67e74705SXin Li   E = E->IgnoreImpCasts();
6918*67e74705SXin Li   E = E->IgnoreConversionOperator();
6919*67e74705SXin Li   E = E->IgnoreImpCasts();
6920*67e74705SXin Li 
6921*67e74705SXin Li   // Built-in binary operator.
6922*67e74705SXin Li   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6923*67e74705SXin Li     if (IsArithmeticOp(OP->getOpcode())) {
6924*67e74705SXin Li       *Opcode = OP->getOpcode();
6925*67e74705SXin Li       *RHSExprs = OP->getRHS();
6926*67e74705SXin Li       return true;
6927*67e74705SXin Li     }
6928*67e74705SXin Li   }
6929*67e74705SXin Li 
6930*67e74705SXin Li   // Overloaded operator.
6931*67e74705SXin Li   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6932*67e74705SXin Li     if (Call->getNumArgs() != 2)
6933*67e74705SXin Li       return false;
6934*67e74705SXin Li 
6935*67e74705SXin Li     // Make sure this is really a binary operator that is safe to pass into
6936*67e74705SXin Li     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6937*67e74705SXin Li     OverloadedOperatorKind OO = Call->getOperator();
6938*67e74705SXin Li     if (OO < OO_Plus || OO > OO_Arrow ||
6939*67e74705SXin Li         OO == OO_PlusPlus || OO == OO_MinusMinus)
6940*67e74705SXin Li       return false;
6941*67e74705SXin Li 
6942*67e74705SXin Li     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6943*67e74705SXin Li     if (IsArithmeticOp(OpKind)) {
6944*67e74705SXin Li       *Opcode = OpKind;
6945*67e74705SXin Li       *RHSExprs = Call->getArg(1);
6946*67e74705SXin Li       return true;
6947*67e74705SXin Li     }
6948*67e74705SXin Li   }
6949*67e74705SXin Li 
6950*67e74705SXin Li   return false;
6951*67e74705SXin Li }
6952*67e74705SXin Li 
6953*67e74705SXin Li /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6954*67e74705SXin Li /// or is a logical expression such as (x==y) which has int type, but is
6955*67e74705SXin Li /// commonly interpreted as boolean.
ExprLooksBoolean(Expr * E)6956*67e74705SXin Li static bool ExprLooksBoolean(Expr *E) {
6957*67e74705SXin Li   E = E->IgnoreParenImpCasts();
6958*67e74705SXin Li 
6959*67e74705SXin Li   if (E->getType()->isBooleanType())
6960*67e74705SXin Li     return true;
6961*67e74705SXin Li   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6962*67e74705SXin Li     return OP->isComparisonOp() || OP->isLogicalOp();
6963*67e74705SXin Li   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6964*67e74705SXin Li     return OP->getOpcode() == UO_LNot;
6965*67e74705SXin Li   if (E->getType()->isPointerType())
6966*67e74705SXin Li     return true;
6967*67e74705SXin Li 
6968*67e74705SXin Li   return false;
6969*67e74705SXin Li }
6970*67e74705SXin Li 
6971*67e74705SXin Li /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6972*67e74705SXin Li /// and binary operator are mixed in a way that suggests the programmer assumed
6973*67e74705SXin Li /// the conditional operator has higher precedence, for example:
6974*67e74705SXin Li /// "int x = a + someBinaryCondition ? 1 : 2".
DiagnoseConditionalPrecedence(Sema & Self,SourceLocation OpLoc,Expr * Condition,Expr * LHSExpr,Expr * RHSExpr)6975*67e74705SXin Li static void DiagnoseConditionalPrecedence(Sema &Self,
6976*67e74705SXin Li                                           SourceLocation OpLoc,
6977*67e74705SXin Li                                           Expr *Condition,
6978*67e74705SXin Li                                           Expr *LHSExpr,
6979*67e74705SXin Li                                           Expr *RHSExpr) {
6980*67e74705SXin Li   BinaryOperatorKind CondOpcode;
6981*67e74705SXin Li   Expr *CondRHS;
6982*67e74705SXin Li 
6983*67e74705SXin Li   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6984*67e74705SXin Li     return;
6985*67e74705SXin Li   if (!ExprLooksBoolean(CondRHS))
6986*67e74705SXin Li     return;
6987*67e74705SXin Li 
6988*67e74705SXin Li   // The condition is an arithmetic binary expression, with a right-
6989*67e74705SXin Li   // hand side that looks boolean, so warn.
6990*67e74705SXin Li 
6991*67e74705SXin Li   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6992*67e74705SXin Li       << Condition->getSourceRange()
6993*67e74705SXin Li       << BinaryOperator::getOpcodeStr(CondOpcode);
6994*67e74705SXin Li 
6995*67e74705SXin Li   SuggestParentheses(Self, OpLoc,
6996*67e74705SXin Li     Self.PDiag(diag::note_precedence_silence)
6997*67e74705SXin Li       << BinaryOperator::getOpcodeStr(CondOpcode),
6998*67e74705SXin Li     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6999*67e74705SXin Li 
7000*67e74705SXin Li   SuggestParentheses(Self, OpLoc,
7001*67e74705SXin Li     Self.PDiag(diag::note_precedence_conditional_first),
7002*67e74705SXin Li     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7003*67e74705SXin Li }
7004*67e74705SXin Li 
7005*67e74705SXin Li /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7006*67e74705SXin Li /// in the case of a the GNU conditional expr extension.
ActOnConditionalOp(SourceLocation QuestionLoc,SourceLocation ColonLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr)7007*67e74705SXin Li ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7008*67e74705SXin Li                                     SourceLocation ColonLoc,
7009*67e74705SXin Li                                     Expr *CondExpr, Expr *LHSExpr,
7010*67e74705SXin Li                                     Expr *RHSExpr) {
7011*67e74705SXin Li   if (!getLangOpts().CPlusPlus) {
7012*67e74705SXin Li     // C cannot handle TypoExpr nodes in the condition because it
7013*67e74705SXin Li     // doesn't handle dependent types properly, so make sure any TypoExprs have
7014*67e74705SXin Li     // been dealt with before checking the operands.
7015*67e74705SXin Li     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7016*67e74705SXin Li     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7017*67e74705SXin Li     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7018*67e74705SXin Li 
7019*67e74705SXin Li     if (!CondResult.isUsable())
7020*67e74705SXin Li       return ExprError();
7021*67e74705SXin Li 
7022*67e74705SXin Li     if (LHSExpr) {
7023*67e74705SXin Li       if (!LHSResult.isUsable())
7024*67e74705SXin Li         return ExprError();
7025*67e74705SXin Li     }
7026*67e74705SXin Li 
7027*67e74705SXin Li     if (!RHSResult.isUsable())
7028*67e74705SXin Li       return ExprError();
7029*67e74705SXin Li 
7030*67e74705SXin Li     CondExpr = CondResult.get();
7031*67e74705SXin Li     LHSExpr = LHSResult.get();
7032*67e74705SXin Li     RHSExpr = RHSResult.get();
7033*67e74705SXin Li   }
7034*67e74705SXin Li 
7035*67e74705SXin Li   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7036*67e74705SXin Li   // was the condition.
7037*67e74705SXin Li   OpaqueValueExpr *opaqueValue = nullptr;
7038*67e74705SXin Li   Expr *commonExpr = nullptr;
7039*67e74705SXin Li   if (!LHSExpr) {
7040*67e74705SXin Li     commonExpr = CondExpr;
7041*67e74705SXin Li     // Lower out placeholder types first.  This is important so that we don't
7042*67e74705SXin Li     // try to capture a placeholder. This happens in few cases in C++; such
7043*67e74705SXin Li     // as Objective-C++'s dictionary subscripting syntax.
7044*67e74705SXin Li     if (commonExpr->hasPlaceholderType()) {
7045*67e74705SXin Li       ExprResult result = CheckPlaceholderExpr(commonExpr);
7046*67e74705SXin Li       if (!result.isUsable()) return ExprError();
7047*67e74705SXin Li       commonExpr = result.get();
7048*67e74705SXin Li     }
7049*67e74705SXin Li     // We usually want to apply unary conversions *before* saving, except
7050*67e74705SXin Li     // in the special case of a C++ l-value conditional.
7051*67e74705SXin Li     if (!(getLangOpts().CPlusPlus
7052*67e74705SXin Li           && !commonExpr->isTypeDependent()
7053*67e74705SXin Li           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7054*67e74705SXin Li           && commonExpr->isGLValue()
7055*67e74705SXin Li           && commonExpr->isOrdinaryOrBitFieldObject()
7056*67e74705SXin Li           && RHSExpr->isOrdinaryOrBitFieldObject()
7057*67e74705SXin Li           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7058*67e74705SXin Li       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7059*67e74705SXin Li       if (commonRes.isInvalid())
7060*67e74705SXin Li         return ExprError();
7061*67e74705SXin Li       commonExpr = commonRes.get();
7062*67e74705SXin Li     }
7063*67e74705SXin Li 
7064*67e74705SXin Li     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7065*67e74705SXin Li                                                 commonExpr->getType(),
7066*67e74705SXin Li                                                 commonExpr->getValueKind(),
7067*67e74705SXin Li                                                 commonExpr->getObjectKind(),
7068*67e74705SXin Li                                                 commonExpr);
7069*67e74705SXin Li     LHSExpr = CondExpr = opaqueValue;
7070*67e74705SXin Li   }
7071*67e74705SXin Li 
7072*67e74705SXin Li   ExprValueKind VK = VK_RValue;
7073*67e74705SXin Li   ExprObjectKind OK = OK_Ordinary;
7074*67e74705SXin Li   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7075*67e74705SXin Li   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7076*67e74705SXin Li                                              VK, OK, QuestionLoc);
7077*67e74705SXin Li   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7078*67e74705SXin Li       RHS.isInvalid())
7079*67e74705SXin Li     return ExprError();
7080*67e74705SXin Li 
7081*67e74705SXin Li   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7082*67e74705SXin Li                                 RHS.get());
7083*67e74705SXin Li 
7084*67e74705SXin Li   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7085*67e74705SXin Li 
7086*67e74705SXin Li   if (!commonExpr)
7087*67e74705SXin Li     return new (Context)
7088*67e74705SXin Li         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7089*67e74705SXin Li                             RHS.get(), result, VK, OK);
7090*67e74705SXin Li 
7091*67e74705SXin Li   return new (Context) BinaryConditionalOperator(
7092*67e74705SXin Li       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7093*67e74705SXin Li       ColonLoc, result, VK, OK);
7094*67e74705SXin Li }
7095*67e74705SXin Li 
7096*67e74705SXin Li // checkPointerTypesForAssignment - This is a very tricky routine (despite
7097*67e74705SXin Li // being closely modeled after the C99 spec:-). The odd characteristic of this
7098*67e74705SXin Li // routine is it effectively iqnores the qualifiers on the top level pointee.
7099*67e74705SXin Li // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7100*67e74705SXin Li // FIXME: add a couple examples in this comment.
7101*67e74705SXin Li static Sema::AssignConvertType
checkPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)7102*67e74705SXin Li checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7103*67e74705SXin Li   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7104*67e74705SXin Li   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7105*67e74705SXin Li 
7106*67e74705SXin Li   // get the "pointed to" type (ignoring qualifiers at the top level)
7107*67e74705SXin Li   const Type *lhptee, *rhptee;
7108*67e74705SXin Li   Qualifiers lhq, rhq;
7109*67e74705SXin Li   std::tie(lhptee, lhq) =
7110*67e74705SXin Li       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7111*67e74705SXin Li   std::tie(rhptee, rhq) =
7112*67e74705SXin Li       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7113*67e74705SXin Li 
7114*67e74705SXin Li   Sema::AssignConvertType ConvTy = Sema::Compatible;
7115*67e74705SXin Li 
7116*67e74705SXin Li   // C99 6.5.16.1p1: This following citation is common to constraints
7117*67e74705SXin Li   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7118*67e74705SXin Li   // qualifiers of the type *pointed to* by the right;
7119*67e74705SXin Li 
7120*67e74705SXin Li   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7121*67e74705SXin Li   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7122*67e74705SXin Li       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7123*67e74705SXin Li     // Ignore lifetime for further calculation.
7124*67e74705SXin Li     lhq.removeObjCLifetime();
7125*67e74705SXin Li     rhq.removeObjCLifetime();
7126*67e74705SXin Li   }
7127*67e74705SXin Li 
7128*67e74705SXin Li   if (!lhq.compatiblyIncludes(rhq)) {
7129*67e74705SXin Li     // Treat address-space mismatches as fatal.  TODO: address subspaces
7130*67e74705SXin Li     if (!lhq.isAddressSpaceSupersetOf(rhq))
7131*67e74705SXin Li       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7132*67e74705SXin Li 
7133*67e74705SXin Li     // It's okay to add or remove GC or lifetime qualifiers when converting to
7134*67e74705SXin Li     // and from void*.
7135*67e74705SXin Li     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7136*67e74705SXin Li                         .compatiblyIncludes(
7137*67e74705SXin Li                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7138*67e74705SXin Li              && (lhptee->isVoidType() || rhptee->isVoidType()))
7139*67e74705SXin Li       ; // keep old
7140*67e74705SXin Li 
7141*67e74705SXin Li     // Treat lifetime mismatches as fatal.
7142*67e74705SXin Li     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7143*67e74705SXin Li       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7144*67e74705SXin Li 
7145*67e74705SXin Li     // For GCC/MS compatibility, other qualifier mismatches are treated
7146*67e74705SXin Li     // as still compatible in C.
7147*67e74705SXin Li     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7148*67e74705SXin Li   }
7149*67e74705SXin Li 
7150*67e74705SXin Li   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7151*67e74705SXin Li   // incomplete type and the other is a pointer to a qualified or unqualified
7152*67e74705SXin Li   // version of void...
7153*67e74705SXin Li   if (lhptee->isVoidType()) {
7154*67e74705SXin Li     if (rhptee->isIncompleteOrObjectType())
7155*67e74705SXin Li       return ConvTy;
7156*67e74705SXin Li 
7157*67e74705SXin Li     // As an extension, we allow cast to/from void* to function pointer.
7158*67e74705SXin Li     assert(rhptee->isFunctionType());
7159*67e74705SXin Li     return Sema::FunctionVoidPointer;
7160*67e74705SXin Li   }
7161*67e74705SXin Li 
7162*67e74705SXin Li   if (rhptee->isVoidType()) {
7163*67e74705SXin Li     if (lhptee->isIncompleteOrObjectType())
7164*67e74705SXin Li       return ConvTy;
7165*67e74705SXin Li 
7166*67e74705SXin Li     // As an extension, we allow cast to/from void* to function pointer.
7167*67e74705SXin Li     assert(lhptee->isFunctionType());
7168*67e74705SXin Li     return Sema::FunctionVoidPointer;
7169*67e74705SXin Li   }
7170*67e74705SXin Li 
7171*67e74705SXin Li   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7172*67e74705SXin Li   // unqualified versions of compatible types, ...
7173*67e74705SXin Li   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7174*67e74705SXin Li   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7175*67e74705SXin Li     // Check if the pointee types are compatible ignoring the sign.
7176*67e74705SXin Li     // We explicitly check for char so that we catch "char" vs
7177*67e74705SXin Li     // "unsigned char" on systems where "char" is unsigned.
7178*67e74705SXin Li     if (lhptee->isCharType())
7179*67e74705SXin Li       ltrans = S.Context.UnsignedCharTy;
7180*67e74705SXin Li     else if (lhptee->hasSignedIntegerRepresentation())
7181*67e74705SXin Li       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7182*67e74705SXin Li 
7183*67e74705SXin Li     if (rhptee->isCharType())
7184*67e74705SXin Li       rtrans = S.Context.UnsignedCharTy;
7185*67e74705SXin Li     else if (rhptee->hasSignedIntegerRepresentation())
7186*67e74705SXin Li       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7187*67e74705SXin Li 
7188*67e74705SXin Li     if (ltrans == rtrans) {
7189*67e74705SXin Li       // Types are compatible ignoring the sign. Qualifier incompatibility
7190*67e74705SXin Li       // takes priority over sign incompatibility because the sign
7191*67e74705SXin Li       // warning can be disabled.
7192*67e74705SXin Li       if (ConvTy != Sema::Compatible)
7193*67e74705SXin Li         return ConvTy;
7194*67e74705SXin Li 
7195*67e74705SXin Li       return Sema::IncompatiblePointerSign;
7196*67e74705SXin Li     }
7197*67e74705SXin Li 
7198*67e74705SXin Li     // If we are a multi-level pointer, it's possible that our issue is simply
7199*67e74705SXin Li     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7200*67e74705SXin Li     // the eventual target type is the same and the pointers have the same
7201*67e74705SXin Li     // level of indirection, this must be the issue.
7202*67e74705SXin Li     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7203*67e74705SXin Li       do {
7204*67e74705SXin Li         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7205*67e74705SXin Li         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7206*67e74705SXin Li       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7207*67e74705SXin Li 
7208*67e74705SXin Li       if (lhptee == rhptee)
7209*67e74705SXin Li         return Sema::IncompatibleNestedPointerQualifiers;
7210*67e74705SXin Li     }
7211*67e74705SXin Li 
7212*67e74705SXin Li     // General pointer incompatibility takes priority over qualifiers.
7213*67e74705SXin Li     return Sema::IncompatiblePointer;
7214*67e74705SXin Li   }
7215*67e74705SXin Li   if (!S.getLangOpts().CPlusPlus &&
7216*67e74705SXin Li       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
7217*67e74705SXin Li     return Sema::IncompatiblePointer;
7218*67e74705SXin Li   return ConvTy;
7219*67e74705SXin Li }
7220*67e74705SXin Li 
7221*67e74705SXin Li /// checkBlockPointerTypesForAssignment - This routine determines whether two
7222*67e74705SXin Li /// block pointer types are compatible or whether a block and normal pointer
7223*67e74705SXin Li /// are compatible. It is more restrict than comparing two function pointer
7224*67e74705SXin Li // types.
7225*67e74705SXin Li static Sema::AssignConvertType
checkBlockPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)7226*67e74705SXin Li checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7227*67e74705SXin Li                                     QualType RHSType) {
7228*67e74705SXin Li   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7229*67e74705SXin Li   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7230*67e74705SXin Li 
7231*67e74705SXin Li   QualType lhptee, rhptee;
7232*67e74705SXin Li 
7233*67e74705SXin Li   // get the "pointed to" type (ignoring qualifiers at the top level)
7234*67e74705SXin Li   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7235*67e74705SXin Li   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7236*67e74705SXin Li 
7237*67e74705SXin Li   // In C++, the types have to match exactly.
7238*67e74705SXin Li   if (S.getLangOpts().CPlusPlus)
7239*67e74705SXin Li     return Sema::IncompatibleBlockPointer;
7240*67e74705SXin Li 
7241*67e74705SXin Li   Sema::AssignConvertType ConvTy = Sema::Compatible;
7242*67e74705SXin Li 
7243*67e74705SXin Li   // For blocks we enforce that qualifiers are identical.
7244*67e74705SXin Li   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7245*67e74705SXin Li     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7246*67e74705SXin Li 
7247*67e74705SXin Li   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7248*67e74705SXin Li     return Sema::IncompatibleBlockPointer;
7249*67e74705SXin Li 
7250*67e74705SXin Li   return ConvTy;
7251*67e74705SXin Li }
7252*67e74705SXin Li 
7253*67e74705SXin Li /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7254*67e74705SXin Li /// for assignment compatibility.
7255*67e74705SXin Li static Sema::AssignConvertType
checkObjCPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)7256*67e74705SXin Li checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7257*67e74705SXin Li                                    QualType RHSType) {
7258*67e74705SXin Li   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7259*67e74705SXin Li   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7260*67e74705SXin Li 
7261*67e74705SXin Li   if (LHSType->isObjCBuiltinType()) {
7262*67e74705SXin Li     // Class is not compatible with ObjC object pointers.
7263*67e74705SXin Li     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7264*67e74705SXin Li         !RHSType->isObjCQualifiedClassType())
7265*67e74705SXin Li       return Sema::IncompatiblePointer;
7266*67e74705SXin Li     return Sema::Compatible;
7267*67e74705SXin Li   }
7268*67e74705SXin Li   if (RHSType->isObjCBuiltinType()) {
7269*67e74705SXin Li     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7270*67e74705SXin Li         !LHSType->isObjCQualifiedClassType())
7271*67e74705SXin Li       return Sema::IncompatiblePointer;
7272*67e74705SXin Li     return Sema::Compatible;
7273*67e74705SXin Li   }
7274*67e74705SXin Li   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7275*67e74705SXin Li   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7276*67e74705SXin Li 
7277*67e74705SXin Li   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7278*67e74705SXin Li       // make an exception for id<P>
7279*67e74705SXin Li       !LHSType->isObjCQualifiedIdType())
7280*67e74705SXin Li     return Sema::CompatiblePointerDiscardsQualifiers;
7281*67e74705SXin Li 
7282*67e74705SXin Li   if (S.Context.typesAreCompatible(LHSType, RHSType))
7283*67e74705SXin Li     return Sema::Compatible;
7284*67e74705SXin Li   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7285*67e74705SXin Li     return Sema::IncompatibleObjCQualifiedId;
7286*67e74705SXin Li   return Sema::IncompatiblePointer;
7287*67e74705SXin Li }
7288*67e74705SXin Li 
7289*67e74705SXin Li Sema::AssignConvertType
CheckAssignmentConstraints(SourceLocation Loc,QualType LHSType,QualType RHSType)7290*67e74705SXin Li Sema::CheckAssignmentConstraints(SourceLocation Loc,
7291*67e74705SXin Li                                  QualType LHSType, QualType RHSType) {
7292*67e74705SXin Li   // Fake up an opaque expression.  We don't actually care about what
7293*67e74705SXin Li   // cast operations are required, so if CheckAssignmentConstraints
7294*67e74705SXin Li   // adds casts to this they'll be wasted, but fortunately that doesn't
7295*67e74705SXin Li   // usually happen on valid code.
7296*67e74705SXin Li   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7297*67e74705SXin Li   ExprResult RHSPtr = &RHSExpr;
7298*67e74705SXin Li   CastKind K = CK_Invalid;
7299*67e74705SXin Li 
7300*67e74705SXin Li   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7301*67e74705SXin Li }
7302*67e74705SXin Li 
7303*67e74705SXin Li /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7304*67e74705SXin Li /// has code to accommodate several GCC extensions when type checking
7305*67e74705SXin Li /// pointers. Here are some objectionable examples that GCC considers warnings:
7306*67e74705SXin Li ///
7307*67e74705SXin Li ///  int a, *pint;
7308*67e74705SXin Li ///  short *pshort;
7309*67e74705SXin Li ///  struct foo *pfoo;
7310*67e74705SXin Li ///
7311*67e74705SXin Li ///  pint = pshort; // warning: assignment from incompatible pointer type
7312*67e74705SXin Li ///  a = pint; // warning: assignment makes integer from pointer without a cast
7313*67e74705SXin Li ///  pint = a; // warning: assignment makes pointer from integer without a cast
7314*67e74705SXin Li ///  pint = pfoo; // warning: assignment from incompatible pointer type
7315*67e74705SXin Li ///
7316*67e74705SXin Li /// As a result, the code for dealing with pointers is more complex than the
7317*67e74705SXin Li /// C99 spec dictates.
7318*67e74705SXin Li ///
7319*67e74705SXin Li /// Sets 'Kind' for any result kind except Incompatible.
7320*67e74705SXin Li Sema::AssignConvertType
CheckAssignmentConstraints(QualType LHSType,ExprResult & RHS,CastKind & Kind,bool ConvertRHS)7321*67e74705SXin Li Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7322*67e74705SXin Li                                  CastKind &Kind, bool ConvertRHS) {
7323*67e74705SXin Li   QualType RHSType = RHS.get()->getType();
7324*67e74705SXin Li   QualType OrigLHSType = LHSType;
7325*67e74705SXin Li 
7326*67e74705SXin Li   // Get canonical types.  We're not formatting these types, just comparing
7327*67e74705SXin Li   // them.
7328*67e74705SXin Li   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7329*67e74705SXin Li   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7330*67e74705SXin Li 
7331*67e74705SXin Li   // Common case: no conversion required.
7332*67e74705SXin Li   if (LHSType == RHSType) {
7333*67e74705SXin Li     Kind = CK_NoOp;
7334*67e74705SXin Li     return Compatible;
7335*67e74705SXin Li   }
7336*67e74705SXin Li 
7337*67e74705SXin Li   // If we have an atomic type, try a non-atomic assignment, then just add an
7338*67e74705SXin Li   // atomic qualification step.
7339*67e74705SXin Li   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7340*67e74705SXin Li     Sema::AssignConvertType result =
7341*67e74705SXin Li       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7342*67e74705SXin Li     if (result != Compatible)
7343*67e74705SXin Li       return result;
7344*67e74705SXin Li     if (Kind != CK_NoOp && ConvertRHS)
7345*67e74705SXin Li       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7346*67e74705SXin Li     Kind = CK_NonAtomicToAtomic;
7347*67e74705SXin Li     return Compatible;
7348*67e74705SXin Li   }
7349*67e74705SXin Li 
7350*67e74705SXin Li   // If the left-hand side is a reference type, then we are in a
7351*67e74705SXin Li   // (rare!) case where we've allowed the use of references in C,
7352*67e74705SXin Li   // e.g., as a parameter type in a built-in function. In this case,
7353*67e74705SXin Li   // just make sure that the type referenced is compatible with the
7354*67e74705SXin Li   // right-hand side type. The caller is responsible for adjusting
7355*67e74705SXin Li   // LHSType so that the resulting expression does not have reference
7356*67e74705SXin Li   // type.
7357*67e74705SXin Li   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7358*67e74705SXin Li     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7359*67e74705SXin Li       Kind = CK_LValueBitCast;
7360*67e74705SXin Li       return Compatible;
7361*67e74705SXin Li     }
7362*67e74705SXin Li     return Incompatible;
7363*67e74705SXin Li   }
7364*67e74705SXin Li 
7365*67e74705SXin Li   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7366*67e74705SXin Li   // to the same ExtVector type.
7367*67e74705SXin Li   if (LHSType->isExtVectorType()) {
7368*67e74705SXin Li     if (RHSType->isExtVectorType())
7369*67e74705SXin Li       return Incompatible;
7370*67e74705SXin Li     if (RHSType->isArithmeticType()) {
7371*67e74705SXin Li       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7372*67e74705SXin Li       if (ConvertRHS)
7373*67e74705SXin Li         RHS = prepareVectorSplat(LHSType, RHS.get());
7374*67e74705SXin Li       Kind = CK_VectorSplat;
7375*67e74705SXin Li       return Compatible;
7376*67e74705SXin Li     }
7377*67e74705SXin Li   }
7378*67e74705SXin Li 
7379*67e74705SXin Li   // Conversions to or from vector type.
7380*67e74705SXin Li   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7381*67e74705SXin Li     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7382*67e74705SXin Li       // Allow assignments of an AltiVec vector type to an equivalent GCC
7383*67e74705SXin Li       // vector type and vice versa
7384*67e74705SXin Li       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7385*67e74705SXin Li         Kind = CK_BitCast;
7386*67e74705SXin Li         return Compatible;
7387*67e74705SXin Li       }
7388*67e74705SXin Li 
7389*67e74705SXin Li       // If we are allowing lax vector conversions, and LHS and RHS are both
7390*67e74705SXin Li       // vectors, the total size only needs to be the same. This is a bitcast;
7391*67e74705SXin Li       // no bits are changed but the result type is different.
7392*67e74705SXin Li       if (isLaxVectorConversion(RHSType, LHSType)) {
7393*67e74705SXin Li         Kind = CK_BitCast;
7394*67e74705SXin Li         return IncompatibleVectors;
7395*67e74705SXin Li       }
7396*67e74705SXin Li     }
7397*67e74705SXin Li 
7398*67e74705SXin Li     // When the RHS comes from another lax conversion (e.g. binops between
7399*67e74705SXin Li     // scalars and vectors) the result is canonicalized as a vector. When the
7400*67e74705SXin Li     // LHS is also a vector, the lax is allowed by the condition above. Handle
7401*67e74705SXin Li     // the case where LHS is a scalar.
7402*67e74705SXin Li     if (LHSType->isScalarType()) {
7403*67e74705SXin Li       const VectorType *VecType = RHSType->getAs<VectorType>();
7404*67e74705SXin Li       if (VecType && VecType->getNumElements() == 1 &&
7405*67e74705SXin Li           isLaxVectorConversion(RHSType, LHSType)) {
7406*67e74705SXin Li         ExprResult *VecExpr = &RHS;
7407*67e74705SXin Li         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7408*67e74705SXin Li         Kind = CK_BitCast;
7409*67e74705SXin Li         return Compatible;
7410*67e74705SXin Li       }
7411*67e74705SXin Li     }
7412*67e74705SXin Li 
7413*67e74705SXin Li     return Incompatible;
7414*67e74705SXin Li   }
7415*67e74705SXin Li 
7416*67e74705SXin Li   // Diagnose attempts to convert between __float128 and long double where
7417*67e74705SXin Li   // such conversions currently can't be handled.
7418*67e74705SXin Li   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7419*67e74705SXin Li     return Incompatible;
7420*67e74705SXin Li 
7421*67e74705SXin Li   // Arithmetic conversions.
7422*67e74705SXin Li   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7423*67e74705SXin Li       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7424*67e74705SXin Li     if (ConvertRHS)
7425*67e74705SXin Li       Kind = PrepareScalarCast(RHS, LHSType);
7426*67e74705SXin Li     return Compatible;
7427*67e74705SXin Li   }
7428*67e74705SXin Li 
7429*67e74705SXin Li   // Conversions to normal pointers.
7430*67e74705SXin Li   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7431*67e74705SXin Li     // U* -> T*
7432*67e74705SXin Li     if (isa<PointerType>(RHSType)) {
7433*67e74705SXin Li       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7434*67e74705SXin Li       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7435*67e74705SXin Li       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7436*67e74705SXin Li       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7437*67e74705SXin Li     }
7438*67e74705SXin Li 
7439*67e74705SXin Li     // int -> T*
7440*67e74705SXin Li     if (RHSType->isIntegerType()) {
7441*67e74705SXin Li       Kind = CK_IntegralToPointer; // FIXME: null?
7442*67e74705SXin Li       return IntToPointer;
7443*67e74705SXin Li     }
7444*67e74705SXin Li 
7445*67e74705SXin Li     // C pointers are not compatible with ObjC object pointers,
7446*67e74705SXin Li     // with two exceptions:
7447*67e74705SXin Li     if (isa<ObjCObjectPointerType>(RHSType)) {
7448*67e74705SXin Li       //  - conversions to void*
7449*67e74705SXin Li       if (LHSPointer->getPointeeType()->isVoidType()) {
7450*67e74705SXin Li         Kind = CK_BitCast;
7451*67e74705SXin Li         return Compatible;
7452*67e74705SXin Li       }
7453*67e74705SXin Li 
7454*67e74705SXin Li       //  - conversions from 'Class' to the redefinition type
7455*67e74705SXin Li       if (RHSType->isObjCClassType() &&
7456*67e74705SXin Li           Context.hasSameType(LHSType,
7457*67e74705SXin Li                               Context.getObjCClassRedefinitionType())) {
7458*67e74705SXin Li         Kind = CK_BitCast;
7459*67e74705SXin Li         return Compatible;
7460*67e74705SXin Li       }
7461*67e74705SXin Li 
7462*67e74705SXin Li       Kind = CK_BitCast;
7463*67e74705SXin Li       return IncompatiblePointer;
7464*67e74705SXin Li     }
7465*67e74705SXin Li 
7466*67e74705SXin Li     // U^ -> void*
7467*67e74705SXin Li     if (RHSType->getAs<BlockPointerType>()) {
7468*67e74705SXin Li       if (LHSPointer->getPointeeType()->isVoidType()) {
7469*67e74705SXin Li         Kind = CK_BitCast;
7470*67e74705SXin Li         return Compatible;
7471*67e74705SXin Li       }
7472*67e74705SXin Li     }
7473*67e74705SXin Li 
7474*67e74705SXin Li     return Incompatible;
7475*67e74705SXin Li   }
7476*67e74705SXin Li 
7477*67e74705SXin Li   // Conversions to block pointers.
7478*67e74705SXin Li   if (isa<BlockPointerType>(LHSType)) {
7479*67e74705SXin Li     // U^ -> T^
7480*67e74705SXin Li     if (RHSType->isBlockPointerType()) {
7481*67e74705SXin Li       Kind = CK_BitCast;
7482*67e74705SXin Li       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7483*67e74705SXin Li     }
7484*67e74705SXin Li 
7485*67e74705SXin Li     // int or null -> T^
7486*67e74705SXin Li     if (RHSType->isIntegerType()) {
7487*67e74705SXin Li       Kind = CK_IntegralToPointer; // FIXME: null
7488*67e74705SXin Li       return IntToBlockPointer;
7489*67e74705SXin Li     }
7490*67e74705SXin Li 
7491*67e74705SXin Li     // id -> T^
7492*67e74705SXin Li     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7493*67e74705SXin Li       Kind = CK_AnyPointerToBlockPointerCast;
7494*67e74705SXin Li       return Compatible;
7495*67e74705SXin Li     }
7496*67e74705SXin Li 
7497*67e74705SXin Li     // void* -> T^
7498*67e74705SXin Li     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7499*67e74705SXin Li       if (RHSPT->getPointeeType()->isVoidType()) {
7500*67e74705SXin Li         Kind = CK_AnyPointerToBlockPointerCast;
7501*67e74705SXin Li         return Compatible;
7502*67e74705SXin Li       }
7503*67e74705SXin Li 
7504*67e74705SXin Li     return Incompatible;
7505*67e74705SXin Li   }
7506*67e74705SXin Li 
7507*67e74705SXin Li   // Conversions to Objective-C pointers.
7508*67e74705SXin Li   if (isa<ObjCObjectPointerType>(LHSType)) {
7509*67e74705SXin Li     // A* -> B*
7510*67e74705SXin Li     if (RHSType->isObjCObjectPointerType()) {
7511*67e74705SXin Li       Kind = CK_BitCast;
7512*67e74705SXin Li       Sema::AssignConvertType result =
7513*67e74705SXin Li         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7514*67e74705SXin Li       if (getLangOpts().ObjCAutoRefCount &&
7515*67e74705SXin Li           result == Compatible &&
7516*67e74705SXin Li           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7517*67e74705SXin Li         result = IncompatibleObjCWeakRef;
7518*67e74705SXin Li       return result;
7519*67e74705SXin Li     }
7520*67e74705SXin Li 
7521*67e74705SXin Li     // int or null -> A*
7522*67e74705SXin Li     if (RHSType->isIntegerType()) {
7523*67e74705SXin Li       Kind = CK_IntegralToPointer; // FIXME: null
7524*67e74705SXin Li       return IntToPointer;
7525*67e74705SXin Li     }
7526*67e74705SXin Li 
7527*67e74705SXin Li     // In general, C pointers are not compatible with ObjC object pointers,
7528*67e74705SXin Li     // with two exceptions:
7529*67e74705SXin Li     if (isa<PointerType>(RHSType)) {
7530*67e74705SXin Li       Kind = CK_CPointerToObjCPointerCast;
7531*67e74705SXin Li 
7532*67e74705SXin Li       //  - conversions from 'void*'
7533*67e74705SXin Li       if (RHSType->isVoidPointerType()) {
7534*67e74705SXin Li         return Compatible;
7535*67e74705SXin Li       }
7536*67e74705SXin Li 
7537*67e74705SXin Li       //  - conversions to 'Class' from its redefinition type
7538*67e74705SXin Li       if (LHSType->isObjCClassType() &&
7539*67e74705SXin Li           Context.hasSameType(RHSType,
7540*67e74705SXin Li                               Context.getObjCClassRedefinitionType())) {
7541*67e74705SXin Li         return Compatible;
7542*67e74705SXin Li       }
7543*67e74705SXin Li 
7544*67e74705SXin Li       return IncompatiblePointer;
7545*67e74705SXin Li     }
7546*67e74705SXin Li 
7547*67e74705SXin Li     // Only under strict condition T^ is compatible with an Objective-C pointer.
7548*67e74705SXin Li     if (RHSType->isBlockPointerType() &&
7549*67e74705SXin Li         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7550*67e74705SXin Li       if (ConvertRHS)
7551*67e74705SXin Li         maybeExtendBlockObject(RHS);
7552*67e74705SXin Li       Kind = CK_BlockPointerToObjCPointerCast;
7553*67e74705SXin Li       return Compatible;
7554*67e74705SXin Li     }
7555*67e74705SXin Li 
7556*67e74705SXin Li     return Incompatible;
7557*67e74705SXin Li   }
7558*67e74705SXin Li 
7559*67e74705SXin Li   // Conversions from pointers that are not covered by the above.
7560*67e74705SXin Li   if (isa<PointerType>(RHSType)) {
7561*67e74705SXin Li     // T* -> _Bool
7562*67e74705SXin Li     if (LHSType == Context.BoolTy) {
7563*67e74705SXin Li       Kind = CK_PointerToBoolean;
7564*67e74705SXin Li       return Compatible;
7565*67e74705SXin Li     }
7566*67e74705SXin Li 
7567*67e74705SXin Li     // T* -> int
7568*67e74705SXin Li     if (LHSType->isIntegerType()) {
7569*67e74705SXin Li       Kind = CK_PointerToIntegral;
7570*67e74705SXin Li       return PointerToInt;
7571*67e74705SXin Li     }
7572*67e74705SXin Li 
7573*67e74705SXin Li     return Incompatible;
7574*67e74705SXin Li   }
7575*67e74705SXin Li 
7576*67e74705SXin Li   // Conversions from Objective-C pointers that are not covered by the above.
7577*67e74705SXin Li   if (isa<ObjCObjectPointerType>(RHSType)) {
7578*67e74705SXin Li     // T* -> _Bool
7579*67e74705SXin Li     if (LHSType == Context.BoolTy) {
7580*67e74705SXin Li       Kind = CK_PointerToBoolean;
7581*67e74705SXin Li       return Compatible;
7582*67e74705SXin Li     }
7583*67e74705SXin Li 
7584*67e74705SXin Li     // T* -> int
7585*67e74705SXin Li     if (LHSType->isIntegerType()) {
7586*67e74705SXin Li       Kind = CK_PointerToIntegral;
7587*67e74705SXin Li       return PointerToInt;
7588*67e74705SXin Li     }
7589*67e74705SXin Li 
7590*67e74705SXin Li     return Incompatible;
7591*67e74705SXin Li   }
7592*67e74705SXin Li 
7593*67e74705SXin Li   // struct A -> struct B
7594*67e74705SXin Li   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7595*67e74705SXin Li     if (Context.typesAreCompatible(LHSType, RHSType)) {
7596*67e74705SXin Li       Kind = CK_NoOp;
7597*67e74705SXin Li       return Compatible;
7598*67e74705SXin Li     }
7599*67e74705SXin Li   }
7600*67e74705SXin Li 
7601*67e74705SXin Li   return Incompatible;
7602*67e74705SXin Li }
7603*67e74705SXin Li 
7604*67e74705SXin Li /// \brief Constructs a transparent union from an expression that is
7605*67e74705SXin Li /// used to initialize the transparent union.
ConstructTransparentUnion(Sema & S,ASTContext & C,ExprResult & EResult,QualType UnionType,FieldDecl * Field)7606*67e74705SXin Li static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7607*67e74705SXin Li                                       ExprResult &EResult, QualType UnionType,
7608*67e74705SXin Li                                       FieldDecl *Field) {
7609*67e74705SXin Li   // Build an initializer list that designates the appropriate member
7610*67e74705SXin Li   // of the transparent union.
7611*67e74705SXin Li   Expr *E = EResult.get();
7612*67e74705SXin Li   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7613*67e74705SXin Li                                                    E, SourceLocation());
7614*67e74705SXin Li   Initializer->setType(UnionType);
7615*67e74705SXin Li   Initializer->setInitializedFieldInUnion(Field);
7616*67e74705SXin Li 
7617*67e74705SXin Li   // Build a compound literal constructing a value of the transparent
7618*67e74705SXin Li   // union type from this initializer list.
7619*67e74705SXin Li   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7620*67e74705SXin Li   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7621*67e74705SXin Li                                         VK_RValue, Initializer, false);
7622*67e74705SXin Li }
7623*67e74705SXin Li 
7624*67e74705SXin Li Sema::AssignConvertType
CheckTransparentUnionArgumentConstraints(QualType ArgType,ExprResult & RHS)7625*67e74705SXin Li Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7626*67e74705SXin Li                                                ExprResult &RHS) {
7627*67e74705SXin Li   QualType RHSType = RHS.get()->getType();
7628*67e74705SXin Li 
7629*67e74705SXin Li   // If the ArgType is a Union type, we want to handle a potential
7630*67e74705SXin Li   // transparent_union GCC extension.
7631*67e74705SXin Li   const RecordType *UT = ArgType->getAsUnionType();
7632*67e74705SXin Li   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7633*67e74705SXin Li     return Incompatible;
7634*67e74705SXin Li 
7635*67e74705SXin Li   // The field to initialize within the transparent union.
7636*67e74705SXin Li   RecordDecl *UD = UT->getDecl();
7637*67e74705SXin Li   FieldDecl *InitField = nullptr;
7638*67e74705SXin Li   // It's compatible if the expression matches any of the fields.
7639*67e74705SXin Li   for (auto *it : UD->fields()) {
7640*67e74705SXin Li     if (it->getType()->isPointerType()) {
7641*67e74705SXin Li       // If the transparent union contains a pointer type, we allow:
7642*67e74705SXin Li       // 1) void pointer
7643*67e74705SXin Li       // 2) null pointer constant
7644*67e74705SXin Li       if (RHSType->isPointerType())
7645*67e74705SXin Li         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7646*67e74705SXin Li           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7647*67e74705SXin Li           InitField = it;
7648*67e74705SXin Li           break;
7649*67e74705SXin Li         }
7650*67e74705SXin Li 
7651*67e74705SXin Li       if (RHS.get()->isNullPointerConstant(Context,
7652*67e74705SXin Li                                            Expr::NPC_ValueDependentIsNull)) {
7653*67e74705SXin Li         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7654*67e74705SXin Li                                 CK_NullToPointer);
7655*67e74705SXin Li         InitField = it;
7656*67e74705SXin Li         break;
7657*67e74705SXin Li       }
7658*67e74705SXin Li     }
7659*67e74705SXin Li 
7660*67e74705SXin Li     CastKind Kind = CK_Invalid;
7661*67e74705SXin Li     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7662*67e74705SXin Li           == Compatible) {
7663*67e74705SXin Li       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7664*67e74705SXin Li       InitField = it;
7665*67e74705SXin Li       break;
7666*67e74705SXin Li     }
7667*67e74705SXin Li   }
7668*67e74705SXin Li 
7669*67e74705SXin Li   if (!InitField)
7670*67e74705SXin Li     return Incompatible;
7671*67e74705SXin Li 
7672*67e74705SXin Li   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7673*67e74705SXin Li   return Compatible;
7674*67e74705SXin Li }
7675*67e74705SXin Li 
7676*67e74705SXin Li Sema::AssignConvertType
CheckSingleAssignmentConstraints(QualType LHSType,ExprResult & CallerRHS,bool Diagnose,bool DiagnoseCFAudited,bool ConvertRHS)7677*67e74705SXin Li Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7678*67e74705SXin Li                                        bool Diagnose,
7679*67e74705SXin Li                                        bool DiagnoseCFAudited,
7680*67e74705SXin Li                                        bool ConvertRHS) {
7681*67e74705SXin Li   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7682*67e74705SXin Li   // we can't avoid *all* modifications at the moment, so we need some somewhere
7683*67e74705SXin Li   // to put the updated value.
7684*67e74705SXin Li   ExprResult LocalRHS = CallerRHS;
7685*67e74705SXin Li   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7686*67e74705SXin Li 
7687*67e74705SXin Li   if (getLangOpts().CPlusPlus) {
7688*67e74705SXin Li     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7689*67e74705SXin Li       // C++ 5.17p3: If the left operand is not of class type, the
7690*67e74705SXin Li       // expression is implicitly converted (C++ 4) to the
7691*67e74705SXin Li       // cv-unqualified type of the left operand.
7692*67e74705SXin Li       ExprResult Res;
7693*67e74705SXin Li       if (Diagnose) {
7694*67e74705SXin Li         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7695*67e74705SXin Li                                         AA_Assigning);
7696*67e74705SXin Li       } else {
7697*67e74705SXin Li         ImplicitConversionSequence ICS =
7698*67e74705SXin Li             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7699*67e74705SXin Li                                   /*SuppressUserConversions=*/false,
7700*67e74705SXin Li                                   /*AllowExplicit=*/false,
7701*67e74705SXin Li                                   /*InOverloadResolution=*/false,
7702*67e74705SXin Li                                   /*CStyle=*/false,
7703*67e74705SXin Li                                   /*AllowObjCWritebackConversion=*/false);
7704*67e74705SXin Li         if (ICS.isFailure())
7705*67e74705SXin Li           return Incompatible;
7706*67e74705SXin Li         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7707*67e74705SXin Li                                         ICS, AA_Assigning);
7708*67e74705SXin Li       }
7709*67e74705SXin Li       if (Res.isInvalid())
7710*67e74705SXin Li         return Incompatible;
7711*67e74705SXin Li       Sema::AssignConvertType result = Compatible;
7712*67e74705SXin Li       if (getLangOpts().ObjCAutoRefCount &&
7713*67e74705SXin Li           !CheckObjCARCUnavailableWeakConversion(LHSType,
7714*67e74705SXin Li                                                  RHS.get()->getType()))
7715*67e74705SXin Li         result = IncompatibleObjCWeakRef;
7716*67e74705SXin Li       RHS = Res;
7717*67e74705SXin Li       return result;
7718*67e74705SXin Li     }
7719*67e74705SXin Li 
7720*67e74705SXin Li     // FIXME: Currently, we fall through and treat C++ classes like C
7721*67e74705SXin Li     // structures.
7722*67e74705SXin Li     // FIXME: We also fall through for atomics; not sure what should
7723*67e74705SXin Li     // happen there, though.
7724*67e74705SXin Li   } else if (RHS.get()->getType() == Context.OverloadTy) {
7725*67e74705SXin Li     // As a set of extensions to C, we support overloading on functions. These
7726*67e74705SXin Li     // functions need to be resolved here.
7727*67e74705SXin Li     DeclAccessPair DAP;
7728*67e74705SXin Li     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7729*67e74705SXin Li             RHS.get(), LHSType, /*Complain=*/false, DAP))
7730*67e74705SXin Li       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7731*67e74705SXin Li     else
7732*67e74705SXin Li       return Incompatible;
7733*67e74705SXin Li   }
7734*67e74705SXin Li 
7735*67e74705SXin Li   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7736*67e74705SXin Li   // a null pointer constant.
7737*67e74705SXin Li   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7738*67e74705SXin Li        LHSType->isBlockPointerType()) &&
7739*67e74705SXin Li       RHS.get()->isNullPointerConstant(Context,
7740*67e74705SXin Li                                        Expr::NPC_ValueDependentIsNull)) {
7741*67e74705SXin Li     if (Diagnose || ConvertRHS) {
7742*67e74705SXin Li       CastKind Kind;
7743*67e74705SXin Li       CXXCastPath Path;
7744*67e74705SXin Li       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7745*67e74705SXin Li                              /*IgnoreBaseAccess=*/false, Diagnose);
7746*67e74705SXin Li       if (ConvertRHS)
7747*67e74705SXin Li         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7748*67e74705SXin Li     }
7749*67e74705SXin Li     return Compatible;
7750*67e74705SXin Li   }
7751*67e74705SXin Li 
7752*67e74705SXin Li   // This check seems unnatural, however it is necessary to ensure the proper
7753*67e74705SXin Li   // conversion of functions/arrays. If the conversion were done for all
7754*67e74705SXin Li   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7755*67e74705SXin Li   // expressions that suppress this implicit conversion (&, sizeof).
7756*67e74705SXin Li   //
7757*67e74705SXin Li   // Suppress this for references: C++ 8.5.3p5.
7758*67e74705SXin Li   if (!LHSType->isReferenceType()) {
7759*67e74705SXin Li     // FIXME: We potentially allocate here even if ConvertRHS is false.
7760*67e74705SXin Li     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7761*67e74705SXin Li     if (RHS.isInvalid())
7762*67e74705SXin Li       return Incompatible;
7763*67e74705SXin Li   }
7764*67e74705SXin Li 
7765*67e74705SXin Li   Expr *PRE = RHS.get()->IgnoreParenCasts();
7766*67e74705SXin Li   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7767*67e74705SXin Li     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7768*67e74705SXin Li     if (PDecl && !PDecl->hasDefinition()) {
7769*67e74705SXin Li       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7770*67e74705SXin Li       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7771*67e74705SXin Li     }
7772*67e74705SXin Li   }
7773*67e74705SXin Li 
7774*67e74705SXin Li   CastKind Kind = CK_Invalid;
7775*67e74705SXin Li   Sema::AssignConvertType result =
7776*67e74705SXin Li     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7777*67e74705SXin Li 
7778*67e74705SXin Li   // C99 6.5.16.1p2: The value of the right operand is converted to the
7779*67e74705SXin Li   // type of the assignment expression.
7780*67e74705SXin Li   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7781*67e74705SXin Li   // so that we can use references in built-in functions even in C.
7782*67e74705SXin Li   // The getNonReferenceType() call makes sure that the resulting expression
7783*67e74705SXin Li   // does not have reference type.
7784*67e74705SXin Li   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7785*67e74705SXin Li     QualType Ty = LHSType.getNonLValueExprType(Context);
7786*67e74705SXin Li     Expr *E = RHS.get();
7787*67e74705SXin Li 
7788*67e74705SXin Li     // Check for various Objective-C errors. If we are not reporting
7789*67e74705SXin Li     // diagnostics and just checking for errors, e.g., during overload
7790*67e74705SXin Li     // resolution, return Incompatible to indicate the failure.
7791*67e74705SXin Li     if (getLangOpts().ObjCAutoRefCount &&
7792*67e74705SXin Li         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7793*67e74705SXin Li                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7794*67e74705SXin Li       if (!Diagnose)
7795*67e74705SXin Li         return Incompatible;
7796*67e74705SXin Li     }
7797*67e74705SXin Li     if (getLangOpts().ObjC1 &&
7798*67e74705SXin Li         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7799*67e74705SXin Li                                            E->getType(), E, Diagnose) ||
7800*67e74705SXin Li          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7801*67e74705SXin Li       if (!Diagnose)
7802*67e74705SXin Li         return Incompatible;
7803*67e74705SXin Li       // Replace the expression with a corrected version and continue so we
7804*67e74705SXin Li       // can find further errors.
7805*67e74705SXin Li       RHS = E;
7806*67e74705SXin Li       return Compatible;
7807*67e74705SXin Li     }
7808*67e74705SXin Li 
7809*67e74705SXin Li     if (ConvertRHS)
7810*67e74705SXin Li       RHS = ImpCastExprToType(E, Ty, Kind);
7811*67e74705SXin Li   }
7812*67e74705SXin Li   return result;
7813*67e74705SXin Li }
7814*67e74705SXin Li 
InvalidOperands(SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)7815*67e74705SXin Li QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7816*67e74705SXin Li                                ExprResult &RHS) {
7817*67e74705SXin Li   Diag(Loc, diag::err_typecheck_invalid_operands)
7818*67e74705SXin Li     << LHS.get()->getType() << RHS.get()->getType()
7819*67e74705SXin Li     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7820*67e74705SXin Li   return QualType();
7821*67e74705SXin Li }
7822*67e74705SXin Li 
7823*67e74705SXin Li /// Try to convert a value of non-vector type to a vector type by converting
7824*67e74705SXin Li /// the type to the element type of the vector and then performing a splat.
7825*67e74705SXin Li /// If the language is OpenCL, we only use conversions that promote scalar
7826*67e74705SXin Li /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7827*67e74705SXin Li /// for float->int.
7828*67e74705SXin Li ///
7829*67e74705SXin Li /// \param scalar - if non-null, actually perform the conversions
7830*67e74705SXin Li /// \return true if the operation fails (but without diagnosing the failure)
tryVectorConvertAndSplat(Sema & S,ExprResult * scalar,QualType scalarTy,QualType vectorEltTy,QualType vectorTy)7831*67e74705SXin Li static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7832*67e74705SXin Li                                      QualType scalarTy,
7833*67e74705SXin Li                                      QualType vectorEltTy,
7834*67e74705SXin Li                                      QualType vectorTy) {
7835*67e74705SXin Li   // The conversion to apply to the scalar before splatting it,
7836*67e74705SXin Li   // if necessary.
7837*67e74705SXin Li   CastKind scalarCast = CK_Invalid;
7838*67e74705SXin Li 
7839*67e74705SXin Li   if (vectorEltTy->isIntegralType(S.Context)) {
7840*67e74705SXin Li     if (!scalarTy->isIntegralType(S.Context))
7841*67e74705SXin Li       return true;
7842*67e74705SXin Li     if (S.getLangOpts().OpenCL &&
7843*67e74705SXin Li         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7844*67e74705SXin Li       return true;
7845*67e74705SXin Li     scalarCast = CK_IntegralCast;
7846*67e74705SXin Li   } else if (vectorEltTy->isRealFloatingType()) {
7847*67e74705SXin Li     if (scalarTy->isRealFloatingType()) {
7848*67e74705SXin Li       if (S.getLangOpts().OpenCL &&
7849*67e74705SXin Li           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7850*67e74705SXin Li         return true;
7851*67e74705SXin Li       scalarCast = CK_FloatingCast;
7852*67e74705SXin Li     }
7853*67e74705SXin Li     else if (scalarTy->isIntegralType(S.Context))
7854*67e74705SXin Li       scalarCast = CK_IntegralToFloating;
7855*67e74705SXin Li     else
7856*67e74705SXin Li       return true;
7857*67e74705SXin Li   } else {
7858*67e74705SXin Li     return true;
7859*67e74705SXin Li   }
7860*67e74705SXin Li 
7861*67e74705SXin Li   // Adjust scalar if desired.
7862*67e74705SXin Li   if (scalar) {
7863*67e74705SXin Li     if (scalarCast != CK_Invalid)
7864*67e74705SXin Li       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7865*67e74705SXin Li     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7866*67e74705SXin Li   }
7867*67e74705SXin Li   return false;
7868*67e74705SXin Li }
7869*67e74705SXin Li 
CheckVectorOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool AllowBothBool,bool AllowBoolConversions)7870*67e74705SXin Li QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7871*67e74705SXin Li                                    SourceLocation Loc, bool IsCompAssign,
7872*67e74705SXin Li                                    bool AllowBothBool,
7873*67e74705SXin Li                                    bool AllowBoolConversions) {
7874*67e74705SXin Li   if (!IsCompAssign) {
7875*67e74705SXin Li     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7876*67e74705SXin Li     if (LHS.isInvalid())
7877*67e74705SXin Li       return QualType();
7878*67e74705SXin Li   }
7879*67e74705SXin Li   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7880*67e74705SXin Li   if (RHS.isInvalid())
7881*67e74705SXin Li     return QualType();
7882*67e74705SXin Li 
7883*67e74705SXin Li   // For conversion purposes, we ignore any qualifiers.
7884*67e74705SXin Li   // For example, "const float" and "float" are equivalent.
7885*67e74705SXin Li   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7886*67e74705SXin Li   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7887*67e74705SXin Li 
7888*67e74705SXin Li   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7889*67e74705SXin Li   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7890*67e74705SXin Li   assert(LHSVecType || RHSVecType);
7891*67e74705SXin Li 
7892*67e74705SXin Li   // AltiVec-style "vector bool op vector bool" combinations are allowed
7893*67e74705SXin Li   // for some operators but not others.
7894*67e74705SXin Li   if (!AllowBothBool &&
7895*67e74705SXin Li       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7896*67e74705SXin Li       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7897*67e74705SXin Li     return InvalidOperands(Loc, LHS, RHS);
7898*67e74705SXin Li 
7899*67e74705SXin Li   // If the vector types are identical, return.
7900*67e74705SXin Li   if (Context.hasSameType(LHSType, RHSType))
7901*67e74705SXin Li     return LHSType;
7902*67e74705SXin Li 
7903*67e74705SXin Li   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7904*67e74705SXin Li   if (LHSVecType && RHSVecType &&
7905*67e74705SXin Li       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7906*67e74705SXin Li     if (isa<ExtVectorType>(LHSVecType)) {
7907*67e74705SXin Li       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7908*67e74705SXin Li       return LHSType;
7909*67e74705SXin Li     }
7910*67e74705SXin Li 
7911*67e74705SXin Li     if (!IsCompAssign)
7912*67e74705SXin Li       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7913*67e74705SXin Li     return RHSType;
7914*67e74705SXin Li   }
7915*67e74705SXin Li 
7916*67e74705SXin Li   // AllowBoolConversions says that bool and non-bool AltiVec vectors
7917*67e74705SXin Li   // can be mixed, with the result being the non-bool type.  The non-bool
7918*67e74705SXin Li   // operand must have integer element type.
7919*67e74705SXin Li   if (AllowBoolConversions && LHSVecType && RHSVecType &&
7920*67e74705SXin Li       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
7921*67e74705SXin Li       (Context.getTypeSize(LHSVecType->getElementType()) ==
7922*67e74705SXin Li        Context.getTypeSize(RHSVecType->getElementType()))) {
7923*67e74705SXin Li     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7924*67e74705SXin Li         LHSVecType->getElementType()->isIntegerType() &&
7925*67e74705SXin Li         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
7926*67e74705SXin Li       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7927*67e74705SXin Li       return LHSType;
7928*67e74705SXin Li     }
7929*67e74705SXin Li     if (!IsCompAssign &&
7930*67e74705SXin Li         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7931*67e74705SXin Li         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7932*67e74705SXin Li         RHSVecType->getElementType()->isIntegerType()) {
7933*67e74705SXin Li       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7934*67e74705SXin Li       return RHSType;
7935*67e74705SXin Li     }
7936*67e74705SXin Li   }
7937*67e74705SXin Li 
7938*67e74705SXin Li   // If there's an ext-vector type and a scalar, try to convert the scalar to
7939*67e74705SXin Li   // the vector element type and splat.
7940*67e74705SXin Li   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7941*67e74705SXin Li     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7942*67e74705SXin Li                                   LHSVecType->getElementType(), LHSType))
7943*67e74705SXin Li       return LHSType;
7944*67e74705SXin Li   }
7945*67e74705SXin Li   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
7946*67e74705SXin Li     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7947*67e74705SXin Li                                   LHSType, RHSVecType->getElementType(),
7948*67e74705SXin Li                                   RHSType))
7949*67e74705SXin Li       return RHSType;
7950*67e74705SXin Li   }
7951*67e74705SXin Li 
7952*67e74705SXin Li   // If we're allowing lax vector conversions, only the total (data) size needs
7953*67e74705SXin Li   // to be the same. If one of the types is scalar, the result is always the
7954*67e74705SXin Li   // vector type. Don't allow this if the scalar operand is an lvalue.
7955*67e74705SXin Li   QualType VecType = LHSVecType ? LHSType : RHSType;
7956*67e74705SXin Li   QualType ScalarType = LHSVecType ? RHSType : LHSType;
7957*67e74705SXin Li   ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS;
7958*67e74705SXin Li   if (isLaxVectorConversion(ScalarType, VecType) &&
7959*67e74705SXin Li       !ScalarExpr->get()->isLValue()) {
7960*67e74705SXin Li     *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast);
7961*67e74705SXin Li     return VecType;
7962*67e74705SXin Li   }
7963*67e74705SXin Li 
7964*67e74705SXin Li   // Okay, the expression is invalid.
7965*67e74705SXin Li 
7966*67e74705SXin Li   // If there's a non-vector, non-real operand, diagnose that.
7967*67e74705SXin Li   if ((!RHSVecType && !RHSType->isRealType()) ||
7968*67e74705SXin Li       (!LHSVecType && !LHSType->isRealType())) {
7969*67e74705SXin Li     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
7970*67e74705SXin Li       << LHSType << RHSType
7971*67e74705SXin Li       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7972*67e74705SXin Li     return QualType();
7973*67e74705SXin Li   }
7974*67e74705SXin Li 
7975*67e74705SXin Li   // OpenCL V1.1 6.2.6.p1:
7976*67e74705SXin Li   // If the operands are of more than one vector type, then an error shall
7977*67e74705SXin Li   // occur. Implicit conversions between vector types are not permitted, per
7978*67e74705SXin Li   // section 6.2.1.
7979*67e74705SXin Li   if (getLangOpts().OpenCL &&
7980*67e74705SXin Li       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
7981*67e74705SXin Li       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
7982*67e74705SXin Li     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
7983*67e74705SXin Li                                                            << RHSType;
7984*67e74705SXin Li     return QualType();
7985*67e74705SXin Li   }
7986*67e74705SXin Li 
7987*67e74705SXin Li   // Otherwise, use the generic diagnostic.
7988*67e74705SXin Li   Diag(Loc, diag::err_typecheck_vector_not_convertable)
7989*67e74705SXin Li     << LHSType << RHSType
7990*67e74705SXin Li     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7991*67e74705SXin Li   return QualType();
7992*67e74705SXin Li }
7993*67e74705SXin Li 
7994*67e74705SXin Li // checkArithmeticNull - Detect when a NULL constant is used improperly in an
7995*67e74705SXin Li // expression.  These are mainly cases where the null pointer is used as an
7996*67e74705SXin Li // integer instead of a pointer.
checkArithmeticNull(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompare)7997*67e74705SXin Li static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7998*67e74705SXin Li                                 SourceLocation Loc, bool IsCompare) {
7999*67e74705SXin Li   // The canonical way to check for a GNU null is with isNullPointerConstant,
8000*67e74705SXin Li   // but we use a bit of a hack here for speed; this is a relatively
8001*67e74705SXin Li   // hot path, and isNullPointerConstant is slow.
8002*67e74705SXin Li   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8003*67e74705SXin Li   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8004*67e74705SXin Li 
8005*67e74705SXin Li   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8006*67e74705SXin Li 
8007*67e74705SXin Li   // Avoid analyzing cases where the result will either be invalid (and
8008*67e74705SXin Li   // diagnosed as such) or entirely valid and not something to warn about.
8009*67e74705SXin Li   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8010*67e74705SXin Li       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8011*67e74705SXin Li     return;
8012*67e74705SXin Li 
8013*67e74705SXin Li   // Comparison operations would not make sense with a null pointer no matter
8014*67e74705SXin Li   // what the other expression is.
8015*67e74705SXin Li   if (!IsCompare) {
8016*67e74705SXin Li     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8017*67e74705SXin Li         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8018*67e74705SXin Li         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8019*67e74705SXin Li     return;
8020*67e74705SXin Li   }
8021*67e74705SXin Li 
8022*67e74705SXin Li   // The rest of the operations only make sense with a null pointer
8023*67e74705SXin Li   // if the other expression is a pointer.
8024*67e74705SXin Li   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8025*67e74705SXin Li       NonNullType->canDecayToPointerType())
8026*67e74705SXin Li     return;
8027*67e74705SXin Li 
8028*67e74705SXin Li   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8029*67e74705SXin Li       << LHSNull /* LHS is NULL */ << NonNullType
8030*67e74705SXin Li       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8031*67e74705SXin Li }
8032*67e74705SXin Li 
DiagnoseBadDivideOrRemainderValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsDiv)8033*67e74705SXin Li static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8034*67e74705SXin Li                                                ExprResult &RHS,
8035*67e74705SXin Li                                                SourceLocation Loc, bool IsDiv) {
8036*67e74705SXin Li   // Check for division/remainder by zero.
8037*67e74705SXin Li   llvm::APSInt RHSValue;
8038*67e74705SXin Li   if (!RHS.get()->isValueDependent() &&
8039*67e74705SXin Li       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8040*67e74705SXin Li     S.DiagRuntimeBehavior(Loc, RHS.get(),
8041*67e74705SXin Li                           S.PDiag(diag::warn_remainder_division_by_zero)
8042*67e74705SXin Li                             << IsDiv << RHS.get()->getSourceRange());
8043*67e74705SXin Li }
8044*67e74705SXin Li 
CheckMultiplyDivideOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool IsDiv)8045*67e74705SXin Li QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8046*67e74705SXin Li                                            SourceLocation Loc,
8047*67e74705SXin Li                                            bool IsCompAssign, bool IsDiv) {
8048*67e74705SXin Li   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8049*67e74705SXin Li 
8050*67e74705SXin Li   if (LHS.get()->getType()->isVectorType() ||
8051*67e74705SXin Li       RHS.get()->getType()->isVectorType())
8052*67e74705SXin Li     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8053*67e74705SXin Li                                /*AllowBothBool*/getLangOpts().AltiVec,
8054*67e74705SXin Li                                /*AllowBoolConversions*/false);
8055*67e74705SXin Li 
8056*67e74705SXin Li   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8057*67e74705SXin Li   if (LHS.isInvalid() || RHS.isInvalid())
8058*67e74705SXin Li     return QualType();
8059*67e74705SXin Li 
8060*67e74705SXin Li 
8061*67e74705SXin Li   if (compType.isNull() || !compType->isArithmeticType())
8062*67e74705SXin Li     return InvalidOperands(Loc, LHS, RHS);
8063*67e74705SXin Li   if (IsDiv)
8064*67e74705SXin Li     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8065*67e74705SXin Li   return compType;
8066*67e74705SXin Li }
8067*67e74705SXin Li 
CheckRemainderOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)8068*67e74705SXin Li QualType Sema::CheckRemainderOperands(
8069*67e74705SXin Li   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8070*67e74705SXin Li   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8071*67e74705SXin Li 
8072*67e74705SXin Li   if (LHS.get()->getType()->isVectorType() ||
8073*67e74705SXin Li       RHS.get()->getType()->isVectorType()) {
8074*67e74705SXin Li     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8075*67e74705SXin Li         RHS.get()->getType()->hasIntegerRepresentation())
8076*67e74705SXin Li       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8077*67e74705SXin Li                                  /*AllowBothBool*/getLangOpts().AltiVec,
8078*67e74705SXin Li                                  /*AllowBoolConversions*/false);
8079*67e74705SXin Li     return InvalidOperands(Loc, LHS, RHS);
8080*67e74705SXin Li   }
8081*67e74705SXin Li 
8082*67e74705SXin Li   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8083*67e74705SXin Li   if (LHS.isInvalid() || RHS.isInvalid())
8084*67e74705SXin Li     return QualType();
8085*67e74705SXin Li 
8086*67e74705SXin Li   if (compType.isNull() || !compType->isIntegerType())
8087*67e74705SXin Li     return InvalidOperands(Loc, LHS, RHS);
8088*67e74705SXin Li   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8089*67e74705SXin Li   return compType;
8090*67e74705SXin Li }
8091*67e74705SXin Li 
8092*67e74705SXin Li /// \brief Diagnose invalid arithmetic on two void pointers.
diagnoseArithmeticOnTwoVoidPointers(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)8093*67e74705SXin Li static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8094*67e74705SXin Li                                                 Expr *LHSExpr, Expr *RHSExpr) {
8095*67e74705SXin Li   S.Diag(Loc, S.getLangOpts().CPlusPlus
8096*67e74705SXin Li                 ? diag::err_typecheck_pointer_arith_void_type
8097*67e74705SXin Li                 : diag::ext_gnu_void_ptr)
8098*67e74705SXin Li     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8099*67e74705SXin Li                             << RHSExpr->getSourceRange();
8100*67e74705SXin Li }
8101*67e74705SXin Li 
8102*67e74705SXin Li /// \brief Diagnose invalid arithmetic on a void pointer.
diagnoseArithmeticOnVoidPointer(Sema & S,SourceLocation Loc,Expr * Pointer)8103*67e74705SXin Li static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8104*67e74705SXin Li                                             Expr *Pointer) {
8105*67e74705SXin Li   S.Diag(Loc, S.getLangOpts().CPlusPlus
8106*67e74705SXin Li                 ? diag::err_typecheck_pointer_arith_void_type
8107*67e74705SXin Li                 : diag::ext_gnu_void_ptr)
8108*67e74705SXin Li     << 0 /* one pointer */ << Pointer->getSourceRange();
8109*67e74705SXin Li }
8110*67e74705SXin Li 
8111*67e74705SXin Li /// \brief Diagnose invalid arithmetic on two function pointers.
diagnoseArithmeticOnTwoFunctionPointers(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)8112*67e74705SXin Li static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8113*67e74705SXin Li                                                     Expr *LHS, Expr *RHS) {
8114*67e74705SXin Li   assert(LHS->getType()->isAnyPointerType());
8115*67e74705SXin Li   assert(RHS->getType()->isAnyPointerType());
8116*67e74705SXin Li   S.Diag(Loc, S.getLangOpts().CPlusPlus
8117*67e74705SXin Li                 ? diag::err_typecheck_pointer_arith_function_type
8118*67e74705SXin Li                 : diag::ext_gnu_ptr_func_arith)
8119*67e74705SXin Li     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8120*67e74705SXin Li     // We only show the second type if it differs from the first.
8121*67e74705SXin Li     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8122*67e74705SXin Li                                                    RHS->getType())
8123*67e74705SXin Li     << RHS->getType()->getPointeeType()
8124*67e74705SXin Li     << LHS->getSourceRange() << RHS->getSourceRange();
8125*67e74705SXin Li }
8126*67e74705SXin Li 
8127*67e74705SXin Li /// \brief Diagnose invalid arithmetic on a function pointer.
diagnoseArithmeticOnFunctionPointer(Sema & S,SourceLocation Loc,Expr * Pointer)8128*67e74705SXin Li static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8129*67e74705SXin Li                                                 Expr *Pointer) {
8130*67e74705SXin Li   assert(Pointer->getType()->isAnyPointerType());
8131*67e74705SXin Li   S.Diag(Loc, S.getLangOpts().CPlusPlus
8132*67e74705SXin Li                 ? diag::err_typecheck_pointer_arith_function_type
8133*67e74705SXin Li                 : diag::ext_gnu_ptr_func_arith)
8134*67e74705SXin Li     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8135*67e74705SXin Li     << 0 /* one pointer, so only one type */
8136*67e74705SXin Li     << Pointer->getSourceRange();
8137*67e74705SXin Li }
8138*67e74705SXin Li 
8139*67e74705SXin Li /// \brief Emit error if Operand is incomplete pointer type
8140*67e74705SXin Li ///
8141*67e74705SXin Li /// \returns True if pointer has incomplete type
checkArithmeticIncompletePointerType(Sema & S,SourceLocation Loc,Expr * Operand)8142*67e74705SXin Li static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8143*67e74705SXin Li                                                  Expr *Operand) {
8144*67e74705SXin Li   QualType ResType = Operand->getType();
8145*67e74705SXin Li   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8146*67e74705SXin Li     ResType = ResAtomicType->getValueType();
8147*67e74705SXin Li 
8148*67e74705SXin Li   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8149*67e74705SXin Li   QualType PointeeTy = ResType->getPointeeType();
8150*67e74705SXin Li   return S.RequireCompleteType(Loc, PointeeTy,
8151*67e74705SXin Li                                diag::err_typecheck_arithmetic_incomplete_type,
8152*67e74705SXin Li                                PointeeTy, Operand->getSourceRange());
8153*67e74705SXin Li }
8154*67e74705SXin Li 
8155*67e74705SXin Li /// \brief Check the validity of an arithmetic pointer operand.
8156*67e74705SXin Li ///
8157*67e74705SXin Li /// If the operand has pointer type, this code will check for pointer types
8158*67e74705SXin Li /// which are invalid in arithmetic operations. These will be diagnosed
8159*67e74705SXin Li /// appropriately, including whether or not the use is supported as an
8160*67e74705SXin Li /// extension.
8161*67e74705SXin Li ///
8162*67e74705SXin Li /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticOpPointerOperand(Sema & S,SourceLocation Loc,Expr * Operand)8163*67e74705SXin Li static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8164*67e74705SXin Li                                             Expr *Operand) {
8165*67e74705SXin Li   QualType ResType = Operand->getType();
8166*67e74705SXin Li   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8167*67e74705SXin Li     ResType = ResAtomicType->getValueType();
8168*67e74705SXin Li 
8169*67e74705SXin Li   if (!ResType->isAnyPointerType()) return true;
8170*67e74705SXin Li 
8171*67e74705SXin Li   QualType PointeeTy = ResType->getPointeeType();
8172*67e74705SXin Li   if (PointeeTy->isVoidType()) {
8173*67e74705SXin Li     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8174*67e74705SXin Li     return !S.getLangOpts().CPlusPlus;
8175*67e74705SXin Li   }
8176*67e74705SXin Li   if (PointeeTy->isFunctionType()) {
8177*67e74705SXin Li     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8178*67e74705SXin Li     return !S.getLangOpts().CPlusPlus;
8179*67e74705SXin Li   }
8180*67e74705SXin Li 
8181*67e74705SXin Li   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8182*67e74705SXin Li 
8183*67e74705SXin Li   return true;
8184*67e74705SXin Li }
8185*67e74705SXin Li 
8186*67e74705SXin Li /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8187*67e74705SXin Li /// operands.
8188*67e74705SXin Li ///
8189*67e74705SXin Li /// This routine will diagnose any invalid arithmetic on pointer operands much
8190*67e74705SXin Li /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8191*67e74705SXin Li /// for emitting a single diagnostic even for operations where both LHS and RHS
8192*67e74705SXin Li /// are (potentially problematic) pointers.
8193*67e74705SXin Li ///
8194*67e74705SXin Li /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticBinOpPointerOperands(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)8195*67e74705SXin Li static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8196*67e74705SXin Li                                                 Expr *LHSExpr, Expr *RHSExpr) {
8197*67e74705SXin Li   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8198*67e74705SXin Li   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8199*67e74705SXin Li   if (!isLHSPointer && !isRHSPointer) return true;
8200*67e74705SXin Li 
8201*67e74705SXin Li   QualType LHSPointeeTy, RHSPointeeTy;
8202*67e74705SXin Li   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8203*67e74705SXin Li   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8204*67e74705SXin Li 
8205*67e74705SXin Li   // if both are pointers check if operation is valid wrt address spaces
8206*67e74705SXin Li   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8207*67e74705SXin Li     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8208*67e74705SXin Li     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8209*67e74705SXin Li     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8210*67e74705SXin Li       S.Diag(Loc,
8211*67e74705SXin Li              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8212*67e74705SXin Li           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8213*67e74705SXin Li           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8214*67e74705SXin Li       return false;
8215*67e74705SXin Li     }
8216*67e74705SXin Li   }
8217*67e74705SXin Li 
8218*67e74705SXin Li   // Check for arithmetic on pointers to incomplete types.
8219*67e74705SXin Li   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8220*67e74705SXin Li   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8221*67e74705SXin Li   if (isLHSVoidPtr || isRHSVoidPtr) {
8222*67e74705SXin Li     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8223*67e74705SXin Li     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8224*67e74705SXin Li     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8225*67e74705SXin Li 
8226*67e74705SXin Li     return !S.getLangOpts().CPlusPlus;
8227*67e74705SXin Li   }
8228*67e74705SXin Li 
8229*67e74705SXin Li   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8230*67e74705SXin Li   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8231*67e74705SXin Li   if (isLHSFuncPtr || isRHSFuncPtr) {
8232*67e74705SXin Li     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8233*67e74705SXin Li     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8234*67e74705SXin Li                                                                 RHSExpr);
8235*67e74705SXin Li     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8236*67e74705SXin Li 
8237*67e74705SXin Li     return !S.getLangOpts().CPlusPlus;
8238*67e74705SXin Li   }
8239*67e74705SXin Li 
8240*67e74705SXin Li   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8241*67e74705SXin Li     return false;
8242*67e74705SXin Li   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8243*67e74705SXin Li     return false;
8244*67e74705SXin Li 
8245*67e74705SXin Li   return true;
8246*67e74705SXin Li }
8247*67e74705SXin Li 
8248*67e74705SXin Li /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8249*67e74705SXin Li /// literal.
diagnoseStringPlusInt(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)8250*67e74705SXin Li static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8251*67e74705SXin Li                                   Expr *LHSExpr, Expr *RHSExpr) {
8252*67e74705SXin Li   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8253*67e74705SXin Li   Expr* IndexExpr = RHSExpr;
8254*67e74705SXin Li   if (!StrExpr) {
8255*67e74705SXin Li     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8256*67e74705SXin Li     IndexExpr = LHSExpr;
8257*67e74705SXin Li   }
8258*67e74705SXin Li 
8259*67e74705SXin Li   bool IsStringPlusInt = StrExpr &&
8260*67e74705SXin Li       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8261*67e74705SXin Li   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8262*67e74705SXin Li     return;
8263*67e74705SXin Li 
8264*67e74705SXin Li   llvm::APSInt index;
8265*67e74705SXin Li   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8266*67e74705SXin Li     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8267*67e74705SXin Li     if (index.isNonNegative() &&
8268*67e74705SXin Li         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8269*67e74705SXin Li                               index.isUnsigned()))
8270*67e74705SXin Li       return;
8271*67e74705SXin Li   }
8272*67e74705SXin Li 
8273*67e74705SXin Li   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8274*67e74705SXin Li   Self.Diag(OpLoc, diag::warn_string_plus_int)
8275*67e74705SXin Li       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8276*67e74705SXin Li 
8277*67e74705SXin Li   // Only print a fixit for "str" + int, not for int + "str".
8278*67e74705SXin Li   if (IndexExpr == RHSExpr) {
8279*67e74705SXin Li     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8280*67e74705SXin Li     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8281*67e74705SXin Li         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8282*67e74705SXin Li         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8283*67e74705SXin Li         << FixItHint::CreateInsertion(EndLoc, "]");
8284*67e74705SXin Li   } else
8285*67e74705SXin Li     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8286*67e74705SXin Li }
8287*67e74705SXin Li 
8288*67e74705SXin Li /// \brief Emit a warning when adding a char literal to a string.
diagnoseStringPlusChar(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)8289*67e74705SXin Li static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8290*67e74705SXin Li                                    Expr *LHSExpr, Expr *RHSExpr) {
8291*67e74705SXin Li   const Expr *StringRefExpr = LHSExpr;
8292*67e74705SXin Li   const CharacterLiteral *CharExpr =
8293*67e74705SXin Li       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8294*67e74705SXin Li 
8295*67e74705SXin Li   if (!CharExpr) {
8296*67e74705SXin Li     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8297*67e74705SXin Li     StringRefExpr = RHSExpr;
8298*67e74705SXin Li   }
8299*67e74705SXin Li 
8300*67e74705SXin Li   if (!CharExpr || !StringRefExpr)
8301*67e74705SXin Li     return;
8302*67e74705SXin Li 
8303*67e74705SXin Li   const QualType StringType = StringRefExpr->getType();
8304*67e74705SXin Li 
8305*67e74705SXin Li   // Return if not a PointerType.
8306*67e74705SXin Li   if (!StringType->isAnyPointerType())
8307*67e74705SXin Li     return;
8308*67e74705SXin Li 
8309*67e74705SXin Li   // Return if not a CharacterType.
8310*67e74705SXin Li   if (!StringType->getPointeeType()->isAnyCharacterType())
8311*67e74705SXin Li     return;
8312*67e74705SXin Li 
8313*67e74705SXin Li   ASTContext &Ctx = Self.getASTContext();
8314*67e74705SXin Li   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8315*67e74705SXin Li 
8316*67e74705SXin Li   const QualType CharType = CharExpr->getType();
8317*67e74705SXin Li   if (!CharType->isAnyCharacterType() &&
8318*67e74705SXin Li       CharType->isIntegerType() &&
8319*67e74705SXin Li       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8320*67e74705SXin Li     Self.Diag(OpLoc, diag::warn_string_plus_char)
8321*67e74705SXin Li         << DiagRange << Ctx.CharTy;
8322*67e74705SXin Li   } else {
8323*67e74705SXin Li     Self.Diag(OpLoc, diag::warn_string_plus_char)
8324*67e74705SXin Li         << DiagRange << CharExpr->getType();
8325*67e74705SXin Li   }
8326*67e74705SXin Li 
8327*67e74705SXin Li   // Only print a fixit for str + char, not for char + str.
8328*67e74705SXin Li   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8329*67e74705SXin Li     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8330*67e74705SXin Li     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8331*67e74705SXin Li         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8332*67e74705SXin Li         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8333*67e74705SXin Li         << FixItHint::CreateInsertion(EndLoc, "]");
8334*67e74705SXin Li   } else {
8335*67e74705SXin Li     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8336*67e74705SXin Li   }
8337*67e74705SXin Li }
8338*67e74705SXin Li 
8339*67e74705SXin Li /// \brief Emit error when two pointers are incompatible.
diagnosePointerIncompatibility(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)8340*67e74705SXin Li static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8341*67e74705SXin Li                                            Expr *LHSExpr, Expr *RHSExpr) {
8342*67e74705SXin Li   assert(LHSExpr->getType()->isAnyPointerType());
8343*67e74705SXin Li   assert(RHSExpr->getType()->isAnyPointerType());
8344*67e74705SXin Li   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8345*67e74705SXin Li     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8346*67e74705SXin Li     << RHSExpr->getSourceRange();
8347*67e74705SXin Li }
8348*67e74705SXin Li 
8349*67e74705SXin Li // C99 6.5.6
CheckAdditionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType * CompLHSTy)8350*67e74705SXin Li QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8351*67e74705SXin Li                                      SourceLocation Loc, BinaryOperatorKind Opc,
8352*67e74705SXin Li                                      QualType* CompLHSTy) {
8353*67e74705SXin Li   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8354*67e74705SXin Li 
8355*67e74705SXin Li   if (LHS.get()->getType()->isVectorType() ||
8356*67e74705SXin Li       RHS.get()->getType()->isVectorType()) {
8357*67e74705SXin Li     QualType compType = CheckVectorOperands(
8358*67e74705SXin Li         LHS, RHS, Loc, CompLHSTy,
8359*67e74705SXin Li         /*AllowBothBool*/getLangOpts().AltiVec,
8360*67e74705SXin Li         /*AllowBoolConversions*/getLangOpts().ZVector);
8361*67e74705SXin Li     if (CompLHSTy) *CompLHSTy = compType;
8362*67e74705SXin Li     return compType;
8363*67e74705SXin Li   }
8364*67e74705SXin Li 
8365*67e74705SXin Li   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8366*67e74705SXin Li   if (LHS.isInvalid() || RHS.isInvalid())
8367*67e74705SXin Li     return QualType();
8368*67e74705SXin Li 
8369*67e74705SXin Li   // Diagnose "string literal" '+' int and string '+' "char literal".
8370*67e74705SXin Li   if (Opc == BO_Add) {
8371*67e74705SXin Li     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8372*67e74705SXin Li     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8373*67e74705SXin Li   }
8374*67e74705SXin Li 
8375*67e74705SXin Li   // handle the common case first (both operands are arithmetic).
8376*67e74705SXin Li   if (!compType.isNull() && compType->isArithmeticType()) {
8377*67e74705SXin Li     if (CompLHSTy) *CompLHSTy = compType;
8378*67e74705SXin Li     return compType;
8379*67e74705SXin Li   }
8380*67e74705SXin Li 
8381*67e74705SXin Li   // Type-checking.  Ultimately the pointer's going to be in PExp;
8382*67e74705SXin Li   // note that we bias towards the LHS being the pointer.
8383*67e74705SXin Li   Expr *PExp = LHS.get(), *IExp = RHS.get();
8384*67e74705SXin Li 
8385*67e74705SXin Li   bool isObjCPointer;
8386*67e74705SXin Li   if (PExp->getType()->isPointerType()) {
8387*67e74705SXin Li     isObjCPointer = false;
8388*67e74705SXin Li   } else if (PExp->getType()->isObjCObjectPointerType()) {
8389*67e74705SXin Li     isObjCPointer = true;
8390*67e74705SXin Li   } else {
8391*67e74705SXin Li     std::swap(PExp, IExp);
8392*67e74705SXin Li     if (PExp->getType()->isPointerType()) {
8393*67e74705SXin Li       isObjCPointer = false;
8394*67e74705SXin Li     } else if (PExp->getType()->isObjCObjectPointerType()) {
8395*67e74705SXin Li       isObjCPointer = true;
8396*67e74705SXin Li     } else {
8397*67e74705SXin Li       return InvalidOperands(Loc, LHS, RHS);
8398*67e74705SXin Li     }
8399*67e74705SXin Li   }
8400*67e74705SXin Li   assert(PExp->getType()->isAnyPointerType());
8401*67e74705SXin Li 
8402*67e74705SXin Li   if (!IExp->getType()->isIntegerType())
8403*67e74705SXin Li     return InvalidOperands(Loc, LHS, RHS);
8404*67e74705SXin Li 
8405*67e74705SXin Li   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8406*67e74705SXin Li     return QualType();
8407*67e74705SXin Li 
8408*67e74705SXin Li   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8409*67e74705SXin Li     return QualType();
8410*67e74705SXin Li 
8411*67e74705SXin Li   // Check array bounds for pointer arithemtic
8412*67e74705SXin Li   CheckArrayAccess(PExp, IExp);
8413*67e74705SXin Li 
8414*67e74705SXin Li   if (CompLHSTy) {
8415*67e74705SXin Li     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8416*67e74705SXin Li     if (LHSTy.isNull()) {
8417*67e74705SXin Li       LHSTy = LHS.get()->getType();
8418*67e74705SXin Li       if (LHSTy->isPromotableIntegerType())
8419*67e74705SXin Li         LHSTy = Context.getPromotedIntegerType(LHSTy);
8420*67e74705SXin Li     }
8421*67e74705SXin Li     *CompLHSTy = LHSTy;
8422*67e74705SXin Li   }
8423*67e74705SXin Li 
8424*67e74705SXin Li   return PExp->getType();
8425*67e74705SXin Li }
8426*67e74705SXin Li 
8427*67e74705SXin Li // C99 6.5.6
CheckSubtractionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,QualType * CompLHSTy)8428*67e74705SXin Li QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8429*67e74705SXin Li                                         SourceLocation Loc,
8430*67e74705SXin Li                                         QualType* CompLHSTy) {
8431*67e74705SXin Li   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8432*67e74705SXin Li 
8433*67e74705SXin Li   if (LHS.get()->getType()->isVectorType() ||
8434*67e74705SXin Li       RHS.get()->getType()->isVectorType()) {
8435*67e74705SXin Li     QualType compType = CheckVectorOperands(
8436*67e74705SXin Li         LHS, RHS, Loc, CompLHSTy,
8437*67e74705SXin Li         /*AllowBothBool*/getLangOpts().AltiVec,
8438*67e74705SXin Li         /*AllowBoolConversions*/getLangOpts().ZVector);
8439*67e74705SXin Li     if (CompLHSTy) *CompLHSTy = compType;
8440*67e74705SXin Li     return compType;
8441*67e74705SXin Li   }
8442*67e74705SXin Li 
8443*67e74705SXin Li   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8444*67e74705SXin Li   if (LHS.isInvalid() || RHS.isInvalid())
8445*67e74705SXin Li     return QualType();
8446*67e74705SXin Li 
8447*67e74705SXin Li   // Enforce type constraints: C99 6.5.6p3.
8448*67e74705SXin Li 
8449*67e74705SXin Li   // Handle the common case first (both operands are arithmetic).
8450*67e74705SXin Li   if (!compType.isNull() && compType->isArithmeticType()) {
8451*67e74705SXin Li     if (CompLHSTy) *CompLHSTy = compType;
8452*67e74705SXin Li     return compType;
8453*67e74705SXin Li   }
8454*67e74705SXin Li 
8455*67e74705SXin Li   // Either ptr - int   or   ptr - ptr.
8456*67e74705SXin Li   if (LHS.get()->getType()->isAnyPointerType()) {
8457*67e74705SXin Li     QualType lpointee = LHS.get()->getType()->getPointeeType();
8458*67e74705SXin Li 
8459*67e74705SXin Li     // Diagnose bad cases where we step over interface counts.
8460*67e74705SXin Li     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8461*67e74705SXin Li         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8462*67e74705SXin Li       return QualType();
8463*67e74705SXin Li 
8464*67e74705SXin Li     // The result type of a pointer-int computation is the pointer type.
8465*67e74705SXin Li     if (RHS.get()->getType()->isIntegerType()) {
8466*67e74705SXin Li       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8467*67e74705SXin Li         return QualType();
8468*67e74705SXin Li 
8469*67e74705SXin Li       // Check array bounds for pointer arithemtic
8470*67e74705SXin Li       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8471*67e74705SXin Li                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8472*67e74705SXin Li 
8473*67e74705SXin Li       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8474*67e74705SXin Li       return LHS.get()->getType();
8475*67e74705SXin Li     }
8476*67e74705SXin Li 
8477*67e74705SXin Li     // Handle pointer-pointer subtractions.
8478*67e74705SXin Li     if (const PointerType *RHSPTy
8479*67e74705SXin Li           = RHS.get()->getType()->getAs<PointerType>()) {
8480*67e74705SXin Li       QualType rpointee = RHSPTy->getPointeeType();
8481*67e74705SXin Li 
8482*67e74705SXin Li       if (getLangOpts().CPlusPlus) {
8483*67e74705SXin Li         // Pointee types must be the same: C++ [expr.add]
8484*67e74705SXin Li         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8485*67e74705SXin Li           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8486*67e74705SXin Li         }
8487*67e74705SXin Li       } else {
8488*67e74705SXin Li         // Pointee types must be compatible C99 6.5.6p3
8489*67e74705SXin Li         if (!Context.typesAreCompatible(
8490*67e74705SXin Li                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8491*67e74705SXin Li                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8492*67e74705SXin Li           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8493*67e74705SXin Li           return QualType();
8494*67e74705SXin Li         }
8495*67e74705SXin Li       }
8496*67e74705SXin Li 
8497*67e74705SXin Li       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8498*67e74705SXin Li                                                LHS.get(), RHS.get()))
8499*67e74705SXin Li         return QualType();
8500*67e74705SXin Li 
8501*67e74705SXin Li       // The pointee type may have zero size.  As an extension, a structure or
8502*67e74705SXin Li       // union may have zero size or an array may have zero length.  In this
8503*67e74705SXin Li       // case subtraction does not make sense.
8504*67e74705SXin Li       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8505*67e74705SXin Li         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8506*67e74705SXin Li         if (ElementSize.isZero()) {
8507*67e74705SXin Li           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8508*67e74705SXin Li             << rpointee.getUnqualifiedType()
8509*67e74705SXin Li             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8510*67e74705SXin Li         }
8511*67e74705SXin Li       }
8512*67e74705SXin Li 
8513*67e74705SXin Li       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8514*67e74705SXin Li       return Context.getPointerDiffType();
8515*67e74705SXin Li     }
8516*67e74705SXin Li   }
8517*67e74705SXin Li 
8518*67e74705SXin Li   return InvalidOperands(Loc, LHS, RHS);
8519*67e74705SXin Li }
8520*67e74705SXin Li 
isScopedEnumerationType(QualType T)8521*67e74705SXin Li static bool isScopedEnumerationType(QualType T) {
8522*67e74705SXin Li   if (const EnumType *ET = T->getAs<EnumType>())
8523*67e74705SXin Li     return ET->getDecl()->isScoped();
8524*67e74705SXin Li   return false;
8525*67e74705SXin Li }
8526*67e74705SXin Li 
DiagnoseBadShiftValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType LHSType)8527*67e74705SXin Li static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8528*67e74705SXin Li                                    SourceLocation Loc, BinaryOperatorKind Opc,
8529*67e74705SXin Li                                    QualType LHSType) {
8530*67e74705SXin Li   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8531*67e74705SXin Li   // so skip remaining warnings as we don't want to modify values within Sema.
8532*67e74705SXin Li   if (S.getLangOpts().OpenCL)
8533*67e74705SXin Li     return;
8534*67e74705SXin Li 
8535*67e74705SXin Li   llvm::APSInt Right;
8536*67e74705SXin Li   // Check right/shifter operand
8537*67e74705SXin Li   if (RHS.get()->isValueDependent() ||
8538*67e74705SXin Li       !RHS.get()->EvaluateAsInt(Right, S.Context))
8539*67e74705SXin Li     return;
8540*67e74705SXin Li 
8541*67e74705SXin Li   if (Right.isNegative()) {
8542*67e74705SXin Li     S.DiagRuntimeBehavior(Loc, RHS.get(),
8543*67e74705SXin Li                           S.PDiag(diag::warn_shift_negative)
8544*67e74705SXin Li                             << RHS.get()->getSourceRange());
8545*67e74705SXin Li     return;
8546*67e74705SXin Li   }
8547*67e74705SXin Li   llvm::APInt LeftBits(Right.getBitWidth(),
8548*67e74705SXin Li                        S.Context.getTypeSize(LHS.get()->getType()));
8549*67e74705SXin Li   if (Right.uge(LeftBits)) {
8550*67e74705SXin Li     S.DiagRuntimeBehavior(Loc, RHS.get(),
8551*67e74705SXin Li                           S.PDiag(diag::warn_shift_gt_typewidth)
8552*67e74705SXin Li                             << RHS.get()->getSourceRange());
8553*67e74705SXin Li     return;
8554*67e74705SXin Li   }
8555*67e74705SXin Li   if (Opc != BO_Shl)
8556*67e74705SXin Li     return;
8557*67e74705SXin Li 
8558*67e74705SXin Li   // When left shifting an ICE which is signed, we can check for overflow which
8559*67e74705SXin Li   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8560*67e74705SXin Li   // integers have defined behavior modulo one more than the maximum value
8561*67e74705SXin Li   // representable in the result type, so never warn for those.
8562*67e74705SXin Li   llvm::APSInt Left;
8563*67e74705SXin Li   if (LHS.get()->isValueDependent() ||
8564*67e74705SXin Li       LHSType->hasUnsignedIntegerRepresentation() ||
8565*67e74705SXin Li       !LHS.get()->EvaluateAsInt(Left, S.Context))
8566*67e74705SXin Li     return;
8567*67e74705SXin Li 
8568*67e74705SXin Li   // If LHS does not have a signed type and non-negative value
8569*67e74705SXin Li   // then, the behavior is undefined. Warn about it.
8570*67e74705SXin Li   if (Left.isNegative()) {
8571*67e74705SXin Li     S.DiagRuntimeBehavior(Loc, LHS.get(),
8572*67e74705SXin Li                           S.PDiag(diag::warn_shift_lhs_negative)
8573*67e74705SXin Li                             << LHS.get()->getSourceRange());
8574*67e74705SXin Li     return;
8575*67e74705SXin Li   }
8576*67e74705SXin Li 
8577*67e74705SXin Li   llvm::APInt ResultBits =
8578*67e74705SXin Li       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8579*67e74705SXin Li   if (LeftBits.uge(ResultBits))
8580*67e74705SXin Li     return;
8581*67e74705SXin Li   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8582*67e74705SXin Li   Result = Result.shl(Right);
8583*67e74705SXin Li 
8584*67e74705SXin Li   // Print the bit representation of the signed integer as an unsigned
8585*67e74705SXin Li   // hexadecimal number.
8586*67e74705SXin Li   SmallString<40> HexResult;
8587*67e74705SXin Li   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8588*67e74705SXin Li 
8589*67e74705SXin Li   // If we are only missing a sign bit, this is less likely to result in actual
8590*67e74705SXin Li   // bugs -- if the result is cast back to an unsigned type, it will have the
8591*67e74705SXin Li   // expected value. Thus we place this behind a different warning that can be
8592*67e74705SXin Li   // turned off separately if needed.
8593*67e74705SXin Li   if (LeftBits == ResultBits - 1) {
8594*67e74705SXin Li     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8595*67e74705SXin Li         << HexResult << LHSType
8596*67e74705SXin Li         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8597*67e74705SXin Li     return;
8598*67e74705SXin Li   }
8599*67e74705SXin Li 
8600*67e74705SXin Li   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8601*67e74705SXin Li     << HexResult.str() << Result.getMinSignedBits() << LHSType
8602*67e74705SXin Li     << Left.getBitWidth() << LHS.get()->getSourceRange()
8603*67e74705SXin Li     << RHS.get()->getSourceRange();
8604*67e74705SXin Li }
8605*67e74705SXin Li 
8606*67e74705SXin Li /// \brief Return the resulting type when an OpenCL vector is shifted
8607*67e74705SXin Li ///        by a scalar or vector shift amount.
checkOpenCLVectorShift(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)8608*67e74705SXin Li static QualType checkOpenCLVectorShift(Sema &S,
8609*67e74705SXin Li                                        ExprResult &LHS, ExprResult &RHS,
8610*67e74705SXin Li                                        SourceLocation Loc, bool IsCompAssign) {
8611*67e74705SXin Li   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8612*67e74705SXin Li   if (!LHS.get()->getType()->isVectorType()) {
8613*67e74705SXin Li     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8614*67e74705SXin Li       << RHS.get()->getType() << LHS.get()->getType()
8615*67e74705SXin Li       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8616*67e74705SXin Li     return QualType();
8617*67e74705SXin Li   }
8618*67e74705SXin Li 
8619*67e74705SXin Li   if (!IsCompAssign) {
8620*67e74705SXin Li     LHS = S.UsualUnaryConversions(LHS.get());
8621*67e74705SXin Li     if (LHS.isInvalid()) return QualType();
8622*67e74705SXin Li   }
8623*67e74705SXin Li 
8624*67e74705SXin Li   RHS = S.UsualUnaryConversions(RHS.get());
8625*67e74705SXin Li   if (RHS.isInvalid()) return QualType();
8626*67e74705SXin Li 
8627*67e74705SXin Li   QualType LHSType = LHS.get()->getType();
8628*67e74705SXin Li   const VectorType *LHSVecTy = LHSType->castAs<VectorType>();
8629*67e74705SXin Li   QualType LHSEleType = LHSVecTy->getElementType();
8630*67e74705SXin Li 
8631*67e74705SXin Li   // Note that RHS might not be a vector.
8632*67e74705SXin Li   QualType RHSType = RHS.get()->getType();
8633*67e74705SXin Li   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8634*67e74705SXin Li   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8635*67e74705SXin Li 
8636*67e74705SXin Li   // OpenCL v1.1 s6.3.j says that the operands need to be integers.
8637*67e74705SXin Li   if (!LHSEleType->isIntegerType()) {
8638*67e74705SXin Li     S.Diag(Loc, diag::err_typecheck_expect_int)
8639*67e74705SXin Li       << LHS.get()->getType() << LHS.get()->getSourceRange();
8640*67e74705SXin Li     return QualType();
8641*67e74705SXin Li   }
8642*67e74705SXin Li 
8643*67e74705SXin Li   if (!RHSEleType->isIntegerType()) {
8644*67e74705SXin Li     S.Diag(Loc, diag::err_typecheck_expect_int)
8645*67e74705SXin Li       << RHS.get()->getType() << RHS.get()->getSourceRange();
8646*67e74705SXin Li     return QualType();
8647*67e74705SXin Li   }
8648*67e74705SXin Li 
8649*67e74705SXin Li   if (RHSVecTy) {
8650*67e74705SXin Li     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8651*67e74705SXin Li     // are applied component-wise. So if RHS is a vector, then ensure
8652*67e74705SXin Li     // that the number of elements is the same as LHS...
8653*67e74705SXin Li     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8654*67e74705SXin Li       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8655*67e74705SXin Li         << LHS.get()->getType() << RHS.get()->getType()
8656*67e74705SXin Li         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8657*67e74705SXin Li       return QualType();
8658*67e74705SXin Li     }
8659*67e74705SXin Li   } else {
8660*67e74705SXin Li     // ...else expand RHS to match the number of elements in LHS.
8661*67e74705SXin Li     QualType VecTy =
8662*67e74705SXin Li       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8663*67e74705SXin Li     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8664*67e74705SXin Li   }
8665*67e74705SXin Li 
8666*67e74705SXin Li   return LHSType;
8667*67e74705SXin Li }
8668*67e74705SXin Li 
8669*67e74705SXin Li // C99 6.5.7
CheckShiftOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,bool IsCompAssign)8670*67e74705SXin Li QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8671*67e74705SXin Li                                   SourceLocation Loc, BinaryOperatorKind Opc,
8672*67e74705SXin Li                                   bool IsCompAssign) {
8673*67e74705SXin Li   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8674*67e74705SXin Li 
8675*67e74705SXin Li   // Vector shifts promote their scalar inputs to vector type.
8676*67e74705SXin Li   if (LHS.get()->getType()->isVectorType() ||
8677*67e74705SXin Li       RHS.get()->getType()->isVectorType()) {
8678*67e74705SXin Li     if (LangOpts.OpenCL)
8679*67e74705SXin Li       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8680*67e74705SXin Li     if (LangOpts.ZVector) {
8681*67e74705SXin Li       // The shift operators for the z vector extensions work basically
8682*67e74705SXin Li       // like OpenCL shifts, except that neither the LHS nor the RHS is
8683*67e74705SXin Li       // allowed to be a "vector bool".
8684*67e74705SXin Li       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8685*67e74705SXin Li         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8686*67e74705SXin Li           return InvalidOperands(Loc, LHS, RHS);
8687*67e74705SXin Li       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8688*67e74705SXin Li         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8689*67e74705SXin Li           return InvalidOperands(Loc, LHS, RHS);
8690*67e74705SXin Li       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8691*67e74705SXin Li     }
8692*67e74705SXin Li     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8693*67e74705SXin Li                                /*AllowBothBool*/true,
8694*67e74705SXin Li                                /*AllowBoolConversions*/false);
8695*67e74705SXin Li   }
8696*67e74705SXin Li 
8697*67e74705SXin Li   // Shifts don't perform usual arithmetic conversions, they just do integer
8698*67e74705SXin Li   // promotions on each operand. C99 6.5.7p3
8699*67e74705SXin Li 
8700*67e74705SXin Li   // For the LHS, do usual unary conversions, but then reset them away
8701*67e74705SXin Li   // if this is a compound assignment.
8702*67e74705SXin Li   ExprResult OldLHS = LHS;
8703*67e74705SXin Li   LHS = UsualUnaryConversions(LHS.get());
8704*67e74705SXin Li   if (LHS.isInvalid())
8705*67e74705SXin Li     return QualType();
8706*67e74705SXin Li   QualType LHSType = LHS.get()->getType();
8707*67e74705SXin Li   if (IsCompAssign) LHS = OldLHS;
8708*67e74705SXin Li 
8709*67e74705SXin Li   // The RHS is simpler.
8710*67e74705SXin Li   RHS = UsualUnaryConversions(RHS.get());
8711*67e74705SXin Li   if (RHS.isInvalid())
8712*67e74705SXin Li     return QualType();
8713*67e74705SXin Li   QualType RHSType = RHS.get()->getType();
8714*67e74705SXin Li 
8715*67e74705SXin Li   // C99 6.5.7p2: Each of the operands shall have integer type.
8716*67e74705SXin Li   if (!LHSType->hasIntegerRepresentation() ||
8717*67e74705SXin Li       !RHSType->hasIntegerRepresentation())
8718*67e74705SXin Li     return InvalidOperands(Loc, LHS, RHS);
8719*67e74705SXin Li 
8720*67e74705SXin Li   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8721*67e74705SXin Li   // hasIntegerRepresentation() above instead of this.
8722*67e74705SXin Li   if (isScopedEnumerationType(LHSType) ||
8723*67e74705SXin Li       isScopedEnumerationType(RHSType)) {
8724*67e74705SXin Li     return InvalidOperands(Loc, LHS, RHS);
8725*67e74705SXin Li   }
8726*67e74705SXin Li   // Sanity-check shift operands
8727*67e74705SXin Li   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8728*67e74705SXin Li 
8729*67e74705SXin Li   // "The type of the result is that of the promoted left operand."
8730*67e74705SXin Li   return LHSType;
8731*67e74705SXin Li }
8732*67e74705SXin Li 
IsWithinTemplateSpecialization(Decl * D)8733*67e74705SXin Li static bool IsWithinTemplateSpecialization(Decl *D) {
8734*67e74705SXin Li   if (DeclContext *DC = D->getDeclContext()) {
8735*67e74705SXin Li     if (isa<ClassTemplateSpecializationDecl>(DC))
8736*67e74705SXin Li       return true;
8737*67e74705SXin Li     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8738*67e74705SXin Li       return FD->isFunctionTemplateSpecialization();
8739*67e74705SXin Li   }
8740*67e74705SXin Li   return false;
8741*67e74705SXin Li }
8742*67e74705SXin Li 
8743*67e74705SXin Li /// If two different enums are compared, raise a warning.
checkEnumComparison(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)8744*67e74705SXin Li static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8745*67e74705SXin Li                                 Expr *RHS) {
8746*67e74705SXin Li   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8747*67e74705SXin Li   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8748*67e74705SXin Li 
8749*67e74705SXin Li   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8750*67e74705SXin Li   if (!LHSEnumType)
8751*67e74705SXin Li     return;
8752*67e74705SXin Li   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8753*67e74705SXin Li   if (!RHSEnumType)
8754*67e74705SXin Li     return;
8755*67e74705SXin Li 
8756*67e74705SXin Li   // Ignore anonymous enums.
8757*67e74705SXin Li   if (!LHSEnumType->getDecl()->getIdentifier())
8758*67e74705SXin Li     return;
8759*67e74705SXin Li   if (!RHSEnumType->getDecl()->getIdentifier())
8760*67e74705SXin Li     return;
8761*67e74705SXin Li 
8762*67e74705SXin Li   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8763*67e74705SXin Li     return;
8764*67e74705SXin Li 
8765*67e74705SXin Li   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8766*67e74705SXin Li       << LHSStrippedType << RHSStrippedType
8767*67e74705SXin Li       << LHS->getSourceRange() << RHS->getSourceRange();
8768*67e74705SXin Li }
8769*67e74705SXin Li 
8770*67e74705SXin Li /// \brief Diagnose bad pointer comparisons.
diagnoseDistinctPointerComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)8771*67e74705SXin Li static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8772*67e74705SXin Li                                               ExprResult &LHS, ExprResult &RHS,
8773*67e74705SXin Li                                               bool IsError) {
8774*67e74705SXin Li   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8775*67e74705SXin Li                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8776*67e74705SXin Li     << LHS.get()->getType() << RHS.get()->getType()
8777*67e74705SXin Li     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8778*67e74705SXin Li }
8779*67e74705SXin Li 
8780*67e74705SXin Li /// \brief Returns false if the pointers are converted to a composite type,
8781*67e74705SXin Li /// true otherwise.
convertPointersToCompositeType(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)8782*67e74705SXin Li static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8783*67e74705SXin Li                                            ExprResult &LHS, ExprResult &RHS) {
8784*67e74705SXin Li   // C++ [expr.rel]p2:
8785*67e74705SXin Li   //   [...] Pointer conversions (4.10) and qualification
8786*67e74705SXin Li   //   conversions (4.4) are performed on pointer operands (or on
8787*67e74705SXin Li   //   a pointer operand and a null pointer constant) to bring
8788*67e74705SXin Li   //   them to their composite pointer type. [...]
8789*67e74705SXin Li   //
8790*67e74705SXin Li   // C++ [expr.eq]p1 uses the same notion for (in)equality
8791*67e74705SXin Li   // comparisons of pointers.
8792*67e74705SXin Li 
8793*67e74705SXin Li   // C++ [expr.eq]p2:
8794*67e74705SXin Li   //   In addition, pointers to members can be compared, or a pointer to
8795*67e74705SXin Li   //   member and a null pointer constant. Pointer to member conversions
8796*67e74705SXin Li   //   (4.11) and qualification conversions (4.4) are performed to bring
8797*67e74705SXin Li   //   them to a common type. If one operand is a null pointer constant,
8798*67e74705SXin Li   //   the common type is the type of the other operand. Otherwise, the
8799*67e74705SXin Li   //   common type is a pointer to member type similar (4.4) to the type
8800*67e74705SXin Li   //   of one of the operands, with a cv-qualification signature (4.4)
8801*67e74705SXin Li   //   that is the union of the cv-qualification signatures of the operand
8802*67e74705SXin Li   //   types.
8803*67e74705SXin Li 
8804*67e74705SXin Li   QualType LHSType = LHS.get()->getType();
8805*67e74705SXin Li   QualType RHSType = RHS.get()->getType();
8806*67e74705SXin Li   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8807*67e74705SXin Li          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8808*67e74705SXin Li 
8809*67e74705SXin Li   bool NonStandardCompositeType = false;
8810*67e74705SXin Li   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8811*67e74705SXin Li   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8812*67e74705SXin Li   if (T.isNull()) {
8813*67e74705SXin Li     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8814*67e74705SXin Li     return true;
8815*67e74705SXin Li   }
8816*67e74705SXin Li 
8817*67e74705SXin Li   if (NonStandardCompositeType)
8818*67e74705SXin Li     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8819*67e74705SXin Li       << LHSType << RHSType << T << LHS.get()->getSourceRange()
8820*67e74705SXin Li       << RHS.get()->getSourceRange();
8821*67e74705SXin Li 
8822*67e74705SXin Li   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8823*67e74705SXin Li   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8824*67e74705SXin Li   return false;
8825*67e74705SXin Li }
8826*67e74705SXin Li 
diagnoseFunctionPointerToVoidComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)8827*67e74705SXin Li static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8828*67e74705SXin Li                                                     ExprResult &LHS,
8829*67e74705SXin Li                                                     ExprResult &RHS,
8830*67e74705SXin Li                                                     bool IsError) {
8831*67e74705SXin Li   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8832*67e74705SXin Li                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8833*67e74705SXin Li     << LHS.get()->getType() << RHS.get()->getType()
8834*67e74705SXin Li     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8835*67e74705SXin Li }
8836*67e74705SXin Li 
isObjCObjectLiteral(ExprResult & E)8837*67e74705SXin Li static bool isObjCObjectLiteral(ExprResult &E) {
8838*67e74705SXin Li   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8839*67e74705SXin Li   case Stmt::ObjCArrayLiteralClass:
8840*67e74705SXin Li   case Stmt::ObjCDictionaryLiteralClass:
8841*67e74705SXin Li   case Stmt::ObjCStringLiteralClass:
8842*67e74705SXin Li   case Stmt::ObjCBoxedExprClass:
8843*67e74705SXin Li     return true;
8844*67e74705SXin Li   default:
8845*67e74705SXin Li     // Note that ObjCBoolLiteral is NOT an object literal!
8846*67e74705SXin Li     return false;
8847*67e74705SXin Li   }
8848*67e74705SXin Li }
8849*67e74705SXin Li 
hasIsEqualMethod(Sema & S,const Expr * LHS,const Expr * RHS)8850*67e74705SXin Li static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8851*67e74705SXin Li   const ObjCObjectPointerType *Type =
8852*67e74705SXin Li     LHS->getType()->getAs<ObjCObjectPointerType>();
8853*67e74705SXin Li 
8854*67e74705SXin Li   // If this is not actually an Objective-C object, bail out.
8855*67e74705SXin Li   if (!Type)
8856*67e74705SXin Li     return false;
8857*67e74705SXin Li 
8858*67e74705SXin Li   // Get the LHS object's interface type.
8859*67e74705SXin Li   QualType InterfaceType = Type->getPointeeType();
8860*67e74705SXin Li 
8861*67e74705SXin Li   // If the RHS isn't an Objective-C object, bail out.
8862*67e74705SXin Li   if (!RHS->getType()->isObjCObjectPointerType())
8863*67e74705SXin Li     return false;
8864*67e74705SXin Li 
8865*67e74705SXin Li   // Try to find the -isEqual: method.
8866*67e74705SXin Li   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8867*67e74705SXin Li   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8868*67e74705SXin Li                                                       InterfaceType,
8869*67e74705SXin Li                                                       /*instance=*/true);
8870*67e74705SXin Li   if (!Method) {
8871*67e74705SXin Li     if (Type->isObjCIdType()) {
8872*67e74705SXin Li       // For 'id', just check the global pool.
8873*67e74705SXin Li       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8874*67e74705SXin Li                                                   /*receiverId=*/true);
8875*67e74705SXin Li     } else {
8876*67e74705SXin Li       // Check protocols.
8877*67e74705SXin Li       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8878*67e74705SXin Li                                              /*instance=*/true);
8879*67e74705SXin Li     }
8880*67e74705SXin Li   }
8881*67e74705SXin Li 
8882*67e74705SXin Li   if (!Method)
8883*67e74705SXin Li     return false;
8884*67e74705SXin Li 
8885*67e74705SXin Li   QualType T = Method->parameters()[0]->getType();
8886*67e74705SXin Li   if (!T->isObjCObjectPointerType())
8887*67e74705SXin Li     return false;
8888*67e74705SXin Li 
8889*67e74705SXin Li   QualType R = Method->getReturnType();
8890*67e74705SXin Li   if (!R->isScalarType())
8891*67e74705SXin Li     return false;
8892*67e74705SXin Li 
8893*67e74705SXin Li   return true;
8894*67e74705SXin Li }
8895*67e74705SXin Li 
CheckLiteralKind(Expr * FromE)8896*67e74705SXin Li Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8897*67e74705SXin Li   FromE = FromE->IgnoreParenImpCasts();
8898*67e74705SXin Li   switch (FromE->getStmtClass()) {
8899*67e74705SXin Li     default:
8900*67e74705SXin Li       break;
8901*67e74705SXin Li     case Stmt::ObjCStringLiteralClass:
8902*67e74705SXin Li       // "string literal"
8903*67e74705SXin Li       return LK_String;
8904*67e74705SXin Li     case Stmt::ObjCArrayLiteralClass:
8905*67e74705SXin Li       // "array literal"
8906*67e74705SXin Li       return LK_Array;
8907*67e74705SXin Li     case Stmt::ObjCDictionaryLiteralClass:
8908*67e74705SXin Li       // "dictionary literal"
8909*67e74705SXin Li       return LK_Dictionary;
8910*67e74705SXin Li     case Stmt::BlockExprClass:
8911*67e74705SXin Li       return LK_Block;
8912*67e74705SXin Li     case Stmt::ObjCBoxedExprClass: {
8913*67e74705SXin Li       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
8914*67e74705SXin Li       switch (Inner->getStmtClass()) {
8915*67e74705SXin Li         case Stmt::IntegerLiteralClass:
8916*67e74705SXin Li         case Stmt::FloatingLiteralClass:
8917*67e74705SXin Li         case Stmt::CharacterLiteralClass:
8918*67e74705SXin Li         case Stmt::ObjCBoolLiteralExprClass:
8919*67e74705SXin Li         case Stmt::CXXBoolLiteralExprClass:
8920*67e74705SXin Li           // "numeric literal"
8921*67e74705SXin Li           return LK_Numeric;
8922*67e74705SXin Li         case Stmt::ImplicitCastExprClass: {
8923*67e74705SXin Li           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8924*67e74705SXin Li           // Boolean literals can be represented by implicit casts.
8925*67e74705SXin Li           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8926*67e74705SXin Li             return LK_Numeric;
8927*67e74705SXin Li           break;
8928*67e74705SXin Li         }
8929*67e74705SXin Li         default:
8930*67e74705SXin Li           break;
8931*67e74705SXin Li       }
8932*67e74705SXin Li       return LK_Boxed;
8933*67e74705SXin Li     }
8934*67e74705SXin Li   }
8935*67e74705SXin Li   return LK_None;
8936*67e74705SXin Li }
8937*67e74705SXin Li 
diagnoseObjCLiteralComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,BinaryOperator::Opcode Opc)8938*67e74705SXin Li static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8939*67e74705SXin Li                                           ExprResult &LHS, ExprResult &RHS,
8940*67e74705SXin Li                                           BinaryOperator::Opcode Opc){
8941*67e74705SXin Li   Expr *Literal;
8942*67e74705SXin Li   Expr *Other;
8943*67e74705SXin Li   if (isObjCObjectLiteral(LHS)) {
8944*67e74705SXin Li     Literal = LHS.get();
8945*67e74705SXin Li     Other = RHS.get();
8946*67e74705SXin Li   } else {
8947*67e74705SXin Li     Literal = RHS.get();
8948*67e74705SXin Li     Other = LHS.get();
8949*67e74705SXin Li   }
8950*67e74705SXin Li 
8951*67e74705SXin Li   // Don't warn on comparisons against nil.
8952*67e74705SXin Li   Other = Other->IgnoreParenCasts();
8953*67e74705SXin Li   if (Other->isNullPointerConstant(S.getASTContext(),
8954*67e74705SXin Li                                    Expr::NPC_ValueDependentIsNotNull))
8955*67e74705SXin Li     return;
8956*67e74705SXin Li 
8957*67e74705SXin Li   // This should be kept in sync with warn_objc_literal_comparison.
8958*67e74705SXin Li   // LK_String should always be after the other literals, since it has its own
8959*67e74705SXin Li   // warning flag.
8960*67e74705SXin Li   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
8961*67e74705SXin Li   assert(LiteralKind != Sema::LK_Block);
8962*67e74705SXin Li   if (LiteralKind == Sema::LK_None) {
8963*67e74705SXin Li     llvm_unreachable("Unknown Objective-C object literal kind");
8964*67e74705SXin Li   }
8965*67e74705SXin Li 
8966*67e74705SXin Li   if (LiteralKind == Sema::LK_String)
8967*67e74705SXin Li     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8968*67e74705SXin Li       << Literal->getSourceRange();
8969*67e74705SXin Li   else
8970*67e74705SXin Li     S.Diag(Loc, diag::warn_objc_literal_comparison)
8971*67e74705SXin Li       << LiteralKind << Literal->getSourceRange();
8972*67e74705SXin Li 
8973*67e74705SXin Li   if (BinaryOperator::isEqualityOp(Opc) &&
8974*67e74705SXin Li       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8975*67e74705SXin Li     SourceLocation Start = LHS.get()->getLocStart();
8976*67e74705SXin Li     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
8977*67e74705SXin Li     CharSourceRange OpRange =
8978*67e74705SXin Li       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
8979*67e74705SXin Li 
8980*67e74705SXin Li     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8981*67e74705SXin Li       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
8982*67e74705SXin Li       << FixItHint::CreateReplacement(OpRange, " isEqual:")
8983*67e74705SXin Li       << FixItHint::CreateInsertion(End, "]");
8984*67e74705SXin Li   }
8985*67e74705SXin Li }
8986*67e74705SXin Li 
diagnoseLogicalNotOnLHSofComparison(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)8987*67e74705SXin Li static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8988*67e74705SXin Li                                                 ExprResult &RHS,
8989*67e74705SXin Li                                                 SourceLocation Loc,
8990*67e74705SXin Li                                                 BinaryOperatorKind Opc) {
8991*67e74705SXin Li   // Check that left hand side is !something.
8992*67e74705SXin Li   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
8993*67e74705SXin Li   if (!UO || UO->getOpcode() != UO_LNot) return;
8994*67e74705SXin Li 
8995*67e74705SXin Li   // Only check if the right hand side is non-bool arithmetic type.
8996*67e74705SXin Li   if (RHS.get()->isKnownToHaveBooleanValue()) return;
8997*67e74705SXin Li 
8998*67e74705SXin Li   // Make sure that the something in !something is not bool.
8999*67e74705SXin Li   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9000*67e74705SXin Li   if (SubExpr->isKnownToHaveBooleanValue()) return;
9001*67e74705SXin Li 
9002*67e74705SXin Li   // Emit warning.
9003*67e74705SXin Li   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
9004*67e74705SXin Li       << Loc;
9005*67e74705SXin Li 
9006*67e74705SXin Li   // First note suggest !(x < y)
9007*67e74705SXin Li   SourceLocation FirstOpen = SubExpr->getLocStart();
9008*67e74705SXin Li   SourceLocation FirstClose = RHS.get()->getLocEnd();
9009*67e74705SXin Li   FirstClose = S.getLocForEndOfToken(FirstClose);
9010*67e74705SXin Li   if (FirstClose.isInvalid())
9011*67e74705SXin Li     FirstOpen = SourceLocation();
9012*67e74705SXin Li   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9013*67e74705SXin Li       << FixItHint::CreateInsertion(FirstOpen, "(")
9014*67e74705SXin Li       << FixItHint::CreateInsertion(FirstClose, ")");
9015*67e74705SXin Li 
9016*67e74705SXin Li   // Second note suggests (!x) < y
9017*67e74705SXin Li   SourceLocation SecondOpen = LHS.get()->getLocStart();
9018*67e74705SXin Li   SourceLocation SecondClose = LHS.get()->getLocEnd();
9019*67e74705SXin Li   SecondClose = S.getLocForEndOfToken(SecondClose);
9020*67e74705SXin Li   if (SecondClose.isInvalid())
9021*67e74705SXin Li     SecondOpen = SourceLocation();
9022*67e74705SXin Li   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9023*67e74705SXin Li       << FixItHint::CreateInsertion(SecondOpen, "(")
9024*67e74705SXin Li       << FixItHint::CreateInsertion(SecondClose, ")");
9025*67e74705SXin Li }
9026*67e74705SXin Li 
9027*67e74705SXin Li // Get the decl for a simple expression: a reference to a variable,
9028*67e74705SXin Li // an implicit C++ field reference, or an implicit ObjC ivar reference.
getCompareDecl(Expr * E)9029*67e74705SXin Li static ValueDecl *getCompareDecl(Expr *E) {
9030*67e74705SXin Li   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9031*67e74705SXin Li     return DR->getDecl();
9032*67e74705SXin Li   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9033*67e74705SXin Li     if (Ivar->isFreeIvar())
9034*67e74705SXin Li       return Ivar->getDecl();
9035*67e74705SXin Li   }
9036*67e74705SXin Li   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9037*67e74705SXin Li     if (Mem->isImplicitAccess())
9038*67e74705SXin Li       return Mem->getMemberDecl();
9039*67e74705SXin Li   }
9040*67e74705SXin Li   return nullptr;
9041*67e74705SXin Li }
9042*67e74705SXin Li 
9043*67e74705SXin Li // C99 6.5.8, C++ [expr.rel]
CheckCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,bool IsRelational)9044*67e74705SXin Li QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9045*67e74705SXin Li                                     SourceLocation Loc, BinaryOperatorKind Opc,
9046*67e74705SXin Li                                     bool IsRelational) {
9047*67e74705SXin Li   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9048*67e74705SXin Li 
9049*67e74705SXin Li   // Handle vector comparisons separately.
9050*67e74705SXin Li   if (LHS.get()->getType()->isVectorType() ||
9051*67e74705SXin Li       RHS.get()->getType()->isVectorType())
9052*67e74705SXin Li     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9053*67e74705SXin Li 
9054*67e74705SXin Li   QualType LHSType = LHS.get()->getType();
9055*67e74705SXin Li   QualType RHSType = RHS.get()->getType();
9056*67e74705SXin Li 
9057*67e74705SXin Li   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9058*67e74705SXin Li   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9059*67e74705SXin Li 
9060*67e74705SXin Li   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9061*67e74705SXin Li   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
9062*67e74705SXin Li 
9063*67e74705SXin Li   if (!LHSType->hasFloatingRepresentation() &&
9064*67e74705SXin Li       !(LHSType->isBlockPointerType() && IsRelational) &&
9065*67e74705SXin Li       !LHS.get()->getLocStart().isMacroID() &&
9066*67e74705SXin Li       !RHS.get()->getLocStart().isMacroID() &&
9067*67e74705SXin Li       ActiveTemplateInstantiations.empty()) {
9068*67e74705SXin Li     // For non-floating point types, check for self-comparisons of the form
9069*67e74705SXin Li     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9070*67e74705SXin Li     // often indicate logic errors in the program.
9071*67e74705SXin Li     //
9072*67e74705SXin Li     // NOTE: Don't warn about comparison expressions resulting from macro
9073*67e74705SXin Li     // expansion. Also don't warn about comparisons which are only self
9074*67e74705SXin Li     // comparisons within a template specialization. The warnings should catch
9075*67e74705SXin Li     // obvious cases in the definition of the template anyways. The idea is to
9076*67e74705SXin Li     // warn when the typed comparison operator will always evaluate to the same
9077*67e74705SXin Li     // result.
9078*67e74705SXin Li     ValueDecl *DL = getCompareDecl(LHSStripped);
9079*67e74705SXin Li     ValueDecl *DR = getCompareDecl(RHSStripped);
9080*67e74705SXin Li     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9081*67e74705SXin Li       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9082*67e74705SXin Li                           << 0 // self-
9083*67e74705SXin Li                           << (Opc == BO_EQ
9084*67e74705SXin Li                               || Opc == BO_LE
9085*67e74705SXin Li                               || Opc == BO_GE));
9086*67e74705SXin Li     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9087*67e74705SXin Li                !DL->getType()->isReferenceType() &&
9088*67e74705SXin Li                !DR->getType()->isReferenceType()) {
9089*67e74705SXin Li         // what is it always going to eval to?
9090*67e74705SXin Li         char always_evals_to;
9091*67e74705SXin Li         switch(Opc) {
9092*67e74705SXin Li         case BO_EQ: // e.g. array1 == array2
9093*67e74705SXin Li           always_evals_to = 0; // false
9094*67e74705SXin Li           break;
9095*67e74705SXin Li         case BO_NE: // e.g. array1 != array2
9096*67e74705SXin Li           always_evals_to = 1; // true
9097*67e74705SXin Li           break;
9098*67e74705SXin Li         default:
9099*67e74705SXin Li           // best we can say is 'a constant'
9100*67e74705SXin Li           always_evals_to = 2; // e.g. array1 <= array2
9101*67e74705SXin Li           break;
9102*67e74705SXin Li         }
9103*67e74705SXin Li         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9104*67e74705SXin Li                             << 1 // array
9105*67e74705SXin Li                             << always_evals_to);
9106*67e74705SXin Li     }
9107*67e74705SXin Li 
9108*67e74705SXin Li     if (isa<CastExpr>(LHSStripped))
9109*67e74705SXin Li       LHSStripped = LHSStripped->IgnoreParenCasts();
9110*67e74705SXin Li     if (isa<CastExpr>(RHSStripped))
9111*67e74705SXin Li       RHSStripped = RHSStripped->IgnoreParenCasts();
9112*67e74705SXin Li 
9113*67e74705SXin Li     // Warn about comparisons against a string constant (unless the other
9114*67e74705SXin Li     // operand is null), the user probably wants strcmp.
9115*67e74705SXin Li     Expr *literalString = nullptr;
9116*67e74705SXin Li     Expr *literalStringStripped = nullptr;
9117*67e74705SXin Li     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9118*67e74705SXin Li         !RHSStripped->isNullPointerConstant(Context,
9119*67e74705SXin Li                                             Expr::NPC_ValueDependentIsNull)) {
9120*67e74705SXin Li       literalString = LHS.get();
9121*67e74705SXin Li       literalStringStripped = LHSStripped;
9122*67e74705SXin Li     } else if ((isa<StringLiteral>(RHSStripped) ||
9123*67e74705SXin Li                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9124*67e74705SXin Li                !LHSStripped->isNullPointerConstant(Context,
9125*67e74705SXin Li                                             Expr::NPC_ValueDependentIsNull)) {
9126*67e74705SXin Li       literalString = RHS.get();
9127*67e74705SXin Li       literalStringStripped = RHSStripped;
9128*67e74705SXin Li     }
9129*67e74705SXin Li 
9130*67e74705SXin Li     if (literalString) {
9131*67e74705SXin Li       DiagRuntimeBehavior(Loc, nullptr,
9132*67e74705SXin Li         PDiag(diag::warn_stringcompare)
9133*67e74705SXin Li           << isa<ObjCEncodeExpr>(literalStringStripped)
9134*67e74705SXin Li           << literalString->getSourceRange());
9135*67e74705SXin Li     }
9136*67e74705SXin Li   }
9137*67e74705SXin Li 
9138*67e74705SXin Li   // C99 6.5.8p3 / C99 6.5.9p4
9139*67e74705SXin Li   UsualArithmeticConversions(LHS, RHS);
9140*67e74705SXin Li   if (LHS.isInvalid() || RHS.isInvalid())
9141*67e74705SXin Li     return QualType();
9142*67e74705SXin Li 
9143*67e74705SXin Li   LHSType = LHS.get()->getType();
9144*67e74705SXin Li   RHSType = RHS.get()->getType();
9145*67e74705SXin Li 
9146*67e74705SXin Li   // The result of comparisons is 'bool' in C++, 'int' in C.
9147*67e74705SXin Li   QualType ResultTy = Context.getLogicalOperationType();
9148*67e74705SXin Li 
9149*67e74705SXin Li   if (IsRelational) {
9150*67e74705SXin Li     if (LHSType->isRealType() && RHSType->isRealType())
9151*67e74705SXin Li       return ResultTy;
9152*67e74705SXin Li   } else {
9153*67e74705SXin Li     // Check for comparisons of floating point operands using != and ==.
9154*67e74705SXin Li     if (LHSType->hasFloatingRepresentation())
9155*67e74705SXin Li       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9156*67e74705SXin Li 
9157*67e74705SXin Li     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9158*67e74705SXin Li       return ResultTy;
9159*67e74705SXin Li   }
9160*67e74705SXin Li 
9161*67e74705SXin Li   const Expr::NullPointerConstantKind LHSNullKind =
9162*67e74705SXin Li       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9163*67e74705SXin Li   const Expr::NullPointerConstantKind RHSNullKind =
9164*67e74705SXin Li       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9165*67e74705SXin Li   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9166*67e74705SXin Li   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9167*67e74705SXin Li 
9168*67e74705SXin Li   if (!IsRelational && LHSIsNull != RHSIsNull) {
9169*67e74705SXin Li     bool IsEquality = Opc == BO_EQ;
9170*67e74705SXin Li     if (RHSIsNull)
9171*67e74705SXin Li       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9172*67e74705SXin Li                                    RHS.get()->getSourceRange());
9173*67e74705SXin Li     else
9174*67e74705SXin Li       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9175*67e74705SXin Li                                    LHS.get()->getSourceRange());
9176*67e74705SXin Li   }
9177*67e74705SXin Li 
9178*67e74705SXin Li   // All of the following pointer-related warnings are GCC extensions, except
9179*67e74705SXin Li   // when handling null pointer constants.
9180*67e74705SXin Li   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
9181*67e74705SXin Li     QualType LCanPointeeTy =
9182*67e74705SXin Li       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9183*67e74705SXin Li     QualType RCanPointeeTy =
9184*67e74705SXin Li       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9185*67e74705SXin Li 
9186*67e74705SXin Li     if (getLangOpts().CPlusPlus) {
9187*67e74705SXin Li       if (LCanPointeeTy == RCanPointeeTy)
9188*67e74705SXin Li         return ResultTy;
9189*67e74705SXin Li       if (!IsRelational &&
9190*67e74705SXin Li           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9191*67e74705SXin Li         // Valid unless comparison between non-null pointer and function pointer
9192*67e74705SXin Li         // This is a gcc extension compatibility comparison.
9193*67e74705SXin Li         // In a SFINAE context, we treat this as a hard error to maintain
9194*67e74705SXin Li         // conformance with the C++ standard.
9195*67e74705SXin Li         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9196*67e74705SXin Li             && !LHSIsNull && !RHSIsNull) {
9197*67e74705SXin Li           diagnoseFunctionPointerToVoidComparison(
9198*67e74705SXin Li               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9199*67e74705SXin Li 
9200*67e74705SXin Li           if (isSFINAEContext())
9201*67e74705SXin Li             return QualType();
9202*67e74705SXin Li 
9203*67e74705SXin Li           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9204*67e74705SXin Li           return ResultTy;
9205*67e74705SXin Li         }
9206*67e74705SXin Li       }
9207*67e74705SXin Li 
9208*67e74705SXin Li       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9209*67e74705SXin Li         return QualType();
9210*67e74705SXin Li       else
9211*67e74705SXin Li         return ResultTy;
9212*67e74705SXin Li     }
9213*67e74705SXin Li     // C99 6.5.9p2 and C99 6.5.8p2
9214*67e74705SXin Li     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9215*67e74705SXin Li                                    RCanPointeeTy.getUnqualifiedType())) {
9216*67e74705SXin Li       // Valid unless a relational comparison of function pointers
9217*67e74705SXin Li       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9218*67e74705SXin Li         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9219*67e74705SXin Li           << LHSType << RHSType << LHS.get()->getSourceRange()
9220*67e74705SXin Li           << RHS.get()->getSourceRange();
9221*67e74705SXin Li       }
9222*67e74705SXin Li     } else if (!IsRelational &&
9223*67e74705SXin Li                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9224*67e74705SXin Li       // Valid unless comparison between non-null pointer and function pointer
9225*67e74705SXin Li       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9226*67e74705SXin Li           && !LHSIsNull && !RHSIsNull)
9227*67e74705SXin Li         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9228*67e74705SXin Li                                                 /*isError*/false);
9229*67e74705SXin Li     } else {
9230*67e74705SXin Li       // Invalid
9231*67e74705SXin Li       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9232*67e74705SXin Li     }
9233*67e74705SXin Li     if (LCanPointeeTy != RCanPointeeTy) {
9234*67e74705SXin Li       // Treat NULL constant as a special case in OpenCL.
9235*67e74705SXin Li       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9236*67e74705SXin Li         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9237*67e74705SXin Li         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9238*67e74705SXin Li           Diag(Loc,
9239*67e74705SXin Li                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9240*67e74705SXin Li               << LHSType << RHSType << 0 /* comparison */
9241*67e74705SXin Li               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9242*67e74705SXin Li         }
9243*67e74705SXin Li       }
9244*67e74705SXin Li       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9245*67e74705SXin Li       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9246*67e74705SXin Li       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9247*67e74705SXin Li                                                : CK_BitCast;
9248*67e74705SXin Li       if (LHSIsNull && !RHSIsNull)
9249*67e74705SXin Li         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9250*67e74705SXin Li       else
9251*67e74705SXin Li         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9252*67e74705SXin Li     }
9253*67e74705SXin Li     return ResultTy;
9254*67e74705SXin Li   }
9255*67e74705SXin Li 
9256*67e74705SXin Li   if (getLangOpts().CPlusPlus) {
9257*67e74705SXin Li     // Comparison of nullptr_t with itself.
9258*67e74705SXin Li     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
9259*67e74705SXin Li       return ResultTy;
9260*67e74705SXin Li 
9261*67e74705SXin Li     // Comparison of pointers with null pointer constants and equality
9262*67e74705SXin Li     // comparisons of member pointers to null pointer constants.
9263*67e74705SXin Li     if (RHSIsNull &&
9264*67e74705SXin Li         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
9265*67e74705SXin Li          (!IsRelational &&
9266*67e74705SXin Li           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
9267*67e74705SXin Li       RHS = ImpCastExprToType(RHS.get(), LHSType,
9268*67e74705SXin Li                         LHSType->isMemberPointerType()
9269*67e74705SXin Li                           ? CK_NullToMemberPointer
9270*67e74705SXin Li                           : CK_NullToPointer);
9271*67e74705SXin Li       return ResultTy;
9272*67e74705SXin Li     }
9273*67e74705SXin Li     if (LHSIsNull &&
9274*67e74705SXin Li         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
9275*67e74705SXin Li          (!IsRelational &&
9276*67e74705SXin Li           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
9277*67e74705SXin Li       LHS = ImpCastExprToType(LHS.get(), RHSType,
9278*67e74705SXin Li                         RHSType->isMemberPointerType()
9279*67e74705SXin Li                           ? CK_NullToMemberPointer
9280*67e74705SXin Li                           : CK_NullToPointer);
9281*67e74705SXin Li       return ResultTy;
9282*67e74705SXin Li     }
9283*67e74705SXin Li 
9284*67e74705SXin Li     // Comparison of member pointers.
9285*67e74705SXin Li     if (!IsRelational &&
9286*67e74705SXin Li         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
9287*67e74705SXin Li       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9288*67e74705SXin Li         return QualType();
9289*67e74705SXin Li       else
9290*67e74705SXin Li         return ResultTy;
9291*67e74705SXin Li     }
9292*67e74705SXin Li 
9293*67e74705SXin Li     // Handle scoped enumeration types specifically, since they don't promote
9294*67e74705SXin Li     // to integers.
9295*67e74705SXin Li     if (LHS.get()->getType()->isEnumeralType() &&
9296*67e74705SXin Li         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9297*67e74705SXin Li                                        RHS.get()->getType()))
9298*67e74705SXin Li       return ResultTy;
9299*67e74705SXin Li   }
9300*67e74705SXin Li 
9301*67e74705SXin Li   // Handle block pointer types.
9302*67e74705SXin Li   if (!IsRelational && LHSType->isBlockPointerType() &&
9303*67e74705SXin Li       RHSType->isBlockPointerType()) {
9304*67e74705SXin Li     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9305*67e74705SXin Li     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9306*67e74705SXin Li 
9307*67e74705SXin Li     if (!LHSIsNull && !RHSIsNull &&
9308*67e74705SXin Li         !Context.typesAreCompatible(lpointee, rpointee)) {
9309*67e74705SXin Li       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9310*67e74705SXin Li         << LHSType << RHSType << LHS.get()->getSourceRange()
9311*67e74705SXin Li         << RHS.get()->getSourceRange();
9312*67e74705SXin Li     }
9313*67e74705SXin Li     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9314*67e74705SXin Li     return ResultTy;
9315*67e74705SXin Li   }
9316*67e74705SXin Li 
9317*67e74705SXin Li   // Allow block pointers to be compared with null pointer constants.
9318*67e74705SXin Li   if (!IsRelational
9319*67e74705SXin Li       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9320*67e74705SXin Li           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9321*67e74705SXin Li     if (!LHSIsNull && !RHSIsNull) {
9322*67e74705SXin Li       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9323*67e74705SXin Li              ->getPointeeType()->isVoidType())
9324*67e74705SXin Li             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9325*67e74705SXin Li                 ->getPointeeType()->isVoidType())))
9326*67e74705SXin Li         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9327*67e74705SXin Li           << LHSType << RHSType << LHS.get()->getSourceRange()
9328*67e74705SXin Li           << RHS.get()->getSourceRange();
9329*67e74705SXin Li     }
9330*67e74705SXin Li     if (LHSIsNull && !RHSIsNull)
9331*67e74705SXin Li       LHS = ImpCastExprToType(LHS.get(), RHSType,
9332*67e74705SXin Li                               RHSType->isPointerType() ? CK_BitCast
9333*67e74705SXin Li                                 : CK_AnyPointerToBlockPointerCast);
9334*67e74705SXin Li     else
9335*67e74705SXin Li       RHS = ImpCastExprToType(RHS.get(), LHSType,
9336*67e74705SXin Li                               LHSType->isPointerType() ? CK_BitCast
9337*67e74705SXin Li                                 : CK_AnyPointerToBlockPointerCast);
9338*67e74705SXin Li     return ResultTy;
9339*67e74705SXin Li   }
9340*67e74705SXin Li 
9341*67e74705SXin Li   if (LHSType->isObjCObjectPointerType() ||
9342*67e74705SXin Li       RHSType->isObjCObjectPointerType()) {
9343*67e74705SXin Li     const PointerType *LPT = LHSType->getAs<PointerType>();
9344*67e74705SXin Li     const PointerType *RPT = RHSType->getAs<PointerType>();
9345*67e74705SXin Li     if (LPT || RPT) {
9346*67e74705SXin Li       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9347*67e74705SXin Li       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9348*67e74705SXin Li 
9349*67e74705SXin Li       if (!LPtrToVoid && !RPtrToVoid &&
9350*67e74705SXin Li           !Context.typesAreCompatible(LHSType, RHSType)) {
9351*67e74705SXin Li         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9352*67e74705SXin Li                                           /*isError*/false);
9353*67e74705SXin Li       }
9354*67e74705SXin Li       if (LHSIsNull && !RHSIsNull) {
9355*67e74705SXin Li         Expr *E = LHS.get();
9356*67e74705SXin Li         if (getLangOpts().ObjCAutoRefCount)
9357*67e74705SXin Li           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9358*67e74705SXin Li         LHS = ImpCastExprToType(E, RHSType,
9359*67e74705SXin Li                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9360*67e74705SXin Li       }
9361*67e74705SXin Li       else {
9362*67e74705SXin Li         Expr *E = RHS.get();
9363*67e74705SXin Li         if (getLangOpts().ObjCAutoRefCount)
9364*67e74705SXin Li           CheckObjCARCConversion(SourceRange(), LHSType, E,
9365*67e74705SXin Li                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9366*67e74705SXin Li                                  /*DiagnoseCFAudited=*/false, Opc);
9367*67e74705SXin Li         RHS = ImpCastExprToType(E, LHSType,
9368*67e74705SXin Li                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9369*67e74705SXin Li       }
9370*67e74705SXin Li       return ResultTy;
9371*67e74705SXin Li     }
9372*67e74705SXin Li     if (LHSType->isObjCObjectPointerType() &&
9373*67e74705SXin Li         RHSType->isObjCObjectPointerType()) {
9374*67e74705SXin Li       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9375*67e74705SXin Li         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9376*67e74705SXin Li                                           /*isError*/false);
9377*67e74705SXin Li       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9378*67e74705SXin Li         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9379*67e74705SXin Li 
9380*67e74705SXin Li       if (LHSIsNull && !RHSIsNull)
9381*67e74705SXin Li         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9382*67e74705SXin Li       else
9383*67e74705SXin Li         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9384*67e74705SXin Li       return ResultTy;
9385*67e74705SXin Li     }
9386*67e74705SXin Li   }
9387*67e74705SXin Li   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9388*67e74705SXin Li       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9389*67e74705SXin Li     unsigned DiagID = 0;
9390*67e74705SXin Li     bool isError = false;
9391*67e74705SXin Li     if (LangOpts.DebuggerSupport) {
9392*67e74705SXin Li       // Under a debugger, allow the comparison of pointers to integers,
9393*67e74705SXin Li       // since users tend to want to compare addresses.
9394*67e74705SXin Li     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9395*67e74705SXin Li         (RHSIsNull && RHSType->isIntegerType())) {
9396*67e74705SXin Li       if (IsRelational && !getLangOpts().CPlusPlus)
9397*67e74705SXin Li         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9398*67e74705SXin Li     } else if (IsRelational && !getLangOpts().CPlusPlus)
9399*67e74705SXin Li       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9400*67e74705SXin Li     else if (getLangOpts().CPlusPlus) {
9401*67e74705SXin Li       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9402*67e74705SXin Li       isError = true;
9403*67e74705SXin Li     } else
9404*67e74705SXin Li       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9405*67e74705SXin Li 
9406*67e74705SXin Li     if (DiagID) {
9407*67e74705SXin Li       Diag(Loc, DiagID)
9408*67e74705SXin Li         << LHSType << RHSType << LHS.get()->getSourceRange()
9409*67e74705SXin Li         << RHS.get()->getSourceRange();
9410*67e74705SXin Li       if (isError)
9411*67e74705SXin Li         return QualType();
9412*67e74705SXin Li     }
9413*67e74705SXin Li 
9414*67e74705SXin Li     if (LHSType->isIntegerType())
9415*67e74705SXin Li       LHS = ImpCastExprToType(LHS.get(), RHSType,
9416*67e74705SXin Li                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9417*67e74705SXin Li     else
9418*67e74705SXin Li       RHS = ImpCastExprToType(RHS.get(), LHSType,
9419*67e74705SXin Li                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9420*67e74705SXin Li     return ResultTy;
9421*67e74705SXin Li   }
9422*67e74705SXin Li 
9423*67e74705SXin Li   // Handle block pointers.
9424*67e74705SXin Li   if (!IsRelational && RHSIsNull
9425*67e74705SXin Li       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9426*67e74705SXin Li     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9427*67e74705SXin Li     return ResultTy;
9428*67e74705SXin Li   }
9429*67e74705SXin Li   if (!IsRelational && LHSIsNull
9430*67e74705SXin Li       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9431*67e74705SXin Li     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9432*67e74705SXin Li     return ResultTy;
9433*67e74705SXin Li   }
9434*67e74705SXin Li 
9435*67e74705SXin Li   return InvalidOperands(Loc, LHS, RHS);
9436*67e74705SXin Li }
9437*67e74705SXin Li 
9438*67e74705SXin Li 
9439*67e74705SXin Li // Return a signed type that is of identical size and number of elements.
9440*67e74705SXin Li // For floating point vectors, return an integer type of identical size
9441*67e74705SXin Li // and number of elements.
GetSignedVectorType(QualType V)9442*67e74705SXin Li QualType Sema::GetSignedVectorType(QualType V) {
9443*67e74705SXin Li   const VectorType *VTy = V->getAs<VectorType>();
9444*67e74705SXin Li   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9445*67e74705SXin Li   if (TypeSize == Context.getTypeSize(Context.CharTy))
9446*67e74705SXin Li     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9447*67e74705SXin Li   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9448*67e74705SXin Li     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9449*67e74705SXin Li   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9450*67e74705SXin Li     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9451*67e74705SXin Li   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9452*67e74705SXin Li     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9453*67e74705SXin Li   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9454*67e74705SXin Li          "Unhandled vector element size in vector compare");
9455*67e74705SXin Li   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9456*67e74705SXin Li }
9457*67e74705SXin Li 
9458*67e74705SXin Li /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9459*67e74705SXin Li /// operates on extended vector types.  Instead of producing an IntTy result,
9460*67e74705SXin Li /// like a scalar comparison, a vector comparison produces a vector of integer
9461*67e74705SXin Li /// types.
CheckVectorCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsRelational)9462*67e74705SXin Li QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9463*67e74705SXin Li                                           SourceLocation Loc,
9464*67e74705SXin Li                                           bool IsRelational) {
9465*67e74705SXin Li   // Check to make sure we're operating on vectors of the same type and width,
9466*67e74705SXin Li   // Allowing one side to be a scalar of element type.
9467*67e74705SXin Li   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9468*67e74705SXin Li                               /*AllowBothBool*/true,
9469*67e74705SXin Li                               /*AllowBoolConversions*/getLangOpts().ZVector);
9470*67e74705SXin Li   if (vType.isNull())
9471*67e74705SXin Li     return vType;
9472*67e74705SXin Li 
9473*67e74705SXin Li   QualType LHSType = LHS.get()->getType();
9474*67e74705SXin Li 
9475*67e74705SXin Li   // If AltiVec, the comparison results in a numeric type, i.e.
9476*67e74705SXin Li   // bool for C++, int for C
9477*67e74705SXin Li   if (getLangOpts().AltiVec &&
9478*67e74705SXin Li       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9479*67e74705SXin Li     return Context.getLogicalOperationType();
9480*67e74705SXin Li 
9481*67e74705SXin Li   // For non-floating point types, check for self-comparisons of the form
9482*67e74705SXin Li   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9483*67e74705SXin Li   // often indicate logic errors in the program.
9484*67e74705SXin Li   if (!LHSType->hasFloatingRepresentation() &&
9485*67e74705SXin Li       ActiveTemplateInstantiations.empty()) {
9486*67e74705SXin Li     if (DeclRefExpr* DRL
9487*67e74705SXin Li           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9488*67e74705SXin Li       if (DeclRefExpr* DRR
9489*67e74705SXin Li             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9490*67e74705SXin Li         if (DRL->getDecl() == DRR->getDecl())
9491*67e74705SXin Li           DiagRuntimeBehavior(Loc, nullptr,
9492*67e74705SXin Li                               PDiag(diag::warn_comparison_always)
9493*67e74705SXin Li                                 << 0 // self-
9494*67e74705SXin Li                                 << 2 // "a constant"
9495*67e74705SXin Li                               );
9496*67e74705SXin Li   }
9497*67e74705SXin Li 
9498*67e74705SXin Li   // Check for comparisons of floating point operands using != and ==.
9499*67e74705SXin Li   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9500*67e74705SXin Li     assert (RHS.get()->getType()->hasFloatingRepresentation());
9501*67e74705SXin Li     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9502*67e74705SXin Li   }
9503*67e74705SXin Li 
9504*67e74705SXin Li   // Return a signed type for the vector.
9505*67e74705SXin Li   return GetSignedVectorType(vType);
9506*67e74705SXin Li }
9507*67e74705SXin Li 
CheckVectorLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)9508*67e74705SXin Li QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9509*67e74705SXin Li                                           SourceLocation Loc) {
9510*67e74705SXin Li   // Ensure that either both operands are of the same vector type, or
9511*67e74705SXin Li   // one operand is of a vector type and the other is of its element type.
9512*67e74705SXin Li   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9513*67e74705SXin Li                                        /*AllowBothBool*/true,
9514*67e74705SXin Li                                        /*AllowBoolConversions*/false);
9515*67e74705SXin Li   if (vType.isNull())
9516*67e74705SXin Li     return InvalidOperands(Loc, LHS, RHS);
9517*67e74705SXin Li   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9518*67e74705SXin Li       vType->hasFloatingRepresentation())
9519*67e74705SXin Li     return InvalidOperands(Loc, LHS, RHS);
9520*67e74705SXin Li 
9521*67e74705SXin Li   return GetSignedVectorType(LHS.get()->getType());
9522*67e74705SXin Li }
9523*67e74705SXin Li 
CheckBitwiseOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)9524*67e74705SXin Li inline QualType Sema::CheckBitwiseOperands(
9525*67e74705SXin Li   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9526*67e74705SXin Li   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9527*67e74705SXin Li 
9528*67e74705SXin Li   if (LHS.get()->getType()->isVectorType() ||
9529*67e74705SXin Li       RHS.get()->getType()->isVectorType()) {
9530*67e74705SXin Li     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9531*67e74705SXin Li         RHS.get()->getType()->hasIntegerRepresentation())
9532*67e74705SXin Li       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9533*67e74705SXin Li                         /*AllowBothBool*/true,
9534*67e74705SXin Li                         /*AllowBoolConversions*/getLangOpts().ZVector);
9535*67e74705SXin Li     return InvalidOperands(Loc, LHS, RHS);
9536*67e74705SXin Li   }
9537*67e74705SXin Li 
9538*67e74705SXin Li   ExprResult LHSResult = LHS, RHSResult = RHS;
9539*67e74705SXin Li   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9540*67e74705SXin Li                                                  IsCompAssign);
9541*67e74705SXin Li   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9542*67e74705SXin Li     return QualType();
9543*67e74705SXin Li   LHS = LHSResult.get();
9544*67e74705SXin Li   RHS = RHSResult.get();
9545*67e74705SXin Li 
9546*67e74705SXin Li   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9547*67e74705SXin Li     return compType;
9548*67e74705SXin Li   return InvalidOperands(Loc, LHS, RHS);
9549*67e74705SXin Li }
9550*67e74705SXin Li 
9551*67e74705SXin Li // C99 6.5.[13,14]
CheckLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)9552*67e74705SXin Li inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9553*67e74705SXin Li                                            SourceLocation Loc,
9554*67e74705SXin Li                                            BinaryOperatorKind Opc) {
9555*67e74705SXin Li   // Check vector operands differently.
9556*67e74705SXin Li   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9557*67e74705SXin Li     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9558*67e74705SXin Li 
9559*67e74705SXin Li   // Diagnose cases where the user write a logical and/or but probably meant a
9560*67e74705SXin Li   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9561*67e74705SXin Li   // is a constant.
9562*67e74705SXin Li   if (LHS.get()->getType()->isIntegerType() &&
9563*67e74705SXin Li       !LHS.get()->getType()->isBooleanType() &&
9564*67e74705SXin Li       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9565*67e74705SXin Li       // Don't warn in macros or template instantiations.
9566*67e74705SXin Li       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9567*67e74705SXin Li     // If the RHS can be constant folded, and if it constant folds to something
9568*67e74705SXin Li     // that isn't 0 or 1 (which indicate a potential logical operation that
9569*67e74705SXin Li     // happened to fold to true/false) then warn.
9570*67e74705SXin Li     // Parens on the RHS are ignored.
9571*67e74705SXin Li     llvm::APSInt Result;
9572*67e74705SXin Li     if (RHS.get()->EvaluateAsInt(Result, Context))
9573*67e74705SXin Li       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9574*67e74705SXin Li            !RHS.get()->getExprLoc().isMacroID()) ||
9575*67e74705SXin Li           (Result != 0 && Result != 1)) {
9576*67e74705SXin Li         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9577*67e74705SXin Li           << RHS.get()->getSourceRange()
9578*67e74705SXin Li           << (Opc == BO_LAnd ? "&&" : "||");
9579*67e74705SXin Li         // Suggest replacing the logical operator with the bitwise version
9580*67e74705SXin Li         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9581*67e74705SXin Li             << (Opc == BO_LAnd ? "&" : "|")
9582*67e74705SXin Li             << FixItHint::CreateReplacement(SourceRange(
9583*67e74705SXin Li                                                  Loc, getLocForEndOfToken(Loc)),
9584*67e74705SXin Li                                             Opc == BO_LAnd ? "&" : "|");
9585*67e74705SXin Li         if (Opc == BO_LAnd)
9586*67e74705SXin Li           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9587*67e74705SXin Li           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9588*67e74705SXin Li               << FixItHint::CreateRemoval(
9589*67e74705SXin Li                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9590*67e74705SXin Li                               RHS.get()->getLocEnd()));
9591*67e74705SXin Li       }
9592*67e74705SXin Li   }
9593*67e74705SXin Li 
9594*67e74705SXin Li   if (!Context.getLangOpts().CPlusPlus) {
9595*67e74705SXin Li     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9596*67e74705SXin Li     // not operate on the built-in scalar and vector float types.
9597*67e74705SXin Li     if (Context.getLangOpts().OpenCL &&
9598*67e74705SXin Li         Context.getLangOpts().OpenCLVersion < 120) {
9599*67e74705SXin Li       if (LHS.get()->getType()->isFloatingType() ||
9600*67e74705SXin Li           RHS.get()->getType()->isFloatingType())
9601*67e74705SXin Li         return InvalidOperands(Loc, LHS, RHS);
9602*67e74705SXin Li     }
9603*67e74705SXin Li 
9604*67e74705SXin Li     LHS = UsualUnaryConversions(LHS.get());
9605*67e74705SXin Li     if (LHS.isInvalid())
9606*67e74705SXin Li       return QualType();
9607*67e74705SXin Li 
9608*67e74705SXin Li     RHS = UsualUnaryConversions(RHS.get());
9609*67e74705SXin Li     if (RHS.isInvalid())
9610*67e74705SXin Li       return QualType();
9611*67e74705SXin Li 
9612*67e74705SXin Li     if (!LHS.get()->getType()->isScalarType() ||
9613*67e74705SXin Li         !RHS.get()->getType()->isScalarType())
9614*67e74705SXin Li       return InvalidOperands(Loc, LHS, RHS);
9615*67e74705SXin Li 
9616*67e74705SXin Li     return Context.IntTy;
9617*67e74705SXin Li   }
9618*67e74705SXin Li 
9619*67e74705SXin Li   // The following is safe because we only use this method for
9620*67e74705SXin Li   // non-overloadable operands.
9621*67e74705SXin Li 
9622*67e74705SXin Li   // C++ [expr.log.and]p1
9623*67e74705SXin Li   // C++ [expr.log.or]p1
9624*67e74705SXin Li   // The operands are both contextually converted to type bool.
9625*67e74705SXin Li   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9626*67e74705SXin Li   if (LHSRes.isInvalid())
9627*67e74705SXin Li     return InvalidOperands(Loc, LHS, RHS);
9628*67e74705SXin Li   LHS = LHSRes;
9629*67e74705SXin Li 
9630*67e74705SXin Li   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9631*67e74705SXin Li   if (RHSRes.isInvalid())
9632*67e74705SXin Li     return InvalidOperands(Loc, LHS, RHS);
9633*67e74705SXin Li   RHS = RHSRes;
9634*67e74705SXin Li 
9635*67e74705SXin Li   // C++ [expr.log.and]p2
9636*67e74705SXin Li   // C++ [expr.log.or]p2
9637*67e74705SXin Li   // The result is a bool.
9638*67e74705SXin Li   return Context.BoolTy;
9639*67e74705SXin Li }
9640*67e74705SXin Li 
IsReadonlyMessage(Expr * E,Sema & S)9641*67e74705SXin Li static bool IsReadonlyMessage(Expr *E, Sema &S) {
9642*67e74705SXin Li   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9643*67e74705SXin Li   if (!ME) return false;
9644*67e74705SXin Li   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9645*67e74705SXin Li   ObjCMessageExpr *Base =
9646*67e74705SXin Li     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9647*67e74705SXin Li   if (!Base) return false;
9648*67e74705SXin Li   return Base->getMethodDecl() != nullptr;
9649*67e74705SXin Li }
9650*67e74705SXin Li 
9651*67e74705SXin Li /// Is the given expression (which must be 'const') a reference to a
9652*67e74705SXin Li /// variable which was originally non-const, but which has become
9653*67e74705SXin Li /// 'const' due to being captured within a block?
9654*67e74705SXin Li enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
isReferenceToNonConstCapture(Sema & S,Expr * E)9655*67e74705SXin Li static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9656*67e74705SXin Li   assert(E->isLValue() && E->getType().isConstQualified());
9657*67e74705SXin Li   E = E->IgnoreParens();
9658*67e74705SXin Li 
9659*67e74705SXin Li   // Must be a reference to a declaration from an enclosing scope.
9660*67e74705SXin Li   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9661*67e74705SXin Li   if (!DRE) return NCCK_None;
9662*67e74705SXin Li   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9663*67e74705SXin Li 
9664*67e74705SXin Li   // The declaration must be a variable which is not declared 'const'.
9665*67e74705SXin Li   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9666*67e74705SXin Li   if (!var) return NCCK_None;
9667*67e74705SXin Li   if (var->getType().isConstQualified()) return NCCK_None;
9668*67e74705SXin Li   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9669*67e74705SXin Li 
9670*67e74705SXin Li   // Decide whether the first capture was for a block or a lambda.
9671*67e74705SXin Li   DeclContext *DC = S.CurContext, *Prev = nullptr;
9672*67e74705SXin Li   // Decide whether the first capture was for a block or a lambda.
9673*67e74705SXin Li   while (DC) {
9674*67e74705SXin Li     // For init-capture, it is possible that the variable belongs to the
9675*67e74705SXin Li     // template pattern of the current context.
9676*67e74705SXin Li     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9677*67e74705SXin Li       if (var->isInitCapture() &&
9678*67e74705SXin Li           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9679*67e74705SXin Li         break;
9680*67e74705SXin Li     if (DC == var->getDeclContext())
9681*67e74705SXin Li       break;
9682*67e74705SXin Li     Prev = DC;
9683*67e74705SXin Li     DC = DC->getParent();
9684*67e74705SXin Li   }
9685*67e74705SXin Li   // Unless we have an init-capture, we've gone one step too far.
9686*67e74705SXin Li   if (!var->isInitCapture())
9687*67e74705SXin Li     DC = Prev;
9688*67e74705SXin Li   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9689*67e74705SXin Li }
9690*67e74705SXin Li 
IsTypeModifiable(QualType Ty,bool IsDereference)9691*67e74705SXin Li static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9692*67e74705SXin Li   Ty = Ty.getNonReferenceType();
9693*67e74705SXin Li   if (IsDereference && Ty->isPointerType())
9694*67e74705SXin Li     Ty = Ty->getPointeeType();
9695*67e74705SXin Li   return !Ty.isConstQualified();
9696*67e74705SXin Li }
9697*67e74705SXin Li 
9698*67e74705SXin Li /// Emit the "read-only variable not assignable" error and print notes to give
9699*67e74705SXin Li /// more information about why the variable is not assignable, such as pointing
9700*67e74705SXin Li /// to the declaration of a const variable, showing that a method is const, or
9701*67e74705SXin Li /// that the function is returning a const reference.
DiagnoseConstAssignment(Sema & S,const Expr * E,SourceLocation Loc)9702*67e74705SXin Li static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9703*67e74705SXin Li                                     SourceLocation Loc) {
9704*67e74705SXin Li   // Update err_typecheck_assign_const and note_typecheck_assign_const
9705*67e74705SXin Li   // when this enum is changed.
9706*67e74705SXin Li   enum {
9707*67e74705SXin Li     ConstFunction,
9708*67e74705SXin Li     ConstVariable,
9709*67e74705SXin Li     ConstMember,
9710*67e74705SXin Li     ConstMethod,
9711*67e74705SXin Li     ConstUnknown,  // Keep as last element
9712*67e74705SXin Li   };
9713*67e74705SXin Li 
9714*67e74705SXin Li   SourceRange ExprRange = E->getSourceRange();
9715*67e74705SXin Li 
9716*67e74705SXin Li   // Only emit one error on the first const found.  All other consts will emit
9717*67e74705SXin Li   // a note to the error.
9718*67e74705SXin Li   bool DiagnosticEmitted = false;
9719*67e74705SXin Li 
9720*67e74705SXin Li   // Track if the current expression is the result of a derefence, and if the
9721*67e74705SXin Li   // next checked expression is the result of a derefence.
9722*67e74705SXin Li   bool IsDereference = false;
9723*67e74705SXin Li   bool NextIsDereference = false;
9724*67e74705SXin Li 
9725*67e74705SXin Li   // Loop to process MemberExpr chains.
9726*67e74705SXin Li   while (true) {
9727*67e74705SXin Li     IsDereference = NextIsDereference;
9728*67e74705SXin Li     NextIsDereference = false;
9729*67e74705SXin Li 
9730*67e74705SXin Li     E = E->IgnoreParenImpCasts();
9731*67e74705SXin Li     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9732*67e74705SXin Li       NextIsDereference = ME->isArrow();
9733*67e74705SXin Li       const ValueDecl *VD = ME->getMemberDecl();
9734*67e74705SXin Li       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9735*67e74705SXin Li         // Mutable fields can be modified even if the class is const.
9736*67e74705SXin Li         if (Field->isMutable()) {
9737*67e74705SXin Li           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9738*67e74705SXin Li           break;
9739*67e74705SXin Li         }
9740*67e74705SXin Li 
9741*67e74705SXin Li         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9742*67e74705SXin Li           if (!DiagnosticEmitted) {
9743*67e74705SXin Li             S.Diag(Loc, diag::err_typecheck_assign_const)
9744*67e74705SXin Li                 << ExprRange << ConstMember << false /*static*/ << Field
9745*67e74705SXin Li                 << Field->getType();
9746*67e74705SXin Li             DiagnosticEmitted = true;
9747*67e74705SXin Li           }
9748*67e74705SXin Li           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9749*67e74705SXin Li               << ConstMember << false /*static*/ << Field << Field->getType()
9750*67e74705SXin Li               << Field->getSourceRange();
9751*67e74705SXin Li         }
9752*67e74705SXin Li         E = ME->getBase();
9753*67e74705SXin Li         continue;
9754*67e74705SXin Li       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9755*67e74705SXin Li         if (VDecl->getType().isConstQualified()) {
9756*67e74705SXin Li           if (!DiagnosticEmitted) {
9757*67e74705SXin Li             S.Diag(Loc, diag::err_typecheck_assign_const)
9758*67e74705SXin Li                 << ExprRange << ConstMember << true /*static*/ << VDecl
9759*67e74705SXin Li                 << VDecl->getType();
9760*67e74705SXin Li             DiagnosticEmitted = true;
9761*67e74705SXin Li           }
9762*67e74705SXin Li           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9763*67e74705SXin Li               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9764*67e74705SXin Li               << VDecl->getSourceRange();
9765*67e74705SXin Li         }
9766*67e74705SXin Li         // Static fields do not inherit constness from parents.
9767*67e74705SXin Li         break;
9768*67e74705SXin Li       }
9769*67e74705SXin Li       break;
9770*67e74705SXin Li     } // End MemberExpr
9771*67e74705SXin Li     break;
9772*67e74705SXin Li   }
9773*67e74705SXin Li 
9774*67e74705SXin Li   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9775*67e74705SXin Li     // Function calls
9776*67e74705SXin Li     const FunctionDecl *FD = CE->getDirectCallee();
9777*67e74705SXin Li     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9778*67e74705SXin Li       if (!DiagnosticEmitted) {
9779*67e74705SXin Li         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9780*67e74705SXin Li                                                       << ConstFunction << FD;
9781*67e74705SXin Li         DiagnosticEmitted = true;
9782*67e74705SXin Li       }
9783*67e74705SXin Li       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9784*67e74705SXin Li              diag::note_typecheck_assign_const)
9785*67e74705SXin Li           << ConstFunction << FD << FD->getReturnType()
9786*67e74705SXin Li           << FD->getReturnTypeSourceRange();
9787*67e74705SXin Li     }
9788*67e74705SXin Li   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9789*67e74705SXin Li     // Point to variable declaration.
9790*67e74705SXin Li     if (const ValueDecl *VD = DRE->getDecl()) {
9791*67e74705SXin Li       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9792*67e74705SXin Li         if (!DiagnosticEmitted) {
9793*67e74705SXin Li           S.Diag(Loc, diag::err_typecheck_assign_const)
9794*67e74705SXin Li               << ExprRange << ConstVariable << VD << VD->getType();
9795*67e74705SXin Li           DiagnosticEmitted = true;
9796*67e74705SXin Li         }
9797*67e74705SXin Li         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9798*67e74705SXin Li             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9799*67e74705SXin Li       }
9800*67e74705SXin Li     }
9801*67e74705SXin Li   } else if (isa<CXXThisExpr>(E)) {
9802*67e74705SXin Li     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9803*67e74705SXin Li       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9804*67e74705SXin Li         if (MD->isConst()) {
9805*67e74705SXin Li           if (!DiagnosticEmitted) {
9806*67e74705SXin Li             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9807*67e74705SXin Li                                                           << ConstMethod << MD;
9808*67e74705SXin Li             DiagnosticEmitted = true;
9809*67e74705SXin Li           }
9810*67e74705SXin Li           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9811*67e74705SXin Li               << ConstMethod << MD << MD->getSourceRange();
9812*67e74705SXin Li         }
9813*67e74705SXin Li       }
9814*67e74705SXin Li     }
9815*67e74705SXin Li   }
9816*67e74705SXin Li 
9817*67e74705SXin Li   if (DiagnosticEmitted)
9818*67e74705SXin Li     return;
9819*67e74705SXin Li 
9820*67e74705SXin Li   // Can't determine a more specific message, so display the generic error.
9821*67e74705SXin Li   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9822*67e74705SXin Li }
9823*67e74705SXin Li 
9824*67e74705SXin Li /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9825*67e74705SXin Li /// emit an error and return true.  If so, return false.
CheckForModifiableLvalue(Expr * E,SourceLocation Loc,Sema & S)9826*67e74705SXin Li static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9827*67e74705SXin Li   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9828*67e74705SXin Li 
9829*67e74705SXin Li   S.CheckShadowingDeclModification(E, Loc);
9830*67e74705SXin Li 
9831*67e74705SXin Li   SourceLocation OrigLoc = Loc;
9832*67e74705SXin Li   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9833*67e74705SXin Li                                                               &Loc);
9834*67e74705SXin Li   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9835*67e74705SXin Li     IsLV = Expr::MLV_InvalidMessageExpression;
9836*67e74705SXin Li   if (IsLV == Expr::MLV_Valid)
9837*67e74705SXin Li     return false;
9838*67e74705SXin Li 
9839*67e74705SXin Li   unsigned DiagID = 0;
9840*67e74705SXin Li   bool NeedType = false;
9841*67e74705SXin Li   switch (IsLV) { // C99 6.5.16p2
9842*67e74705SXin Li   case Expr::MLV_ConstQualified:
9843*67e74705SXin Li     // Use a specialized diagnostic when we're assigning to an object
9844*67e74705SXin Li     // from an enclosing function or block.
9845*67e74705SXin Li     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9846*67e74705SXin Li       if (NCCK == NCCK_Block)
9847*67e74705SXin Li         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9848*67e74705SXin Li       else
9849*67e74705SXin Li         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9850*67e74705SXin Li       break;
9851*67e74705SXin Li     }
9852*67e74705SXin Li 
9853*67e74705SXin Li     // In ARC, use some specialized diagnostics for occasions where we
9854*67e74705SXin Li     // infer 'const'.  These are always pseudo-strong variables.
9855*67e74705SXin Li     if (S.getLangOpts().ObjCAutoRefCount) {
9856*67e74705SXin Li       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9857*67e74705SXin Li       if (declRef && isa<VarDecl>(declRef->getDecl())) {
9858*67e74705SXin Li         VarDecl *var = cast<VarDecl>(declRef->getDecl());
9859*67e74705SXin Li 
9860*67e74705SXin Li         // Use the normal diagnostic if it's pseudo-__strong but the
9861*67e74705SXin Li         // user actually wrote 'const'.
9862*67e74705SXin Li         if (var->isARCPseudoStrong() &&
9863*67e74705SXin Li             (!var->getTypeSourceInfo() ||
9864*67e74705SXin Li              !var->getTypeSourceInfo()->getType().isConstQualified())) {
9865*67e74705SXin Li           // There are two pseudo-strong cases:
9866*67e74705SXin Li           //  - self
9867*67e74705SXin Li           ObjCMethodDecl *method = S.getCurMethodDecl();
9868*67e74705SXin Li           if (method && var == method->getSelfDecl())
9869*67e74705SXin Li             DiagID = method->isClassMethod()
9870*67e74705SXin Li               ? diag::err_typecheck_arc_assign_self_class_method
9871*67e74705SXin Li               : diag::err_typecheck_arc_assign_self;
9872*67e74705SXin Li 
9873*67e74705SXin Li           //  - fast enumeration variables
9874*67e74705SXin Li           else
9875*67e74705SXin Li             DiagID = diag::err_typecheck_arr_assign_enumeration;
9876*67e74705SXin Li 
9877*67e74705SXin Li           SourceRange Assign;
9878*67e74705SXin Li           if (Loc != OrigLoc)
9879*67e74705SXin Li             Assign = SourceRange(OrigLoc, OrigLoc);
9880*67e74705SXin Li           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9881*67e74705SXin Li           // We need to preserve the AST regardless, so migration tool
9882*67e74705SXin Li           // can do its job.
9883*67e74705SXin Li           return false;
9884*67e74705SXin Li         }
9885*67e74705SXin Li       }
9886*67e74705SXin Li     }
9887*67e74705SXin Li 
9888*67e74705SXin Li     // If none of the special cases above are triggered, then this is a
9889*67e74705SXin Li     // simple const assignment.
9890*67e74705SXin Li     if (DiagID == 0) {
9891*67e74705SXin Li       DiagnoseConstAssignment(S, E, Loc);
9892*67e74705SXin Li       return true;
9893*67e74705SXin Li     }
9894*67e74705SXin Li 
9895*67e74705SXin Li     break;
9896*67e74705SXin Li   case Expr::MLV_ConstAddrSpace:
9897*67e74705SXin Li     DiagnoseConstAssignment(S, E, Loc);
9898*67e74705SXin Li     return true;
9899*67e74705SXin Li   case Expr::MLV_ArrayType:
9900*67e74705SXin Li   case Expr::MLV_ArrayTemporary:
9901*67e74705SXin Li     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
9902*67e74705SXin Li     NeedType = true;
9903*67e74705SXin Li     break;
9904*67e74705SXin Li   case Expr::MLV_NotObjectType:
9905*67e74705SXin Li     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
9906*67e74705SXin Li     NeedType = true;
9907*67e74705SXin Li     break;
9908*67e74705SXin Li   case Expr::MLV_LValueCast:
9909*67e74705SXin Li     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
9910*67e74705SXin Li     break;
9911*67e74705SXin Li   case Expr::MLV_Valid:
9912*67e74705SXin Li     llvm_unreachable("did not take early return for MLV_Valid");
9913*67e74705SXin Li   case Expr::MLV_InvalidExpression:
9914*67e74705SXin Li   case Expr::MLV_MemberFunction:
9915*67e74705SXin Li   case Expr::MLV_ClassTemporary:
9916*67e74705SXin Li     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
9917*67e74705SXin Li     break;
9918*67e74705SXin Li   case Expr::MLV_IncompleteType:
9919*67e74705SXin Li   case Expr::MLV_IncompleteVoidType:
9920*67e74705SXin Li     return S.RequireCompleteType(Loc, E->getType(),
9921*67e74705SXin Li              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
9922*67e74705SXin Li   case Expr::MLV_DuplicateVectorComponents:
9923*67e74705SXin Li     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
9924*67e74705SXin Li     break;
9925*67e74705SXin Li   case Expr::MLV_NoSetterProperty:
9926*67e74705SXin Li     llvm_unreachable("readonly properties should be processed differently");
9927*67e74705SXin Li   case Expr::MLV_InvalidMessageExpression:
9928*67e74705SXin Li     DiagID = diag::error_readonly_message_assignment;
9929*67e74705SXin Li     break;
9930*67e74705SXin Li   case Expr::MLV_SubObjCPropertySetting:
9931*67e74705SXin Li     DiagID = diag::error_no_subobject_property_setting;
9932*67e74705SXin Li     break;
9933*67e74705SXin Li   }
9934*67e74705SXin Li 
9935*67e74705SXin Li   SourceRange Assign;
9936*67e74705SXin Li   if (Loc != OrigLoc)
9937*67e74705SXin Li     Assign = SourceRange(OrigLoc, OrigLoc);
9938*67e74705SXin Li   if (NeedType)
9939*67e74705SXin Li     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
9940*67e74705SXin Li   else
9941*67e74705SXin Li     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9942*67e74705SXin Li   return true;
9943*67e74705SXin Li }
9944*67e74705SXin Li 
CheckIdentityFieldAssignment(Expr * LHSExpr,Expr * RHSExpr,SourceLocation Loc,Sema & Sema)9945*67e74705SXin Li static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9946*67e74705SXin Li                                          SourceLocation Loc,
9947*67e74705SXin Li                                          Sema &Sema) {
9948*67e74705SXin Li   // C / C++ fields
9949*67e74705SXin Li   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9950*67e74705SXin Li   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9951*67e74705SXin Li   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9952*67e74705SXin Li     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
9953*67e74705SXin Li       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
9954*67e74705SXin Li   }
9955*67e74705SXin Li 
9956*67e74705SXin Li   // Objective-C instance variables
9957*67e74705SXin Li   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9958*67e74705SXin Li   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9959*67e74705SXin Li   if (OL && OR && OL->getDecl() == OR->getDecl()) {
9960*67e74705SXin Li     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9961*67e74705SXin Li     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9962*67e74705SXin Li     if (RL && RR && RL->getDecl() == RR->getDecl())
9963*67e74705SXin Li       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
9964*67e74705SXin Li   }
9965*67e74705SXin Li }
9966*67e74705SXin Li 
9967*67e74705SXin Li // C99 6.5.16.1
CheckAssignmentOperands(Expr * LHSExpr,ExprResult & RHS,SourceLocation Loc,QualType CompoundType)9968*67e74705SXin Li QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
9969*67e74705SXin Li                                        SourceLocation Loc,
9970*67e74705SXin Li                                        QualType CompoundType) {
9971*67e74705SXin Li   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9972*67e74705SXin Li 
9973*67e74705SXin Li   // Verify that LHS is a modifiable lvalue, and emit error if not.
9974*67e74705SXin Li   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
9975*67e74705SXin Li     return QualType();
9976*67e74705SXin Li 
9977*67e74705SXin Li   QualType LHSType = LHSExpr->getType();
9978*67e74705SXin Li   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9979*67e74705SXin Li                                              CompoundType;
9980*67e74705SXin Li   AssignConvertType ConvTy;
9981*67e74705SXin Li   if (CompoundType.isNull()) {
9982*67e74705SXin Li     Expr *RHSCheck = RHS.get();
9983*67e74705SXin Li 
9984*67e74705SXin Li     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
9985*67e74705SXin Li 
9986*67e74705SXin Li     QualType LHSTy(LHSType);
9987*67e74705SXin Li     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
9988*67e74705SXin Li     if (RHS.isInvalid())
9989*67e74705SXin Li       return QualType();
9990*67e74705SXin Li     // Special case of NSObject attributes on c-style pointer types.
9991*67e74705SXin Li     if (ConvTy == IncompatiblePointer &&
9992*67e74705SXin Li         ((Context.isObjCNSObjectType(LHSType) &&
9993*67e74705SXin Li           RHSType->isObjCObjectPointerType()) ||
9994*67e74705SXin Li          (Context.isObjCNSObjectType(RHSType) &&
9995*67e74705SXin Li           LHSType->isObjCObjectPointerType())))
9996*67e74705SXin Li       ConvTy = Compatible;
9997*67e74705SXin Li 
9998*67e74705SXin Li     if (ConvTy == Compatible &&
9999*67e74705SXin Li         LHSType->isObjCObjectType())
10000*67e74705SXin Li         Diag(Loc, diag::err_objc_object_assignment)
10001*67e74705SXin Li           << LHSType;
10002*67e74705SXin Li 
10003*67e74705SXin Li     // If the RHS is a unary plus or minus, check to see if they = and + are
10004*67e74705SXin Li     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10005*67e74705SXin Li     // instead of "x += 4".
10006*67e74705SXin Li     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10007*67e74705SXin Li       RHSCheck = ICE->getSubExpr();
10008*67e74705SXin Li     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10009*67e74705SXin Li       if ((UO->getOpcode() == UO_Plus ||
10010*67e74705SXin Li            UO->getOpcode() == UO_Minus) &&
10011*67e74705SXin Li           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10012*67e74705SXin Li           // Only if the two operators are exactly adjacent.
10013*67e74705SXin Li           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10014*67e74705SXin Li           // And there is a space or other character before the subexpr of the
10015*67e74705SXin Li           // unary +/-.  We don't want to warn on "x=-1".
10016*67e74705SXin Li           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10017*67e74705SXin Li           UO->getSubExpr()->getLocStart().isFileID()) {
10018*67e74705SXin Li         Diag(Loc, diag::warn_not_compound_assign)
10019*67e74705SXin Li           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10020*67e74705SXin Li           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10021*67e74705SXin Li       }
10022*67e74705SXin Li     }
10023*67e74705SXin Li 
10024*67e74705SXin Li     if (ConvTy == Compatible) {
10025*67e74705SXin Li       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10026*67e74705SXin Li         // Warn about retain cycles where a block captures the LHS, but
10027*67e74705SXin Li         // not if the LHS is a simple variable into which the block is
10028*67e74705SXin Li         // being stored...unless that variable can be captured by reference!
10029*67e74705SXin Li         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10030*67e74705SXin Li         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10031*67e74705SXin Li         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10032*67e74705SXin Li           checkRetainCycles(LHSExpr, RHS.get());
10033*67e74705SXin Li 
10034*67e74705SXin Li         // It is safe to assign a weak reference into a strong variable.
10035*67e74705SXin Li         // Although this code can still have problems:
10036*67e74705SXin Li         //   id x = self.weakProp;
10037*67e74705SXin Li         //   id y = self.weakProp;
10038*67e74705SXin Li         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10039*67e74705SXin Li         // paths through the function. This should be revisited if
10040*67e74705SXin Li         // -Wrepeated-use-of-weak is made flow-sensitive.
10041*67e74705SXin Li         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10042*67e74705SXin Li                              RHS.get()->getLocStart()))
10043*67e74705SXin Li           getCurFunction()->markSafeWeakUse(RHS.get());
10044*67e74705SXin Li 
10045*67e74705SXin Li       } else if (getLangOpts().ObjCAutoRefCount) {
10046*67e74705SXin Li         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10047*67e74705SXin Li       }
10048*67e74705SXin Li     }
10049*67e74705SXin Li   } else {
10050*67e74705SXin Li     // Compound assignment "x += y"
10051*67e74705SXin Li     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10052*67e74705SXin Li   }
10053*67e74705SXin Li 
10054*67e74705SXin Li   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10055*67e74705SXin Li                                RHS.get(), AA_Assigning))
10056*67e74705SXin Li     return QualType();
10057*67e74705SXin Li 
10058*67e74705SXin Li   CheckForNullPointerDereference(*this, LHSExpr);
10059*67e74705SXin Li 
10060*67e74705SXin Li   // C99 6.5.16p3: The type of an assignment expression is the type of the
10061*67e74705SXin Li   // left operand unless the left operand has qualified type, in which case
10062*67e74705SXin Li   // it is the unqualified version of the type of the left operand.
10063*67e74705SXin Li   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10064*67e74705SXin Li   // is converted to the type of the assignment expression (above).
10065*67e74705SXin Li   // C++ 5.17p1: the type of the assignment expression is that of its left
10066*67e74705SXin Li   // operand.
10067*67e74705SXin Li   return (getLangOpts().CPlusPlus
10068*67e74705SXin Li           ? LHSType : LHSType.getUnqualifiedType());
10069*67e74705SXin Li }
10070*67e74705SXin Li 
10071*67e74705SXin Li // Only ignore explicit casts to void.
IgnoreCommaOperand(const Expr * E)10072*67e74705SXin Li static bool IgnoreCommaOperand(const Expr *E) {
10073*67e74705SXin Li   E = E->IgnoreParens();
10074*67e74705SXin Li 
10075*67e74705SXin Li   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10076*67e74705SXin Li     if (CE->getCastKind() == CK_ToVoid) {
10077*67e74705SXin Li       return true;
10078*67e74705SXin Li     }
10079*67e74705SXin Li   }
10080*67e74705SXin Li 
10081*67e74705SXin Li   return false;
10082*67e74705SXin Li }
10083*67e74705SXin Li 
10084*67e74705SXin Li // Look for instances where it is likely the comma operator is confused with
10085*67e74705SXin Li // another operator.  There is a whitelist of acceptable expressions for the
10086*67e74705SXin Li // left hand side of the comma operator, otherwise emit a warning.
DiagnoseCommaOperator(const Expr * LHS,SourceLocation Loc)10087*67e74705SXin Li void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10088*67e74705SXin Li   // No warnings in macros
10089*67e74705SXin Li   if (Loc.isMacroID())
10090*67e74705SXin Li     return;
10091*67e74705SXin Li 
10092*67e74705SXin Li   // Don't warn in template instantiations.
10093*67e74705SXin Li   if (!ActiveTemplateInstantiations.empty())
10094*67e74705SXin Li     return;
10095*67e74705SXin Li 
10096*67e74705SXin Li   // Scope isn't fine-grained enough to whitelist the specific cases, so
10097*67e74705SXin Li   // instead, skip more than needed, then call back into here with the
10098*67e74705SXin Li   // CommaVisitor in SemaStmt.cpp.
10099*67e74705SXin Li   // The whitelisted locations are the initialization and increment portions
10100*67e74705SXin Li   // of a for loop.  The additional checks are on the condition of
10101*67e74705SXin Li   // if statements, do/while loops, and for loops.
10102*67e74705SXin Li   const unsigned ForIncrementFlags =
10103*67e74705SXin Li       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10104*67e74705SXin Li   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10105*67e74705SXin Li   const unsigned ScopeFlags = getCurScope()->getFlags();
10106*67e74705SXin Li   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10107*67e74705SXin Li       (ScopeFlags & ForInitFlags) == ForInitFlags)
10108*67e74705SXin Li     return;
10109*67e74705SXin Li 
10110*67e74705SXin Li   // If there are multiple comma operators used together, get the RHS of the
10111*67e74705SXin Li   // of the comma operator as the LHS.
10112*67e74705SXin Li   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10113*67e74705SXin Li     if (BO->getOpcode() != BO_Comma)
10114*67e74705SXin Li       break;
10115*67e74705SXin Li     LHS = BO->getRHS();
10116*67e74705SXin Li   }
10117*67e74705SXin Li 
10118*67e74705SXin Li   // Only allow some expressions on LHS to not warn.
10119*67e74705SXin Li   if (IgnoreCommaOperand(LHS))
10120*67e74705SXin Li     return;
10121*67e74705SXin Li 
10122*67e74705SXin Li   Diag(Loc, diag::warn_comma_operator);
10123*67e74705SXin Li   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10124*67e74705SXin Li       << LHS->getSourceRange()
10125*67e74705SXin Li       << FixItHint::CreateInsertion(LHS->getLocStart(),
10126*67e74705SXin Li                                     LangOpts.CPlusPlus ? "static_cast<void>("
10127*67e74705SXin Li                                                        : "(void)(")
10128*67e74705SXin Li       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10129*67e74705SXin Li                                     ")");
10130*67e74705SXin Li }
10131*67e74705SXin Li 
10132*67e74705SXin Li // C99 6.5.17
CheckCommaOperands(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)10133*67e74705SXin Li static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10134*67e74705SXin Li                                    SourceLocation Loc) {
10135*67e74705SXin Li   LHS = S.CheckPlaceholderExpr(LHS.get());
10136*67e74705SXin Li   RHS = S.CheckPlaceholderExpr(RHS.get());
10137*67e74705SXin Li   if (LHS.isInvalid() || RHS.isInvalid())
10138*67e74705SXin Li     return QualType();
10139*67e74705SXin Li 
10140*67e74705SXin Li   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10141*67e74705SXin Li   // operands, but not unary promotions.
10142*67e74705SXin Li   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10143*67e74705SXin Li 
10144*67e74705SXin Li   // So we treat the LHS as a ignored value, and in C++ we allow the
10145*67e74705SXin Li   // containing site to determine what should be done with the RHS.
10146*67e74705SXin Li   LHS = S.IgnoredValueConversions(LHS.get());
10147*67e74705SXin Li   if (LHS.isInvalid())
10148*67e74705SXin Li     return QualType();
10149*67e74705SXin Li 
10150*67e74705SXin Li   S.DiagnoseUnusedExprResult(LHS.get());
10151*67e74705SXin Li 
10152*67e74705SXin Li   if (!S.getLangOpts().CPlusPlus) {
10153*67e74705SXin Li     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10154*67e74705SXin Li     if (RHS.isInvalid())
10155*67e74705SXin Li       return QualType();
10156*67e74705SXin Li     if (!RHS.get()->getType()->isVoidType())
10157*67e74705SXin Li       S.RequireCompleteType(Loc, RHS.get()->getType(),
10158*67e74705SXin Li                             diag::err_incomplete_type);
10159*67e74705SXin Li   }
10160*67e74705SXin Li 
10161*67e74705SXin Li   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10162*67e74705SXin Li     S.DiagnoseCommaOperator(LHS.get(), Loc);
10163*67e74705SXin Li 
10164*67e74705SXin Li   return RHS.get()->getType();
10165*67e74705SXin Li }
10166*67e74705SXin Li 
10167*67e74705SXin Li /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10168*67e74705SXin Li /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
CheckIncrementDecrementOperand(Sema & S,Expr * Op,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation OpLoc,bool IsInc,bool IsPrefix)10169*67e74705SXin Li static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10170*67e74705SXin Li                                                ExprValueKind &VK,
10171*67e74705SXin Li                                                ExprObjectKind &OK,
10172*67e74705SXin Li                                                SourceLocation OpLoc,
10173*67e74705SXin Li                                                bool IsInc, bool IsPrefix) {
10174*67e74705SXin Li   if (Op->isTypeDependent())
10175*67e74705SXin Li     return S.Context.DependentTy;
10176*67e74705SXin Li 
10177*67e74705SXin Li   QualType ResType = Op->getType();
10178*67e74705SXin Li   // Atomic types can be used for increment / decrement where the non-atomic
10179*67e74705SXin Li   // versions can, so ignore the _Atomic() specifier for the purpose of
10180*67e74705SXin Li   // checking.
10181*67e74705SXin Li   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10182*67e74705SXin Li     ResType = ResAtomicType->getValueType();
10183*67e74705SXin Li 
10184*67e74705SXin Li   assert(!ResType.isNull() && "no type for increment/decrement expression");
10185*67e74705SXin Li 
10186*67e74705SXin Li   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10187*67e74705SXin Li     // Decrement of bool is not allowed.
10188*67e74705SXin Li     if (!IsInc) {
10189*67e74705SXin Li       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10190*67e74705SXin Li       return QualType();
10191*67e74705SXin Li     }
10192*67e74705SXin Li     // Increment of bool sets it to true, but is deprecated.
10193*67e74705SXin Li     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10194*67e74705SXin Li                                               : diag::warn_increment_bool)
10195*67e74705SXin Li       << Op->getSourceRange();
10196*67e74705SXin Li   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10197*67e74705SXin Li     // Error on enum increments and decrements in C++ mode
10198*67e74705SXin Li     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10199*67e74705SXin Li     return QualType();
10200*67e74705SXin Li   } else if (ResType->isRealType()) {
10201*67e74705SXin Li     // OK!
10202*67e74705SXin Li   } else if (ResType->isPointerType()) {
10203*67e74705SXin Li     // C99 6.5.2.4p2, 6.5.6p2
10204*67e74705SXin Li     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10205*67e74705SXin Li       return QualType();
10206*67e74705SXin Li   } else if (ResType->isObjCObjectPointerType()) {
10207*67e74705SXin Li     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10208*67e74705SXin Li     // Otherwise, we just need a complete type.
10209*67e74705SXin Li     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10210*67e74705SXin Li         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10211*67e74705SXin Li       return QualType();
10212*67e74705SXin Li   } else if (ResType->isAnyComplexType()) {
10213*67e74705SXin Li     // C99 does not support ++/-- on complex types, we allow as an extension.
10214*67e74705SXin Li     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10215*67e74705SXin Li       << ResType << Op->getSourceRange();
10216*67e74705SXin Li   } else if (ResType->isPlaceholderType()) {
10217*67e74705SXin Li     ExprResult PR = S.CheckPlaceholderExpr(Op);
10218*67e74705SXin Li     if (PR.isInvalid()) return QualType();
10219*67e74705SXin Li     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10220*67e74705SXin Li                                           IsInc, IsPrefix);
10221*67e74705SXin Li   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10222*67e74705SXin Li     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10223*67e74705SXin Li   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10224*67e74705SXin Li              (ResType->getAs<VectorType>()->getVectorKind() !=
10225*67e74705SXin Li               VectorType::AltiVecBool)) {
10226*67e74705SXin Li     // The z vector extensions allow ++ and -- for non-bool vectors.
10227*67e74705SXin Li   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10228*67e74705SXin Li             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10229*67e74705SXin Li     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10230*67e74705SXin Li   } else {
10231*67e74705SXin Li     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10232*67e74705SXin Li       << ResType << int(IsInc) << Op->getSourceRange();
10233*67e74705SXin Li     return QualType();
10234*67e74705SXin Li   }
10235*67e74705SXin Li   // At this point, we know we have a real, complex or pointer type.
10236*67e74705SXin Li   // Now make sure the operand is a modifiable lvalue.
10237*67e74705SXin Li   if (CheckForModifiableLvalue(Op, OpLoc, S))
10238*67e74705SXin Li     return QualType();
10239*67e74705SXin Li   // In C++, a prefix increment is the same type as the operand. Otherwise
10240*67e74705SXin Li   // (in C or with postfix), the increment is the unqualified type of the
10241*67e74705SXin Li   // operand.
10242*67e74705SXin Li   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10243*67e74705SXin Li     VK = VK_LValue;
10244*67e74705SXin Li     OK = Op->getObjectKind();
10245*67e74705SXin Li     return ResType;
10246*67e74705SXin Li   } else {
10247*67e74705SXin Li     VK = VK_RValue;
10248*67e74705SXin Li     return ResType.getUnqualifiedType();
10249*67e74705SXin Li   }
10250*67e74705SXin Li }
10251*67e74705SXin Li 
10252*67e74705SXin Li 
10253*67e74705SXin Li /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10254*67e74705SXin Li /// This routine allows us to typecheck complex/recursive expressions
10255*67e74705SXin Li /// where the declaration is needed for type checking. We only need to
10256*67e74705SXin Li /// handle cases when the expression references a function designator
10257*67e74705SXin Li /// or is an lvalue. Here are some examples:
10258*67e74705SXin Li ///  - &(x) => x
10259*67e74705SXin Li ///  - &*****f => f for f a function designator.
10260*67e74705SXin Li ///  - &s.xx => s
10261*67e74705SXin Li ///  - &s.zz[1].yy -> s, if zz is an array
10262*67e74705SXin Li ///  - *(x + 1) -> x, if x is an array
10263*67e74705SXin Li ///  - &"123"[2] -> 0
10264*67e74705SXin Li ///  - & __real__ x -> x
getPrimaryDecl(Expr * E)10265*67e74705SXin Li static ValueDecl *getPrimaryDecl(Expr *E) {
10266*67e74705SXin Li   switch (E->getStmtClass()) {
10267*67e74705SXin Li   case Stmt::DeclRefExprClass:
10268*67e74705SXin Li     return cast<DeclRefExpr>(E)->getDecl();
10269*67e74705SXin Li   case Stmt::MemberExprClass:
10270*67e74705SXin Li     // If this is an arrow operator, the address is an offset from
10271*67e74705SXin Li     // the base's value, so the object the base refers to is
10272*67e74705SXin Li     // irrelevant.
10273*67e74705SXin Li     if (cast<MemberExpr>(E)->isArrow())
10274*67e74705SXin Li       return nullptr;
10275*67e74705SXin Li     // Otherwise, the expression refers to a part of the base
10276*67e74705SXin Li     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10277*67e74705SXin Li   case Stmt::ArraySubscriptExprClass: {
10278*67e74705SXin Li     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10279*67e74705SXin Li     // promotion of register arrays earlier.
10280*67e74705SXin Li     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10281*67e74705SXin Li     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10282*67e74705SXin Li       if (ICE->getSubExpr()->getType()->isArrayType())
10283*67e74705SXin Li         return getPrimaryDecl(ICE->getSubExpr());
10284*67e74705SXin Li     }
10285*67e74705SXin Li     return nullptr;
10286*67e74705SXin Li   }
10287*67e74705SXin Li   case Stmt::UnaryOperatorClass: {
10288*67e74705SXin Li     UnaryOperator *UO = cast<UnaryOperator>(E);
10289*67e74705SXin Li 
10290*67e74705SXin Li     switch(UO->getOpcode()) {
10291*67e74705SXin Li     case UO_Real:
10292*67e74705SXin Li     case UO_Imag:
10293*67e74705SXin Li     case UO_Extension:
10294*67e74705SXin Li       return getPrimaryDecl(UO->getSubExpr());
10295*67e74705SXin Li     default:
10296*67e74705SXin Li       return nullptr;
10297*67e74705SXin Li     }
10298*67e74705SXin Li   }
10299*67e74705SXin Li   case Stmt::ParenExprClass:
10300*67e74705SXin Li     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10301*67e74705SXin Li   case Stmt::ImplicitCastExprClass:
10302*67e74705SXin Li     // If the result of an implicit cast is an l-value, we care about
10303*67e74705SXin Li     // the sub-expression; otherwise, the result here doesn't matter.
10304*67e74705SXin Li     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10305*67e74705SXin Li   default:
10306*67e74705SXin Li     return nullptr;
10307*67e74705SXin Li   }
10308*67e74705SXin Li }
10309*67e74705SXin Li 
10310*67e74705SXin Li namespace {
10311*67e74705SXin Li   enum {
10312*67e74705SXin Li     AO_Bit_Field = 0,
10313*67e74705SXin Li     AO_Vector_Element = 1,
10314*67e74705SXin Li     AO_Property_Expansion = 2,
10315*67e74705SXin Li     AO_Register_Variable = 3,
10316*67e74705SXin Li     AO_No_Error = 4
10317*67e74705SXin Li   };
10318*67e74705SXin Li }
10319*67e74705SXin Li /// \brief Diagnose invalid operand for address of operations.
10320*67e74705SXin Li ///
10321*67e74705SXin Li /// \param Type The type of operand which cannot have its address taken.
diagnoseAddressOfInvalidType(Sema & S,SourceLocation Loc,Expr * E,unsigned Type)10322*67e74705SXin Li static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10323*67e74705SXin Li                                          Expr *E, unsigned Type) {
10324*67e74705SXin Li   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10325*67e74705SXin Li }
10326*67e74705SXin Li 
10327*67e74705SXin Li /// CheckAddressOfOperand - The operand of & must be either a function
10328*67e74705SXin Li /// designator or an lvalue designating an object. If it is an lvalue, the
10329*67e74705SXin Li /// object cannot be declared with storage class register or be a bit field.
10330*67e74705SXin Li /// Note: The usual conversions are *not* applied to the operand of the &
10331*67e74705SXin Li /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10332*67e74705SXin Li /// In C++, the operand might be an overloaded function name, in which case
10333*67e74705SXin Li /// we allow the '&' but retain the overloaded-function type.
CheckAddressOfOperand(ExprResult & OrigOp,SourceLocation OpLoc)10334*67e74705SXin Li QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10335*67e74705SXin Li   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10336*67e74705SXin Li     if (PTy->getKind() == BuiltinType::Overload) {
10337*67e74705SXin Li       Expr *E = OrigOp.get()->IgnoreParens();
10338*67e74705SXin Li       if (!isa<OverloadExpr>(E)) {
10339*67e74705SXin Li         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10340*67e74705SXin Li         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10341*67e74705SXin Li           << OrigOp.get()->getSourceRange();
10342*67e74705SXin Li         return QualType();
10343*67e74705SXin Li       }
10344*67e74705SXin Li 
10345*67e74705SXin Li       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10346*67e74705SXin Li       if (isa<UnresolvedMemberExpr>(Ovl))
10347*67e74705SXin Li         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10348*67e74705SXin Li           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10349*67e74705SXin Li             << OrigOp.get()->getSourceRange();
10350*67e74705SXin Li           return QualType();
10351*67e74705SXin Li         }
10352*67e74705SXin Li 
10353*67e74705SXin Li       return Context.OverloadTy;
10354*67e74705SXin Li     }
10355*67e74705SXin Li 
10356*67e74705SXin Li     if (PTy->getKind() == BuiltinType::UnknownAny)
10357*67e74705SXin Li       return Context.UnknownAnyTy;
10358*67e74705SXin Li 
10359*67e74705SXin Li     if (PTy->getKind() == BuiltinType::BoundMember) {
10360*67e74705SXin Li       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10361*67e74705SXin Li         << OrigOp.get()->getSourceRange();
10362*67e74705SXin Li       return QualType();
10363*67e74705SXin Li     }
10364*67e74705SXin Li 
10365*67e74705SXin Li     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10366*67e74705SXin Li     if (OrigOp.isInvalid()) return QualType();
10367*67e74705SXin Li   }
10368*67e74705SXin Li 
10369*67e74705SXin Li   if (OrigOp.get()->isTypeDependent())
10370*67e74705SXin Li     return Context.DependentTy;
10371*67e74705SXin Li 
10372*67e74705SXin Li   assert(!OrigOp.get()->getType()->isPlaceholderType());
10373*67e74705SXin Li 
10374*67e74705SXin Li   // Make sure to ignore parentheses in subsequent checks
10375*67e74705SXin Li   Expr *op = OrigOp.get()->IgnoreParens();
10376*67e74705SXin Li 
10377*67e74705SXin Li   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10378*67e74705SXin Li   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10379*67e74705SXin Li     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10380*67e74705SXin Li     return QualType();
10381*67e74705SXin Li   }
10382*67e74705SXin Li 
10383*67e74705SXin Li   if (getLangOpts().C99) {
10384*67e74705SXin Li     // Implement C99-only parts of addressof rules.
10385*67e74705SXin Li     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10386*67e74705SXin Li       if (uOp->getOpcode() == UO_Deref)
10387*67e74705SXin Li         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10388*67e74705SXin Li         // (assuming the deref expression is valid).
10389*67e74705SXin Li         return uOp->getSubExpr()->getType();
10390*67e74705SXin Li     }
10391*67e74705SXin Li     // Technically, there should be a check for array subscript
10392*67e74705SXin Li     // expressions here, but the result of one is always an lvalue anyway.
10393*67e74705SXin Li   }
10394*67e74705SXin Li   ValueDecl *dcl = getPrimaryDecl(op);
10395*67e74705SXin Li 
10396*67e74705SXin Li   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10397*67e74705SXin Li     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10398*67e74705SXin Li                                            op->getLocStart()))
10399*67e74705SXin Li       return QualType();
10400*67e74705SXin Li 
10401*67e74705SXin Li   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10402*67e74705SXin Li   unsigned AddressOfError = AO_No_Error;
10403*67e74705SXin Li 
10404*67e74705SXin Li   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10405*67e74705SXin Li     bool sfinae = (bool)isSFINAEContext();
10406*67e74705SXin Li     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10407*67e74705SXin Li                                   : diag::ext_typecheck_addrof_temporary)
10408*67e74705SXin Li       << op->getType() << op->getSourceRange();
10409*67e74705SXin Li     if (sfinae)
10410*67e74705SXin Li       return QualType();
10411*67e74705SXin Li     // Materialize the temporary as an lvalue so that we can take its address.
10412*67e74705SXin Li     OrigOp = op =
10413*67e74705SXin Li         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10414*67e74705SXin Li   } else if (isa<ObjCSelectorExpr>(op)) {
10415*67e74705SXin Li     return Context.getPointerType(op->getType());
10416*67e74705SXin Li   } else if (lval == Expr::LV_MemberFunction) {
10417*67e74705SXin Li     // If it's an instance method, make a member pointer.
10418*67e74705SXin Li     // The expression must have exactly the form &A::foo.
10419*67e74705SXin Li 
10420*67e74705SXin Li     // If the underlying expression isn't a decl ref, give up.
10421*67e74705SXin Li     if (!isa<DeclRefExpr>(op)) {
10422*67e74705SXin Li       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10423*67e74705SXin Li         << OrigOp.get()->getSourceRange();
10424*67e74705SXin Li       return QualType();
10425*67e74705SXin Li     }
10426*67e74705SXin Li     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10427*67e74705SXin Li     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10428*67e74705SXin Li 
10429*67e74705SXin Li     // The id-expression was parenthesized.
10430*67e74705SXin Li     if (OrigOp.get() != DRE) {
10431*67e74705SXin Li       Diag(OpLoc, diag::err_parens_pointer_member_function)
10432*67e74705SXin Li         << OrigOp.get()->getSourceRange();
10433*67e74705SXin Li 
10434*67e74705SXin Li     // The method was named without a qualifier.
10435*67e74705SXin Li     } else if (!DRE->getQualifier()) {
10436*67e74705SXin Li       if (MD->getParent()->getName().empty())
10437*67e74705SXin Li         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10438*67e74705SXin Li           << op->getSourceRange();
10439*67e74705SXin Li       else {
10440*67e74705SXin Li         SmallString<32> Str;
10441*67e74705SXin Li         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10442*67e74705SXin Li         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10443*67e74705SXin Li           << op->getSourceRange()
10444*67e74705SXin Li           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10445*67e74705SXin Li       }
10446*67e74705SXin Li     }
10447*67e74705SXin Li 
10448*67e74705SXin Li     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10449*67e74705SXin Li     if (isa<CXXDestructorDecl>(MD))
10450*67e74705SXin Li       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10451*67e74705SXin Li 
10452*67e74705SXin Li     QualType MPTy = Context.getMemberPointerType(
10453*67e74705SXin Li         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10454*67e74705SXin Li     // Under the MS ABI, lock down the inheritance model now.
10455*67e74705SXin Li     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10456*67e74705SXin Li       (void)isCompleteType(OpLoc, MPTy);
10457*67e74705SXin Li     return MPTy;
10458*67e74705SXin Li   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10459*67e74705SXin Li     // C99 6.5.3.2p1
10460*67e74705SXin Li     // The operand must be either an l-value or a function designator
10461*67e74705SXin Li     if (!op->getType()->isFunctionType()) {
10462*67e74705SXin Li       // Use a special diagnostic for loads from property references.
10463*67e74705SXin Li       if (isa<PseudoObjectExpr>(op)) {
10464*67e74705SXin Li         AddressOfError = AO_Property_Expansion;
10465*67e74705SXin Li       } else {
10466*67e74705SXin Li         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10467*67e74705SXin Li           << op->getType() << op->getSourceRange();
10468*67e74705SXin Li         return QualType();
10469*67e74705SXin Li       }
10470*67e74705SXin Li     }
10471*67e74705SXin Li   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10472*67e74705SXin Li     // The operand cannot be a bit-field
10473*67e74705SXin Li     AddressOfError = AO_Bit_Field;
10474*67e74705SXin Li   } else if (op->getObjectKind() == OK_VectorComponent) {
10475*67e74705SXin Li     // The operand cannot be an element of a vector
10476*67e74705SXin Li     AddressOfError = AO_Vector_Element;
10477*67e74705SXin Li   } else if (dcl) { // C99 6.5.3.2p1
10478*67e74705SXin Li     // We have an lvalue with a decl. Make sure the decl is not declared
10479*67e74705SXin Li     // with the register storage-class specifier.
10480*67e74705SXin Li     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10481*67e74705SXin Li       // in C++ it is not error to take address of a register
10482*67e74705SXin Li       // variable (c++03 7.1.1P3)
10483*67e74705SXin Li       if (vd->getStorageClass() == SC_Register &&
10484*67e74705SXin Li           !getLangOpts().CPlusPlus) {
10485*67e74705SXin Li         AddressOfError = AO_Register_Variable;
10486*67e74705SXin Li       }
10487*67e74705SXin Li     } else if (isa<MSPropertyDecl>(dcl)) {
10488*67e74705SXin Li       AddressOfError = AO_Property_Expansion;
10489*67e74705SXin Li     } else if (isa<FunctionTemplateDecl>(dcl)) {
10490*67e74705SXin Li       return Context.OverloadTy;
10491*67e74705SXin Li     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10492*67e74705SXin Li       // Okay: we can take the address of a field.
10493*67e74705SXin Li       // Could be a pointer to member, though, if there is an explicit
10494*67e74705SXin Li       // scope qualifier for the class.
10495*67e74705SXin Li       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10496*67e74705SXin Li         DeclContext *Ctx = dcl->getDeclContext();
10497*67e74705SXin Li         if (Ctx && Ctx->isRecord()) {
10498*67e74705SXin Li           if (dcl->getType()->isReferenceType()) {
10499*67e74705SXin Li             Diag(OpLoc,
10500*67e74705SXin Li                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10501*67e74705SXin Li               << dcl->getDeclName() << dcl->getType();
10502*67e74705SXin Li             return QualType();
10503*67e74705SXin Li           }
10504*67e74705SXin Li 
10505*67e74705SXin Li           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10506*67e74705SXin Li             Ctx = Ctx->getParent();
10507*67e74705SXin Li 
10508*67e74705SXin Li           QualType MPTy = Context.getMemberPointerType(
10509*67e74705SXin Li               op->getType(),
10510*67e74705SXin Li               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10511*67e74705SXin Li           // Under the MS ABI, lock down the inheritance model now.
10512*67e74705SXin Li           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10513*67e74705SXin Li             (void)isCompleteType(OpLoc, MPTy);
10514*67e74705SXin Li           return MPTy;
10515*67e74705SXin Li         }
10516*67e74705SXin Li       }
10517*67e74705SXin Li     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
10518*67e74705SXin Li       llvm_unreachable("Unknown/unexpected decl type");
10519*67e74705SXin Li   }
10520*67e74705SXin Li 
10521*67e74705SXin Li   if (AddressOfError != AO_No_Error) {
10522*67e74705SXin Li     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10523*67e74705SXin Li     return QualType();
10524*67e74705SXin Li   }
10525*67e74705SXin Li 
10526*67e74705SXin Li   if (lval == Expr::LV_IncompleteVoidType) {
10527*67e74705SXin Li     // Taking the address of a void variable is technically illegal, but we
10528*67e74705SXin Li     // allow it in cases which are otherwise valid.
10529*67e74705SXin Li     // Example: "extern void x; void* y = &x;".
10530*67e74705SXin Li     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10531*67e74705SXin Li   }
10532*67e74705SXin Li 
10533*67e74705SXin Li   // If the operand has type "type", the result has type "pointer to type".
10534*67e74705SXin Li   if (op->getType()->isObjCObjectType())
10535*67e74705SXin Li     return Context.getObjCObjectPointerType(op->getType());
10536*67e74705SXin Li 
10537*67e74705SXin Li   return Context.getPointerType(op->getType());
10538*67e74705SXin Li }
10539*67e74705SXin Li 
RecordModifiableNonNullParam(Sema & S,const Expr * Exp)10540*67e74705SXin Li static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10541*67e74705SXin Li   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10542*67e74705SXin Li   if (!DRE)
10543*67e74705SXin Li     return;
10544*67e74705SXin Li   const Decl *D = DRE->getDecl();
10545*67e74705SXin Li   if (!D)
10546*67e74705SXin Li     return;
10547*67e74705SXin Li   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10548*67e74705SXin Li   if (!Param)
10549*67e74705SXin Li     return;
10550*67e74705SXin Li   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10551*67e74705SXin Li     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10552*67e74705SXin Li       return;
10553*67e74705SXin Li   if (FunctionScopeInfo *FD = S.getCurFunction())
10554*67e74705SXin Li     if (!FD->ModifiedNonNullParams.count(Param))
10555*67e74705SXin Li       FD->ModifiedNonNullParams.insert(Param);
10556*67e74705SXin Li }
10557*67e74705SXin Li 
10558*67e74705SXin Li /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
CheckIndirectionOperand(Sema & S,Expr * Op,ExprValueKind & VK,SourceLocation OpLoc)10559*67e74705SXin Li static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10560*67e74705SXin Li                                         SourceLocation OpLoc) {
10561*67e74705SXin Li   if (Op->isTypeDependent())
10562*67e74705SXin Li     return S.Context.DependentTy;
10563*67e74705SXin Li 
10564*67e74705SXin Li   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10565*67e74705SXin Li   if (ConvResult.isInvalid())
10566*67e74705SXin Li     return QualType();
10567*67e74705SXin Li   Op = ConvResult.get();
10568*67e74705SXin Li   QualType OpTy = Op->getType();
10569*67e74705SXin Li   QualType Result;
10570*67e74705SXin Li 
10571*67e74705SXin Li   if (isa<CXXReinterpretCastExpr>(Op)) {
10572*67e74705SXin Li     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10573*67e74705SXin Li     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10574*67e74705SXin Li                                      Op->getSourceRange());
10575*67e74705SXin Li   }
10576*67e74705SXin Li 
10577*67e74705SXin Li   if (const PointerType *PT = OpTy->getAs<PointerType>())
10578*67e74705SXin Li   {
10579*67e74705SXin Li     Result = PT->getPointeeType();
10580*67e74705SXin Li   }
10581*67e74705SXin Li   else if (const ObjCObjectPointerType *OPT =
10582*67e74705SXin Li              OpTy->getAs<ObjCObjectPointerType>())
10583*67e74705SXin Li     Result = OPT->getPointeeType();
10584*67e74705SXin Li   else {
10585*67e74705SXin Li     ExprResult PR = S.CheckPlaceholderExpr(Op);
10586*67e74705SXin Li     if (PR.isInvalid()) return QualType();
10587*67e74705SXin Li     if (PR.get() != Op)
10588*67e74705SXin Li       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10589*67e74705SXin Li   }
10590*67e74705SXin Li 
10591*67e74705SXin Li   if (Result.isNull()) {
10592*67e74705SXin Li     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10593*67e74705SXin Li       << OpTy << Op->getSourceRange();
10594*67e74705SXin Li     return QualType();
10595*67e74705SXin Li   }
10596*67e74705SXin Li 
10597*67e74705SXin Li   // Note that per both C89 and C99, indirection is always legal, even if Result
10598*67e74705SXin Li   // is an incomplete type or void.  It would be possible to warn about
10599*67e74705SXin Li   // dereferencing a void pointer, but it's completely well-defined, and such a
10600*67e74705SXin Li   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10601*67e74705SXin Li   // for pointers to 'void' but is fine for any other pointer type:
10602*67e74705SXin Li   //
10603*67e74705SXin Li   // C++ [expr.unary.op]p1:
10604*67e74705SXin Li   //   [...] the expression to which [the unary * operator] is applied shall
10605*67e74705SXin Li   //   be a pointer to an object type, or a pointer to a function type
10606*67e74705SXin Li   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10607*67e74705SXin Li     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10608*67e74705SXin Li       << OpTy << Op->getSourceRange();
10609*67e74705SXin Li 
10610*67e74705SXin Li   // Dereferences are usually l-values...
10611*67e74705SXin Li   VK = VK_LValue;
10612*67e74705SXin Li 
10613*67e74705SXin Li   // ...except that certain expressions are never l-values in C.
10614*67e74705SXin Li   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10615*67e74705SXin Li     VK = VK_RValue;
10616*67e74705SXin Li 
10617*67e74705SXin Li   return Result;
10618*67e74705SXin Li }
10619*67e74705SXin Li 
ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind)10620*67e74705SXin Li BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10621*67e74705SXin Li   BinaryOperatorKind Opc;
10622*67e74705SXin Li   switch (Kind) {
10623*67e74705SXin Li   default: llvm_unreachable("Unknown binop!");
10624*67e74705SXin Li   case tok::periodstar:           Opc = BO_PtrMemD; break;
10625*67e74705SXin Li   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10626*67e74705SXin Li   case tok::star:                 Opc = BO_Mul; break;
10627*67e74705SXin Li   case tok::slash:                Opc = BO_Div; break;
10628*67e74705SXin Li   case tok::percent:              Opc = BO_Rem; break;
10629*67e74705SXin Li   case tok::plus:                 Opc = BO_Add; break;
10630*67e74705SXin Li   case tok::minus:                Opc = BO_Sub; break;
10631*67e74705SXin Li   case tok::lessless:             Opc = BO_Shl; break;
10632*67e74705SXin Li   case tok::greatergreater:       Opc = BO_Shr; break;
10633*67e74705SXin Li   case tok::lessequal:            Opc = BO_LE; break;
10634*67e74705SXin Li   case tok::less:                 Opc = BO_LT; break;
10635*67e74705SXin Li   case tok::greaterequal:         Opc = BO_GE; break;
10636*67e74705SXin Li   case tok::greater:              Opc = BO_GT; break;
10637*67e74705SXin Li   case tok::exclaimequal:         Opc = BO_NE; break;
10638*67e74705SXin Li   case tok::equalequal:           Opc = BO_EQ; break;
10639*67e74705SXin Li   case tok::amp:                  Opc = BO_And; break;
10640*67e74705SXin Li   case tok::caret:                Opc = BO_Xor; break;
10641*67e74705SXin Li   case tok::pipe:                 Opc = BO_Or; break;
10642*67e74705SXin Li   case tok::ampamp:               Opc = BO_LAnd; break;
10643*67e74705SXin Li   case tok::pipepipe:             Opc = BO_LOr; break;
10644*67e74705SXin Li   case tok::equal:                Opc = BO_Assign; break;
10645*67e74705SXin Li   case tok::starequal:            Opc = BO_MulAssign; break;
10646*67e74705SXin Li   case tok::slashequal:           Opc = BO_DivAssign; break;
10647*67e74705SXin Li   case tok::percentequal:         Opc = BO_RemAssign; break;
10648*67e74705SXin Li   case tok::plusequal:            Opc = BO_AddAssign; break;
10649*67e74705SXin Li   case tok::minusequal:           Opc = BO_SubAssign; break;
10650*67e74705SXin Li   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10651*67e74705SXin Li   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10652*67e74705SXin Li   case tok::ampequal:             Opc = BO_AndAssign; break;
10653*67e74705SXin Li   case tok::caretequal:           Opc = BO_XorAssign; break;
10654*67e74705SXin Li   case tok::pipeequal:            Opc = BO_OrAssign; break;
10655*67e74705SXin Li   case tok::comma:                Opc = BO_Comma; break;
10656*67e74705SXin Li   }
10657*67e74705SXin Li   return Opc;
10658*67e74705SXin Li }
10659*67e74705SXin Li 
ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)10660*67e74705SXin Li static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10661*67e74705SXin Li   tok::TokenKind Kind) {
10662*67e74705SXin Li   UnaryOperatorKind Opc;
10663*67e74705SXin Li   switch (Kind) {
10664*67e74705SXin Li   default: llvm_unreachable("Unknown unary op!");
10665*67e74705SXin Li   case tok::plusplus:     Opc = UO_PreInc; break;
10666*67e74705SXin Li   case tok::minusminus:   Opc = UO_PreDec; break;
10667*67e74705SXin Li   case tok::amp:          Opc = UO_AddrOf; break;
10668*67e74705SXin Li   case tok::star:         Opc = UO_Deref; break;
10669*67e74705SXin Li   case tok::plus:         Opc = UO_Plus; break;
10670*67e74705SXin Li   case tok::minus:        Opc = UO_Minus; break;
10671*67e74705SXin Li   case tok::tilde:        Opc = UO_Not; break;
10672*67e74705SXin Li   case tok::exclaim:      Opc = UO_LNot; break;
10673*67e74705SXin Li   case tok::kw___real:    Opc = UO_Real; break;
10674*67e74705SXin Li   case tok::kw___imag:    Opc = UO_Imag; break;
10675*67e74705SXin Li   case tok::kw___extension__: Opc = UO_Extension; break;
10676*67e74705SXin Li   }
10677*67e74705SXin Li   return Opc;
10678*67e74705SXin Li }
10679*67e74705SXin Li 
10680*67e74705SXin Li /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10681*67e74705SXin Li /// This warning is only emitted for builtin assignment operations. It is also
10682*67e74705SXin Li /// suppressed in the event of macro expansions.
DiagnoseSelfAssignment(Sema & S,Expr * LHSExpr,Expr * RHSExpr,SourceLocation OpLoc)10683*67e74705SXin Li static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10684*67e74705SXin Li                                    SourceLocation OpLoc) {
10685*67e74705SXin Li   if (!S.ActiveTemplateInstantiations.empty())
10686*67e74705SXin Li     return;
10687*67e74705SXin Li   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10688*67e74705SXin Li     return;
10689*67e74705SXin Li   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10690*67e74705SXin Li   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10691*67e74705SXin Li   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10692*67e74705SXin Li   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10693*67e74705SXin Li   if (!LHSDeclRef || !RHSDeclRef ||
10694*67e74705SXin Li       LHSDeclRef->getLocation().isMacroID() ||
10695*67e74705SXin Li       RHSDeclRef->getLocation().isMacroID())
10696*67e74705SXin Li     return;
10697*67e74705SXin Li   const ValueDecl *LHSDecl =
10698*67e74705SXin Li     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10699*67e74705SXin Li   const ValueDecl *RHSDecl =
10700*67e74705SXin Li     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10701*67e74705SXin Li   if (LHSDecl != RHSDecl)
10702*67e74705SXin Li     return;
10703*67e74705SXin Li   if (LHSDecl->getType().isVolatileQualified())
10704*67e74705SXin Li     return;
10705*67e74705SXin Li   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10706*67e74705SXin Li     if (RefTy->getPointeeType().isVolatileQualified())
10707*67e74705SXin Li       return;
10708*67e74705SXin Li 
10709*67e74705SXin Li   S.Diag(OpLoc, diag::warn_self_assignment)
10710*67e74705SXin Li       << LHSDeclRef->getType()
10711*67e74705SXin Li       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10712*67e74705SXin Li }
10713*67e74705SXin Li 
10714*67e74705SXin Li /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10715*67e74705SXin Li /// is usually indicative of introspection within the Objective-C pointer.
checkObjCPointerIntrospection(Sema & S,ExprResult & L,ExprResult & R,SourceLocation OpLoc)10716*67e74705SXin Li static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10717*67e74705SXin Li                                           SourceLocation OpLoc) {
10718*67e74705SXin Li   if (!S.getLangOpts().ObjC1)
10719*67e74705SXin Li     return;
10720*67e74705SXin Li 
10721*67e74705SXin Li   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10722*67e74705SXin Li   const Expr *LHS = L.get();
10723*67e74705SXin Li   const Expr *RHS = R.get();
10724*67e74705SXin Li 
10725*67e74705SXin Li   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10726*67e74705SXin Li     ObjCPointerExpr = LHS;
10727*67e74705SXin Li     OtherExpr = RHS;
10728*67e74705SXin Li   }
10729*67e74705SXin Li   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10730*67e74705SXin Li     ObjCPointerExpr = RHS;
10731*67e74705SXin Li     OtherExpr = LHS;
10732*67e74705SXin Li   }
10733*67e74705SXin Li 
10734*67e74705SXin Li   // This warning is deliberately made very specific to reduce false
10735*67e74705SXin Li   // positives with logic that uses '&' for hashing.  This logic mainly
10736*67e74705SXin Li   // looks for code trying to introspect into tagged pointers, which
10737*67e74705SXin Li   // code should generally never do.
10738*67e74705SXin Li   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10739*67e74705SXin Li     unsigned Diag = diag::warn_objc_pointer_masking;
10740*67e74705SXin Li     // Determine if we are introspecting the result of performSelectorXXX.
10741*67e74705SXin Li     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10742*67e74705SXin Li     // Special case messages to -performSelector and friends, which
10743*67e74705SXin Li     // can return non-pointer values boxed in a pointer value.
10744*67e74705SXin Li     // Some clients may wish to silence warnings in this subcase.
10745*67e74705SXin Li     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10746*67e74705SXin Li       Selector S = ME->getSelector();
10747*67e74705SXin Li       StringRef SelArg0 = S.getNameForSlot(0);
10748*67e74705SXin Li       if (SelArg0.startswith("performSelector"))
10749*67e74705SXin Li         Diag = diag::warn_objc_pointer_masking_performSelector;
10750*67e74705SXin Li     }
10751*67e74705SXin Li 
10752*67e74705SXin Li     S.Diag(OpLoc, Diag)
10753*67e74705SXin Li       << ObjCPointerExpr->getSourceRange();
10754*67e74705SXin Li   }
10755*67e74705SXin Li }
10756*67e74705SXin Li 
getDeclFromExpr(Expr * E)10757*67e74705SXin Li static NamedDecl *getDeclFromExpr(Expr *E) {
10758*67e74705SXin Li   if (!E)
10759*67e74705SXin Li     return nullptr;
10760*67e74705SXin Li   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10761*67e74705SXin Li     return DRE->getDecl();
10762*67e74705SXin Li   if (auto *ME = dyn_cast<MemberExpr>(E))
10763*67e74705SXin Li     return ME->getMemberDecl();
10764*67e74705SXin Li   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10765*67e74705SXin Li     return IRE->getDecl();
10766*67e74705SXin Li   return nullptr;
10767*67e74705SXin Li }
10768*67e74705SXin Li 
10769*67e74705SXin Li /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10770*67e74705SXin Li /// operator @p Opc at location @c TokLoc. This routine only supports
10771*67e74705SXin Li /// built-in operations; ActOnBinOp handles overloaded operators.
CreateBuiltinBinOp(SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)10772*67e74705SXin Li ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10773*67e74705SXin Li                                     BinaryOperatorKind Opc,
10774*67e74705SXin Li                                     Expr *LHSExpr, Expr *RHSExpr) {
10775*67e74705SXin Li   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10776*67e74705SXin Li     // The syntax only allows initializer lists on the RHS of assignment,
10777*67e74705SXin Li     // so we don't need to worry about accepting invalid code for
10778*67e74705SXin Li     // non-assignment operators.
10779*67e74705SXin Li     // C++11 5.17p9:
10780*67e74705SXin Li     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10781*67e74705SXin Li     //   of x = {} is x = T().
10782*67e74705SXin Li     InitializationKind Kind =
10783*67e74705SXin Li         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10784*67e74705SXin Li     InitializedEntity Entity =
10785*67e74705SXin Li         InitializedEntity::InitializeTemporary(LHSExpr->getType());
10786*67e74705SXin Li     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10787*67e74705SXin Li     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10788*67e74705SXin Li     if (Init.isInvalid())
10789*67e74705SXin Li       return Init;
10790*67e74705SXin Li     RHSExpr = Init.get();
10791*67e74705SXin Li   }
10792*67e74705SXin Li 
10793*67e74705SXin Li   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10794*67e74705SXin Li   QualType ResultTy;     // Result type of the binary operator.
10795*67e74705SXin Li   // The following two variables are used for compound assignment operators
10796*67e74705SXin Li   QualType CompLHSTy;    // Type of LHS after promotions for computation
10797*67e74705SXin Li   QualType CompResultTy; // Type of computation result
10798*67e74705SXin Li   ExprValueKind VK = VK_RValue;
10799*67e74705SXin Li   ExprObjectKind OK = OK_Ordinary;
10800*67e74705SXin Li 
10801*67e74705SXin Li   if (!getLangOpts().CPlusPlus) {
10802*67e74705SXin Li     // C cannot handle TypoExpr nodes on either side of a binop because it
10803*67e74705SXin Li     // doesn't handle dependent types properly, so make sure any TypoExprs have
10804*67e74705SXin Li     // been dealt with before checking the operands.
10805*67e74705SXin Li     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10806*67e74705SXin Li     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10807*67e74705SXin Li       if (Opc != BO_Assign)
10808*67e74705SXin Li         return ExprResult(E);
10809*67e74705SXin Li       // Avoid correcting the RHS to the same Expr as the LHS.
10810*67e74705SXin Li       Decl *D = getDeclFromExpr(E);
10811*67e74705SXin Li       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10812*67e74705SXin Li     });
10813*67e74705SXin Li     if (!LHS.isUsable() || !RHS.isUsable())
10814*67e74705SXin Li       return ExprError();
10815*67e74705SXin Li   }
10816*67e74705SXin Li 
10817*67e74705SXin Li   if (getLangOpts().OpenCL) {
10818*67e74705SXin Li     QualType LHSTy = LHSExpr->getType();
10819*67e74705SXin Li     QualType RHSTy = RHSExpr->getType();
10820*67e74705SXin Li     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10821*67e74705SXin Li     // the ATOMIC_VAR_INIT macro.
10822*67e74705SXin Li     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
10823*67e74705SXin Li       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10824*67e74705SXin Li       if (BO_Assign == Opc)
10825*67e74705SXin Li         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10826*67e74705SXin Li       else
10827*67e74705SXin Li         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10828*67e74705SXin Li       return ExprError();
10829*67e74705SXin Li     }
10830*67e74705SXin Li 
10831*67e74705SXin Li     // OpenCL special types - image, sampler, pipe, and blocks are to be used
10832*67e74705SXin Li     // only with a builtin functions and therefore should be disallowed here.
10833*67e74705SXin Li     if (LHSTy->isImageType() || RHSTy->isImageType() ||
10834*67e74705SXin Li         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
10835*67e74705SXin Li         LHSTy->isPipeType() || RHSTy->isPipeType() ||
10836*67e74705SXin Li         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
10837*67e74705SXin Li       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10838*67e74705SXin Li       return ExprError();
10839*67e74705SXin Li     }
10840*67e74705SXin Li   }
10841*67e74705SXin Li 
10842*67e74705SXin Li   switch (Opc) {
10843*67e74705SXin Li   case BO_Assign:
10844*67e74705SXin Li     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10845*67e74705SXin Li     if (getLangOpts().CPlusPlus &&
10846*67e74705SXin Li         LHS.get()->getObjectKind() != OK_ObjCProperty) {
10847*67e74705SXin Li       VK = LHS.get()->getValueKind();
10848*67e74705SXin Li       OK = LHS.get()->getObjectKind();
10849*67e74705SXin Li     }
10850*67e74705SXin Li     if (!ResultTy.isNull()) {
10851*67e74705SXin Li       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10852*67e74705SXin Li       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10853*67e74705SXin Li     }
10854*67e74705SXin Li     RecordModifiableNonNullParam(*this, LHS.get());
10855*67e74705SXin Li     break;
10856*67e74705SXin Li   case BO_PtrMemD:
10857*67e74705SXin Li   case BO_PtrMemI:
10858*67e74705SXin Li     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10859*67e74705SXin Li                                             Opc == BO_PtrMemI);
10860*67e74705SXin Li     break;
10861*67e74705SXin Li   case BO_Mul:
10862*67e74705SXin Li   case BO_Div:
10863*67e74705SXin Li     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10864*67e74705SXin Li                                            Opc == BO_Div);
10865*67e74705SXin Li     break;
10866*67e74705SXin Li   case BO_Rem:
10867*67e74705SXin Li     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10868*67e74705SXin Li     break;
10869*67e74705SXin Li   case BO_Add:
10870*67e74705SXin Li     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10871*67e74705SXin Li     break;
10872*67e74705SXin Li   case BO_Sub:
10873*67e74705SXin Li     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10874*67e74705SXin Li     break;
10875*67e74705SXin Li   case BO_Shl:
10876*67e74705SXin Li   case BO_Shr:
10877*67e74705SXin Li     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10878*67e74705SXin Li     break;
10879*67e74705SXin Li   case BO_LE:
10880*67e74705SXin Li   case BO_LT:
10881*67e74705SXin Li   case BO_GE:
10882*67e74705SXin Li   case BO_GT:
10883*67e74705SXin Li     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
10884*67e74705SXin Li     break;
10885*67e74705SXin Li   case BO_EQ:
10886*67e74705SXin Li   case BO_NE:
10887*67e74705SXin Li     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
10888*67e74705SXin Li     break;
10889*67e74705SXin Li   case BO_And:
10890*67e74705SXin Li     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
10891*67e74705SXin Li   case BO_Xor:
10892*67e74705SXin Li   case BO_Or:
10893*67e74705SXin Li     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
10894*67e74705SXin Li     break;
10895*67e74705SXin Li   case BO_LAnd:
10896*67e74705SXin Li   case BO_LOr:
10897*67e74705SXin Li     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
10898*67e74705SXin Li     break;
10899*67e74705SXin Li   case BO_MulAssign:
10900*67e74705SXin Li   case BO_DivAssign:
10901*67e74705SXin Li     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
10902*67e74705SXin Li                                                Opc == BO_DivAssign);
10903*67e74705SXin Li     CompLHSTy = CompResultTy;
10904*67e74705SXin Li     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10905*67e74705SXin Li       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10906*67e74705SXin Li     break;
10907*67e74705SXin Li   case BO_RemAssign:
10908*67e74705SXin Li     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
10909*67e74705SXin Li     CompLHSTy = CompResultTy;
10910*67e74705SXin Li     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10911*67e74705SXin Li       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10912*67e74705SXin Li     break;
10913*67e74705SXin Li   case BO_AddAssign:
10914*67e74705SXin Li     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
10915*67e74705SXin Li     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10916*67e74705SXin Li       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10917*67e74705SXin Li     break;
10918*67e74705SXin Li   case BO_SubAssign:
10919*67e74705SXin Li     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10920*67e74705SXin Li     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10921*67e74705SXin Li       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10922*67e74705SXin Li     break;
10923*67e74705SXin Li   case BO_ShlAssign:
10924*67e74705SXin Li   case BO_ShrAssign:
10925*67e74705SXin Li     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
10926*67e74705SXin Li     CompLHSTy = CompResultTy;
10927*67e74705SXin Li     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10928*67e74705SXin Li       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10929*67e74705SXin Li     break;
10930*67e74705SXin Li   case BO_AndAssign:
10931*67e74705SXin Li   case BO_OrAssign: // fallthrough
10932*67e74705SXin Li     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10933*67e74705SXin Li   case BO_XorAssign:
10934*67e74705SXin Li     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
10935*67e74705SXin Li     CompLHSTy = CompResultTy;
10936*67e74705SXin Li     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10937*67e74705SXin Li       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10938*67e74705SXin Li     break;
10939*67e74705SXin Li   case BO_Comma:
10940*67e74705SXin Li     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
10941*67e74705SXin Li     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
10942*67e74705SXin Li       VK = RHS.get()->getValueKind();
10943*67e74705SXin Li       OK = RHS.get()->getObjectKind();
10944*67e74705SXin Li     }
10945*67e74705SXin Li     break;
10946*67e74705SXin Li   }
10947*67e74705SXin Li   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
10948*67e74705SXin Li     return ExprError();
10949*67e74705SXin Li 
10950*67e74705SXin Li   // Check for array bounds violations for both sides of the BinaryOperator
10951*67e74705SXin Li   CheckArrayAccess(LHS.get());
10952*67e74705SXin Li   CheckArrayAccess(RHS.get());
10953*67e74705SXin Li 
10954*67e74705SXin Li   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10955*67e74705SXin Li     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10956*67e74705SXin Li                                                  &Context.Idents.get("object_setClass"),
10957*67e74705SXin Li                                                  SourceLocation(), LookupOrdinaryName);
10958*67e74705SXin Li     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
10959*67e74705SXin Li       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
10960*67e74705SXin Li       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10961*67e74705SXin Li       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10962*67e74705SXin Li       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10963*67e74705SXin Li       FixItHint::CreateInsertion(RHSLocEnd, ")");
10964*67e74705SXin Li     }
10965*67e74705SXin Li     else
10966*67e74705SXin Li       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10967*67e74705SXin Li   }
10968*67e74705SXin Li   else if (const ObjCIvarRefExpr *OIRE =
10969*67e74705SXin Li            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
10970*67e74705SXin Li     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
10971*67e74705SXin Li 
10972*67e74705SXin Li   if (CompResultTy.isNull())
10973*67e74705SXin Li     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10974*67e74705SXin Li                                         OK, OpLoc, FPFeatures.fp_contract);
10975*67e74705SXin Li   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
10976*67e74705SXin Li       OK_ObjCProperty) {
10977*67e74705SXin Li     VK = VK_LValue;
10978*67e74705SXin Li     OK = LHS.get()->getObjectKind();
10979*67e74705SXin Li   }
10980*67e74705SXin Li   return new (Context) CompoundAssignOperator(
10981*67e74705SXin Li       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10982*67e74705SXin Li       OpLoc, FPFeatures.fp_contract);
10983*67e74705SXin Li }
10984*67e74705SXin Li 
10985*67e74705SXin Li /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10986*67e74705SXin Li /// operators are mixed in a way that suggests that the programmer forgot that
10987*67e74705SXin Li /// comparison operators have higher precedence. The most typical example of
10988*67e74705SXin Li /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
DiagnoseBitwisePrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10989*67e74705SXin Li static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
10990*67e74705SXin Li                                       SourceLocation OpLoc, Expr *LHSExpr,
10991*67e74705SXin Li                                       Expr *RHSExpr) {
10992*67e74705SXin Li   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10993*67e74705SXin Li   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
10994*67e74705SXin Li 
10995*67e74705SXin Li   // Check that one of the sides is a comparison operator and the other isn't.
10996*67e74705SXin Li   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
10997*67e74705SXin Li   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
10998*67e74705SXin Li   if (isLeftComp == isRightComp)
10999*67e74705SXin Li     return;
11000*67e74705SXin Li 
11001*67e74705SXin Li   // Bitwise operations are sometimes used as eager logical ops.
11002*67e74705SXin Li   // Don't diagnose this.
11003*67e74705SXin Li   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11004*67e74705SXin Li   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11005*67e74705SXin Li   if (isLeftBitwise || isRightBitwise)
11006*67e74705SXin Li     return;
11007*67e74705SXin Li 
11008*67e74705SXin Li   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11009*67e74705SXin Li                                                    OpLoc)
11010*67e74705SXin Li                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11011*67e74705SXin Li   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11012*67e74705SXin Li   SourceRange ParensRange = isLeftComp ?
11013*67e74705SXin Li       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11014*67e74705SXin Li     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11015*67e74705SXin Li 
11016*67e74705SXin Li   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11017*67e74705SXin Li     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11018*67e74705SXin Li   SuggestParentheses(Self, OpLoc,
11019*67e74705SXin Li     Self.PDiag(diag::note_precedence_silence) << OpStr,
11020*67e74705SXin Li     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11021*67e74705SXin Li   SuggestParentheses(Self, OpLoc,
11022*67e74705SXin Li     Self.PDiag(diag::note_precedence_bitwise_first)
11023*67e74705SXin Li       << BinaryOperator::getOpcodeStr(Opc),
11024*67e74705SXin Li     ParensRange);
11025*67e74705SXin Li }
11026*67e74705SXin Li 
11027*67e74705SXin Li /// \brief It accepts a '&&' expr that is inside a '||' one.
11028*67e74705SXin Li /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11029*67e74705SXin Li /// in parentheses.
11030*67e74705SXin Li static void
EmitDiagnosticForLogicalAndInLogicalOr(Sema & Self,SourceLocation OpLoc,BinaryOperator * Bop)11031*67e74705SXin Li EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11032*67e74705SXin Li                                        BinaryOperator *Bop) {
11033*67e74705SXin Li   assert(Bop->getOpcode() == BO_LAnd);
11034*67e74705SXin Li   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11035*67e74705SXin Li       << Bop->getSourceRange() << OpLoc;
11036*67e74705SXin Li   SuggestParentheses(Self, Bop->getOperatorLoc(),
11037*67e74705SXin Li     Self.PDiag(diag::note_precedence_silence)
11038*67e74705SXin Li       << Bop->getOpcodeStr(),
11039*67e74705SXin Li     Bop->getSourceRange());
11040*67e74705SXin Li }
11041*67e74705SXin Li 
11042*67e74705SXin Li /// \brief Returns true if the given expression can be evaluated as a constant
11043*67e74705SXin Li /// 'true'.
EvaluatesAsTrue(Sema & S,Expr * E)11044*67e74705SXin Li static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11045*67e74705SXin Li   bool Res;
11046*67e74705SXin Li   return !E->isValueDependent() &&
11047*67e74705SXin Li          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11048*67e74705SXin Li }
11049*67e74705SXin Li 
11050*67e74705SXin Li /// \brief Returns true if the given expression can be evaluated as a constant
11051*67e74705SXin Li /// 'false'.
EvaluatesAsFalse(Sema & S,Expr * E)11052*67e74705SXin Li static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11053*67e74705SXin Li   bool Res;
11054*67e74705SXin Li   return !E->isValueDependent() &&
11055*67e74705SXin Li          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11056*67e74705SXin Li }
11057*67e74705SXin Li 
11058*67e74705SXin Li /// \brief Look for '&&' in the left hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrLHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)11059*67e74705SXin Li static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11060*67e74705SXin Li                                              Expr *LHSExpr, Expr *RHSExpr) {
11061*67e74705SXin Li   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11062*67e74705SXin Li     if (Bop->getOpcode() == BO_LAnd) {
11063*67e74705SXin Li       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11064*67e74705SXin Li       if (EvaluatesAsFalse(S, RHSExpr))
11065*67e74705SXin Li         return;
11066*67e74705SXin Li       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11067*67e74705SXin Li       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11068*67e74705SXin Li         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11069*67e74705SXin Li     } else if (Bop->getOpcode() == BO_LOr) {
11070*67e74705SXin Li       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11071*67e74705SXin Li         // If it's "a || b && 1 || c" we didn't warn earlier for
11072*67e74705SXin Li         // "a || b && 1", but warn now.
11073*67e74705SXin Li         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11074*67e74705SXin Li           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11075*67e74705SXin Li       }
11076*67e74705SXin Li     }
11077*67e74705SXin Li   }
11078*67e74705SXin Li }
11079*67e74705SXin Li 
11080*67e74705SXin Li /// \brief Look for '&&' in the right hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrRHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)11081*67e74705SXin Li static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11082*67e74705SXin Li                                              Expr *LHSExpr, Expr *RHSExpr) {
11083*67e74705SXin Li   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11084*67e74705SXin Li     if (Bop->getOpcode() == BO_LAnd) {
11085*67e74705SXin Li       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11086*67e74705SXin Li       if (EvaluatesAsFalse(S, LHSExpr))
11087*67e74705SXin Li         return;
11088*67e74705SXin Li       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11089*67e74705SXin Li       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11090*67e74705SXin Li         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11091*67e74705SXin Li     }
11092*67e74705SXin Li   }
11093*67e74705SXin Li }
11094*67e74705SXin Li 
11095*67e74705SXin Li /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11096*67e74705SXin Li /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11097*67e74705SXin Li /// the '&' expression in parentheses.
DiagnoseBitwiseOpInBitwiseOp(Sema & S,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * SubExpr)11098*67e74705SXin Li static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11099*67e74705SXin Li                                          SourceLocation OpLoc, Expr *SubExpr) {
11100*67e74705SXin Li   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11101*67e74705SXin Li     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11102*67e74705SXin Li       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11103*67e74705SXin Li         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11104*67e74705SXin Li         << Bop->getSourceRange() << OpLoc;
11105*67e74705SXin Li       SuggestParentheses(S, Bop->getOperatorLoc(),
11106*67e74705SXin Li         S.PDiag(diag::note_precedence_silence)
11107*67e74705SXin Li           << Bop->getOpcodeStr(),
11108*67e74705SXin Li         Bop->getSourceRange());
11109*67e74705SXin Li     }
11110*67e74705SXin Li   }
11111*67e74705SXin Li }
11112*67e74705SXin Li 
DiagnoseAdditionInShift(Sema & S,SourceLocation OpLoc,Expr * SubExpr,StringRef Shift)11113*67e74705SXin Li static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11114*67e74705SXin Li                                     Expr *SubExpr, StringRef Shift) {
11115*67e74705SXin Li   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11116*67e74705SXin Li     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11117*67e74705SXin Li       StringRef Op = Bop->getOpcodeStr();
11118*67e74705SXin Li       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11119*67e74705SXin Li           << Bop->getSourceRange() << OpLoc << Shift << Op;
11120*67e74705SXin Li       SuggestParentheses(S, Bop->getOperatorLoc(),
11121*67e74705SXin Li           S.PDiag(diag::note_precedence_silence) << Op,
11122*67e74705SXin Li           Bop->getSourceRange());
11123*67e74705SXin Li     }
11124*67e74705SXin Li   }
11125*67e74705SXin Li }
11126*67e74705SXin Li 
DiagnoseShiftCompare(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)11127*67e74705SXin Li static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11128*67e74705SXin Li                                  Expr *LHSExpr, Expr *RHSExpr) {
11129*67e74705SXin Li   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11130*67e74705SXin Li   if (!OCE)
11131*67e74705SXin Li     return;
11132*67e74705SXin Li 
11133*67e74705SXin Li   FunctionDecl *FD = OCE->getDirectCallee();
11134*67e74705SXin Li   if (!FD || !FD->isOverloadedOperator())
11135*67e74705SXin Li     return;
11136*67e74705SXin Li 
11137*67e74705SXin Li   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11138*67e74705SXin Li   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11139*67e74705SXin Li     return;
11140*67e74705SXin Li 
11141*67e74705SXin Li   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11142*67e74705SXin Li       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11143*67e74705SXin Li       << (Kind == OO_LessLess);
11144*67e74705SXin Li   SuggestParentheses(S, OCE->getOperatorLoc(),
11145*67e74705SXin Li                      S.PDiag(diag::note_precedence_silence)
11146*67e74705SXin Li                          << (Kind == OO_LessLess ? "<<" : ">>"),
11147*67e74705SXin Li                      OCE->getSourceRange());
11148*67e74705SXin Li   SuggestParentheses(S, OpLoc,
11149*67e74705SXin Li                      S.PDiag(diag::note_evaluate_comparison_first),
11150*67e74705SXin Li                      SourceRange(OCE->getArg(1)->getLocStart(),
11151*67e74705SXin Li                                  RHSExpr->getLocEnd()));
11152*67e74705SXin Li }
11153*67e74705SXin Li 
11154*67e74705SXin Li /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11155*67e74705SXin Li /// precedence.
DiagnoseBinOpPrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)11156*67e74705SXin Li static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11157*67e74705SXin Li                                     SourceLocation OpLoc, Expr *LHSExpr,
11158*67e74705SXin Li                                     Expr *RHSExpr){
11159*67e74705SXin Li   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11160*67e74705SXin Li   if (BinaryOperator::isBitwiseOp(Opc))
11161*67e74705SXin Li     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11162*67e74705SXin Li 
11163*67e74705SXin Li   // Diagnose "arg1 & arg2 | arg3"
11164*67e74705SXin Li   if ((Opc == BO_Or || Opc == BO_Xor) &&
11165*67e74705SXin Li       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11166*67e74705SXin Li     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11167*67e74705SXin Li     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11168*67e74705SXin Li   }
11169*67e74705SXin Li 
11170*67e74705SXin Li   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11171*67e74705SXin Li   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11172*67e74705SXin Li   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11173*67e74705SXin Li     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11174*67e74705SXin Li     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11175*67e74705SXin Li   }
11176*67e74705SXin Li 
11177*67e74705SXin Li   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11178*67e74705SXin Li       || Opc == BO_Shr) {
11179*67e74705SXin Li     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11180*67e74705SXin Li     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11181*67e74705SXin Li     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11182*67e74705SXin Li   }
11183*67e74705SXin Li 
11184*67e74705SXin Li   // Warn on overloaded shift operators and comparisons, such as:
11185*67e74705SXin Li   // cout << 5 == 4;
11186*67e74705SXin Li   if (BinaryOperator::isComparisonOp(Opc))
11187*67e74705SXin Li     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11188*67e74705SXin Li }
11189*67e74705SXin Li 
11190*67e74705SXin Li // Binary Operators.  'Tok' is the token for the operator.
ActOnBinOp(Scope * S,SourceLocation TokLoc,tok::TokenKind Kind,Expr * LHSExpr,Expr * RHSExpr)11191*67e74705SXin Li ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11192*67e74705SXin Li                             tok::TokenKind Kind,
11193*67e74705SXin Li                             Expr *LHSExpr, Expr *RHSExpr) {
11194*67e74705SXin Li   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11195*67e74705SXin Li   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11196*67e74705SXin Li   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11197*67e74705SXin Li 
11198*67e74705SXin Li   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11199*67e74705SXin Li   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11200*67e74705SXin Li 
11201*67e74705SXin Li   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11202*67e74705SXin Li }
11203*67e74705SXin Li 
11204*67e74705SXin Li /// Build an overloaded binary operator expression in the given scope.
BuildOverloadedBinOp(Sema & S,Scope * Sc,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHS,Expr * RHS)11205*67e74705SXin Li static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11206*67e74705SXin Li                                        BinaryOperatorKind Opc,
11207*67e74705SXin Li                                        Expr *LHS, Expr *RHS) {
11208*67e74705SXin Li   // Find all of the overloaded operators visible from this
11209*67e74705SXin Li   // point. We perform both an operator-name lookup from the local
11210*67e74705SXin Li   // scope and an argument-dependent lookup based on the types of
11211*67e74705SXin Li   // the arguments.
11212*67e74705SXin Li   UnresolvedSet<16> Functions;
11213*67e74705SXin Li   OverloadedOperatorKind OverOp
11214*67e74705SXin Li     = BinaryOperator::getOverloadedOperator(Opc);
11215*67e74705SXin Li   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11216*67e74705SXin Li     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11217*67e74705SXin Li                                    RHS->getType(), Functions);
11218*67e74705SXin Li 
11219*67e74705SXin Li   // Build the (potentially-overloaded, potentially-dependent)
11220*67e74705SXin Li   // binary operation.
11221*67e74705SXin Li   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11222*67e74705SXin Li }
11223*67e74705SXin Li 
BuildBinOp(Scope * S,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)11224*67e74705SXin Li ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11225*67e74705SXin Li                             BinaryOperatorKind Opc,
11226*67e74705SXin Li                             Expr *LHSExpr, Expr *RHSExpr) {
11227*67e74705SXin Li   // We want to end up calling one of checkPseudoObjectAssignment
11228*67e74705SXin Li   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11229*67e74705SXin Li   // both expressions are overloadable or either is type-dependent),
11230*67e74705SXin Li   // or CreateBuiltinBinOp (in any other case).  We also want to get
11231*67e74705SXin Li   // any placeholder types out of the way.
11232*67e74705SXin Li 
11233*67e74705SXin Li   // Handle pseudo-objects in the LHS.
11234*67e74705SXin Li   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11235*67e74705SXin Li     // Assignments with a pseudo-object l-value need special analysis.
11236*67e74705SXin Li     if (pty->getKind() == BuiltinType::PseudoObject &&
11237*67e74705SXin Li         BinaryOperator::isAssignmentOp(Opc))
11238*67e74705SXin Li       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11239*67e74705SXin Li 
11240*67e74705SXin Li     // Don't resolve overloads if the other type is overloadable.
11241*67e74705SXin Li     if (pty->getKind() == BuiltinType::Overload) {
11242*67e74705SXin Li       // We can't actually test that if we still have a placeholder,
11243*67e74705SXin Li       // though.  Fortunately, none of the exceptions we see in that
11244*67e74705SXin Li       // code below are valid when the LHS is an overload set.  Note
11245*67e74705SXin Li       // that an overload set can be dependently-typed, but it never
11246*67e74705SXin Li       // instantiates to having an overloadable type.
11247*67e74705SXin Li       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11248*67e74705SXin Li       if (resolvedRHS.isInvalid()) return ExprError();
11249*67e74705SXin Li       RHSExpr = resolvedRHS.get();
11250*67e74705SXin Li 
11251*67e74705SXin Li       if (RHSExpr->isTypeDependent() ||
11252*67e74705SXin Li           RHSExpr->getType()->isOverloadableType())
11253*67e74705SXin Li         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11254*67e74705SXin Li     }
11255*67e74705SXin Li 
11256*67e74705SXin Li     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11257*67e74705SXin Li     if (LHS.isInvalid()) return ExprError();
11258*67e74705SXin Li     LHSExpr = LHS.get();
11259*67e74705SXin Li   }
11260*67e74705SXin Li 
11261*67e74705SXin Li   // Handle pseudo-objects in the RHS.
11262*67e74705SXin Li   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11263*67e74705SXin Li     // An overload in the RHS can potentially be resolved by the type
11264*67e74705SXin Li     // being assigned to.
11265*67e74705SXin Li     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11266*67e74705SXin Li       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11267*67e74705SXin Li         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11268*67e74705SXin Li 
11269*67e74705SXin Li       if (LHSExpr->getType()->isOverloadableType())
11270*67e74705SXin Li         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11271*67e74705SXin Li 
11272*67e74705SXin Li       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11273*67e74705SXin Li     }
11274*67e74705SXin Li 
11275*67e74705SXin Li     // Don't resolve overloads if the other type is overloadable.
11276*67e74705SXin Li     if (pty->getKind() == BuiltinType::Overload &&
11277*67e74705SXin Li         LHSExpr->getType()->isOverloadableType())
11278*67e74705SXin Li       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11279*67e74705SXin Li 
11280*67e74705SXin Li     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11281*67e74705SXin Li     if (!resolvedRHS.isUsable()) return ExprError();
11282*67e74705SXin Li     RHSExpr = resolvedRHS.get();
11283*67e74705SXin Li   }
11284*67e74705SXin Li 
11285*67e74705SXin Li   if (getLangOpts().CPlusPlus) {
11286*67e74705SXin Li     // If either expression is type-dependent, always build an
11287*67e74705SXin Li     // overloaded op.
11288*67e74705SXin Li     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11289*67e74705SXin Li       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11290*67e74705SXin Li 
11291*67e74705SXin Li     // Otherwise, build an overloaded op if either expression has an
11292*67e74705SXin Li     // overloadable type.
11293*67e74705SXin Li     if (LHSExpr->getType()->isOverloadableType() ||
11294*67e74705SXin Li         RHSExpr->getType()->isOverloadableType())
11295*67e74705SXin Li       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11296*67e74705SXin Li   }
11297*67e74705SXin Li 
11298*67e74705SXin Li   // Build a built-in binary operation.
11299*67e74705SXin Li   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11300*67e74705SXin Li }
11301*67e74705SXin Li 
CreateBuiltinUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * InputExpr)11302*67e74705SXin Li ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11303*67e74705SXin Li                                       UnaryOperatorKind Opc,
11304*67e74705SXin Li                                       Expr *InputExpr) {
11305*67e74705SXin Li   ExprResult Input = InputExpr;
11306*67e74705SXin Li   ExprValueKind VK = VK_RValue;
11307*67e74705SXin Li   ExprObjectKind OK = OK_Ordinary;
11308*67e74705SXin Li   QualType resultType;
11309*67e74705SXin Li   if (getLangOpts().OpenCL) {
11310*67e74705SXin Li     QualType Ty = InputExpr->getType();
11311*67e74705SXin Li     // The only legal unary operation for atomics is '&'.
11312*67e74705SXin Li     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11313*67e74705SXin Li     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11314*67e74705SXin Li     // only with a builtin functions and therefore should be disallowed here.
11315*67e74705SXin Li         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11316*67e74705SXin Li         || Ty->isBlockPointerType())) {
11317*67e74705SXin Li       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11318*67e74705SXin Li                        << InputExpr->getType()
11319*67e74705SXin Li                        << Input.get()->getSourceRange());
11320*67e74705SXin Li     }
11321*67e74705SXin Li   }
11322*67e74705SXin Li   switch (Opc) {
11323*67e74705SXin Li   case UO_PreInc:
11324*67e74705SXin Li   case UO_PreDec:
11325*67e74705SXin Li   case UO_PostInc:
11326*67e74705SXin Li   case UO_PostDec:
11327*67e74705SXin Li     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11328*67e74705SXin Li                                                 OpLoc,
11329*67e74705SXin Li                                                 Opc == UO_PreInc ||
11330*67e74705SXin Li                                                 Opc == UO_PostInc,
11331*67e74705SXin Li                                                 Opc == UO_PreInc ||
11332*67e74705SXin Li                                                 Opc == UO_PreDec);
11333*67e74705SXin Li     break;
11334*67e74705SXin Li   case UO_AddrOf:
11335*67e74705SXin Li     resultType = CheckAddressOfOperand(Input, OpLoc);
11336*67e74705SXin Li     RecordModifiableNonNullParam(*this, InputExpr);
11337*67e74705SXin Li     break;
11338*67e74705SXin Li   case UO_Deref: {
11339*67e74705SXin Li     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11340*67e74705SXin Li     if (Input.isInvalid()) return ExprError();
11341*67e74705SXin Li     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11342*67e74705SXin Li     break;
11343*67e74705SXin Li   }
11344*67e74705SXin Li   case UO_Plus:
11345*67e74705SXin Li   case UO_Minus:
11346*67e74705SXin Li     Input = UsualUnaryConversions(Input.get());
11347*67e74705SXin Li     if (Input.isInvalid()) return ExprError();
11348*67e74705SXin Li     resultType = Input.get()->getType();
11349*67e74705SXin Li     if (resultType->isDependentType())
11350*67e74705SXin Li       break;
11351*67e74705SXin Li     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11352*67e74705SXin Li       break;
11353*67e74705SXin Li     else if (resultType->isVectorType() &&
11354*67e74705SXin Li              // The z vector extensions don't allow + or - with bool vectors.
11355*67e74705SXin Li              (!Context.getLangOpts().ZVector ||
11356*67e74705SXin Li               resultType->getAs<VectorType>()->getVectorKind() !=
11357*67e74705SXin Li               VectorType::AltiVecBool))
11358*67e74705SXin Li       break;
11359*67e74705SXin Li     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11360*67e74705SXin Li              Opc == UO_Plus &&
11361*67e74705SXin Li              resultType->isPointerType())
11362*67e74705SXin Li       break;
11363*67e74705SXin Li 
11364*67e74705SXin Li     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11365*67e74705SXin Li       << resultType << Input.get()->getSourceRange());
11366*67e74705SXin Li 
11367*67e74705SXin Li   case UO_Not: // bitwise complement
11368*67e74705SXin Li     Input = UsualUnaryConversions(Input.get());
11369*67e74705SXin Li     if (Input.isInvalid())
11370*67e74705SXin Li       return ExprError();
11371*67e74705SXin Li     resultType = Input.get()->getType();
11372*67e74705SXin Li     if (resultType->isDependentType())
11373*67e74705SXin Li       break;
11374*67e74705SXin Li     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11375*67e74705SXin Li     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11376*67e74705SXin Li       // C99 does not support '~' for complex conjugation.
11377*67e74705SXin Li       Diag(OpLoc, diag::ext_integer_complement_complex)
11378*67e74705SXin Li           << resultType << Input.get()->getSourceRange();
11379*67e74705SXin Li     else if (resultType->hasIntegerRepresentation())
11380*67e74705SXin Li       break;
11381*67e74705SXin Li     else if (resultType->isExtVectorType()) {
11382*67e74705SXin Li       if (Context.getLangOpts().OpenCL) {
11383*67e74705SXin Li         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11384*67e74705SXin Li         // on vector float types.
11385*67e74705SXin Li         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11386*67e74705SXin Li         if (!T->isIntegerType())
11387*67e74705SXin Li           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11388*67e74705SXin Li                            << resultType << Input.get()->getSourceRange());
11389*67e74705SXin Li       }
11390*67e74705SXin Li       break;
11391*67e74705SXin Li     } else {
11392*67e74705SXin Li       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11393*67e74705SXin Li                        << resultType << Input.get()->getSourceRange());
11394*67e74705SXin Li     }
11395*67e74705SXin Li     break;
11396*67e74705SXin Li 
11397*67e74705SXin Li   case UO_LNot: // logical negation
11398*67e74705SXin Li     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11399*67e74705SXin Li     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11400*67e74705SXin Li     if (Input.isInvalid()) return ExprError();
11401*67e74705SXin Li     resultType = Input.get()->getType();
11402*67e74705SXin Li 
11403*67e74705SXin Li     // Though we still have to promote half FP to float...
11404*67e74705SXin Li     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11405*67e74705SXin Li       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11406*67e74705SXin Li       resultType = Context.FloatTy;
11407*67e74705SXin Li     }
11408*67e74705SXin Li 
11409*67e74705SXin Li     if (resultType->isDependentType())
11410*67e74705SXin Li       break;
11411*67e74705SXin Li     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11412*67e74705SXin Li       // C99 6.5.3.3p1: ok, fallthrough;
11413*67e74705SXin Li       if (Context.getLangOpts().CPlusPlus) {
11414*67e74705SXin Li         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11415*67e74705SXin Li         // operand contextually converted to bool.
11416*67e74705SXin Li         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11417*67e74705SXin Li                                   ScalarTypeToBooleanCastKind(resultType));
11418*67e74705SXin Li       } else if (Context.getLangOpts().OpenCL &&
11419*67e74705SXin Li                  Context.getLangOpts().OpenCLVersion < 120) {
11420*67e74705SXin Li         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11421*67e74705SXin Li         // operate on scalar float types.
11422*67e74705SXin Li         if (!resultType->isIntegerType())
11423*67e74705SXin Li           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11424*67e74705SXin Li                            << resultType << Input.get()->getSourceRange());
11425*67e74705SXin Li       }
11426*67e74705SXin Li     } else if (resultType->isExtVectorType()) {
11427*67e74705SXin Li       if (Context.getLangOpts().OpenCL &&
11428*67e74705SXin Li           Context.getLangOpts().OpenCLVersion < 120) {
11429*67e74705SXin Li         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11430*67e74705SXin Li         // operate on vector float types.
11431*67e74705SXin Li         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11432*67e74705SXin Li         if (!T->isIntegerType())
11433*67e74705SXin Li           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11434*67e74705SXin Li                            << resultType << Input.get()->getSourceRange());
11435*67e74705SXin Li       }
11436*67e74705SXin Li       // Vector logical not returns the signed variant of the operand type.
11437*67e74705SXin Li       resultType = GetSignedVectorType(resultType);
11438*67e74705SXin Li       break;
11439*67e74705SXin Li     } else {
11440*67e74705SXin Li       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11441*67e74705SXin Li         << resultType << Input.get()->getSourceRange());
11442*67e74705SXin Li     }
11443*67e74705SXin Li 
11444*67e74705SXin Li     // LNot always has type int. C99 6.5.3.3p5.
11445*67e74705SXin Li     // In C++, it's bool. C++ 5.3.1p8
11446*67e74705SXin Li     resultType = Context.getLogicalOperationType();
11447*67e74705SXin Li     break;
11448*67e74705SXin Li   case UO_Real:
11449*67e74705SXin Li   case UO_Imag:
11450*67e74705SXin Li     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11451*67e74705SXin Li     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11452*67e74705SXin Li     // complex l-values to ordinary l-values and all other values to r-values.
11453*67e74705SXin Li     if (Input.isInvalid()) return ExprError();
11454*67e74705SXin Li     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11455*67e74705SXin Li       if (Input.get()->getValueKind() != VK_RValue &&
11456*67e74705SXin Li           Input.get()->getObjectKind() == OK_Ordinary)
11457*67e74705SXin Li         VK = Input.get()->getValueKind();
11458*67e74705SXin Li     } else if (!getLangOpts().CPlusPlus) {
11459*67e74705SXin Li       // In C, a volatile scalar is read by __imag. In C++, it is not.
11460*67e74705SXin Li       Input = DefaultLvalueConversion(Input.get());
11461*67e74705SXin Li     }
11462*67e74705SXin Li     break;
11463*67e74705SXin Li   case UO_Extension:
11464*67e74705SXin Li   case UO_Coawait:
11465*67e74705SXin Li     resultType = Input.get()->getType();
11466*67e74705SXin Li     VK = Input.get()->getValueKind();
11467*67e74705SXin Li     OK = Input.get()->getObjectKind();
11468*67e74705SXin Li     break;
11469*67e74705SXin Li   }
11470*67e74705SXin Li   if (resultType.isNull() || Input.isInvalid())
11471*67e74705SXin Li     return ExprError();
11472*67e74705SXin Li 
11473*67e74705SXin Li   // Check for array bounds violations in the operand of the UnaryOperator,
11474*67e74705SXin Li   // except for the '*' and '&' operators that have to be handled specially
11475*67e74705SXin Li   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11476*67e74705SXin Li   // that are explicitly defined as valid by the standard).
11477*67e74705SXin Li   if (Opc != UO_AddrOf && Opc != UO_Deref)
11478*67e74705SXin Li     CheckArrayAccess(Input.get());
11479*67e74705SXin Li 
11480*67e74705SXin Li   return new (Context)
11481*67e74705SXin Li       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11482*67e74705SXin Li }
11483*67e74705SXin Li 
11484*67e74705SXin Li /// \brief Determine whether the given expression is a qualified member
11485*67e74705SXin Li /// access expression, of a form that could be turned into a pointer to member
11486*67e74705SXin Li /// with the address-of operator.
isQualifiedMemberAccess(Expr * E)11487*67e74705SXin Li static bool isQualifiedMemberAccess(Expr *E) {
11488*67e74705SXin Li   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11489*67e74705SXin Li     if (!DRE->getQualifier())
11490*67e74705SXin Li       return false;
11491*67e74705SXin Li 
11492*67e74705SXin Li     ValueDecl *VD = DRE->getDecl();
11493*67e74705SXin Li     if (!VD->isCXXClassMember())
11494*67e74705SXin Li       return false;
11495*67e74705SXin Li 
11496*67e74705SXin Li     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11497*67e74705SXin Li       return true;
11498*67e74705SXin Li     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11499*67e74705SXin Li       return Method->isInstance();
11500*67e74705SXin Li 
11501*67e74705SXin Li     return false;
11502*67e74705SXin Li   }
11503*67e74705SXin Li 
11504*67e74705SXin Li   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11505*67e74705SXin Li     if (!ULE->getQualifier())
11506*67e74705SXin Li       return false;
11507*67e74705SXin Li 
11508*67e74705SXin Li     for (NamedDecl *D : ULE->decls()) {
11509*67e74705SXin Li       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11510*67e74705SXin Li         if (Method->isInstance())
11511*67e74705SXin Li           return true;
11512*67e74705SXin Li       } else {
11513*67e74705SXin Li         // Overload set does not contain methods.
11514*67e74705SXin Li         break;
11515*67e74705SXin Li       }
11516*67e74705SXin Li     }
11517*67e74705SXin Li 
11518*67e74705SXin Li     return false;
11519*67e74705SXin Li   }
11520*67e74705SXin Li 
11521*67e74705SXin Li   return false;
11522*67e74705SXin Li }
11523*67e74705SXin Li 
BuildUnaryOp(Scope * S,SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * Input)11524*67e74705SXin Li ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11525*67e74705SXin Li                               UnaryOperatorKind Opc, Expr *Input) {
11526*67e74705SXin Li   // First things first: handle placeholders so that the
11527*67e74705SXin Li   // overloaded-operator check considers the right type.
11528*67e74705SXin Li   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11529*67e74705SXin Li     // Increment and decrement of pseudo-object references.
11530*67e74705SXin Li     if (pty->getKind() == BuiltinType::PseudoObject &&
11531*67e74705SXin Li         UnaryOperator::isIncrementDecrementOp(Opc))
11532*67e74705SXin Li       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11533*67e74705SXin Li 
11534*67e74705SXin Li     // extension is always a builtin operator.
11535*67e74705SXin Li     if (Opc == UO_Extension)
11536*67e74705SXin Li       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11537*67e74705SXin Li 
11538*67e74705SXin Li     // & gets special logic for several kinds of placeholder.
11539*67e74705SXin Li     // The builtin code knows what to do.
11540*67e74705SXin Li     if (Opc == UO_AddrOf &&
11541*67e74705SXin Li         (pty->getKind() == BuiltinType::Overload ||
11542*67e74705SXin Li          pty->getKind() == BuiltinType::UnknownAny ||
11543*67e74705SXin Li          pty->getKind() == BuiltinType::BoundMember))
11544*67e74705SXin Li       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11545*67e74705SXin Li 
11546*67e74705SXin Li     // Anything else needs to be handled now.
11547*67e74705SXin Li     ExprResult Result = CheckPlaceholderExpr(Input);
11548*67e74705SXin Li     if (Result.isInvalid()) return ExprError();
11549*67e74705SXin Li     Input = Result.get();
11550*67e74705SXin Li   }
11551*67e74705SXin Li 
11552*67e74705SXin Li   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11553*67e74705SXin Li       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11554*67e74705SXin Li       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11555*67e74705SXin Li     // Find all of the overloaded operators visible from this
11556*67e74705SXin Li     // point. We perform both an operator-name lookup from the local
11557*67e74705SXin Li     // scope and an argument-dependent lookup based on the types of
11558*67e74705SXin Li     // the arguments.
11559*67e74705SXin Li     UnresolvedSet<16> Functions;
11560*67e74705SXin Li     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11561*67e74705SXin Li     if (S && OverOp != OO_None)
11562*67e74705SXin Li       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11563*67e74705SXin Li                                    Functions);
11564*67e74705SXin Li 
11565*67e74705SXin Li     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11566*67e74705SXin Li   }
11567*67e74705SXin Li 
11568*67e74705SXin Li   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11569*67e74705SXin Li }
11570*67e74705SXin Li 
11571*67e74705SXin Li // Unary Operators.  'Tok' is the token for the operator.
ActOnUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Op,Expr * Input)11572*67e74705SXin Li ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11573*67e74705SXin Li                               tok::TokenKind Op, Expr *Input) {
11574*67e74705SXin Li   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11575*67e74705SXin Li }
11576*67e74705SXin Li 
11577*67e74705SXin Li /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ActOnAddrLabel(SourceLocation OpLoc,SourceLocation LabLoc,LabelDecl * TheDecl)11578*67e74705SXin Li ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11579*67e74705SXin Li                                 LabelDecl *TheDecl) {
11580*67e74705SXin Li   TheDecl->markUsed(Context);
11581*67e74705SXin Li   // Create the AST node.  The address of a label always has type 'void*'.
11582*67e74705SXin Li   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11583*67e74705SXin Li                                      Context.getPointerType(Context.VoidTy));
11584*67e74705SXin Li }
11585*67e74705SXin Li 
11586*67e74705SXin Li /// Given the last statement in a statement-expression, check whether
11587*67e74705SXin Li /// the result is a producing expression (like a call to an
11588*67e74705SXin Li /// ns_returns_retained function) and, if so, rebuild it to hoist the
11589*67e74705SXin Li /// release out of the full-expression.  Otherwise, return null.
11590*67e74705SXin Li /// Cannot fail.
maybeRebuildARCConsumingStmt(Stmt * Statement)11591*67e74705SXin Li static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11592*67e74705SXin Li   // Should always be wrapped with one of these.
11593*67e74705SXin Li   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11594*67e74705SXin Li   if (!cleanups) return nullptr;
11595*67e74705SXin Li 
11596*67e74705SXin Li   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11597*67e74705SXin Li   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11598*67e74705SXin Li     return nullptr;
11599*67e74705SXin Li 
11600*67e74705SXin Li   // Splice out the cast.  This shouldn't modify any interesting
11601*67e74705SXin Li   // features of the statement.
11602*67e74705SXin Li   Expr *producer = cast->getSubExpr();
11603*67e74705SXin Li   assert(producer->getType() == cast->getType());
11604*67e74705SXin Li   assert(producer->getValueKind() == cast->getValueKind());
11605*67e74705SXin Li   cleanups->setSubExpr(producer);
11606*67e74705SXin Li   return cleanups;
11607*67e74705SXin Li }
11608*67e74705SXin Li 
ActOnStartStmtExpr()11609*67e74705SXin Li void Sema::ActOnStartStmtExpr() {
11610*67e74705SXin Li   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11611*67e74705SXin Li }
11612*67e74705SXin Li 
ActOnStmtExprError()11613*67e74705SXin Li void Sema::ActOnStmtExprError() {
11614*67e74705SXin Li   // Note that function is also called by TreeTransform when leaving a
11615*67e74705SXin Li   // StmtExpr scope without rebuilding anything.
11616*67e74705SXin Li 
11617*67e74705SXin Li   DiscardCleanupsInEvaluationContext();
11618*67e74705SXin Li   PopExpressionEvaluationContext();
11619*67e74705SXin Li }
11620*67e74705SXin Li 
11621*67e74705SXin Li ExprResult
ActOnStmtExpr(SourceLocation LPLoc,Stmt * SubStmt,SourceLocation RPLoc)11622*67e74705SXin Li Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11623*67e74705SXin Li                     SourceLocation RPLoc) { // "({..})"
11624*67e74705SXin Li   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11625*67e74705SXin Li   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11626*67e74705SXin Li 
11627*67e74705SXin Li   if (hasAnyUnrecoverableErrorsInThisFunction())
11628*67e74705SXin Li     DiscardCleanupsInEvaluationContext();
11629*67e74705SXin Li   assert(!Cleanup.exprNeedsCleanups() &&
11630*67e74705SXin Li          "cleanups within StmtExpr not correctly bound!");
11631*67e74705SXin Li   PopExpressionEvaluationContext();
11632*67e74705SXin Li 
11633*67e74705SXin Li   // FIXME: there are a variety of strange constraints to enforce here, for
11634*67e74705SXin Li   // example, it is not possible to goto into a stmt expression apparently.
11635*67e74705SXin Li   // More semantic analysis is needed.
11636*67e74705SXin Li 
11637*67e74705SXin Li   // If there are sub-stmts in the compound stmt, take the type of the last one
11638*67e74705SXin Li   // as the type of the stmtexpr.
11639*67e74705SXin Li   QualType Ty = Context.VoidTy;
11640*67e74705SXin Li   bool StmtExprMayBindToTemp = false;
11641*67e74705SXin Li   if (!Compound->body_empty()) {
11642*67e74705SXin Li     Stmt *LastStmt = Compound->body_back();
11643*67e74705SXin Li     LabelStmt *LastLabelStmt = nullptr;
11644*67e74705SXin Li     // If LastStmt is a label, skip down through into the body.
11645*67e74705SXin Li     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11646*67e74705SXin Li       LastLabelStmt = Label;
11647*67e74705SXin Li       LastStmt = Label->getSubStmt();
11648*67e74705SXin Li     }
11649*67e74705SXin Li 
11650*67e74705SXin Li     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11651*67e74705SXin Li       // Do function/array conversion on the last expression, but not
11652*67e74705SXin Li       // lvalue-to-rvalue.  However, initialize an unqualified type.
11653*67e74705SXin Li       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11654*67e74705SXin Li       if (LastExpr.isInvalid())
11655*67e74705SXin Li         return ExprError();
11656*67e74705SXin Li       Ty = LastExpr.get()->getType().getUnqualifiedType();
11657*67e74705SXin Li 
11658*67e74705SXin Li       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11659*67e74705SXin Li         // In ARC, if the final expression ends in a consume, splice
11660*67e74705SXin Li         // the consume out and bind it later.  In the alternate case
11661*67e74705SXin Li         // (when dealing with a retainable type), the result
11662*67e74705SXin Li         // initialization will create a produce.  In both cases the
11663*67e74705SXin Li         // result will be +1, and we'll need to balance that out with
11664*67e74705SXin Li         // a bind.
11665*67e74705SXin Li         if (Expr *rebuiltLastStmt
11666*67e74705SXin Li               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11667*67e74705SXin Li           LastExpr = rebuiltLastStmt;
11668*67e74705SXin Li         } else {
11669*67e74705SXin Li           LastExpr = PerformCopyInitialization(
11670*67e74705SXin Li                             InitializedEntity::InitializeResult(LPLoc,
11671*67e74705SXin Li                                                                 Ty,
11672*67e74705SXin Li                                                                 false),
11673*67e74705SXin Li                                                    SourceLocation(),
11674*67e74705SXin Li                                                LastExpr);
11675*67e74705SXin Li         }
11676*67e74705SXin Li 
11677*67e74705SXin Li         if (LastExpr.isInvalid())
11678*67e74705SXin Li           return ExprError();
11679*67e74705SXin Li         if (LastExpr.get() != nullptr) {
11680*67e74705SXin Li           if (!LastLabelStmt)
11681*67e74705SXin Li             Compound->setLastStmt(LastExpr.get());
11682*67e74705SXin Li           else
11683*67e74705SXin Li             LastLabelStmt->setSubStmt(LastExpr.get());
11684*67e74705SXin Li           StmtExprMayBindToTemp = true;
11685*67e74705SXin Li         }
11686*67e74705SXin Li       }
11687*67e74705SXin Li     }
11688*67e74705SXin Li   }
11689*67e74705SXin Li 
11690*67e74705SXin Li   // FIXME: Check that expression type is complete/non-abstract; statement
11691*67e74705SXin Li   // expressions are not lvalues.
11692*67e74705SXin Li   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11693*67e74705SXin Li   if (StmtExprMayBindToTemp)
11694*67e74705SXin Li     return MaybeBindToTemporary(ResStmtExpr);
11695*67e74705SXin Li   return ResStmtExpr;
11696*67e74705SXin Li }
11697*67e74705SXin Li 
BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,TypeSourceInfo * TInfo,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)11698*67e74705SXin Li ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11699*67e74705SXin Li                                       TypeSourceInfo *TInfo,
11700*67e74705SXin Li                                       ArrayRef<OffsetOfComponent> Components,
11701*67e74705SXin Li                                       SourceLocation RParenLoc) {
11702*67e74705SXin Li   QualType ArgTy = TInfo->getType();
11703*67e74705SXin Li   bool Dependent = ArgTy->isDependentType();
11704*67e74705SXin Li   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11705*67e74705SXin Li 
11706*67e74705SXin Li   // We must have at least one component that refers to the type, and the first
11707*67e74705SXin Li   // one is known to be a field designator.  Verify that the ArgTy represents
11708*67e74705SXin Li   // a struct/union/class.
11709*67e74705SXin Li   if (!Dependent && !ArgTy->isRecordType())
11710*67e74705SXin Li     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11711*67e74705SXin Li                        << ArgTy << TypeRange);
11712*67e74705SXin Li 
11713*67e74705SXin Li   // Type must be complete per C99 7.17p3 because a declaring a variable
11714*67e74705SXin Li   // with an incomplete type would be ill-formed.
11715*67e74705SXin Li   if (!Dependent
11716*67e74705SXin Li       && RequireCompleteType(BuiltinLoc, ArgTy,
11717*67e74705SXin Li                              diag::err_offsetof_incomplete_type, TypeRange))
11718*67e74705SXin Li     return ExprError();
11719*67e74705SXin Li 
11720*67e74705SXin Li   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11721*67e74705SXin Li   // GCC extension, diagnose them.
11722*67e74705SXin Li   // FIXME: This diagnostic isn't actually visible because the location is in
11723*67e74705SXin Li   // a system header!
11724*67e74705SXin Li   if (Components.size() != 1)
11725*67e74705SXin Li     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11726*67e74705SXin Li       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11727*67e74705SXin Li 
11728*67e74705SXin Li   bool DidWarnAboutNonPOD = false;
11729*67e74705SXin Li   QualType CurrentType = ArgTy;
11730*67e74705SXin Li   SmallVector<OffsetOfNode, 4> Comps;
11731*67e74705SXin Li   SmallVector<Expr*, 4> Exprs;
11732*67e74705SXin Li   for (const OffsetOfComponent &OC : Components) {
11733*67e74705SXin Li     if (OC.isBrackets) {
11734*67e74705SXin Li       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11735*67e74705SXin Li       if (!CurrentType->isDependentType()) {
11736*67e74705SXin Li         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11737*67e74705SXin Li         if(!AT)
11738*67e74705SXin Li           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11739*67e74705SXin Li                            << CurrentType);
11740*67e74705SXin Li         CurrentType = AT->getElementType();
11741*67e74705SXin Li       } else
11742*67e74705SXin Li         CurrentType = Context.DependentTy;
11743*67e74705SXin Li 
11744*67e74705SXin Li       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11745*67e74705SXin Li       if (IdxRval.isInvalid())
11746*67e74705SXin Li         return ExprError();
11747*67e74705SXin Li       Expr *Idx = IdxRval.get();
11748*67e74705SXin Li 
11749*67e74705SXin Li       // The expression must be an integral expression.
11750*67e74705SXin Li       // FIXME: An integral constant expression?
11751*67e74705SXin Li       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11752*67e74705SXin Li           !Idx->getType()->isIntegerType())
11753*67e74705SXin Li         return ExprError(Diag(Idx->getLocStart(),
11754*67e74705SXin Li                               diag::err_typecheck_subscript_not_integer)
11755*67e74705SXin Li                          << Idx->getSourceRange());
11756*67e74705SXin Li 
11757*67e74705SXin Li       // Record this array index.
11758*67e74705SXin Li       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11759*67e74705SXin Li       Exprs.push_back(Idx);
11760*67e74705SXin Li       continue;
11761*67e74705SXin Li     }
11762*67e74705SXin Li 
11763*67e74705SXin Li     // Offset of a field.
11764*67e74705SXin Li     if (CurrentType->isDependentType()) {
11765*67e74705SXin Li       // We have the offset of a field, but we can't look into the dependent
11766*67e74705SXin Li       // type. Just record the identifier of the field.
11767*67e74705SXin Li       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11768*67e74705SXin Li       CurrentType = Context.DependentTy;
11769*67e74705SXin Li       continue;
11770*67e74705SXin Li     }
11771*67e74705SXin Li 
11772*67e74705SXin Li     // We need to have a complete type to look into.
11773*67e74705SXin Li     if (RequireCompleteType(OC.LocStart, CurrentType,
11774*67e74705SXin Li                             diag::err_offsetof_incomplete_type))
11775*67e74705SXin Li       return ExprError();
11776*67e74705SXin Li 
11777*67e74705SXin Li     // Look for the designated field.
11778*67e74705SXin Li     const RecordType *RC = CurrentType->getAs<RecordType>();
11779*67e74705SXin Li     if (!RC)
11780*67e74705SXin Li       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11781*67e74705SXin Li                        << CurrentType);
11782*67e74705SXin Li     RecordDecl *RD = RC->getDecl();
11783*67e74705SXin Li 
11784*67e74705SXin Li     // C++ [lib.support.types]p5:
11785*67e74705SXin Li     //   The macro offsetof accepts a restricted set of type arguments in this
11786*67e74705SXin Li     //   International Standard. type shall be a POD structure or a POD union
11787*67e74705SXin Li     //   (clause 9).
11788*67e74705SXin Li     // C++11 [support.types]p4:
11789*67e74705SXin Li     //   If type is not a standard-layout class (Clause 9), the results are
11790*67e74705SXin Li     //   undefined.
11791*67e74705SXin Li     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11792*67e74705SXin Li       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11793*67e74705SXin Li       unsigned DiagID =
11794*67e74705SXin Li         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11795*67e74705SXin Li                             : diag::ext_offsetof_non_pod_type;
11796*67e74705SXin Li 
11797*67e74705SXin Li       if (!IsSafe && !DidWarnAboutNonPOD &&
11798*67e74705SXin Li           DiagRuntimeBehavior(BuiltinLoc, nullptr,
11799*67e74705SXin Li                               PDiag(DiagID)
11800*67e74705SXin Li                               << SourceRange(Components[0].LocStart, OC.LocEnd)
11801*67e74705SXin Li                               << CurrentType))
11802*67e74705SXin Li         DidWarnAboutNonPOD = true;
11803*67e74705SXin Li     }
11804*67e74705SXin Li 
11805*67e74705SXin Li     // Look for the field.
11806*67e74705SXin Li     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11807*67e74705SXin Li     LookupQualifiedName(R, RD);
11808*67e74705SXin Li     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11809*67e74705SXin Li     IndirectFieldDecl *IndirectMemberDecl = nullptr;
11810*67e74705SXin Li     if (!MemberDecl) {
11811*67e74705SXin Li       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11812*67e74705SXin Li         MemberDecl = IndirectMemberDecl->getAnonField();
11813*67e74705SXin Li     }
11814*67e74705SXin Li 
11815*67e74705SXin Li     if (!MemberDecl)
11816*67e74705SXin Li       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11817*67e74705SXin Li                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11818*67e74705SXin Li                                                               OC.LocEnd));
11819*67e74705SXin Li 
11820*67e74705SXin Li     // C99 7.17p3:
11821*67e74705SXin Li     //   (If the specified member is a bit-field, the behavior is undefined.)
11822*67e74705SXin Li     //
11823*67e74705SXin Li     // We diagnose this as an error.
11824*67e74705SXin Li     if (MemberDecl->isBitField()) {
11825*67e74705SXin Li       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11826*67e74705SXin Li         << MemberDecl->getDeclName()
11827*67e74705SXin Li         << SourceRange(BuiltinLoc, RParenLoc);
11828*67e74705SXin Li       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11829*67e74705SXin Li       return ExprError();
11830*67e74705SXin Li     }
11831*67e74705SXin Li 
11832*67e74705SXin Li     RecordDecl *Parent = MemberDecl->getParent();
11833*67e74705SXin Li     if (IndirectMemberDecl)
11834*67e74705SXin Li       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11835*67e74705SXin Li 
11836*67e74705SXin Li     // If the member was found in a base class, introduce OffsetOfNodes for
11837*67e74705SXin Li     // the base class indirections.
11838*67e74705SXin Li     CXXBasePaths Paths;
11839*67e74705SXin Li     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
11840*67e74705SXin Li                       Paths)) {
11841*67e74705SXin Li       if (Paths.getDetectedVirtual()) {
11842*67e74705SXin Li         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11843*67e74705SXin Li           << MemberDecl->getDeclName()
11844*67e74705SXin Li           << SourceRange(BuiltinLoc, RParenLoc);
11845*67e74705SXin Li         return ExprError();
11846*67e74705SXin Li       }
11847*67e74705SXin Li 
11848*67e74705SXin Li       CXXBasePath &Path = Paths.front();
11849*67e74705SXin Li       for (const CXXBasePathElement &B : Path)
11850*67e74705SXin Li         Comps.push_back(OffsetOfNode(B.Base));
11851*67e74705SXin Li     }
11852*67e74705SXin Li 
11853*67e74705SXin Li     if (IndirectMemberDecl) {
11854*67e74705SXin Li       for (auto *FI : IndirectMemberDecl->chain()) {
11855*67e74705SXin Li         assert(isa<FieldDecl>(FI));
11856*67e74705SXin Li         Comps.push_back(OffsetOfNode(OC.LocStart,
11857*67e74705SXin Li                                      cast<FieldDecl>(FI), OC.LocEnd));
11858*67e74705SXin Li       }
11859*67e74705SXin Li     } else
11860*67e74705SXin Li       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11861*67e74705SXin Li 
11862*67e74705SXin Li     CurrentType = MemberDecl->getType().getNonReferenceType();
11863*67e74705SXin Li   }
11864*67e74705SXin Li 
11865*67e74705SXin Li   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11866*67e74705SXin Li                               Comps, Exprs, RParenLoc);
11867*67e74705SXin Li }
11868*67e74705SXin Li 
ActOnBuiltinOffsetOf(Scope * S,SourceLocation BuiltinLoc,SourceLocation TypeLoc,ParsedType ParsedArgTy,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)11869*67e74705SXin Li ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11870*67e74705SXin Li                                       SourceLocation BuiltinLoc,
11871*67e74705SXin Li                                       SourceLocation TypeLoc,
11872*67e74705SXin Li                                       ParsedType ParsedArgTy,
11873*67e74705SXin Li                                       ArrayRef<OffsetOfComponent> Components,
11874*67e74705SXin Li                                       SourceLocation RParenLoc) {
11875*67e74705SXin Li 
11876*67e74705SXin Li   TypeSourceInfo *ArgTInfo;
11877*67e74705SXin Li   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11878*67e74705SXin Li   if (ArgTy.isNull())
11879*67e74705SXin Li     return ExprError();
11880*67e74705SXin Li 
11881*67e74705SXin Li   if (!ArgTInfo)
11882*67e74705SXin Li     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11883*67e74705SXin Li 
11884*67e74705SXin Li   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
11885*67e74705SXin Li }
11886*67e74705SXin Li 
11887*67e74705SXin Li 
ActOnChooseExpr(SourceLocation BuiltinLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr,SourceLocation RPLoc)11888*67e74705SXin Li ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
11889*67e74705SXin Li                                  Expr *CondExpr,
11890*67e74705SXin Li                                  Expr *LHSExpr, Expr *RHSExpr,
11891*67e74705SXin Li                                  SourceLocation RPLoc) {
11892*67e74705SXin Li   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11893*67e74705SXin Li 
11894*67e74705SXin Li   ExprValueKind VK = VK_RValue;
11895*67e74705SXin Li   ExprObjectKind OK = OK_Ordinary;
11896*67e74705SXin Li   QualType resType;
11897*67e74705SXin Li   bool ValueDependent = false;
11898*67e74705SXin Li   bool CondIsTrue = false;
11899*67e74705SXin Li   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
11900*67e74705SXin Li     resType = Context.DependentTy;
11901*67e74705SXin Li     ValueDependent = true;
11902*67e74705SXin Li   } else {
11903*67e74705SXin Li     // The conditional expression is required to be a constant expression.
11904*67e74705SXin Li     llvm::APSInt condEval(32);
11905*67e74705SXin Li     ExprResult CondICE
11906*67e74705SXin Li       = VerifyIntegerConstantExpression(CondExpr, &condEval,
11907*67e74705SXin Li           diag::err_typecheck_choose_expr_requires_constant, false);
11908*67e74705SXin Li     if (CondICE.isInvalid())
11909*67e74705SXin Li       return ExprError();
11910*67e74705SXin Li     CondExpr = CondICE.get();
11911*67e74705SXin Li     CondIsTrue = condEval.getZExtValue();
11912*67e74705SXin Li 
11913*67e74705SXin Li     // If the condition is > zero, then the AST type is the same as the LSHExpr.
11914*67e74705SXin Li     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
11915*67e74705SXin Li 
11916*67e74705SXin Li     resType = ActiveExpr->getType();
11917*67e74705SXin Li     ValueDependent = ActiveExpr->isValueDependent();
11918*67e74705SXin Li     VK = ActiveExpr->getValueKind();
11919*67e74705SXin Li     OK = ActiveExpr->getObjectKind();
11920*67e74705SXin Li   }
11921*67e74705SXin Li 
11922*67e74705SXin Li   return new (Context)
11923*67e74705SXin Li       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11924*67e74705SXin Li                  CondIsTrue, resType->isDependentType(), ValueDependent);
11925*67e74705SXin Li }
11926*67e74705SXin Li 
11927*67e74705SXin Li //===----------------------------------------------------------------------===//
11928*67e74705SXin Li // Clang Extensions.
11929*67e74705SXin Li //===----------------------------------------------------------------------===//
11930*67e74705SXin Li 
11931*67e74705SXin Li /// ActOnBlockStart - This callback is invoked when a block literal is started.
ActOnBlockStart(SourceLocation CaretLoc,Scope * CurScope)11932*67e74705SXin Li void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
11933*67e74705SXin Li   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
11934*67e74705SXin Li 
11935*67e74705SXin Li   if (LangOpts.CPlusPlus) {
11936*67e74705SXin Li     Decl *ManglingContextDecl;
11937*67e74705SXin Li     if (MangleNumberingContext *MCtx =
11938*67e74705SXin Li             getCurrentMangleNumberContext(Block->getDeclContext(),
11939*67e74705SXin Li                                           ManglingContextDecl)) {
11940*67e74705SXin Li       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11941*67e74705SXin Li       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11942*67e74705SXin Li     }
11943*67e74705SXin Li   }
11944*67e74705SXin Li 
11945*67e74705SXin Li   PushBlockScope(CurScope, Block);
11946*67e74705SXin Li   CurContext->addDecl(Block);
11947*67e74705SXin Li   if (CurScope)
11948*67e74705SXin Li     PushDeclContext(CurScope, Block);
11949*67e74705SXin Li   else
11950*67e74705SXin Li     CurContext = Block;
11951*67e74705SXin Li 
11952*67e74705SXin Li   getCurBlock()->HasImplicitReturnType = true;
11953*67e74705SXin Li 
11954*67e74705SXin Li   // Enter a new evaluation context to insulate the block from any
11955*67e74705SXin Li   // cleanups from the enclosing full-expression.
11956*67e74705SXin Li   PushExpressionEvaluationContext(PotentiallyEvaluated);
11957*67e74705SXin Li }
11958*67e74705SXin Li 
ActOnBlockArguments(SourceLocation CaretLoc,Declarator & ParamInfo,Scope * CurScope)11959*67e74705SXin Li void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11960*67e74705SXin Li                                Scope *CurScope) {
11961*67e74705SXin Li   assert(ParamInfo.getIdentifier() == nullptr &&
11962*67e74705SXin Li          "block-id should have no identifier!");
11963*67e74705SXin Li   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
11964*67e74705SXin Li   BlockScopeInfo *CurBlock = getCurBlock();
11965*67e74705SXin Li 
11966*67e74705SXin Li   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
11967*67e74705SXin Li   QualType T = Sig->getType();
11968*67e74705SXin Li 
11969*67e74705SXin Li   // FIXME: We should allow unexpanded parameter packs here, but that would,
11970*67e74705SXin Li   // in turn, make the block expression contain unexpanded parameter packs.
11971*67e74705SXin Li   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11972*67e74705SXin Li     // Drop the parameters.
11973*67e74705SXin Li     FunctionProtoType::ExtProtoInfo EPI;
11974*67e74705SXin Li     EPI.HasTrailingReturn = false;
11975*67e74705SXin Li     EPI.TypeQuals |= DeclSpec::TQ_const;
11976*67e74705SXin Li     T = Context.getFunctionType(Context.DependentTy, None, EPI);
11977*67e74705SXin Li     Sig = Context.getTrivialTypeSourceInfo(T);
11978*67e74705SXin Li   }
11979*67e74705SXin Li 
11980*67e74705SXin Li   // GetTypeForDeclarator always produces a function type for a block
11981*67e74705SXin Li   // literal signature.  Furthermore, it is always a FunctionProtoType
11982*67e74705SXin Li   // unless the function was written with a typedef.
11983*67e74705SXin Li   assert(T->isFunctionType() &&
11984*67e74705SXin Li          "GetTypeForDeclarator made a non-function block signature");
11985*67e74705SXin Li 
11986*67e74705SXin Li   // Look for an explicit signature in that function type.
11987*67e74705SXin Li   FunctionProtoTypeLoc ExplicitSignature;
11988*67e74705SXin Li 
11989*67e74705SXin Li   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
11990*67e74705SXin Li   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
11991*67e74705SXin Li 
11992*67e74705SXin Li     // Check whether that explicit signature was synthesized by
11993*67e74705SXin Li     // GetTypeForDeclarator.  If so, don't save that as part of the
11994*67e74705SXin Li     // written signature.
11995*67e74705SXin Li     if (ExplicitSignature.getLocalRangeBegin() ==
11996*67e74705SXin Li         ExplicitSignature.getLocalRangeEnd()) {
11997*67e74705SXin Li       // This would be much cheaper if we stored TypeLocs instead of
11998*67e74705SXin Li       // TypeSourceInfos.
11999*67e74705SXin Li       TypeLoc Result = ExplicitSignature.getReturnLoc();
12000*67e74705SXin Li       unsigned Size = Result.getFullDataSize();
12001*67e74705SXin Li       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12002*67e74705SXin Li       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12003*67e74705SXin Li 
12004*67e74705SXin Li       ExplicitSignature = FunctionProtoTypeLoc();
12005*67e74705SXin Li     }
12006*67e74705SXin Li   }
12007*67e74705SXin Li 
12008*67e74705SXin Li   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12009*67e74705SXin Li   CurBlock->FunctionType = T;
12010*67e74705SXin Li 
12011*67e74705SXin Li   const FunctionType *Fn = T->getAs<FunctionType>();
12012*67e74705SXin Li   QualType RetTy = Fn->getReturnType();
12013*67e74705SXin Li   bool isVariadic =
12014*67e74705SXin Li     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12015*67e74705SXin Li 
12016*67e74705SXin Li   CurBlock->TheDecl->setIsVariadic(isVariadic);
12017*67e74705SXin Li 
12018*67e74705SXin Li   // Context.DependentTy is used as a placeholder for a missing block
12019*67e74705SXin Li   // return type.  TODO:  what should we do with declarators like:
12020*67e74705SXin Li   //   ^ * { ... }
12021*67e74705SXin Li   // If the answer is "apply template argument deduction"....
12022*67e74705SXin Li   if (RetTy != Context.DependentTy) {
12023*67e74705SXin Li     CurBlock->ReturnType = RetTy;
12024*67e74705SXin Li     CurBlock->TheDecl->setBlockMissingReturnType(false);
12025*67e74705SXin Li     CurBlock->HasImplicitReturnType = false;
12026*67e74705SXin Li   }
12027*67e74705SXin Li 
12028*67e74705SXin Li   // Push block parameters from the declarator if we had them.
12029*67e74705SXin Li   SmallVector<ParmVarDecl*, 8> Params;
12030*67e74705SXin Li   if (ExplicitSignature) {
12031*67e74705SXin Li     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12032*67e74705SXin Li       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12033*67e74705SXin Li       if (Param->getIdentifier() == nullptr &&
12034*67e74705SXin Li           !Param->isImplicit() &&
12035*67e74705SXin Li           !Param->isInvalidDecl() &&
12036*67e74705SXin Li           !getLangOpts().CPlusPlus)
12037*67e74705SXin Li         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12038*67e74705SXin Li       Params.push_back(Param);
12039*67e74705SXin Li     }
12040*67e74705SXin Li 
12041*67e74705SXin Li   // Fake up parameter variables if we have a typedef, like
12042*67e74705SXin Li   //   ^ fntype { ... }
12043*67e74705SXin Li   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12044*67e74705SXin Li     for (const auto &I : Fn->param_types()) {
12045*67e74705SXin Li       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12046*67e74705SXin Li           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12047*67e74705SXin Li       Params.push_back(Param);
12048*67e74705SXin Li     }
12049*67e74705SXin Li   }
12050*67e74705SXin Li 
12051*67e74705SXin Li   // Set the parameters on the block decl.
12052*67e74705SXin Li   if (!Params.empty()) {
12053*67e74705SXin Li     CurBlock->TheDecl->setParams(Params);
12054*67e74705SXin Li     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12055*67e74705SXin Li                              /*CheckParameterNames=*/false);
12056*67e74705SXin Li   }
12057*67e74705SXin Li 
12058*67e74705SXin Li   // Finally we can process decl attributes.
12059*67e74705SXin Li   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12060*67e74705SXin Li 
12061*67e74705SXin Li   // Put the parameter variables in scope.
12062*67e74705SXin Li   for (auto AI : CurBlock->TheDecl->parameters()) {
12063*67e74705SXin Li     AI->setOwningFunction(CurBlock->TheDecl);
12064*67e74705SXin Li 
12065*67e74705SXin Li     // If this has an identifier, add it to the scope stack.
12066*67e74705SXin Li     if (AI->getIdentifier()) {
12067*67e74705SXin Li       CheckShadow(CurBlock->TheScope, AI);
12068*67e74705SXin Li 
12069*67e74705SXin Li       PushOnScopeChains(AI, CurBlock->TheScope);
12070*67e74705SXin Li     }
12071*67e74705SXin Li   }
12072*67e74705SXin Li }
12073*67e74705SXin Li 
12074*67e74705SXin Li /// ActOnBlockError - If there is an error parsing a block, this callback
12075*67e74705SXin Li /// is invoked to pop the information about the block from the action impl.
ActOnBlockError(SourceLocation CaretLoc,Scope * CurScope)12076*67e74705SXin Li void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12077*67e74705SXin Li   // Leave the expression-evaluation context.
12078*67e74705SXin Li   DiscardCleanupsInEvaluationContext();
12079*67e74705SXin Li   PopExpressionEvaluationContext();
12080*67e74705SXin Li 
12081*67e74705SXin Li   // Pop off CurBlock, handle nested blocks.
12082*67e74705SXin Li   PopDeclContext();
12083*67e74705SXin Li   PopFunctionScopeInfo();
12084*67e74705SXin Li }
12085*67e74705SXin Li 
12086*67e74705SXin Li /// ActOnBlockStmtExpr - This is called when the body of a block statement
12087*67e74705SXin Li /// literal was successfully completed.  ^(int x){...}
ActOnBlockStmtExpr(SourceLocation CaretLoc,Stmt * Body,Scope * CurScope)12088*67e74705SXin Li ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12089*67e74705SXin Li                                     Stmt *Body, Scope *CurScope) {
12090*67e74705SXin Li   // If blocks are disabled, emit an error.
12091*67e74705SXin Li   if (!LangOpts.Blocks)
12092*67e74705SXin Li     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12093*67e74705SXin Li 
12094*67e74705SXin Li   // Leave the expression-evaluation context.
12095*67e74705SXin Li   if (hasAnyUnrecoverableErrorsInThisFunction())
12096*67e74705SXin Li     DiscardCleanupsInEvaluationContext();
12097*67e74705SXin Li   assert(!Cleanup.exprNeedsCleanups() &&
12098*67e74705SXin Li          "cleanups within block not correctly bound!");
12099*67e74705SXin Li   PopExpressionEvaluationContext();
12100*67e74705SXin Li 
12101*67e74705SXin Li   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12102*67e74705SXin Li 
12103*67e74705SXin Li   if (BSI->HasImplicitReturnType)
12104*67e74705SXin Li     deduceClosureReturnType(*BSI);
12105*67e74705SXin Li 
12106*67e74705SXin Li   PopDeclContext();
12107*67e74705SXin Li 
12108*67e74705SXin Li   QualType RetTy = Context.VoidTy;
12109*67e74705SXin Li   if (!BSI->ReturnType.isNull())
12110*67e74705SXin Li     RetTy = BSI->ReturnType;
12111*67e74705SXin Li 
12112*67e74705SXin Li   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12113*67e74705SXin Li   QualType BlockTy;
12114*67e74705SXin Li 
12115*67e74705SXin Li   // Set the captured variables on the block.
12116*67e74705SXin Li   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12117*67e74705SXin Li   SmallVector<BlockDecl::Capture, 4> Captures;
12118*67e74705SXin Li   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12119*67e74705SXin Li     if (Cap.isThisCapture())
12120*67e74705SXin Li       continue;
12121*67e74705SXin Li     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12122*67e74705SXin Li                               Cap.isNested(), Cap.getInitExpr());
12123*67e74705SXin Li     Captures.push_back(NewCap);
12124*67e74705SXin Li   }
12125*67e74705SXin Li   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12126*67e74705SXin Li 
12127*67e74705SXin Li   // If the user wrote a function type in some form, try to use that.
12128*67e74705SXin Li   if (!BSI->FunctionType.isNull()) {
12129*67e74705SXin Li     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12130*67e74705SXin Li 
12131*67e74705SXin Li     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12132*67e74705SXin Li     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12133*67e74705SXin Li 
12134*67e74705SXin Li     // Turn protoless block types into nullary block types.
12135*67e74705SXin Li     if (isa<FunctionNoProtoType>(FTy)) {
12136*67e74705SXin Li       FunctionProtoType::ExtProtoInfo EPI;
12137*67e74705SXin Li       EPI.ExtInfo = Ext;
12138*67e74705SXin Li       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12139*67e74705SXin Li 
12140*67e74705SXin Li     // Otherwise, if we don't need to change anything about the function type,
12141*67e74705SXin Li     // preserve its sugar structure.
12142*67e74705SXin Li     } else if (FTy->getReturnType() == RetTy &&
12143*67e74705SXin Li                (!NoReturn || FTy->getNoReturnAttr())) {
12144*67e74705SXin Li       BlockTy = BSI->FunctionType;
12145*67e74705SXin Li 
12146*67e74705SXin Li     // Otherwise, make the minimal modifications to the function type.
12147*67e74705SXin Li     } else {
12148*67e74705SXin Li       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12149*67e74705SXin Li       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12150*67e74705SXin Li       EPI.TypeQuals = 0; // FIXME: silently?
12151*67e74705SXin Li       EPI.ExtInfo = Ext;
12152*67e74705SXin Li       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12153*67e74705SXin Li     }
12154*67e74705SXin Li 
12155*67e74705SXin Li   // If we don't have a function type, just build one from nothing.
12156*67e74705SXin Li   } else {
12157*67e74705SXin Li     FunctionProtoType::ExtProtoInfo EPI;
12158*67e74705SXin Li     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12159*67e74705SXin Li     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12160*67e74705SXin Li   }
12161*67e74705SXin Li 
12162*67e74705SXin Li   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12163*67e74705SXin Li   BlockTy = Context.getBlockPointerType(BlockTy);
12164*67e74705SXin Li 
12165*67e74705SXin Li   // If needed, diagnose invalid gotos and switches in the block.
12166*67e74705SXin Li   if (getCurFunction()->NeedsScopeChecking() &&
12167*67e74705SXin Li       !PP.isCodeCompletionEnabled())
12168*67e74705SXin Li     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12169*67e74705SXin Li 
12170*67e74705SXin Li   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12171*67e74705SXin Li 
12172*67e74705SXin Li   // Try to apply the named return value optimization. We have to check again
12173*67e74705SXin Li   // if we can do this, though, because blocks keep return statements around
12174*67e74705SXin Li   // to deduce an implicit return type.
12175*67e74705SXin Li   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12176*67e74705SXin Li       !BSI->TheDecl->isDependentContext())
12177*67e74705SXin Li     computeNRVO(Body, BSI);
12178*67e74705SXin Li 
12179*67e74705SXin Li   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12180*67e74705SXin Li   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12181*67e74705SXin Li   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12182*67e74705SXin Li 
12183*67e74705SXin Li   // If the block isn't obviously global, i.e. it captures anything at
12184*67e74705SXin Li   // all, then we need to do a few things in the surrounding context:
12185*67e74705SXin Li   if (Result->getBlockDecl()->hasCaptures()) {
12186*67e74705SXin Li     // First, this expression has a new cleanup object.
12187*67e74705SXin Li     ExprCleanupObjects.push_back(Result->getBlockDecl());
12188*67e74705SXin Li     Cleanup.setExprNeedsCleanups(true);
12189*67e74705SXin Li 
12190*67e74705SXin Li     // It also gets a branch-protected scope if any of the captured
12191*67e74705SXin Li     // variables needs destruction.
12192*67e74705SXin Li     for (const auto &CI : Result->getBlockDecl()->captures()) {
12193*67e74705SXin Li       const VarDecl *var = CI.getVariable();
12194*67e74705SXin Li       if (var->getType().isDestructedType() != QualType::DK_none) {
12195*67e74705SXin Li         getCurFunction()->setHasBranchProtectedScope();
12196*67e74705SXin Li         break;
12197*67e74705SXin Li       }
12198*67e74705SXin Li     }
12199*67e74705SXin Li   }
12200*67e74705SXin Li 
12201*67e74705SXin Li   return Result;
12202*67e74705SXin Li }
12203*67e74705SXin Li 
ActOnVAArg(SourceLocation BuiltinLoc,Expr * E,ParsedType Ty,SourceLocation RPLoc)12204*67e74705SXin Li ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12205*67e74705SXin Li                             SourceLocation RPLoc) {
12206*67e74705SXin Li   TypeSourceInfo *TInfo;
12207*67e74705SXin Li   GetTypeFromParser(Ty, &TInfo);
12208*67e74705SXin Li   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12209*67e74705SXin Li }
12210*67e74705SXin Li 
BuildVAArgExpr(SourceLocation BuiltinLoc,Expr * E,TypeSourceInfo * TInfo,SourceLocation RPLoc)12211*67e74705SXin Li ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12212*67e74705SXin Li                                 Expr *E, TypeSourceInfo *TInfo,
12213*67e74705SXin Li                                 SourceLocation RPLoc) {
12214*67e74705SXin Li   Expr *OrigExpr = E;
12215*67e74705SXin Li   bool IsMS = false;
12216*67e74705SXin Li 
12217*67e74705SXin Li   // CUDA device code does not support varargs.
12218*67e74705SXin Li   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12219*67e74705SXin Li     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12220*67e74705SXin Li       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12221*67e74705SXin Li       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12222*67e74705SXin Li         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12223*67e74705SXin Li     }
12224*67e74705SXin Li   }
12225*67e74705SXin Li 
12226*67e74705SXin Li   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12227*67e74705SXin Li   // as Microsoft ABI on an actual Microsoft platform, where
12228*67e74705SXin Li   // __builtin_ms_va_list and __builtin_va_list are the same.)
12229*67e74705SXin Li   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12230*67e74705SXin Li       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12231*67e74705SXin Li     QualType MSVaListType = Context.getBuiltinMSVaListType();
12232*67e74705SXin Li     if (Context.hasSameType(MSVaListType, E->getType())) {
12233*67e74705SXin Li       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12234*67e74705SXin Li         return ExprError();
12235*67e74705SXin Li       IsMS = true;
12236*67e74705SXin Li     }
12237*67e74705SXin Li   }
12238*67e74705SXin Li 
12239*67e74705SXin Li   // Get the va_list type
12240*67e74705SXin Li   QualType VaListType = Context.getBuiltinVaListType();
12241*67e74705SXin Li   if (!IsMS) {
12242*67e74705SXin Li     if (VaListType->isArrayType()) {
12243*67e74705SXin Li       // Deal with implicit array decay; for example, on x86-64,
12244*67e74705SXin Li       // va_list is an array, but it's supposed to decay to
12245*67e74705SXin Li       // a pointer for va_arg.
12246*67e74705SXin Li       VaListType = Context.getArrayDecayedType(VaListType);
12247*67e74705SXin Li       // Make sure the input expression also decays appropriately.
12248*67e74705SXin Li       ExprResult Result = UsualUnaryConversions(E);
12249*67e74705SXin Li       if (Result.isInvalid())
12250*67e74705SXin Li         return ExprError();
12251*67e74705SXin Li       E = Result.get();
12252*67e74705SXin Li     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12253*67e74705SXin Li       // If va_list is a record type and we are compiling in C++ mode,
12254*67e74705SXin Li       // check the argument using reference binding.
12255*67e74705SXin Li       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12256*67e74705SXin Li           Context, Context.getLValueReferenceType(VaListType), false);
12257*67e74705SXin Li       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12258*67e74705SXin Li       if (Init.isInvalid())
12259*67e74705SXin Li         return ExprError();
12260*67e74705SXin Li       E = Init.getAs<Expr>();
12261*67e74705SXin Li     } else {
12262*67e74705SXin Li       // Otherwise, the va_list argument must be an l-value because
12263*67e74705SXin Li       // it is modified by va_arg.
12264*67e74705SXin Li       if (!E->isTypeDependent() &&
12265*67e74705SXin Li           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12266*67e74705SXin Li         return ExprError();
12267*67e74705SXin Li     }
12268*67e74705SXin Li   }
12269*67e74705SXin Li 
12270*67e74705SXin Li   if (!IsMS && !E->isTypeDependent() &&
12271*67e74705SXin Li       !Context.hasSameType(VaListType, E->getType()))
12272*67e74705SXin Li     return ExprError(Diag(E->getLocStart(),
12273*67e74705SXin Li                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12274*67e74705SXin Li       << OrigExpr->getType() << E->getSourceRange());
12275*67e74705SXin Li 
12276*67e74705SXin Li   if (!TInfo->getType()->isDependentType()) {
12277*67e74705SXin Li     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12278*67e74705SXin Li                             diag::err_second_parameter_to_va_arg_incomplete,
12279*67e74705SXin Li                             TInfo->getTypeLoc()))
12280*67e74705SXin Li       return ExprError();
12281*67e74705SXin Li 
12282*67e74705SXin Li     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12283*67e74705SXin Li                                TInfo->getType(),
12284*67e74705SXin Li                                diag::err_second_parameter_to_va_arg_abstract,
12285*67e74705SXin Li                                TInfo->getTypeLoc()))
12286*67e74705SXin Li       return ExprError();
12287*67e74705SXin Li 
12288*67e74705SXin Li     if (!TInfo->getType().isPODType(Context)) {
12289*67e74705SXin Li       Diag(TInfo->getTypeLoc().getBeginLoc(),
12290*67e74705SXin Li            TInfo->getType()->isObjCLifetimeType()
12291*67e74705SXin Li              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12292*67e74705SXin Li              : diag::warn_second_parameter_to_va_arg_not_pod)
12293*67e74705SXin Li         << TInfo->getType()
12294*67e74705SXin Li         << TInfo->getTypeLoc().getSourceRange();
12295*67e74705SXin Li     }
12296*67e74705SXin Li 
12297*67e74705SXin Li     // Check for va_arg where arguments of the given type will be promoted
12298*67e74705SXin Li     // (i.e. this va_arg is guaranteed to have undefined behavior).
12299*67e74705SXin Li     QualType PromoteType;
12300*67e74705SXin Li     if (TInfo->getType()->isPromotableIntegerType()) {
12301*67e74705SXin Li       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12302*67e74705SXin Li       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12303*67e74705SXin Li         PromoteType = QualType();
12304*67e74705SXin Li     }
12305*67e74705SXin Li     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12306*67e74705SXin Li       PromoteType = Context.DoubleTy;
12307*67e74705SXin Li     if (!PromoteType.isNull())
12308*67e74705SXin Li       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12309*67e74705SXin Li                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12310*67e74705SXin Li                           << TInfo->getType()
12311*67e74705SXin Li                           << PromoteType
12312*67e74705SXin Li                           << TInfo->getTypeLoc().getSourceRange());
12313*67e74705SXin Li   }
12314*67e74705SXin Li 
12315*67e74705SXin Li   QualType T = TInfo->getType().getNonLValueExprType(Context);
12316*67e74705SXin Li   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12317*67e74705SXin Li }
12318*67e74705SXin Li 
ActOnGNUNullExpr(SourceLocation TokenLoc)12319*67e74705SXin Li ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12320*67e74705SXin Li   // The type of __null will be int or long, depending on the size of
12321*67e74705SXin Li   // pointers on the target.
12322*67e74705SXin Li   QualType Ty;
12323*67e74705SXin Li   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12324*67e74705SXin Li   if (pw == Context.getTargetInfo().getIntWidth())
12325*67e74705SXin Li     Ty = Context.IntTy;
12326*67e74705SXin Li   else if (pw == Context.getTargetInfo().getLongWidth())
12327*67e74705SXin Li     Ty = Context.LongTy;
12328*67e74705SXin Li   else if (pw == Context.getTargetInfo().getLongLongWidth())
12329*67e74705SXin Li     Ty = Context.LongLongTy;
12330*67e74705SXin Li   else {
12331*67e74705SXin Li     llvm_unreachable("I don't know size of pointer!");
12332*67e74705SXin Li   }
12333*67e74705SXin Li 
12334*67e74705SXin Li   return new (Context) GNUNullExpr(Ty, TokenLoc);
12335*67e74705SXin Li }
12336*67e74705SXin Li 
ConversionToObjCStringLiteralCheck(QualType DstType,Expr * & Exp,bool Diagnose)12337*67e74705SXin Li bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12338*67e74705SXin Li                                               bool Diagnose) {
12339*67e74705SXin Li   if (!getLangOpts().ObjC1)
12340*67e74705SXin Li     return false;
12341*67e74705SXin Li 
12342*67e74705SXin Li   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12343*67e74705SXin Li   if (!PT)
12344*67e74705SXin Li     return false;
12345*67e74705SXin Li 
12346*67e74705SXin Li   if (!PT->isObjCIdType()) {
12347*67e74705SXin Li     // Check if the destination is the 'NSString' interface.
12348*67e74705SXin Li     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12349*67e74705SXin Li     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12350*67e74705SXin Li       return false;
12351*67e74705SXin Li   }
12352*67e74705SXin Li 
12353*67e74705SXin Li   // Ignore any parens, implicit casts (should only be
12354*67e74705SXin Li   // array-to-pointer decays), and not-so-opaque values.  The last is
12355*67e74705SXin Li   // important for making this trigger for property assignments.
12356*67e74705SXin Li   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12357*67e74705SXin Li   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12358*67e74705SXin Li     if (OV->getSourceExpr())
12359*67e74705SXin Li       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12360*67e74705SXin Li 
12361*67e74705SXin Li   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12362*67e74705SXin Li   if (!SL || !SL->isAscii())
12363*67e74705SXin Li     return false;
12364*67e74705SXin Li   if (Diagnose) {
12365*67e74705SXin Li     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12366*67e74705SXin Li       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12367*67e74705SXin Li     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12368*67e74705SXin Li   }
12369*67e74705SXin Li   return true;
12370*67e74705SXin Li }
12371*67e74705SXin Li 
maybeDiagnoseAssignmentToFunction(Sema & S,QualType DstType,const Expr * SrcExpr)12372*67e74705SXin Li static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12373*67e74705SXin Li                                               const Expr *SrcExpr) {
12374*67e74705SXin Li   if (!DstType->isFunctionPointerType() ||
12375*67e74705SXin Li       !SrcExpr->getType()->isFunctionType())
12376*67e74705SXin Li     return false;
12377*67e74705SXin Li 
12378*67e74705SXin Li   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12379*67e74705SXin Li   if (!DRE)
12380*67e74705SXin Li     return false;
12381*67e74705SXin Li 
12382*67e74705SXin Li   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12383*67e74705SXin Li   if (!FD)
12384*67e74705SXin Li     return false;
12385*67e74705SXin Li 
12386*67e74705SXin Li   return !S.checkAddressOfFunctionIsAvailable(FD,
12387*67e74705SXin Li                                               /*Complain=*/true,
12388*67e74705SXin Li                                               SrcExpr->getLocStart());
12389*67e74705SXin Li }
12390*67e74705SXin Li 
DiagnoseAssignmentResult(AssignConvertType ConvTy,SourceLocation Loc,QualType DstType,QualType SrcType,Expr * SrcExpr,AssignmentAction Action,bool * Complained)12391*67e74705SXin Li bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12392*67e74705SXin Li                                     SourceLocation Loc,
12393*67e74705SXin Li                                     QualType DstType, QualType SrcType,
12394*67e74705SXin Li                                     Expr *SrcExpr, AssignmentAction Action,
12395*67e74705SXin Li                                     bool *Complained) {
12396*67e74705SXin Li   if (Complained)
12397*67e74705SXin Li     *Complained = false;
12398*67e74705SXin Li 
12399*67e74705SXin Li   // Decode the result (notice that AST's are still created for extensions).
12400*67e74705SXin Li   bool CheckInferredResultType = false;
12401*67e74705SXin Li   bool isInvalid = false;
12402*67e74705SXin Li   unsigned DiagKind = 0;
12403*67e74705SXin Li   FixItHint Hint;
12404*67e74705SXin Li   ConversionFixItGenerator ConvHints;
12405*67e74705SXin Li   bool MayHaveConvFixit = false;
12406*67e74705SXin Li   bool MayHaveFunctionDiff = false;
12407*67e74705SXin Li   const ObjCInterfaceDecl *IFace = nullptr;
12408*67e74705SXin Li   const ObjCProtocolDecl *PDecl = nullptr;
12409*67e74705SXin Li 
12410*67e74705SXin Li   switch (ConvTy) {
12411*67e74705SXin Li   case Compatible:
12412*67e74705SXin Li       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12413*67e74705SXin Li       return false;
12414*67e74705SXin Li 
12415*67e74705SXin Li   case PointerToInt:
12416*67e74705SXin Li     DiagKind = diag::ext_typecheck_convert_pointer_int;
12417*67e74705SXin Li     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12418*67e74705SXin Li     MayHaveConvFixit = true;
12419*67e74705SXin Li     break;
12420*67e74705SXin Li   case IntToPointer:
12421*67e74705SXin Li     DiagKind = diag::ext_typecheck_convert_int_pointer;
12422*67e74705SXin Li     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12423*67e74705SXin Li     MayHaveConvFixit = true;
12424*67e74705SXin Li     break;
12425*67e74705SXin Li   case IncompatiblePointer:
12426*67e74705SXin Li       DiagKind =
12427*67e74705SXin Li         (Action == AA_Passing_CFAudited ?
12428*67e74705SXin Li           diag::err_arc_typecheck_convert_incompatible_pointer :
12429*67e74705SXin Li           diag::ext_typecheck_convert_incompatible_pointer);
12430*67e74705SXin Li     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12431*67e74705SXin Li       SrcType->isObjCObjectPointerType();
12432*67e74705SXin Li     if (Hint.isNull() && !CheckInferredResultType) {
12433*67e74705SXin Li       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12434*67e74705SXin Li     }
12435*67e74705SXin Li     else if (CheckInferredResultType) {
12436*67e74705SXin Li       SrcType = SrcType.getUnqualifiedType();
12437*67e74705SXin Li       DstType = DstType.getUnqualifiedType();
12438*67e74705SXin Li     }
12439*67e74705SXin Li     MayHaveConvFixit = true;
12440*67e74705SXin Li     break;
12441*67e74705SXin Li   case IncompatiblePointerSign:
12442*67e74705SXin Li     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12443*67e74705SXin Li     break;
12444*67e74705SXin Li   case FunctionVoidPointer:
12445*67e74705SXin Li     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12446*67e74705SXin Li     break;
12447*67e74705SXin Li   case IncompatiblePointerDiscardsQualifiers: {
12448*67e74705SXin Li     // Perform array-to-pointer decay if necessary.
12449*67e74705SXin Li     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12450*67e74705SXin Li 
12451*67e74705SXin Li     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12452*67e74705SXin Li     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12453*67e74705SXin Li     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12454*67e74705SXin Li       DiagKind = diag::err_typecheck_incompatible_address_space;
12455*67e74705SXin Li       break;
12456*67e74705SXin Li 
12457*67e74705SXin Li 
12458*67e74705SXin Li     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12459*67e74705SXin Li       DiagKind = diag::err_typecheck_incompatible_ownership;
12460*67e74705SXin Li       break;
12461*67e74705SXin Li     }
12462*67e74705SXin Li 
12463*67e74705SXin Li     llvm_unreachable("unknown error case for discarding qualifiers!");
12464*67e74705SXin Li     // fallthrough
12465*67e74705SXin Li   }
12466*67e74705SXin Li   case CompatiblePointerDiscardsQualifiers:
12467*67e74705SXin Li     // If the qualifiers lost were because we were applying the
12468*67e74705SXin Li     // (deprecated) C++ conversion from a string literal to a char*
12469*67e74705SXin Li     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12470*67e74705SXin Li     // Ideally, this check would be performed in
12471*67e74705SXin Li     // checkPointerTypesForAssignment. However, that would require a
12472*67e74705SXin Li     // bit of refactoring (so that the second argument is an
12473*67e74705SXin Li     // expression, rather than a type), which should be done as part
12474*67e74705SXin Li     // of a larger effort to fix checkPointerTypesForAssignment for
12475*67e74705SXin Li     // C++ semantics.
12476*67e74705SXin Li     if (getLangOpts().CPlusPlus &&
12477*67e74705SXin Li         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12478*67e74705SXin Li       return false;
12479*67e74705SXin Li     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12480*67e74705SXin Li     break;
12481*67e74705SXin Li   case IncompatibleNestedPointerQualifiers:
12482*67e74705SXin Li     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12483*67e74705SXin Li     break;
12484*67e74705SXin Li   case IntToBlockPointer:
12485*67e74705SXin Li     DiagKind = diag::err_int_to_block_pointer;
12486*67e74705SXin Li     break;
12487*67e74705SXin Li   case IncompatibleBlockPointer:
12488*67e74705SXin Li     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12489*67e74705SXin Li     break;
12490*67e74705SXin Li   case IncompatibleObjCQualifiedId: {
12491*67e74705SXin Li     if (SrcType->isObjCQualifiedIdType()) {
12492*67e74705SXin Li       const ObjCObjectPointerType *srcOPT =
12493*67e74705SXin Li                 SrcType->getAs<ObjCObjectPointerType>();
12494*67e74705SXin Li       for (auto *srcProto : srcOPT->quals()) {
12495*67e74705SXin Li         PDecl = srcProto;
12496*67e74705SXin Li         break;
12497*67e74705SXin Li       }
12498*67e74705SXin Li       if (const ObjCInterfaceType *IFaceT =
12499*67e74705SXin Li             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12500*67e74705SXin Li         IFace = IFaceT->getDecl();
12501*67e74705SXin Li     }
12502*67e74705SXin Li     else if (DstType->isObjCQualifiedIdType()) {
12503*67e74705SXin Li       const ObjCObjectPointerType *dstOPT =
12504*67e74705SXin Li         DstType->getAs<ObjCObjectPointerType>();
12505*67e74705SXin Li       for (auto *dstProto : dstOPT->quals()) {
12506*67e74705SXin Li         PDecl = dstProto;
12507*67e74705SXin Li         break;
12508*67e74705SXin Li       }
12509*67e74705SXin Li       if (const ObjCInterfaceType *IFaceT =
12510*67e74705SXin Li             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12511*67e74705SXin Li         IFace = IFaceT->getDecl();
12512*67e74705SXin Li     }
12513*67e74705SXin Li     DiagKind = diag::warn_incompatible_qualified_id;
12514*67e74705SXin Li     break;
12515*67e74705SXin Li   }
12516*67e74705SXin Li   case IncompatibleVectors:
12517*67e74705SXin Li     DiagKind = diag::warn_incompatible_vectors;
12518*67e74705SXin Li     break;
12519*67e74705SXin Li   case IncompatibleObjCWeakRef:
12520*67e74705SXin Li     DiagKind = diag::err_arc_weak_unavailable_assign;
12521*67e74705SXin Li     break;
12522*67e74705SXin Li   case Incompatible:
12523*67e74705SXin Li     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12524*67e74705SXin Li       if (Complained)
12525*67e74705SXin Li         *Complained = true;
12526*67e74705SXin Li       return true;
12527*67e74705SXin Li     }
12528*67e74705SXin Li 
12529*67e74705SXin Li     DiagKind = diag::err_typecheck_convert_incompatible;
12530*67e74705SXin Li     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12531*67e74705SXin Li     MayHaveConvFixit = true;
12532*67e74705SXin Li     isInvalid = true;
12533*67e74705SXin Li     MayHaveFunctionDiff = true;
12534*67e74705SXin Li     break;
12535*67e74705SXin Li   }
12536*67e74705SXin Li 
12537*67e74705SXin Li   QualType FirstType, SecondType;
12538*67e74705SXin Li   switch (Action) {
12539*67e74705SXin Li   case AA_Assigning:
12540*67e74705SXin Li   case AA_Initializing:
12541*67e74705SXin Li     // The destination type comes first.
12542*67e74705SXin Li     FirstType = DstType;
12543*67e74705SXin Li     SecondType = SrcType;
12544*67e74705SXin Li     break;
12545*67e74705SXin Li 
12546*67e74705SXin Li   case AA_Returning:
12547*67e74705SXin Li   case AA_Passing:
12548*67e74705SXin Li   case AA_Passing_CFAudited:
12549*67e74705SXin Li   case AA_Converting:
12550*67e74705SXin Li   case AA_Sending:
12551*67e74705SXin Li   case AA_Casting:
12552*67e74705SXin Li     // The source type comes first.
12553*67e74705SXin Li     FirstType = SrcType;
12554*67e74705SXin Li     SecondType = DstType;
12555*67e74705SXin Li     break;
12556*67e74705SXin Li   }
12557*67e74705SXin Li 
12558*67e74705SXin Li   PartialDiagnostic FDiag = PDiag(DiagKind);
12559*67e74705SXin Li   if (Action == AA_Passing_CFAudited)
12560*67e74705SXin Li     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12561*67e74705SXin Li   else
12562*67e74705SXin Li     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12563*67e74705SXin Li 
12564*67e74705SXin Li   // If we can fix the conversion, suggest the FixIts.
12565*67e74705SXin Li   assert(ConvHints.isNull() || Hint.isNull());
12566*67e74705SXin Li   if (!ConvHints.isNull()) {
12567*67e74705SXin Li     for (FixItHint &H : ConvHints.Hints)
12568*67e74705SXin Li       FDiag << H;
12569*67e74705SXin Li   } else {
12570*67e74705SXin Li     FDiag << Hint;
12571*67e74705SXin Li   }
12572*67e74705SXin Li   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12573*67e74705SXin Li 
12574*67e74705SXin Li   if (MayHaveFunctionDiff)
12575*67e74705SXin Li     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12576*67e74705SXin Li 
12577*67e74705SXin Li   Diag(Loc, FDiag);
12578*67e74705SXin Li   if (DiagKind == diag::warn_incompatible_qualified_id &&
12579*67e74705SXin Li       PDecl && IFace && !IFace->hasDefinition())
12580*67e74705SXin Li       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12581*67e74705SXin Li         << IFace->getName() << PDecl->getName();
12582*67e74705SXin Li 
12583*67e74705SXin Li   if (SecondType == Context.OverloadTy)
12584*67e74705SXin Li     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12585*67e74705SXin Li                               FirstType, /*TakingAddress=*/true);
12586*67e74705SXin Li 
12587*67e74705SXin Li   if (CheckInferredResultType)
12588*67e74705SXin Li     EmitRelatedResultTypeNote(SrcExpr);
12589*67e74705SXin Li 
12590*67e74705SXin Li   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12591*67e74705SXin Li     EmitRelatedResultTypeNoteForReturn(DstType);
12592*67e74705SXin Li 
12593*67e74705SXin Li   if (Complained)
12594*67e74705SXin Li     *Complained = true;
12595*67e74705SXin Li   return isInvalid;
12596*67e74705SXin Li }
12597*67e74705SXin Li 
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result)12598*67e74705SXin Li ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12599*67e74705SXin Li                                                  llvm::APSInt *Result) {
12600*67e74705SXin Li   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12601*67e74705SXin Li   public:
12602*67e74705SXin Li     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12603*67e74705SXin Li       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12604*67e74705SXin Li     }
12605*67e74705SXin Li   } Diagnoser;
12606*67e74705SXin Li 
12607*67e74705SXin Li   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12608*67e74705SXin Li }
12609*67e74705SXin Li 
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,unsigned DiagID,bool AllowFold)12610*67e74705SXin Li ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12611*67e74705SXin Li                                                  llvm::APSInt *Result,
12612*67e74705SXin Li                                                  unsigned DiagID,
12613*67e74705SXin Li                                                  bool AllowFold) {
12614*67e74705SXin Li   class IDDiagnoser : public VerifyICEDiagnoser {
12615*67e74705SXin Li     unsigned DiagID;
12616*67e74705SXin Li 
12617*67e74705SXin Li   public:
12618*67e74705SXin Li     IDDiagnoser(unsigned DiagID)
12619*67e74705SXin Li       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12620*67e74705SXin Li 
12621*67e74705SXin Li     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12622*67e74705SXin Li       S.Diag(Loc, DiagID) << SR;
12623*67e74705SXin Li     }
12624*67e74705SXin Li   } Diagnoser(DiagID);
12625*67e74705SXin Li 
12626*67e74705SXin Li   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12627*67e74705SXin Li }
12628*67e74705SXin Li 
diagnoseFold(Sema & S,SourceLocation Loc,SourceRange SR)12629*67e74705SXin Li void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12630*67e74705SXin Li                                             SourceRange SR) {
12631*67e74705SXin Li   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12632*67e74705SXin Li }
12633*67e74705SXin Li 
12634*67e74705SXin Li ExprResult
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,VerifyICEDiagnoser & Diagnoser,bool AllowFold)12635*67e74705SXin Li Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12636*67e74705SXin Li                                       VerifyICEDiagnoser &Diagnoser,
12637*67e74705SXin Li                                       bool AllowFold) {
12638*67e74705SXin Li   SourceLocation DiagLoc = E->getLocStart();
12639*67e74705SXin Li 
12640*67e74705SXin Li   if (getLangOpts().CPlusPlus11) {
12641*67e74705SXin Li     // C++11 [expr.const]p5:
12642*67e74705SXin Li     //   If an expression of literal class type is used in a context where an
12643*67e74705SXin Li     //   integral constant expression is required, then that class type shall
12644*67e74705SXin Li     //   have a single non-explicit conversion function to an integral or
12645*67e74705SXin Li     //   unscoped enumeration type
12646*67e74705SXin Li     ExprResult Converted;
12647*67e74705SXin Li     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12648*67e74705SXin Li     public:
12649*67e74705SXin Li       CXX11ConvertDiagnoser(bool Silent)
12650*67e74705SXin Li           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12651*67e74705SXin Li                                 Silent, true) {}
12652*67e74705SXin Li 
12653*67e74705SXin Li       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12654*67e74705SXin Li                                            QualType T) override {
12655*67e74705SXin Li         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12656*67e74705SXin Li       }
12657*67e74705SXin Li 
12658*67e74705SXin Li       SemaDiagnosticBuilder diagnoseIncomplete(
12659*67e74705SXin Li           Sema &S, SourceLocation Loc, QualType T) override {
12660*67e74705SXin Li         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12661*67e74705SXin Li       }
12662*67e74705SXin Li 
12663*67e74705SXin Li       SemaDiagnosticBuilder diagnoseExplicitConv(
12664*67e74705SXin Li           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12665*67e74705SXin Li         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12666*67e74705SXin Li       }
12667*67e74705SXin Li 
12668*67e74705SXin Li       SemaDiagnosticBuilder noteExplicitConv(
12669*67e74705SXin Li           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12670*67e74705SXin Li         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12671*67e74705SXin Li                  << ConvTy->isEnumeralType() << ConvTy;
12672*67e74705SXin Li       }
12673*67e74705SXin Li 
12674*67e74705SXin Li       SemaDiagnosticBuilder diagnoseAmbiguous(
12675*67e74705SXin Li           Sema &S, SourceLocation Loc, QualType T) override {
12676*67e74705SXin Li         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12677*67e74705SXin Li       }
12678*67e74705SXin Li 
12679*67e74705SXin Li       SemaDiagnosticBuilder noteAmbiguous(
12680*67e74705SXin Li           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12681*67e74705SXin Li         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12682*67e74705SXin Li                  << ConvTy->isEnumeralType() << ConvTy;
12683*67e74705SXin Li       }
12684*67e74705SXin Li 
12685*67e74705SXin Li       SemaDiagnosticBuilder diagnoseConversion(
12686*67e74705SXin Li           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12687*67e74705SXin Li         llvm_unreachable("conversion functions are permitted");
12688*67e74705SXin Li       }
12689*67e74705SXin Li     } ConvertDiagnoser(Diagnoser.Suppress);
12690*67e74705SXin Li 
12691*67e74705SXin Li     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12692*67e74705SXin Li                                                     ConvertDiagnoser);
12693*67e74705SXin Li     if (Converted.isInvalid())
12694*67e74705SXin Li       return Converted;
12695*67e74705SXin Li     E = Converted.get();
12696*67e74705SXin Li     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12697*67e74705SXin Li       return ExprError();
12698*67e74705SXin Li   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12699*67e74705SXin Li     // An ICE must be of integral or unscoped enumeration type.
12700*67e74705SXin Li     if (!Diagnoser.Suppress)
12701*67e74705SXin Li       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12702*67e74705SXin Li     return ExprError();
12703*67e74705SXin Li   }
12704*67e74705SXin Li 
12705*67e74705SXin Li   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12706*67e74705SXin Li   // in the non-ICE case.
12707*67e74705SXin Li   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12708*67e74705SXin Li     if (Result)
12709*67e74705SXin Li       *Result = E->EvaluateKnownConstInt(Context);
12710*67e74705SXin Li     return E;
12711*67e74705SXin Li   }
12712*67e74705SXin Li 
12713*67e74705SXin Li   Expr::EvalResult EvalResult;
12714*67e74705SXin Li   SmallVector<PartialDiagnosticAt, 8> Notes;
12715*67e74705SXin Li   EvalResult.Diag = &Notes;
12716*67e74705SXin Li 
12717*67e74705SXin Li   // Try to evaluate the expression, and produce diagnostics explaining why it's
12718*67e74705SXin Li   // not a constant expression as a side-effect.
12719*67e74705SXin Li   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12720*67e74705SXin Li                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12721*67e74705SXin Li 
12722*67e74705SXin Li   // In C++11, we can rely on diagnostics being produced for any expression
12723*67e74705SXin Li   // which is not a constant expression. If no diagnostics were produced, then
12724*67e74705SXin Li   // this is a constant expression.
12725*67e74705SXin Li   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12726*67e74705SXin Li     if (Result)
12727*67e74705SXin Li       *Result = EvalResult.Val.getInt();
12728*67e74705SXin Li     return E;
12729*67e74705SXin Li   }
12730*67e74705SXin Li 
12731*67e74705SXin Li   // If our only note is the usual "invalid subexpression" note, just point
12732*67e74705SXin Li   // the caret at its location rather than producing an essentially
12733*67e74705SXin Li   // redundant note.
12734*67e74705SXin Li   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12735*67e74705SXin Li         diag::note_invalid_subexpr_in_const_expr) {
12736*67e74705SXin Li     DiagLoc = Notes[0].first;
12737*67e74705SXin Li     Notes.clear();
12738*67e74705SXin Li   }
12739*67e74705SXin Li 
12740*67e74705SXin Li   if (!Folded || !AllowFold) {
12741*67e74705SXin Li     if (!Diagnoser.Suppress) {
12742*67e74705SXin Li       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12743*67e74705SXin Li       for (const PartialDiagnosticAt &Note : Notes)
12744*67e74705SXin Li         Diag(Note.first, Note.second);
12745*67e74705SXin Li     }
12746*67e74705SXin Li 
12747*67e74705SXin Li     return ExprError();
12748*67e74705SXin Li   }
12749*67e74705SXin Li 
12750*67e74705SXin Li   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12751*67e74705SXin Li   for (const PartialDiagnosticAt &Note : Notes)
12752*67e74705SXin Li     Diag(Note.first, Note.second);
12753*67e74705SXin Li 
12754*67e74705SXin Li   if (Result)
12755*67e74705SXin Li     *Result = EvalResult.Val.getInt();
12756*67e74705SXin Li   return E;
12757*67e74705SXin Li }
12758*67e74705SXin Li 
12759*67e74705SXin Li namespace {
12760*67e74705SXin Li   // Handle the case where we conclude a expression which we speculatively
12761*67e74705SXin Li   // considered to be unevaluated is actually evaluated.
12762*67e74705SXin Li   class TransformToPE : public TreeTransform<TransformToPE> {
12763*67e74705SXin Li     typedef TreeTransform<TransformToPE> BaseTransform;
12764*67e74705SXin Li 
12765*67e74705SXin Li   public:
TransformToPE(Sema & SemaRef)12766*67e74705SXin Li     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12767*67e74705SXin Li 
12768*67e74705SXin Li     // Make sure we redo semantic analysis
AlwaysRebuild()12769*67e74705SXin Li     bool AlwaysRebuild() { return true; }
12770*67e74705SXin Li 
12771*67e74705SXin Li     // Make sure we handle LabelStmts correctly.
12772*67e74705SXin Li     // FIXME: This does the right thing, but maybe we need a more general
12773*67e74705SXin Li     // fix to TreeTransform?
TransformLabelStmt(LabelStmt * S)12774*67e74705SXin Li     StmtResult TransformLabelStmt(LabelStmt *S) {
12775*67e74705SXin Li       S->getDecl()->setStmt(nullptr);
12776*67e74705SXin Li       return BaseTransform::TransformLabelStmt(S);
12777*67e74705SXin Li     }
12778*67e74705SXin Li 
12779*67e74705SXin Li     // We need to special-case DeclRefExprs referring to FieldDecls which
12780*67e74705SXin Li     // are not part of a member pointer formation; normal TreeTransforming
12781*67e74705SXin Li     // doesn't catch this case because of the way we represent them in the AST.
12782*67e74705SXin Li     // FIXME: This is a bit ugly; is it really the best way to handle this
12783*67e74705SXin Li     // case?
12784*67e74705SXin Li     //
12785*67e74705SXin Li     // Error on DeclRefExprs referring to FieldDecls.
TransformDeclRefExpr(DeclRefExpr * E)12786*67e74705SXin Li     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12787*67e74705SXin Li       if (isa<FieldDecl>(E->getDecl()) &&
12788*67e74705SXin Li           !SemaRef.isUnevaluatedContext())
12789*67e74705SXin Li         return SemaRef.Diag(E->getLocation(),
12790*67e74705SXin Li                             diag::err_invalid_non_static_member_use)
12791*67e74705SXin Li             << E->getDecl() << E->getSourceRange();
12792*67e74705SXin Li 
12793*67e74705SXin Li       return BaseTransform::TransformDeclRefExpr(E);
12794*67e74705SXin Li     }
12795*67e74705SXin Li 
12796*67e74705SXin Li     // Exception: filter out member pointer formation
TransformUnaryOperator(UnaryOperator * E)12797*67e74705SXin Li     ExprResult TransformUnaryOperator(UnaryOperator *E) {
12798*67e74705SXin Li       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12799*67e74705SXin Li         return E;
12800*67e74705SXin Li 
12801*67e74705SXin Li       return BaseTransform::TransformUnaryOperator(E);
12802*67e74705SXin Li     }
12803*67e74705SXin Li 
TransformLambdaExpr(LambdaExpr * E)12804*67e74705SXin Li     ExprResult TransformLambdaExpr(LambdaExpr *E) {
12805*67e74705SXin Li       // Lambdas never need to be transformed.
12806*67e74705SXin Li       return E;
12807*67e74705SXin Li     }
12808*67e74705SXin Li   };
12809*67e74705SXin Li }
12810*67e74705SXin Li 
TransformToPotentiallyEvaluated(Expr * E)12811*67e74705SXin Li ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12812*67e74705SXin Li   assert(isUnevaluatedContext() &&
12813*67e74705SXin Li          "Should only transform unevaluated expressions");
12814*67e74705SXin Li   ExprEvalContexts.back().Context =
12815*67e74705SXin Li       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12816*67e74705SXin Li   if (isUnevaluatedContext())
12817*67e74705SXin Li     return E;
12818*67e74705SXin Li   return TransformToPE(*this).TransformExpr(E);
12819*67e74705SXin Li }
12820*67e74705SXin Li 
12821*67e74705SXin Li void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,Decl * LambdaContextDecl,bool IsDecltype)12822*67e74705SXin Li Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12823*67e74705SXin Li                                       Decl *LambdaContextDecl,
12824*67e74705SXin Li                                       bool IsDecltype) {
12825*67e74705SXin Li   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
12826*67e74705SXin Li                                 LambdaContextDecl, IsDecltype);
12827*67e74705SXin Li   Cleanup.reset();
12828*67e74705SXin Li   if (!MaybeODRUseExprs.empty())
12829*67e74705SXin Li     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
12830*67e74705SXin Li }
12831*67e74705SXin Li 
12832*67e74705SXin Li void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,ReuseLambdaContextDecl_t,bool IsDecltype)12833*67e74705SXin Li Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12834*67e74705SXin Li                                       ReuseLambdaContextDecl_t,
12835*67e74705SXin Li                                       bool IsDecltype) {
12836*67e74705SXin Li   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12837*67e74705SXin Li   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
12838*67e74705SXin Li }
12839*67e74705SXin Li 
PopExpressionEvaluationContext()12840*67e74705SXin Li void Sema::PopExpressionEvaluationContext() {
12841*67e74705SXin Li   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
12842*67e74705SXin Li   unsigned NumTypos = Rec.NumTypos;
12843*67e74705SXin Li 
12844*67e74705SXin Li   if (!Rec.Lambdas.empty()) {
12845*67e74705SXin Li     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12846*67e74705SXin Li       unsigned D;
12847*67e74705SXin Li       if (Rec.isUnevaluated()) {
12848*67e74705SXin Li         // C++11 [expr.prim.lambda]p2:
12849*67e74705SXin Li         //   A lambda-expression shall not appear in an unevaluated operand
12850*67e74705SXin Li         //   (Clause 5).
12851*67e74705SXin Li         D = diag::err_lambda_unevaluated_operand;
12852*67e74705SXin Li       } else {
12853*67e74705SXin Li         // C++1y [expr.const]p2:
12854*67e74705SXin Li         //   A conditional-expression e is a core constant expression unless the
12855*67e74705SXin Li         //   evaluation of e, following the rules of the abstract machine, would
12856*67e74705SXin Li         //   evaluate [...] a lambda-expression.
12857*67e74705SXin Li         D = diag::err_lambda_in_constant_expression;
12858*67e74705SXin Li       }
12859*67e74705SXin Li       for (const auto *L : Rec.Lambdas)
12860*67e74705SXin Li         Diag(L->getLocStart(), D);
12861*67e74705SXin Li     } else {
12862*67e74705SXin Li       // Mark the capture expressions odr-used. This was deferred
12863*67e74705SXin Li       // during lambda expression creation.
12864*67e74705SXin Li       for (auto *Lambda : Rec.Lambdas) {
12865*67e74705SXin Li         for (auto *C : Lambda->capture_inits())
12866*67e74705SXin Li           MarkDeclarationsReferencedInExpr(C);
12867*67e74705SXin Li       }
12868*67e74705SXin Li     }
12869*67e74705SXin Li   }
12870*67e74705SXin Li 
12871*67e74705SXin Li   // When are coming out of an unevaluated context, clear out any
12872*67e74705SXin Li   // temporaries that we may have created as part of the evaluation of
12873*67e74705SXin Li   // the expression in that context: they aren't relevant because they
12874*67e74705SXin Li   // will never be constructed.
12875*67e74705SXin Li   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12876*67e74705SXin Li     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12877*67e74705SXin Li                              ExprCleanupObjects.end());
12878*67e74705SXin Li     Cleanup = Rec.ParentCleanup;
12879*67e74705SXin Li     CleanupVarDeclMarking();
12880*67e74705SXin Li     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
12881*67e74705SXin Li   // Otherwise, merge the contexts together.
12882*67e74705SXin Li   } else {
12883*67e74705SXin Li     Cleanup.mergeFrom(Rec.ParentCleanup);
12884*67e74705SXin Li     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12885*67e74705SXin Li                             Rec.SavedMaybeODRUseExprs.end());
12886*67e74705SXin Li   }
12887*67e74705SXin Li 
12888*67e74705SXin Li   // Pop the current expression evaluation context off the stack.
12889*67e74705SXin Li   ExprEvalContexts.pop_back();
12890*67e74705SXin Li 
12891*67e74705SXin Li   if (!ExprEvalContexts.empty())
12892*67e74705SXin Li     ExprEvalContexts.back().NumTypos += NumTypos;
12893*67e74705SXin Li   else
12894*67e74705SXin Li     assert(NumTypos == 0 && "There are outstanding typos after popping the "
12895*67e74705SXin Li                             "last ExpressionEvaluationContextRecord");
12896*67e74705SXin Li }
12897*67e74705SXin Li 
DiscardCleanupsInEvaluationContext()12898*67e74705SXin Li void Sema::DiscardCleanupsInEvaluationContext() {
12899*67e74705SXin Li   ExprCleanupObjects.erase(
12900*67e74705SXin Li          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12901*67e74705SXin Li          ExprCleanupObjects.end());
12902*67e74705SXin Li   Cleanup.reset();
12903*67e74705SXin Li   MaybeODRUseExprs.clear();
12904*67e74705SXin Li }
12905*67e74705SXin Li 
HandleExprEvaluationContextForTypeof(Expr * E)12906*67e74705SXin Li ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12907*67e74705SXin Li   if (!E->getType()->isVariablyModifiedType())
12908*67e74705SXin Li     return E;
12909*67e74705SXin Li   return TransformToPotentiallyEvaluated(E);
12910*67e74705SXin Li }
12911*67e74705SXin Li 
IsPotentiallyEvaluatedContext(Sema & SemaRef)12912*67e74705SXin Li static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
12913*67e74705SXin Li   // Do not mark anything as "used" within a dependent context; wait for
12914*67e74705SXin Li   // an instantiation.
12915*67e74705SXin Li   if (SemaRef.CurContext->isDependentContext())
12916*67e74705SXin Li     return false;
12917*67e74705SXin Li 
12918*67e74705SXin Li   switch (SemaRef.ExprEvalContexts.back().Context) {
12919*67e74705SXin Li     case Sema::Unevaluated:
12920*67e74705SXin Li     case Sema::UnevaluatedAbstract:
12921*67e74705SXin Li       // We are in an expression that is not potentially evaluated; do nothing.
12922*67e74705SXin Li       // (Depending on how you read the standard, we actually do need to do
12923*67e74705SXin Li       // something here for null pointer constants, but the standard's
12924*67e74705SXin Li       // definition of a null pointer constant is completely crazy.)
12925*67e74705SXin Li       return false;
12926*67e74705SXin Li 
12927*67e74705SXin Li     case Sema::DiscardedStatement:
12928*67e74705SXin Li       // These are technically a potentially evaluated but they have the effect
12929*67e74705SXin Li       // of suppressing use marking.
12930*67e74705SXin Li       return false;
12931*67e74705SXin Li 
12932*67e74705SXin Li     case Sema::ConstantEvaluated:
12933*67e74705SXin Li     case Sema::PotentiallyEvaluated:
12934*67e74705SXin Li       // We are in a potentially evaluated expression (or a constant-expression
12935*67e74705SXin Li       // in C++03); we need to do implicit template instantiation, implicitly
12936*67e74705SXin Li       // define class members, and mark most declarations as used.
12937*67e74705SXin Li       return true;
12938*67e74705SXin Li 
12939*67e74705SXin Li     case Sema::PotentiallyEvaluatedIfUsed:
12940*67e74705SXin Li       // Referenced declarations will only be used if the construct in the
12941*67e74705SXin Li       // containing expression is used.
12942*67e74705SXin Li       return false;
12943*67e74705SXin Li   }
12944*67e74705SXin Li   llvm_unreachable("Invalid context");
12945*67e74705SXin Li }
12946*67e74705SXin Li 
12947*67e74705SXin Li /// \brief Mark a function referenced, and check whether it is odr-used
12948*67e74705SXin Li /// (C++ [basic.def.odr]p2, C99 6.9p3)
MarkFunctionReferenced(SourceLocation Loc,FunctionDecl * Func,bool MightBeOdrUse)12949*67e74705SXin Li void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
12950*67e74705SXin Li                                   bool MightBeOdrUse) {
12951*67e74705SXin Li   assert(Func && "No function?");
12952*67e74705SXin Li 
12953*67e74705SXin Li   Func->setReferenced();
12954*67e74705SXin Li 
12955*67e74705SXin Li   // C++11 [basic.def.odr]p3:
12956*67e74705SXin Li   //   A function whose name appears as a potentially-evaluated expression is
12957*67e74705SXin Li   //   odr-used if it is the unique lookup result or the selected member of a
12958*67e74705SXin Li   //   set of overloaded functions [...].
12959*67e74705SXin Li   //
12960*67e74705SXin Li   // We (incorrectly) mark overload resolution as an unevaluated context, so we
12961*67e74705SXin Li   // can just check that here.
12962*67e74705SXin Li   bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
12963*67e74705SXin Li 
12964*67e74705SXin Li   // Determine whether we require a function definition to exist, per
12965*67e74705SXin Li   // C++11 [temp.inst]p3:
12966*67e74705SXin Li   //   Unless a function template specialization has been explicitly
12967*67e74705SXin Li   //   instantiated or explicitly specialized, the function template
12968*67e74705SXin Li   //   specialization is implicitly instantiated when the specialization is
12969*67e74705SXin Li   //   referenced in a context that requires a function definition to exist.
12970*67e74705SXin Li   //
12971*67e74705SXin Li   // We consider constexpr function templates to be referenced in a context
12972*67e74705SXin Li   // that requires a definition to exist whenever they are referenced.
12973*67e74705SXin Li   //
12974*67e74705SXin Li   // FIXME: This instantiates constexpr functions too frequently. If this is
12975*67e74705SXin Li   // really an unevaluated context (and we're not just in the definition of a
12976*67e74705SXin Li   // function template or overload resolution or other cases which we
12977*67e74705SXin Li   // incorrectly consider to be unevaluated contexts), and we're not in a
12978*67e74705SXin Li   // subexpression which we actually need to evaluate (for instance, a
12979*67e74705SXin Li   // template argument, array bound or an expression in a braced-init-list),
12980*67e74705SXin Li   // we are not permitted to instantiate this constexpr function definition.
12981*67e74705SXin Li   //
12982*67e74705SXin Li   // FIXME: This also implicitly defines special members too frequently. They
12983*67e74705SXin Li   // are only supposed to be implicitly defined if they are odr-used, but they
12984*67e74705SXin Li   // are not odr-used from constant expressions in unevaluated contexts.
12985*67e74705SXin Li   // However, they cannot be referenced if they are deleted, and they are
12986*67e74705SXin Li   // deleted whenever the implicit definition of the special member would
12987*67e74705SXin Li   // fail (with very few exceptions).
12988*67e74705SXin Li   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12989*67e74705SXin Li   bool NeedDefinition =
12990*67e74705SXin Li       OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
12991*67e74705SXin Li                                          (MD && !MD->isUserProvided())));
12992*67e74705SXin Li 
12993*67e74705SXin Li   // C++14 [temp.expl.spec]p6:
12994*67e74705SXin Li   //   If a template [...] is explicitly specialized then that specialization
12995*67e74705SXin Li   //   shall be declared before the first use of that specialization that would
12996*67e74705SXin Li   //   cause an implicit instantiation to take place, in every translation unit
12997*67e74705SXin Li   //   in which such a use occurs
12998*67e74705SXin Li   if (NeedDefinition &&
12999*67e74705SXin Li       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13000*67e74705SXin Li        Func->getMemberSpecializationInfo()))
13001*67e74705SXin Li     checkSpecializationVisibility(Loc, Func);
13002*67e74705SXin Li 
13003*67e74705SXin Li   // If we don't need to mark the function as used, and we don't need to
13004*67e74705SXin Li   // try to provide a definition, there's nothing more to do.
13005*67e74705SXin Li   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13006*67e74705SXin Li       (!NeedDefinition || Func->getBody()))
13007*67e74705SXin Li     return;
13008*67e74705SXin Li 
13009*67e74705SXin Li   // Note that this declaration has been used.
13010*67e74705SXin Li   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13011*67e74705SXin Li     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13012*67e74705SXin Li     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13013*67e74705SXin Li       if (Constructor->isDefaultConstructor()) {
13014*67e74705SXin Li         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13015*67e74705SXin Li           return;
13016*67e74705SXin Li         DefineImplicitDefaultConstructor(Loc, Constructor);
13017*67e74705SXin Li       } else if (Constructor->isCopyConstructor()) {
13018*67e74705SXin Li         DefineImplicitCopyConstructor(Loc, Constructor);
13019*67e74705SXin Li       } else if (Constructor->isMoveConstructor()) {
13020*67e74705SXin Li         DefineImplicitMoveConstructor(Loc, Constructor);
13021*67e74705SXin Li       }
13022*67e74705SXin Li     } else if (Constructor->getInheritedConstructor()) {
13023*67e74705SXin Li       DefineInheritingConstructor(Loc, Constructor);
13024*67e74705SXin Li     }
13025*67e74705SXin Li   } else if (CXXDestructorDecl *Destructor =
13026*67e74705SXin Li                  dyn_cast<CXXDestructorDecl>(Func)) {
13027*67e74705SXin Li     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13028*67e74705SXin Li     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13029*67e74705SXin Li       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13030*67e74705SXin Li         return;
13031*67e74705SXin Li       DefineImplicitDestructor(Loc, Destructor);
13032*67e74705SXin Li     }
13033*67e74705SXin Li     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13034*67e74705SXin Li       MarkVTableUsed(Loc, Destructor->getParent());
13035*67e74705SXin Li   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13036*67e74705SXin Li     if (MethodDecl->isOverloadedOperator() &&
13037*67e74705SXin Li         MethodDecl->getOverloadedOperator() == OO_Equal) {
13038*67e74705SXin Li       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13039*67e74705SXin Li       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13040*67e74705SXin Li         if (MethodDecl->isCopyAssignmentOperator())
13041*67e74705SXin Li           DefineImplicitCopyAssignment(Loc, MethodDecl);
13042*67e74705SXin Li         else if (MethodDecl->isMoveAssignmentOperator())
13043*67e74705SXin Li           DefineImplicitMoveAssignment(Loc, MethodDecl);
13044*67e74705SXin Li       }
13045*67e74705SXin Li     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13046*67e74705SXin Li                MethodDecl->getParent()->isLambda()) {
13047*67e74705SXin Li       CXXConversionDecl *Conversion =
13048*67e74705SXin Li           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13049*67e74705SXin Li       if (Conversion->isLambdaToBlockPointerConversion())
13050*67e74705SXin Li         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13051*67e74705SXin Li       else
13052*67e74705SXin Li         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13053*67e74705SXin Li     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13054*67e74705SXin Li       MarkVTableUsed(Loc, MethodDecl->getParent());
13055*67e74705SXin Li   }
13056*67e74705SXin Li 
13057*67e74705SXin Li   // Recursive functions should be marked when used from another function.
13058*67e74705SXin Li   // FIXME: Is this really right?
13059*67e74705SXin Li   if (CurContext == Func) return;
13060*67e74705SXin Li 
13061*67e74705SXin Li   // Resolve the exception specification for any function which is
13062*67e74705SXin Li   // used: CodeGen will need it.
13063*67e74705SXin Li   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13064*67e74705SXin Li   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13065*67e74705SXin Li     ResolveExceptionSpec(Loc, FPT);
13066*67e74705SXin Li 
13067*67e74705SXin Li   // Implicit instantiation of function templates and member functions of
13068*67e74705SXin Li   // class templates.
13069*67e74705SXin Li   if (Func->isImplicitlyInstantiable()) {
13070*67e74705SXin Li     bool AlreadyInstantiated = false;
13071*67e74705SXin Li     SourceLocation PointOfInstantiation = Loc;
13072*67e74705SXin Li     if (FunctionTemplateSpecializationInfo *SpecInfo
13073*67e74705SXin Li                               = Func->getTemplateSpecializationInfo()) {
13074*67e74705SXin Li       if (SpecInfo->getPointOfInstantiation().isInvalid())
13075*67e74705SXin Li         SpecInfo->setPointOfInstantiation(Loc);
13076*67e74705SXin Li       else if (SpecInfo->getTemplateSpecializationKind()
13077*67e74705SXin Li                  == TSK_ImplicitInstantiation) {
13078*67e74705SXin Li         AlreadyInstantiated = true;
13079*67e74705SXin Li         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13080*67e74705SXin Li       }
13081*67e74705SXin Li     } else if (MemberSpecializationInfo *MSInfo
13082*67e74705SXin Li                                 = Func->getMemberSpecializationInfo()) {
13083*67e74705SXin Li       if (MSInfo->getPointOfInstantiation().isInvalid())
13084*67e74705SXin Li         MSInfo->setPointOfInstantiation(Loc);
13085*67e74705SXin Li       else if (MSInfo->getTemplateSpecializationKind()
13086*67e74705SXin Li                  == TSK_ImplicitInstantiation) {
13087*67e74705SXin Li         AlreadyInstantiated = true;
13088*67e74705SXin Li         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13089*67e74705SXin Li       }
13090*67e74705SXin Li     }
13091*67e74705SXin Li 
13092*67e74705SXin Li     if (!AlreadyInstantiated || Func->isConstexpr()) {
13093*67e74705SXin Li       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13094*67e74705SXin Li           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13095*67e74705SXin Li           ActiveTemplateInstantiations.size())
13096*67e74705SXin Li         PendingLocalImplicitInstantiations.push_back(
13097*67e74705SXin Li             std::make_pair(Func, PointOfInstantiation));
13098*67e74705SXin Li       else if (Func->isConstexpr())
13099*67e74705SXin Li         // Do not defer instantiations of constexpr functions, to avoid the
13100*67e74705SXin Li         // expression evaluator needing to call back into Sema if it sees a
13101*67e74705SXin Li         // call to such a function.
13102*67e74705SXin Li         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13103*67e74705SXin Li       else {
13104*67e74705SXin Li         PendingInstantiations.push_back(std::make_pair(Func,
13105*67e74705SXin Li                                                        PointOfInstantiation));
13106*67e74705SXin Li         // Notify the consumer that a function was implicitly instantiated.
13107*67e74705SXin Li         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13108*67e74705SXin Li       }
13109*67e74705SXin Li     }
13110*67e74705SXin Li   } else {
13111*67e74705SXin Li     // Walk redefinitions, as some of them may be instantiable.
13112*67e74705SXin Li     for (auto i : Func->redecls()) {
13113*67e74705SXin Li       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13114*67e74705SXin Li         MarkFunctionReferenced(Loc, i, OdrUse);
13115*67e74705SXin Li     }
13116*67e74705SXin Li   }
13117*67e74705SXin Li 
13118*67e74705SXin Li   if (!OdrUse) return;
13119*67e74705SXin Li 
13120*67e74705SXin Li   // Keep track of used but undefined functions.
13121*67e74705SXin Li   if (!Func->isDefined()) {
13122*67e74705SXin Li     if (mightHaveNonExternalLinkage(Func))
13123*67e74705SXin Li       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13124*67e74705SXin Li     else if (Func->getMostRecentDecl()->isInlined() &&
13125*67e74705SXin Li              !LangOpts.GNUInline &&
13126*67e74705SXin Li              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13127*67e74705SXin Li       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13128*67e74705SXin Li   }
13129*67e74705SXin Li 
13130*67e74705SXin Li   Func->markUsed(Context);
13131*67e74705SXin Li }
13132*67e74705SXin Li 
13133*67e74705SXin Li static void
diagnoseUncapturableValueReference(Sema & S,SourceLocation loc,VarDecl * var,DeclContext * DC)13134*67e74705SXin Li diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13135*67e74705SXin Li                                    VarDecl *var, DeclContext *DC) {
13136*67e74705SXin Li   DeclContext *VarDC = var->getDeclContext();
13137*67e74705SXin Li 
13138*67e74705SXin Li   //  If the parameter still belongs to the translation unit, then
13139*67e74705SXin Li   //  we're actually just using one parameter in the declaration of
13140*67e74705SXin Li   //  the next.
13141*67e74705SXin Li   if (isa<ParmVarDecl>(var) &&
13142*67e74705SXin Li       isa<TranslationUnitDecl>(VarDC))
13143*67e74705SXin Li     return;
13144*67e74705SXin Li 
13145*67e74705SXin Li   // For C code, don't diagnose about capture if we're not actually in code
13146*67e74705SXin Li   // right now; it's impossible to write a non-constant expression outside of
13147*67e74705SXin Li   // function context, so we'll get other (more useful) diagnostics later.
13148*67e74705SXin Li   //
13149*67e74705SXin Li   // For C++, things get a bit more nasty... it would be nice to suppress this
13150*67e74705SXin Li   // diagnostic for certain cases like using a local variable in an array bound
13151*67e74705SXin Li   // for a member of a local class, but the correct predicate is not obvious.
13152*67e74705SXin Li   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13153*67e74705SXin Li     return;
13154*67e74705SXin Li 
13155*67e74705SXin Li   if (isa<CXXMethodDecl>(VarDC) &&
13156*67e74705SXin Li       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13157*67e74705SXin Li     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
13158*67e74705SXin Li       << var->getIdentifier();
13159*67e74705SXin Li   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
13160*67e74705SXin Li     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
13161*67e74705SXin Li       << var->getIdentifier() << fn->getDeclName();
13162*67e74705SXin Li   } else if (isa<BlockDecl>(VarDC)) {
13163*67e74705SXin Li     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
13164*67e74705SXin Li       << var->getIdentifier();
13165*67e74705SXin Li   } else {
13166*67e74705SXin Li     // FIXME: Is there any other context where a local variable can be
13167*67e74705SXin Li     // declared?
13168*67e74705SXin Li     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
13169*67e74705SXin Li       << var->getIdentifier();
13170*67e74705SXin Li   }
13171*67e74705SXin Li 
13172*67e74705SXin Li   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13173*67e74705SXin Li       << var->getIdentifier();
13174*67e74705SXin Li 
13175*67e74705SXin Li   // FIXME: Add additional diagnostic info about class etc. which prevents
13176*67e74705SXin Li   // capture.
13177*67e74705SXin Li }
13178*67e74705SXin Li 
13179*67e74705SXin Li 
isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo * CSI,VarDecl * Var,bool & SubCapturesAreNested,QualType & CaptureType,QualType & DeclRefType)13180*67e74705SXin Li static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13181*67e74705SXin Li                                       bool &SubCapturesAreNested,
13182*67e74705SXin Li                                       QualType &CaptureType,
13183*67e74705SXin Li                                       QualType &DeclRefType) {
13184*67e74705SXin Li    // Check whether we've already captured it.
13185*67e74705SXin Li   if (CSI->CaptureMap.count(Var)) {
13186*67e74705SXin Li     // If we found a capture, any subcaptures are nested.
13187*67e74705SXin Li     SubCapturesAreNested = true;
13188*67e74705SXin Li 
13189*67e74705SXin Li     // Retrieve the capture type for this variable.
13190*67e74705SXin Li     CaptureType = CSI->getCapture(Var).getCaptureType();
13191*67e74705SXin Li 
13192*67e74705SXin Li     // Compute the type of an expression that refers to this variable.
13193*67e74705SXin Li     DeclRefType = CaptureType.getNonReferenceType();
13194*67e74705SXin Li 
13195*67e74705SXin Li     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13196*67e74705SXin Li     // are mutable in the sense that user can change their value - they are
13197*67e74705SXin Li     // private instances of the captured declarations.
13198*67e74705SXin Li     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13199*67e74705SXin Li     if (Cap.isCopyCapture() &&
13200*67e74705SXin Li         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13201*67e74705SXin Li         !(isa<CapturedRegionScopeInfo>(CSI) &&
13202*67e74705SXin Li           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13203*67e74705SXin Li       DeclRefType.addConst();
13204*67e74705SXin Li     return true;
13205*67e74705SXin Li   }
13206*67e74705SXin Li   return false;
13207*67e74705SXin Li }
13208*67e74705SXin Li 
13209*67e74705SXin Li // Only block literals, captured statements, and lambda expressions can
13210*67e74705SXin Li // capture; other scopes don't work.
getParentOfCapturingContextOrNull(DeclContext * DC,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)13211*67e74705SXin Li static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13212*67e74705SXin Li                                  SourceLocation Loc,
13213*67e74705SXin Li                                  const bool Diagnose, Sema &S) {
13214*67e74705SXin Li   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13215*67e74705SXin Li     return getLambdaAwareParentOfDeclContext(DC);
13216*67e74705SXin Li   else if (Var->hasLocalStorage()) {
13217*67e74705SXin Li     if (Diagnose)
13218*67e74705SXin Li        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13219*67e74705SXin Li   }
13220*67e74705SXin Li   return nullptr;
13221*67e74705SXin Li }
13222*67e74705SXin Li 
13223*67e74705SXin Li // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13224*67e74705SXin Li // certain types of variables (unnamed, variably modified types etc.)
13225*67e74705SXin Li // so check for eligibility.
isVariableCapturable(CapturingScopeInfo * CSI,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)13226*67e74705SXin Li static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13227*67e74705SXin Li                                  SourceLocation Loc,
13228*67e74705SXin Li                                  const bool Diagnose, Sema &S) {
13229*67e74705SXin Li 
13230*67e74705SXin Li   bool IsBlock = isa<BlockScopeInfo>(CSI);
13231*67e74705SXin Li   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13232*67e74705SXin Li 
13233*67e74705SXin Li   // Lambdas are not allowed to capture unnamed variables
13234*67e74705SXin Li   // (e.g. anonymous unions).
13235*67e74705SXin Li   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13236*67e74705SXin Li   // assuming that's the intent.
13237*67e74705SXin Li   if (IsLambda && !Var->getDeclName()) {
13238*67e74705SXin Li     if (Diagnose) {
13239*67e74705SXin Li       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13240*67e74705SXin Li       S.Diag(Var->getLocation(), diag::note_declared_at);
13241*67e74705SXin Li     }
13242*67e74705SXin Li     return false;
13243*67e74705SXin Li   }
13244*67e74705SXin Li 
13245*67e74705SXin Li   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13246*67e74705SXin Li   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13247*67e74705SXin Li     if (Diagnose) {
13248*67e74705SXin Li       S.Diag(Loc, diag::err_ref_vm_type);
13249*67e74705SXin Li       S.Diag(Var->getLocation(), diag::note_previous_decl)
13250*67e74705SXin Li         << Var->getDeclName();
13251*67e74705SXin Li     }
13252*67e74705SXin Li     return false;
13253*67e74705SXin Li   }
13254*67e74705SXin Li   // Prohibit structs with flexible array members too.
13255*67e74705SXin Li   // We cannot capture what is in the tail end of the struct.
13256*67e74705SXin Li   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13257*67e74705SXin Li     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13258*67e74705SXin Li       if (Diagnose) {
13259*67e74705SXin Li         if (IsBlock)
13260*67e74705SXin Li           S.Diag(Loc, diag::err_ref_flexarray_type);
13261*67e74705SXin Li         else
13262*67e74705SXin Li           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13263*67e74705SXin Li             << Var->getDeclName();
13264*67e74705SXin Li         S.Diag(Var->getLocation(), diag::note_previous_decl)
13265*67e74705SXin Li           << Var->getDeclName();
13266*67e74705SXin Li       }
13267*67e74705SXin Li       return false;
13268*67e74705SXin Li     }
13269*67e74705SXin Li   }
13270*67e74705SXin Li   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13271*67e74705SXin Li   // Lambdas and captured statements are not allowed to capture __block
13272*67e74705SXin Li   // variables; they don't support the expected semantics.
13273*67e74705SXin Li   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13274*67e74705SXin Li     if (Diagnose) {
13275*67e74705SXin Li       S.Diag(Loc, diag::err_capture_block_variable)
13276*67e74705SXin Li         << Var->getDeclName() << !IsLambda;
13277*67e74705SXin Li       S.Diag(Var->getLocation(), diag::note_previous_decl)
13278*67e74705SXin Li         << Var->getDeclName();
13279*67e74705SXin Li     }
13280*67e74705SXin Li     return false;
13281*67e74705SXin Li   }
13282*67e74705SXin Li 
13283*67e74705SXin Li   return true;
13284*67e74705SXin Li }
13285*67e74705SXin Li 
13286*67e74705SXin Li // Returns true if the capture by block was successful.
captureInBlock(BlockScopeInfo * BSI,VarDecl * Var,SourceLocation Loc,const bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const bool Nested,Sema & S)13287*67e74705SXin Li static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13288*67e74705SXin Li                                  SourceLocation Loc,
13289*67e74705SXin Li                                  const bool BuildAndDiagnose,
13290*67e74705SXin Li                                  QualType &CaptureType,
13291*67e74705SXin Li                                  QualType &DeclRefType,
13292*67e74705SXin Li                                  const bool Nested,
13293*67e74705SXin Li                                  Sema &S) {
13294*67e74705SXin Li   Expr *CopyExpr = nullptr;
13295*67e74705SXin Li   bool ByRef = false;
13296*67e74705SXin Li 
13297*67e74705SXin Li   // Blocks are not allowed to capture arrays.
13298*67e74705SXin Li   if (CaptureType->isArrayType()) {
13299*67e74705SXin Li     if (BuildAndDiagnose) {
13300*67e74705SXin Li       S.Diag(Loc, diag::err_ref_array_type);
13301*67e74705SXin Li       S.Diag(Var->getLocation(), diag::note_previous_decl)
13302*67e74705SXin Li       << Var->getDeclName();
13303*67e74705SXin Li     }
13304*67e74705SXin Li     return false;
13305*67e74705SXin Li   }
13306*67e74705SXin Li 
13307*67e74705SXin Li   // Forbid the block-capture of autoreleasing variables.
13308*67e74705SXin Li   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13309*67e74705SXin Li     if (BuildAndDiagnose) {
13310*67e74705SXin Li       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13311*67e74705SXin Li         << /*block*/ 0;
13312*67e74705SXin Li       S.Diag(Var->getLocation(), diag::note_previous_decl)
13313*67e74705SXin Li         << Var->getDeclName();
13314*67e74705SXin Li     }
13315*67e74705SXin Li     return false;
13316*67e74705SXin Li   }
13317*67e74705SXin Li   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13318*67e74705SXin Li   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13319*67e74705SXin Li       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13320*67e74705SXin Li     // Block capture by reference does not change the capture or
13321*67e74705SXin Li     // declaration reference types.
13322*67e74705SXin Li     ByRef = true;
13323*67e74705SXin Li   } else {
13324*67e74705SXin Li     // Block capture by copy introduces 'const'.
13325*67e74705SXin Li     CaptureType = CaptureType.getNonReferenceType().withConst();
13326*67e74705SXin Li     DeclRefType = CaptureType;
13327*67e74705SXin Li 
13328*67e74705SXin Li     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13329*67e74705SXin Li       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13330*67e74705SXin Li         // The capture logic needs the destructor, so make sure we mark it.
13331*67e74705SXin Li         // Usually this is unnecessary because most local variables have
13332*67e74705SXin Li         // their destructors marked at declaration time, but parameters are
13333*67e74705SXin Li         // an exception because it's technically only the call site that
13334*67e74705SXin Li         // actually requires the destructor.
13335*67e74705SXin Li         if (isa<ParmVarDecl>(Var))
13336*67e74705SXin Li           S.FinalizeVarWithDestructor(Var, Record);
13337*67e74705SXin Li 
13338*67e74705SXin Li         // Enter a new evaluation context to insulate the copy
13339*67e74705SXin Li         // full-expression.
13340*67e74705SXin Li         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13341*67e74705SXin Li 
13342*67e74705SXin Li         // According to the blocks spec, the capture of a variable from
13343*67e74705SXin Li         // the stack requires a const copy constructor.  This is not true
13344*67e74705SXin Li         // of the copy/move done to move a __block variable to the heap.
13345*67e74705SXin Li         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13346*67e74705SXin Li                                                   DeclRefType.withConst(),
13347*67e74705SXin Li                                                   VK_LValue, Loc);
13348*67e74705SXin Li 
13349*67e74705SXin Li         ExprResult Result
13350*67e74705SXin Li           = S.PerformCopyInitialization(
13351*67e74705SXin Li               InitializedEntity::InitializeBlock(Var->getLocation(),
13352*67e74705SXin Li                                                   CaptureType, false),
13353*67e74705SXin Li               Loc, DeclRef);
13354*67e74705SXin Li 
13355*67e74705SXin Li         // Build a full-expression copy expression if initialization
13356*67e74705SXin Li         // succeeded and used a non-trivial constructor.  Recover from
13357*67e74705SXin Li         // errors by pretending that the copy isn't necessary.
13358*67e74705SXin Li         if (!Result.isInvalid() &&
13359*67e74705SXin Li             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13360*67e74705SXin Li                 ->isTrivial()) {
13361*67e74705SXin Li           Result = S.MaybeCreateExprWithCleanups(Result);
13362*67e74705SXin Li           CopyExpr = Result.get();
13363*67e74705SXin Li         }
13364*67e74705SXin Li       }
13365*67e74705SXin Li     }
13366*67e74705SXin Li   }
13367*67e74705SXin Li 
13368*67e74705SXin Li   // Actually capture the variable.
13369*67e74705SXin Li   if (BuildAndDiagnose)
13370*67e74705SXin Li     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13371*67e74705SXin Li                     SourceLocation(), CaptureType, CopyExpr);
13372*67e74705SXin Li 
13373*67e74705SXin Li   return true;
13374*67e74705SXin Li 
13375*67e74705SXin Li }
13376*67e74705SXin Li 
13377*67e74705SXin Li 
13378*67e74705SXin Li /// \brief Capture the given variable in the captured region.
captureInCapturedRegion(CapturedRegionScopeInfo * RSI,VarDecl * Var,SourceLocation Loc,const bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const bool RefersToCapturedVariable,Sema & S)13379*67e74705SXin Li static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13380*67e74705SXin Li                                     VarDecl *Var,
13381*67e74705SXin Li                                     SourceLocation Loc,
13382*67e74705SXin Li                                     const bool BuildAndDiagnose,
13383*67e74705SXin Li                                     QualType &CaptureType,
13384*67e74705SXin Li                                     QualType &DeclRefType,
13385*67e74705SXin Li                                     const bool RefersToCapturedVariable,
13386*67e74705SXin Li                                     Sema &S) {
13387*67e74705SXin Li   // By default, capture variables by reference.
13388*67e74705SXin Li   bool ByRef = true;
13389*67e74705SXin Li   // Using an LValue reference type is consistent with Lambdas (see below).
13390*67e74705SXin Li   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13391*67e74705SXin Li     if (S.IsOpenMPCapturedDecl(Var))
13392*67e74705SXin Li       DeclRefType = DeclRefType.getUnqualifiedType();
13393*67e74705SXin Li     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13394*67e74705SXin Li   }
13395*67e74705SXin Li 
13396*67e74705SXin Li   if (ByRef)
13397*67e74705SXin Li     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13398*67e74705SXin Li   else
13399*67e74705SXin Li     CaptureType = DeclRefType;
13400*67e74705SXin Li 
13401*67e74705SXin Li   Expr *CopyExpr = nullptr;
13402*67e74705SXin Li   if (BuildAndDiagnose) {
13403*67e74705SXin Li     // The current implementation assumes that all variables are captured
13404*67e74705SXin Li     // by references. Since there is no capture by copy, no expression
13405*67e74705SXin Li     // evaluation will be needed.
13406*67e74705SXin Li     RecordDecl *RD = RSI->TheRecordDecl;
13407*67e74705SXin Li 
13408*67e74705SXin Li     FieldDecl *Field
13409*67e74705SXin Li       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13410*67e74705SXin Li                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13411*67e74705SXin Li                           nullptr, false, ICIS_NoInit);
13412*67e74705SXin Li     Field->setImplicit(true);
13413*67e74705SXin Li     Field->setAccess(AS_private);
13414*67e74705SXin Li     RD->addDecl(Field);
13415*67e74705SXin Li 
13416*67e74705SXin Li     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13417*67e74705SXin Li                                             DeclRefType, VK_LValue, Loc);
13418*67e74705SXin Li     Var->setReferenced(true);
13419*67e74705SXin Li     Var->markUsed(S.Context);
13420*67e74705SXin Li   }
13421*67e74705SXin Li 
13422*67e74705SXin Li   // Actually capture the variable.
13423*67e74705SXin Li   if (BuildAndDiagnose)
13424*67e74705SXin Li     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13425*67e74705SXin Li                     SourceLocation(), CaptureType, CopyExpr);
13426*67e74705SXin Li 
13427*67e74705SXin Li 
13428*67e74705SXin Li   return true;
13429*67e74705SXin Li }
13430*67e74705SXin Li 
13431*67e74705SXin Li /// \brief Create a field within the lambda class for the variable
13432*67e74705SXin Li /// being captured.
addAsFieldToClosureType(Sema & S,LambdaScopeInfo * LSI,QualType FieldType,QualType DeclRefType,SourceLocation Loc,bool RefersToCapturedVariable)13433*67e74705SXin Li static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13434*67e74705SXin Li                                     QualType FieldType, QualType DeclRefType,
13435*67e74705SXin Li                                     SourceLocation Loc,
13436*67e74705SXin Li                                     bool RefersToCapturedVariable) {
13437*67e74705SXin Li   CXXRecordDecl *Lambda = LSI->Lambda;
13438*67e74705SXin Li 
13439*67e74705SXin Li   // Build the non-static data member.
13440*67e74705SXin Li   FieldDecl *Field
13441*67e74705SXin Li     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13442*67e74705SXin Li                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13443*67e74705SXin Li                         nullptr, false, ICIS_NoInit);
13444*67e74705SXin Li   Field->setImplicit(true);
13445*67e74705SXin Li   Field->setAccess(AS_private);
13446*67e74705SXin Li   Lambda->addDecl(Field);
13447*67e74705SXin Li }
13448*67e74705SXin Li 
13449*67e74705SXin Li /// \brief Capture the given variable in the lambda.
captureInLambda(LambdaScopeInfo * LSI,VarDecl * Var,SourceLocation Loc,const bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const bool RefersToCapturedVariable,const Sema::TryCaptureKind Kind,SourceLocation EllipsisLoc,const bool IsTopScope,Sema & S)13450*67e74705SXin Li static bool captureInLambda(LambdaScopeInfo *LSI,
13451*67e74705SXin Li                             VarDecl *Var,
13452*67e74705SXin Li                             SourceLocation Loc,
13453*67e74705SXin Li                             const bool BuildAndDiagnose,
13454*67e74705SXin Li                             QualType &CaptureType,
13455*67e74705SXin Li                             QualType &DeclRefType,
13456*67e74705SXin Li                             const bool RefersToCapturedVariable,
13457*67e74705SXin Li                             const Sema::TryCaptureKind Kind,
13458*67e74705SXin Li                             SourceLocation EllipsisLoc,
13459*67e74705SXin Li                             const bool IsTopScope,
13460*67e74705SXin Li                             Sema &S) {
13461*67e74705SXin Li 
13462*67e74705SXin Li   // Determine whether we are capturing by reference or by value.
13463*67e74705SXin Li   bool ByRef = false;
13464*67e74705SXin Li   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13465*67e74705SXin Li     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13466*67e74705SXin Li   } else {
13467*67e74705SXin Li     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13468*67e74705SXin Li   }
13469*67e74705SXin Li 
13470*67e74705SXin Li   // Compute the type of the field that will capture this variable.
13471*67e74705SXin Li   if (ByRef) {
13472*67e74705SXin Li     // C++11 [expr.prim.lambda]p15:
13473*67e74705SXin Li     //   An entity is captured by reference if it is implicitly or
13474*67e74705SXin Li     //   explicitly captured but not captured by copy. It is
13475*67e74705SXin Li     //   unspecified whether additional unnamed non-static data
13476*67e74705SXin Li     //   members are declared in the closure type for entities
13477*67e74705SXin Li     //   captured by reference.
13478*67e74705SXin Li     //
13479*67e74705SXin Li     // FIXME: It is not clear whether we want to build an lvalue reference
13480*67e74705SXin Li     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13481*67e74705SXin Li     // to do the former, while EDG does the latter. Core issue 1249 will
13482*67e74705SXin Li     // clarify, but for now we follow GCC because it's a more permissive and
13483*67e74705SXin Li     // easily defensible position.
13484*67e74705SXin Li     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13485*67e74705SXin Li   } else {
13486*67e74705SXin Li     // C++11 [expr.prim.lambda]p14:
13487*67e74705SXin Li     //   For each entity captured by copy, an unnamed non-static
13488*67e74705SXin Li     //   data member is declared in the closure type. The
13489*67e74705SXin Li     //   declaration order of these members is unspecified. The type
13490*67e74705SXin Li     //   of such a data member is the type of the corresponding
13491*67e74705SXin Li     //   captured entity if the entity is not a reference to an
13492*67e74705SXin Li     //   object, or the referenced type otherwise. [Note: If the
13493*67e74705SXin Li     //   captured entity is a reference to a function, the
13494*67e74705SXin Li     //   corresponding data member is also a reference to a
13495*67e74705SXin Li     //   function. - end note ]
13496*67e74705SXin Li     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13497*67e74705SXin Li       if (!RefType->getPointeeType()->isFunctionType())
13498*67e74705SXin Li         CaptureType = RefType->getPointeeType();
13499*67e74705SXin Li     }
13500*67e74705SXin Li 
13501*67e74705SXin Li     // Forbid the lambda copy-capture of autoreleasing variables.
13502*67e74705SXin Li     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13503*67e74705SXin Li       if (BuildAndDiagnose) {
13504*67e74705SXin Li         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13505*67e74705SXin Li         S.Diag(Var->getLocation(), diag::note_previous_decl)
13506*67e74705SXin Li           << Var->getDeclName();
13507*67e74705SXin Li       }
13508*67e74705SXin Li       return false;
13509*67e74705SXin Li     }
13510*67e74705SXin Li 
13511*67e74705SXin Li     // Make sure that by-copy captures are of a complete and non-abstract type.
13512*67e74705SXin Li     if (BuildAndDiagnose) {
13513*67e74705SXin Li       if (!CaptureType->isDependentType() &&
13514*67e74705SXin Li           S.RequireCompleteType(Loc, CaptureType,
13515*67e74705SXin Li                                 diag::err_capture_of_incomplete_type,
13516*67e74705SXin Li                                 Var->getDeclName()))
13517*67e74705SXin Li         return false;
13518*67e74705SXin Li 
13519*67e74705SXin Li       if (S.RequireNonAbstractType(Loc, CaptureType,
13520*67e74705SXin Li                                    diag::err_capture_of_abstract_type))
13521*67e74705SXin Li         return false;
13522*67e74705SXin Li     }
13523*67e74705SXin Li   }
13524*67e74705SXin Li 
13525*67e74705SXin Li   // Capture this variable in the lambda.
13526*67e74705SXin Li   if (BuildAndDiagnose)
13527*67e74705SXin Li     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13528*67e74705SXin Li                             RefersToCapturedVariable);
13529*67e74705SXin Li 
13530*67e74705SXin Li   // Compute the type of a reference to this captured variable.
13531*67e74705SXin Li   if (ByRef)
13532*67e74705SXin Li     DeclRefType = CaptureType.getNonReferenceType();
13533*67e74705SXin Li   else {
13534*67e74705SXin Li     // C++ [expr.prim.lambda]p5:
13535*67e74705SXin Li     //   The closure type for a lambda-expression has a public inline
13536*67e74705SXin Li     //   function call operator [...]. This function call operator is
13537*67e74705SXin Li     //   declared const (9.3.1) if and only if the lambda-expression’s
13538*67e74705SXin Li     //   parameter-declaration-clause is not followed by mutable.
13539*67e74705SXin Li     DeclRefType = CaptureType.getNonReferenceType();
13540*67e74705SXin Li     if (!LSI->Mutable && !CaptureType->isReferenceType())
13541*67e74705SXin Li       DeclRefType.addConst();
13542*67e74705SXin Li   }
13543*67e74705SXin Li 
13544*67e74705SXin Li   // Add the capture.
13545*67e74705SXin Li   if (BuildAndDiagnose)
13546*67e74705SXin Li     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13547*67e74705SXin Li                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13548*67e74705SXin Li 
13549*67e74705SXin Li   return true;
13550*67e74705SXin Li }
13551*67e74705SXin Li 
tryCaptureVariable(VarDecl * Var,SourceLocation ExprLoc,TryCaptureKind Kind,SourceLocation EllipsisLoc,bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const unsigned * const FunctionScopeIndexToStopAt)13552*67e74705SXin Li bool Sema::tryCaptureVariable(
13553*67e74705SXin Li     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13554*67e74705SXin Li     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13555*67e74705SXin Li     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13556*67e74705SXin Li   // An init-capture is notionally from the context surrounding its
13557*67e74705SXin Li   // declaration, but its parent DC is the lambda class.
13558*67e74705SXin Li   DeclContext *VarDC = Var->getDeclContext();
13559*67e74705SXin Li   if (Var->isInitCapture())
13560*67e74705SXin Li     VarDC = VarDC->getParent();
13561*67e74705SXin Li 
13562*67e74705SXin Li   DeclContext *DC = CurContext;
13563*67e74705SXin Li   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13564*67e74705SXin Li       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13565*67e74705SXin Li   // We need to sync up the Declaration Context with the
13566*67e74705SXin Li   // FunctionScopeIndexToStopAt
13567*67e74705SXin Li   if (FunctionScopeIndexToStopAt) {
13568*67e74705SXin Li     unsigned FSIndex = FunctionScopes.size() - 1;
13569*67e74705SXin Li     while (FSIndex != MaxFunctionScopesIndex) {
13570*67e74705SXin Li       DC = getLambdaAwareParentOfDeclContext(DC);
13571*67e74705SXin Li       --FSIndex;
13572*67e74705SXin Li     }
13573*67e74705SXin Li   }
13574*67e74705SXin Li 
13575*67e74705SXin Li 
13576*67e74705SXin Li   // If the variable is declared in the current context, there is no need to
13577*67e74705SXin Li   // capture it.
13578*67e74705SXin Li   if (VarDC == DC) return true;
13579*67e74705SXin Li 
13580*67e74705SXin Li   // Capture global variables if it is required to use private copy of this
13581*67e74705SXin Li   // variable.
13582*67e74705SXin Li   bool IsGlobal = !Var->hasLocalStorage();
13583*67e74705SXin Li   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13584*67e74705SXin Li     return true;
13585*67e74705SXin Li 
13586*67e74705SXin Li   // Walk up the stack to determine whether we can capture the variable,
13587*67e74705SXin Li   // performing the "simple" checks that don't depend on type. We stop when
13588*67e74705SXin Li   // we've either hit the declared scope of the variable or find an existing
13589*67e74705SXin Li   // capture of that variable.  We start from the innermost capturing-entity
13590*67e74705SXin Li   // (the DC) and ensure that all intervening capturing-entities
13591*67e74705SXin Li   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13592*67e74705SXin Li   // declcontext can either capture the variable or have already captured
13593*67e74705SXin Li   // the variable.
13594*67e74705SXin Li   CaptureType = Var->getType();
13595*67e74705SXin Li   DeclRefType = CaptureType.getNonReferenceType();
13596*67e74705SXin Li   bool Nested = false;
13597*67e74705SXin Li   bool Explicit = (Kind != TryCapture_Implicit);
13598*67e74705SXin Li   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13599*67e74705SXin Li   do {
13600*67e74705SXin Li     // Only block literals, captured statements, and lambda expressions can
13601*67e74705SXin Li     // capture; other scopes don't work.
13602*67e74705SXin Li     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13603*67e74705SXin Li                                                               ExprLoc,
13604*67e74705SXin Li                                                               BuildAndDiagnose,
13605*67e74705SXin Li                                                               *this);
13606*67e74705SXin Li     // We need to check for the parent *first* because, if we *have*
13607*67e74705SXin Li     // private-captured a global variable, we need to recursively capture it in
13608*67e74705SXin Li     // intermediate blocks, lambdas, etc.
13609*67e74705SXin Li     if (!ParentDC) {
13610*67e74705SXin Li       if (IsGlobal) {
13611*67e74705SXin Li         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13612*67e74705SXin Li         break;
13613*67e74705SXin Li       }
13614*67e74705SXin Li       return true;
13615*67e74705SXin Li     }
13616*67e74705SXin Li 
13617*67e74705SXin Li     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13618*67e74705SXin Li     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13619*67e74705SXin Li 
13620*67e74705SXin Li 
13621*67e74705SXin Li     // Check whether we've already captured it.
13622*67e74705SXin Li     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13623*67e74705SXin Li                                              DeclRefType))
13624*67e74705SXin Li       break;
13625*67e74705SXin Li     // If we are instantiating a generic lambda call operator body,
13626*67e74705SXin Li     // we do not want to capture new variables.  What was captured
13627*67e74705SXin Li     // during either a lambdas transformation or initial parsing
13628*67e74705SXin Li     // should be used.
13629*67e74705SXin Li     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13630*67e74705SXin Li       if (BuildAndDiagnose) {
13631*67e74705SXin Li         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13632*67e74705SXin Li         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13633*67e74705SXin Li           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13634*67e74705SXin Li           Diag(Var->getLocation(), diag::note_previous_decl)
13635*67e74705SXin Li              << Var->getDeclName();
13636*67e74705SXin Li           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13637*67e74705SXin Li         } else
13638*67e74705SXin Li           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13639*67e74705SXin Li       }
13640*67e74705SXin Li       return true;
13641*67e74705SXin Li     }
13642*67e74705SXin Li     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13643*67e74705SXin Li     // certain types of variables (unnamed, variably modified types etc.)
13644*67e74705SXin Li     // so check for eligibility.
13645*67e74705SXin Li     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13646*67e74705SXin Li        return true;
13647*67e74705SXin Li 
13648*67e74705SXin Li     // Try to capture variable-length arrays types.
13649*67e74705SXin Li     if (Var->getType()->isVariablyModifiedType()) {
13650*67e74705SXin Li       // We're going to walk down into the type and look for VLA
13651*67e74705SXin Li       // expressions.
13652*67e74705SXin Li       QualType QTy = Var->getType();
13653*67e74705SXin Li       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13654*67e74705SXin Li         QTy = PVD->getOriginalType();
13655*67e74705SXin Li       captureVariablyModifiedType(Context, QTy, CSI);
13656*67e74705SXin Li     }
13657*67e74705SXin Li 
13658*67e74705SXin Li     if (getLangOpts().OpenMP) {
13659*67e74705SXin Li       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13660*67e74705SXin Li         // OpenMP private variables should not be captured in outer scope, so
13661*67e74705SXin Li         // just break here. Similarly, global variables that are captured in a
13662*67e74705SXin Li         // target region should not be captured outside the scope of the region.
13663*67e74705SXin Li         if (RSI->CapRegionKind == CR_OpenMP) {
13664*67e74705SXin Li           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13665*67e74705SXin Li           // When we detect target captures we are looking from inside the
13666*67e74705SXin Li           // target region, therefore we need to propagate the capture from the
13667*67e74705SXin Li           // enclosing region. Therefore, the capture is not initially nested.
13668*67e74705SXin Li           if (IsTargetCap)
13669*67e74705SXin Li             FunctionScopesIndex--;
13670*67e74705SXin Li 
13671*67e74705SXin Li           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13672*67e74705SXin Li             Nested = !IsTargetCap;
13673*67e74705SXin Li             DeclRefType = DeclRefType.getUnqualifiedType();
13674*67e74705SXin Li             CaptureType = Context.getLValueReferenceType(DeclRefType);
13675*67e74705SXin Li             break;
13676*67e74705SXin Li           }
13677*67e74705SXin Li         }
13678*67e74705SXin Li       }
13679*67e74705SXin Li     }
13680*67e74705SXin Li     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13681*67e74705SXin Li       // No capture-default, and this is not an explicit capture
13682*67e74705SXin Li       // so cannot capture this variable.
13683*67e74705SXin Li       if (BuildAndDiagnose) {
13684*67e74705SXin Li         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13685*67e74705SXin Li         Diag(Var->getLocation(), diag::note_previous_decl)
13686*67e74705SXin Li           << Var->getDeclName();
13687*67e74705SXin Li         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13688*67e74705SXin Li           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13689*67e74705SXin Li                diag::note_lambda_decl);
13690*67e74705SXin Li         // FIXME: If we error out because an outer lambda can not implicitly
13691*67e74705SXin Li         // capture a variable that an inner lambda explicitly captures, we
13692*67e74705SXin Li         // should have the inner lambda do the explicit capture - because
13693*67e74705SXin Li         // it makes for cleaner diagnostics later.  This would purely be done
13694*67e74705SXin Li         // so that the diagnostic does not misleadingly claim that a variable
13695*67e74705SXin Li         // can not be captured by a lambda implicitly even though it is captured
13696*67e74705SXin Li         // explicitly.  Suggestion:
13697*67e74705SXin Li         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13698*67e74705SXin Li         //    at the function head
13699*67e74705SXin Li         //  - cache the StartingDeclContext - this must be a lambda
13700*67e74705SXin Li         //  - captureInLambda in the innermost lambda the variable.
13701*67e74705SXin Li       }
13702*67e74705SXin Li       return true;
13703*67e74705SXin Li     }
13704*67e74705SXin Li 
13705*67e74705SXin Li     FunctionScopesIndex--;
13706*67e74705SXin Li     DC = ParentDC;
13707*67e74705SXin Li     Explicit = false;
13708*67e74705SXin Li   } while (!VarDC->Equals(DC));
13709*67e74705SXin Li 
13710*67e74705SXin Li   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13711*67e74705SXin Li   // computing the type of the capture at each step, checking type-specific
13712*67e74705SXin Li   // requirements, and adding captures if requested.
13713*67e74705SXin Li   // If the variable had already been captured previously, we start capturing
13714*67e74705SXin Li   // at the lambda nested within that one.
13715*67e74705SXin Li   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13716*67e74705SXin Li        ++I) {
13717*67e74705SXin Li     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13718*67e74705SXin Li 
13719*67e74705SXin Li     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13720*67e74705SXin Li       if (!captureInBlock(BSI, Var, ExprLoc,
13721*67e74705SXin Li                           BuildAndDiagnose, CaptureType,
13722*67e74705SXin Li                           DeclRefType, Nested, *this))
13723*67e74705SXin Li         return true;
13724*67e74705SXin Li       Nested = true;
13725*67e74705SXin Li     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13726*67e74705SXin Li       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13727*67e74705SXin Li                                    BuildAndDiagnose, CaptureType,
13728*67e74705SXin Li                                    DeclRefType, Nested, *this))
13729*67e74705SXin Li         return true;
13730*67e74705SXin Li       Nested = true;
13731*67e74705SXin Li     } else {
13732*67e74705SXin Li       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13733*67e74705SXin Li       if (!captureInLambda(LSI, Var, ExprLoc,
13734*67e74705SXin Li                            BuildAndDiagnose, CaptureType,
13735*67e74705SXin Li                            DeclRefType, Nested, Kind, EllipsisLoc,
13736*67e74705SXin Li                             /*IsTopScope*/I == N - 1, *this))
13737*67e74705SXin Li         return true;
13738*67e74705SXin Li       Nested = true;
13739*67e74705SXin Li     }
13740*67e74705SXin Li   }
13741*67e74705SXin Li   return false;
13742*67e74705SXin Li }
13743*67e74705SXin Li 
tryCaptureVariable(VarDecl * Var,SourceLocation Loc,TryCaptureKind Kind,SourceLocation EllipsisLoc)13744*67e74705SXin Li bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13745*67e74705SXin Li                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13746*67e74705SXin Li   QualType CaptureType;
13747*67e74705SXin Li   QualType DeclRefType;
13748*67e74705SXin Li   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13749*67e74705SXin Li                             /*BuildAndDiagnose=*/true, CaptureType,
13750*67e74705SXin Li                             DeclRefType, nullptr);
13751*67e74705SXin Li }
13752*67e74705SXin Li 
NeedToCaptureVariable(VarDecl * Var,SourceLocation Loc)13753*67e74705SXin Li bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13754*67e74705SXin Li   QualType CaptureType;
13755*67e74705SXin Li   QualType DeclRefType;
13756*67e74705SXin Li   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13757*67e74705SXin Li                              /*BuildAndDiagnose=*/false, CaptureType,
13758*67e74705SXin Li                              DeclRefType, nullptr);
13759*67e74705SXin Li }
13760*67e74705SXin Li 
getCapturedDeclRefType(VarDecl * Var,SourceLocation Loc)13761*67e74705SXin Li QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13762*67e74705SXin Li   QualType CaptureType;
13763*67e74705SXin Li   QualType DeclRefType;
13764*67e74705SXin Li 
13765*67e74705SXin Li   // Determine whether we can capture this variable.
13766*67e74705SXin Li   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13767*67e74705SXin Li                          /*BuildAndDiagnose=*/false, CaptureType,
13768*67e74705SXin Li                          DeclRefType, nullptr))
13769*67e74705SXin Li     return QualType();
13770*67e74705SXin Li 
13771*67e74705SXin Li   return DeclRefType;
13772*67e74705SXin Li }
13773*67e74705SXin Li 
13774*67e74705SXin Li 
13775*67e74705SXin Li 
13776*67e74705SXin Li // If either the type of the variable or the initializer is dependent,
13777*67e74705SXin Li // return false. Otherwise, determine whether the variable is a constant
13778*67e74705SXin Li // expression. Use this if you need to know if a variable that might or
13779*67e74705SXin Li // might not be dependent is truly a constant expression.
IsVariableNonDependentAndAConstantExpression(VarDecl * Var,ASTContext & Context)13780*67e74705SXin Li static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13781*67e74705SXin Li     ASTContext &Context) {
13782*67e74705SXin Li 
13783*67e74705SXin Li   if (Var->getType()->isDependentType())
13784*67e74705SXin Li     return false;
13785*67e74705SXin Li   const VarDecl *DefVD = nullptr;
13786*67e74705SXin Li   Var->getAnyInitializer(DefVD);
13787*67e74705SXin Li   if (!DefVD)
13788*67e74705SXin Li     return false;
13789*67e74705SXin Li   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13790*67e74705SXin Li   Expr *Init = cast<Expr>(Eval->Value);
13791*67e74705SXin Li   if (Init->isValueDependent())
13792*67e74705SXin Li     return false;
13793*67e74705SXin Li   return IsVariableAConstantExpression(Var, Context);
13794*67e74705SXin Li }
13795*67e74705SXin Li 
13796*67e74705SXin Li 
UpdateMarkingForLValueToRValue(Expr * E)13797*67e74705SXin Li void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13798*67e74705SXin Li   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13799*67e74705SXin Li   // an object that satisfies the requirements for appearing in a
13800*67e74705SXin Li   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13801*67e74705SXin Li   // is immediately applied."  This function handles the lvalue-to-rvalue
13802*67e74705SXin Li   // conversion part.
13803*67e74705SXin Li   MaybeODRUseExprs.erase(E->IgnoreParens());
13804*67e74705SXin Li 
13805*67e74705SXin Li   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13806*67e74705SXin Li   // to a variable that is a constant expression, and if so, identify it as
13807*67e74705SXin Li   // a reference to a variable that does not involve an odr-use of that
13808*67e74705SXin Li   // variable.
13809*67e74705SXin Li   if (LambdaScopeInfo *LSI = getCurLambda()) {
13810*67e74705SXin Li     Expr *SansParensExpr = E->IgnoreParens();
13811*67e74705SXin Li     VarDecl *Var = nullptr;
13812*67e74705SXin Li     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13813*67e74705SXin Li       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13814*67e74705SXin Li     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13815*67e74705SXin Li       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13816*67e74705SXin Li 
13817*67e74705SXin Li     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13818*67e74705SXin Li       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13819*67e74705SXin Li   }
13820*67e74705SXin Li }
13821*67e74705SXin Li 
ActOnConstantExpression(ExprResult Res)13822*67e74705SXin Li ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13823*67e74705SXin Li   Res = CorrectDelayedTyposInExpr(Res);
13824*67e74705SXin Li 
13825*67e74705SXin Li   if (!Res.isUsable())
13826*67e74705SXin Li     return Res;
13827*67e74705SXin Li 
13828*67e74705SXin Li   // If a constant-expression is a reference to a variable where we delay
13829*67e74705SXin Li   // deciding whether it is an odr-use, just assume we will apply the
13830*67e74705SXin Li   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13831*67e74705SXin Li   // (a non-type template argument), we have special handling anyway.
13832*67e74705SXin Li   UpdateMarkingForLValueToRValue(Res.get());
13833*67e74705SXin Li   return Res;
13834*67e74705SXin Li }
13835*67e74705SXin Li 
CleanupVarDeclMarking()13836*67e74705SXin Li void Sema::CleanupVarDeclMarking() {
13837*67e74705SXin Li   for (Expr *E : MaybeODRUseExprs) {
13838*67e74705SXin Li     VarDecl *Var;
13839*67e74705SXin Li     SourceLocation Loc;
13840*67e74705SXin Li     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13841*67e74705SXin Li       Var = cast<VarDecl>(DRE->getDecl());
13842*67e74705SXin Li       Loc = DRE->getLocation();
13843*67e74705SXin Li     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13844*67e74705SXin Li       Var = cast<VarDecl>(ME->getMemberDecl());
13845*67e74705SXin Li       Loc = ME->getMemberLoc();
13846*67e74705SXin Li     } else {
13847*67e74705SXin Li       llvm_unreachable("Unexpected expression");
13848*67e74705SXin Li     }
13849*67e74705SXin Li 
13850*67e74705SXin Li     MarkVarDeclODRUsed(Var, Loc, *this,
13851*67e74705SXin Li                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
13852*67e74705SXin Li   }
13853*67e74705SXin Li 
13854*67e74705SXin Li   MaybeODRUseExprs.clear();
13855*67e74705SXin Li }
13856*67e74705SXin Li 
13857*67e74705SXin Li 
DoMarkVarDeclReferenced(Sema & SemaRef,SourceLocation Loc,VarDecl * Var,Expr * E)13858*67e74705SXin Li static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13859*67e74705SXin Li                                     VarDecl *Var, Expr *E) {
13860*67e74705SXin Li   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13861*67e74705SXin Li          "Invalid Expr argument to DoMarkVarDeclReferenced");
13862*67e74705SXin Li   Var->setReferenced();
13863*67e74705SXin Li 
13864*67e74705SXin Li   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13865*67e74705SXin Li   bool MarkODRUsed = true;
13866*67e74705SXin Li 
13867*67e74705SXin Li   // If the context is not potentially evaluated, this is not an odr-use and
13868*67e74705SXin Li   // does not trigger instantiation.
13869*67e74705SXin Li   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13870*67e74705SXin Li     if (SemaRef.isUnevaluatedContext())
13871*67e74705SXin Li       return;
13872*67e74705SXin Li 
13873*67e74705SXin Li     // If we don't yet know whether this context is going to end up being an
13874*67e74705SXin Li     // evaluated context, and we're referencing a variable from an enclosing
13875*67e74705SXin Li     // scope, add a potential capture.
13876*67e74705SXin Li     //
13877*67e74705SXin Li     // FIXME: Is this necessary? These contexts are only used for default
13878*67e74705SXin Li     // arguments, where local variables can't be used.
13879*67e74705SXin Li     const bool RefersToEnclosingScope =
13880*67e74705SXin Li         (SemaRef.CurContext != Var->getDeclContext() &&
13881*67e74705SXin Li          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13882*67e74705SXin Li     if (RefersToEnclosingScope) {
13883*67e74705SXin Li       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13884*67e74705SXin Li         // If a variable could potentially be odr-used, defer marking it so
13885*67e74705SXin Li         // until we finish analyzing the full expression for any
13886*67e74705SXin Li         // lvalue-to-rvalue
13887*67e74705SXin Li         // or discarded value conversions that would obviate odr-use.
13888*67e74705SXin Li         // Add it to the list of potential captures that will be analyzed
13889*67e74705SXin Li         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13890*67e74705SXin Li         // unless the variable is a reference that was initialized by a constant
13891*67e74705SXin Li         // expression (this will never need to be captured or odr-used).
13892*67e74705SXin Li         assert(E && "Capture variable should be used in an expression.");
13893*67e74705SXin Li         if (!Var->getType()->isReferenceType() ||
13894*67e74705SXin Li             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13895*67e74705SXin Li           LSI->addPotentialCapture(E->IgnoreParens());
13896*67e74705SXin Li       }
13897*67e74705SXin Li     }
13898*67e74705SXin Li 
13899*67e74705SXin Li     if (!isTemplateInstantiation(TSK))
13900*67e74705SXin Li       return;
13901*67e74705SXin Li 
13902*67e74705SXin Li     // Instantiate, but do not mark as odr-used, variable templates.
13903*67e74705SXin Li     MarkODRUsed = false;
13904*67e74705SXin Li   }
13905*67e74705SXin Li 
13906*67e74705SXin Li   VarTemplateSpecializationDecl *VarSpec =
13907*67e74705SXin Li       dyn_cast<VarTemplateSpecializationDecl>(Var);
13908*67e74705SXin Li   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13909*67e74705SXin Li          "Can't instantiate a partial template specialization.");
13910*67e74705SXin Li 
13911*67e74705SXin Li   // If this might be a member specialization of a static data member, check
13912*67e74705SXin Li   // the specialization is visible. We already did the checks for variable
13913*67e74705SXin Li   // template specializations when we created them.
13914*67e74705SXin Li   if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
13915*67e74705SXin Li     SemaRef.checkSpecializationVisibility(Loc, Var);
13916*67e74705SXin Li 
13917*67e74705SXin Li   // Perform implicit instantiation of static data members, static data member
13918*67e74705SXin Li   // templates of class templates, and variable template specializations. Delay
13919*67e74705SXin Li   // instantiations of variable templates, except for those that could be used
13920*67e74705SXin Li   // in a constant expression.
13921*67e74705SXin Li   if (isTemplateInstantiation(TSK)) {
13922*67e74705SXin Li     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
13923*67e74705SXin Li 
13924*67e74705SXin Li     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13925*67e74705SXin Li       if (Var->getPointOfInstantiation().isInvalid()) {
13926*67e74705SXin Li         // This is a modification of an existing AST node. Notify listeners.
13927*67e74705SXin Li         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13928*67e74705SXin Li           L->StaticDataMemberInstantiated(Var);
13929*67e74705SXin Li       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13930*67e74705SXin Li         // Don't bother trying to instantiate it again, unless we might need
13931*67e74705SXin Li         // its initializer before we get to the end of the TU.
13932*67e74705SXin Li         TryInstantiating = false;
13933*67e74705SXin Li     }
13934*67e74705SXin Li 
13935*67e74705SXin Li     if (Var->getPointOfInstantiation().isInvalid())
13936*67e74705SXin Li       Var->setTemplateSpecializationKind(TSK, Loc);
13937*67e74705SXin Li 
13938*67e74705SXin Li     if (TryInstantiating) {
13939*67e74705SXin Li       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
13940*67e74705SXin Li       bool InstantiationDependent = false;
13941*67e74705SXin Li       bool IsNonDependent =
13942*67e74705SXin Li           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13943*67e74705SXin Li                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13944*67e74705SXin Li                   : true;
13945*67e74705SXin Li 
13946*67e74705SXin Li       // Do not instantiate specializations that are still type-dependent.
13947*67e74705SXin Li       if (IsNonDependent) {
13948*67e74705SXin Li         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13949*67e74705SXin Li           // Do not defer instantiations of variables which could be used in a
13950*67e74705SXin Li           // constant expression.
13951*67e74705SXin Li           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13952*67e74705SXin Li         } else {
13953*67e74705SXin Li           SemaRef.PendingInstantiations
13954*67e74705SXin Li               .push_back(std::make_pair(Var, PointOfInstantiation));
13955*67e74705SXin Li         }
13956*67e74705SXin Li       }
13957*67e74705SXin Li     }
13958*67e74705SXin Li   }
13959*67e74705SXin Li 
13960*67e74705SXin Li   if (!MarkODRUsed)
13961*67e74705SXin Li     return;
13962*67e74705SXin Li 
13963*67e74705SXin Li   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13964*67e74705SXin Li   // the requirements for appearing in a constant expression (5.19) and, if
13965*67e74705SXin Li   // it is an object, the lvalue-to-rvalue conversion (4.1)
13966*67e74705SXin Li   // is immediately applied."  We check the first part here, and
13967*67e74705SXin Li   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13968*67e74705SXin Li   // Note that we use the C++11 definition everywhere because nothing in
13969*67e74705SXin Li   // C++03 depends on whether we get the C++03 version correct. The second
13970*67e74705SXin Li   // part does not apply to references, since they are not objects.
13971*67e74705SXin Li   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
13972*67e74705SXin Li     // A reference initialized by a constant expression can never be
13973*67e74705SXin Li     // odr-used, so simply ignore it.
13974*67e74705SXin Li     if (!Var->getType()->isReferenceType())
13975*67e74705SXin Li       SemaRef.MaybeODRUseExprs.insert(E);
13976*67e74705SXin Li   } else
13977*67e74705SXin Li     MarkVarDeclODRUsed(Var, Loc, SemaRef,
13978*67e74705SXin Li                        /*MaxFunctionScopeIndex ptr*/ nullptr);
13979*67e74705SXin Li }
13980*67e74705SXin Li 
13981*67e74705SXin Li /// \brief Mark a variable referenced, and check whether it is odr-used
13982*67e74705SXin Li /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
13983*67e74705SXin Li /// used directly for normal expressions referring to VarDecl.
MarkVariableReferenced(SourceLocation Loc,VarDecl * Var)13984*67e74705SXin Li void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
13985*67e74705SXin Li   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
13986*67e74705SXin Li }
13987*67e74705SXin Li 
MarkExprReferenced(Sema & SemaRef,SourceLocation Loc,Decl * D,Expr * E,bool MightBeOdrUse)13988*67e74705SXin Li static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
13989*67e74705SXin Li                                Decl *D, Expr *E, bool MightBeOdrUse) {
13990*67e74705SXin Li   if (SemaRef.isInOpenMPDeclareTargetContext())
13991*67e74705SXin Li     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
13992*67e74705SXin Li 
13993*67e74705SXin Li   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
13994*67e74705SXin Li     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
13995*67e74705SXin Li     return;
13996*67e74705SXin Li   }
13997*67e74705SXin Li 
13998*67e74705SXin Li   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
13999*67e74705SXin Li 
14000*67e74705SXin Li   // If this is a call to a method via a cast, also mark the method in the
14001*67e74705SXin Li   // derived class used in case codegen can devirtualize the call.
14002*67e74705SXin Li   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14003*67e74705SXin Li   if (!ME)
14004*67e74705SXin Li     return;
14005*67e74705SXin Li   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14006*67e74705SXin Li   if (!MD)
14007*67e74705SXin Li     return;
14008*67e74705SXin Li   // Only attempt to devirtualize if this is truly a virtual call.
14009*67e74705SXin Li   bool IsVirtualCall = MD->isVirtual() &&
14010*67e74705SXin Li                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14011*67e74705SXin Li   if (!IsVirtualCall)
14012*67e74705SXin Li     return;
14013*67e74705SXin Li   const Expr *Base = ME->getBase();
14014*67e74705SXin Li   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14015*67e74705SXin Li   if (!MostDerivedClassDecl)
14016*67e74705SXin Li     return;
14017*67e74705SXin Li   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14018*67e74705SXin Li   if (!DM || DM->isPure())
14019*67e74705SXin Li     return;
14020*67e74705SXin Li   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14021*67e74705SXin Li }
14022*67e74705SXin Li 
14023*67e74705SXin Li /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
MarkDeclRefReferenced(DeclRefExpr * E)14024*67e74705SXin Li void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14025*67e74705SXin Li   // TODO: update this with DR# once a defect report is filed.
14026*67e74705SXin Li   // C++11 defect. The address of a pure member should not be an ODR use, even
14027*67e74705SXin Li   // if it's a qualified reference.
14028*67e74705SXin Li   bool OdrUse = true;
14029*67e74705SXin Li   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14030*67e74705SXin Li     if (Method->isVirtual())
14031*67e74705SXin Li       OdrUse = false;
14032*67e74705SXin Li   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14033*67e74705SXin Li }
14034*67e74705SXin Li 
14035*67e74705SXin Li /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
MarkMemberReferenced(MemberExpr * E)14036*67e74705SXin Li void Sema::MarkMemberReferenced(MemberExpr *E) {
14037*67e74705SXin Li   // C++11 [basic.def.odr]p2:
14038*67e74705SXin Li   //   A non-overloaded function whose name appears as a potentially-evaluated
14039*67e74705SXin Li   //   expression or a member of a set of candidate functions, if selected by
14040*67e74705SXin Li   //   overload resolution when referred to from a potentially-evaluated
14041*67e74705SXin Li   //   expression, is odr-used, unless it is a pure virtual function and its
14042*67e74705SXin Li   //   name is not explicitly qualified.
14043*67e74705SXin Li   bool MightBeOdrUse = true;
14044*67e74705SXin Li   if (E->performsVirtualDispatch(getLangOpts())) {
14045*67e74705SXin Li     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14046*67e74705SXin Li       if (Method->isPure())
14047*67e74705SXin Li         MightBeOdrUse = false;
14048*67e74705SXin Li   }
14049*67e74705SXin Li   SourceLocation Loc = E->getMemberLoc().isValid() ?
14050*67e74705SXin Li                             E->getMemberLoc() : E->getLocStart();
14051*67e74705SXin Li   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14052*67e74705SXin Li }
14053*67e74705SXin Li 
14054*67e74705SXin Li /// \brief Perform marking for a reference to an arbitrary declaration.  It
14055*67e74705SXin Li /// marks the declaration referenced, and performs odr-use checking for
14056*67e74705SXin Li /// functions and variables. This method should not be used when building a
14057*67e74705SXin Li /// normal expression which refers to a variable.
MarkAnyDeclReferenced(SourceLocation Loc,Decl * D,bool MightBeOdrUse)14058*67e74705SXin Li void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14059*67e74705SXin Li                                  bool MightBeOdrUse) {
14060*67e74705SXin Li   if (MightBeOdrUse) {
14061*67e74705SXin Li     if (auto *VD = dyn_cast<VarDecl>(D)) {
14062*67e74705SXin Li       MarkVariableReferenced(Loc, VD);
14063*67e74705SXin Li       return;
14064*67e74705SXin Li     }
14065*67e74705SXin Li   }
14066*67e74705SXin Li   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14067*67e74705SXin Li     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14068*67e74705SXin Li     return;
14069*67e74705SXin Li   }
14070*67e74705SXin Li   D->setReferenced();
14071*67e74705SXin Li }
14072*67e74705SXin Li 
14073*67e74705SXin Li namespace {
14074*67e74705SXin Li   // Mark all of the declarations referenced
14075*67e74705SXin Li   // FIXME: Not fully implemented yet! We need to have a better understanding
14076*67e74705SXin Li   // of when we're entering
14077*67e74705SXin Li   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14078*67e74705SXin Li     Sema &S;
14079*67e74705SXin Li     SourceLocation Loc;
14080*67e74705SXin Li 
14081*67e74705SXin Li   public:
14082*67e74705SXin Li     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14083*67e74705SXin Li 
MarkReferencedDecls(Sema & S,SourceLocation Loc)14084*67e74705SXin Li     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14085*67e74705SXin Li 
14086*67e74705SXin Li     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14087*67e74705SXin Li     bool TraverseRecordType(RecordType *T);
14088*67e74705SXin Li   };
14089*67e74705SXin Li }
14090*67e74705SXin Li 
TraverseTemplateArgument(const TemplateArgument & Arg)14091*67e74705SXin Li bool MarkReferencedDecls::TraverseTemplateArgument(
14092*67e74705SXin Li     const TemplateArgument &Arg) {
14093*67e74705SXin Li   if (Arg.getKind() == TemplateArgument::Declaration) {
14094*67e74705SXin Li     if (Decl *D = Arg.getAsDecl())
14095*67e74705SXin Li       S.MarkAnyDeclReferenced(Loc, D, true);
14096*67e74705SXin Li   }
14097*67e74705SXin Li 
14098*67e74705SXin Li   return Inherited::TraverseTemplateArgument(Arg);
14099*67e74705SXin Li }
14100*67e74705SXin Li 
TraverseRecordType(RecordType * T)14101*67e74705SXin Li bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
14102*67e74705SXin Li   if (ClassTemplateSpecializationDecl *Spec
14103*67e74705SXin Li                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14104*67e74705SXin Li     const TemplateArgumentList &Args = Spec->getTemplateArgs();
14105*67e74705SXin Li     return TraverseTemplateArguments(Args.data(), Args.size());
14106*67e74705SXin Li   }
14107*67e74705SXin Li 
14108*67e74705SXin Li   return true;
14109*67e74705SXin Li }
14110*67e74705SXin Li 
MarkDeclarationsReferencedInType(SourceLocation Loc,QualType T)14111*67e74705SXin Li void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14112*67e74705SXin Li   MarkReferencedDecls Marker(*this, Loc);
14113*67e74705SXin Li   Marker.TraverseType(Context.getCanonicalType(T));
14114*67e74705SXin Li }
14115*67e74705SXin Li 
14116*67e74705SXin Li namespace {
14117*67e74705SXin Li   /// \brief Helper class that marks all of the declarations referenced by
14118*67e74705SXin Li   /// potentially-evaluated subexpressions as "referenced".
14119*67e74705SXin Li   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14120*67e74705SXin Li     Sema &S;
14121*67e74705SXin Li     bool SkipLocalVariables;
14122*67e74705SXin Li 
14123*67e74705SXin Li   public:
14124*67e74705SXin Li     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14125*67e74705SXin Li 
EvaluatedExprMarker(Sema & S,bool SkipLocalVariables)14126*67e74705SXin Li     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14127*67e74705SXin Li       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14128*67e74705SXin Li 
VisitDeclRefExpr(DeclRefExpr * E)14129*67e74705SXin Li     void VisitDeclRefExpr(DeclRefExpr *E) {
14130*67e74705SXin Li       // If we were asked not to visit local variables, don't.
14131*67e74705SXin Li       if (SkipLocalVariables) {
14132*67e74705SXin Li         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14133*67e74705SXin Li           if (VD->hasLocalStorage())
14134*67e74705SXin Li             return;
14135*67e74705SXin Li       }
14136*67e74705SXin Li 
14137*67e74705SXin Li       S.MarkDeclRefReferenced(E);
14138*67e74705SXin Li     }
14139*67e74705SXin Li 
VisitMemberExpr(MemberExpr * E)14140*67e74705SXin Li     void VisitMemberExpr(MemberExpr *E) {
14141*67e74705SXin Li       S.MarkMemberReferenced(E);
14142*67e74705SXin Li       Inherited::VisitMemberExpr(E);
14143*67e74705SXin Li     }
14144*67e74705SXin Li 
VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr * E)14145*67e74705SXin Li     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14146*67e74705SXin Li       S.MarkFunctionReferenced(E->getLocStart(),
14147*67e74705SXin Li             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14148*67e74705SXin Li       Visit(E->getSubExpr());
14149*67e74705SXin Li     }
14150*67e74705SXin Li 
VisitCXXNewExpr(CXXNewExpr * E)14151*67e74705SXin Li     void VisitCXXNewExpr(CXXNewExpr *E) {
14152*67e74705SXin Li       if (E->getOperatorNew())
14153*67e74705SXin Li         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14154*67e74705SXin Li       if (E->getOperatorDelete())
14155*67e74705SXin Li         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14156*67e74705SXin Li       Inherited::VisitCXXNewExpr(E);
14157*67e74705SXin Li     }
14158*67e74705SXin Li 
VisitCXXDeleteExpr(CXXDeleteExpr * E)14159*67e74705SXin Li     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14160*67e74705SXin Li       if (E->getOperatorDelete())
14161*67e74705SXin Li         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14162*67e74705SXin Li       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14163*67e74705SXin Li       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14164*67e74705SXin Li         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14165*67e74705SXin Li         S.MarkFunctionReferenced(E->getLocStart(),
14166*67e74705SXin Li                                     S.LookupDestructor(Record));
14167*67e74705SXin Li       }
14168*67e74705SXin Li 
14169*67e74705SXin Li       Inherited::VisitCXXDeleteExpr(E);
14170*67e74705SXin Li     }
14171*67e74705SXin Li 
VisitCXXConstructExpr(CXXConstructExpr * E)14172*67e74705SXin Li     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14173*67e74705SXin Li       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14174*67e74705SXin Li       Inherited::VisitCXXConstructExpr(E);
14175*67e74705SXin Li     }
14176*67e74705SXin Li 
VisitCXXDefaultArgExpr(CXXDefaultArgExpr * E)14177*67e74705SXin Li     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14178*67e74705SXin Li       Visit(E->getExpr());
14179*67e74705SXin Li     }
14180*67e74705SXin Li 
VisitImplicitCastExpr(ImplicitCastExpr * E)14181*67e74705SXin Li     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14182*67e74705SXin Li       Inherited::VisitImplicitCastExpr(E);
14183*67e74705SXin Li 
14184*67e74705SXin Li       if (E->getCastKind() == CK_LValueToRValue)
14185*67e74705SXin Li         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14186*67e74705SXin Li     }
14187*67e74705SXin Li   };
14188*67e74705SXin Li }
14189*67e74705SXin Li 
14190*67e74705SXin Li /// \brief Mark any declarations that appear within this expression or any
14191*67e74705SXin Li /// potentially-evaluated subexpressions as "referenced".
14192*67e74705SXin Li ///
14193*67e74705SXin Li /// \param SkipLocalVariables If true, don't mark local variables as
14194*67e74705SXin Li /// 'referenced'.
MarkDeclarationsReferencedInExpr(Expr * E,bool SkipLocalVariables)14195*67e74705SXin Li void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14196*67e74705SXin Li                                             bool SkipLocalVariables) {
14197*67e74705SXin Li   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14198*67e74705SXin Li }
14199*67e74705SXin Li 
14200*67e74705SXin Li /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14201*67e74705SXin Li /// of the program being compiled.
14202*67e74705SXin Li ///
14203*67e74705SXin Li /// This routine emits the given diagnostic when the code currently being
14204*67e74705SXin Li /// type-checked is "potentially evaluated", meaning that there is a
14205*67e74705SXin Li /// possibility that the code will actually be executable. Code in sizeof()
14206*67e74705SXin Li /// expressions, code used only during overload resolution, etc., are not
14207*67e74705SXin Li /// potentially evaluated. This routine will suppress such diagnostics or,
14208*67e74705SXin Li /// in the absolutely nutty case of potentially potentially evaluated
14209*67e74705SXin Li /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14210*67e74705SXin Li /// later.
14211*67e74705SXin Li ///
14212*67e74705SXin Li /// This routine should be used for all diagnostics that describe the run-time
14213*67e74705SXin Li /// behavior of a program, such as passing a non-POD value through an ellipsis.
14214*67e74705SXin Li /// Failure to do so will likely result in spurious diagnostics or failures
14215*67e74705SXin Li /// during overload resolution or within sizeof/alignof/typeof/typeid.
DiagRuntimeBehavior(SourceLocation Loc,const Stmt * Statement,const PartialDiagnostic & PD)14216*67e74705SXin Li bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14217*67e74705SXin Li                                const PartialDiagnostic &PD) {
14218*67e74705SXin Li   switch (ExprEvalContexts.back().Context) {
14219*67e74705SXin Li   case Unevaluated:
14220*67e74705SXin Li   case UnevaluatedAbstract:
14221*67e74705SXin Li   case DiscardedStatement:
14222*67e74705SXin Li     // The argument will never be evaluated, so don't complain.
14223*67e74705SXin Li     break;
14224*67e74705SXin Li 
14225*67e74705SXin Li   case ConstantEvaluated:
14226*67e74705SXin Li     // Relevant diagnostics should be produced by constant evaluation.
14227*67e74705SXin Li     break;
14228*67e74705SXin Li 
14229*67e74705SXin Li   case PotentiallyEvaluated:
14230*67e74705SXin Li   case PotentiallyEvaluatedIfUsed:
14231*67e74705SXin Li     if (Statement && getCurFunctionOrMethodDecl()) {
14232*67e74705SXin Li       FunctionScopes.back()->PossiblyUnreachableDiags.
14233*67e74705SXin Li         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14234*67e74705SXin Li     }
14235*67e74705SXin Li     else
14236*67e74705SXin Li       Diag(Loc, PD);
14237*67e74705SXin Li 
14238*67e74705SXin Li     return true;
14239*67e74705SXin Li   }
14240*67e74705SXin Li 
14241*67e74705SXin Li   return false;
14242*67e74705SXin Li }
14243*67e74705SXin Li 
CheckCallReturnType(QualType ReturnType,SourceLocation Loc,CallExpr * CE,FunctionDecl * FD)14244*67e74705SXin Li bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14245*67e74705SXin Li                                CallExpr *CE, FunctionDecl *FD) {
14246*67e74705SXin Li   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14247*67e74705SXin Li     return false;
14248*67e74705SXin Li 
14249*67e74705SXin Li   // If we're inside a decltype's expression, don't check for a valid return
14250*67e74705SXin Li   // type or construct temporaries until we know whether this is the last call.
14251*67e74705SXin Li   if (ExprEvalContexts.back().IsDecltype) {
14252*67e74705SXin Li     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14253*67e74705SXin Li     return false;
14254*67e74705SXin Li   }
14255*67e74705SXin Li 
14256*67e74705SXin Li   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14257*67e74705SXin Li     FunctionDecl *FD;
14258*67e74705SXin Li     CallExpr *CE;
14259*67e74705SXin Li 
14260*67e74705SXin Li   public:
14261*67e74705SXin Li     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14262*67e74705SXin Li       : FD(FD), CE(CE) { }
14263*67e74705SXin Li 
14264*67e74705SXin Li     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14265*67e74705SXin Li       if (!FD) {
14266*67e74705SXin Li         S.Diag(Loc, diag::err_call_incomplete_return)
14267*67e74705SXin Li           << T << CE->getSourceRange();
14268*67e74705SXin Li         return;
14269*67e74705SXin Li       }
14270*67e74705SXin Li 
14271*67e74705SXin Li       S.Diag(Loc, diag::err_call_function_incomplete_return)
14272*67e74705SXin Li         << CE->getSourceRange() << FD->getDeclName() << T;
14273*67e74705SXin Li       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14274*67e74705SXin Li           << FD->getDeclName();
14275*67e74705SXin Li     }
14276*67e74705SXin Li   } Diagnoser(FD, CE);
14277*67e74705SXin Li 
14278*67e74705SXin Li   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14279*67e74705SXin Li     return true;
14280*67e74705SXin Li 
14281*67e74705SXin Li   return false;
14282*67e74705SXin Li }
14283*67e74705SXin Li 
14284*67e74705SXin Li // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14285*67e74705SXin Li // will prevent this condition from triggering, which is what we want.
DiagnoseAssignmentAsCondition(Expr * E)14286*67e74705SXin Li void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14287*67e74705SXin Li   SourceLocation Loc;
14288*67e74705SXin Li 
14289*67e74705SXin Li   unsigned diagnostic = diag::warn_condition_is_assignment;
14290*67e74705SXin Li   bool IsOrAssign = false;
14291*67e74705SXin Li 
14292*67e74705SXin Li   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14293*67e74705SXin Li     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14294*67e74705SXin Li       return;
14295*67e74705SXin Li 
14296*67e74705SXin Li     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14297*67e74705SXin Li 
14298*67e74705SXin Li     // Greylist some idioms by putting them into a warning subcategory.
14299*67e74705SXin Li     if (ObjCMessageExpr *ME
14300*67e74705SXin Li           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14301*67e74705SXin Li       Selector Sel = ME->getSelector();
14302*67e74705SXin Li 
14303*67e74705SXin Li       // self = [<foo> init...]
14304*67e74705SXin Li       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14305*67e74705SXin Li         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14306*67e74705SXin Li 
14307*67e74705SXin Li       // <foo> = [<bar> nextObject]
14308*67e74705SXin Li       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14309*67e74705SXin Li         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14310*67e74705SXin Li     }
14311*67e74705SXin Li 
14312*67e74705SXin Li     Loc = Op->getOperatorLoc();
14313*67e74705SXin Li   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14314*67e74705SXin Li     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14315*67e74705SXin Li       return;
14316*67e74705SXin Li 
14317*67e74705SXin Li     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14318*67e74705SXin Li     Loc = Op->getOperatorLoc();
14319*67e74705SXin Li   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14320*67e74705SXin Li     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14321*67e74705SXin Li   else {
14322*67e74705SXin Li     // Not an assignment.
14323*67e74705SXin Li     return;
14324*67e74705SXin Li   }
14325*67e74705SXin Li 
14326*67e74705SXin Li   Diag(Loc, diagnostic) << E->getSourceRange();
14327*67e74705SXin Li 
14328*67e74705SXin Li   SourceLocation Open = E->getLocStart();
14329*67e74705SXin Li   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14330*67e74705SXin Li   Diag(Loc, diag::note_condition_assign_silence)
14331*67e74705SXin Li         << FixItHint::CreateInsertion(Open, "(")
14332*67e74705SXin Li         << FixItHint::CreateInsertion(Close, ")");
14333*67e74705SXin Li 
14334*67e74705SXin Li   if (IsOrAssign)
14335*67e74705SXin Li     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14336*67e74705SXin Li       << FixItHint::CreateReplacement(Loc, "!=");
14337*67e74705SXin Li   else
14338*67e74705SXin Li     Diag(Loc, diag::note_condition_assign_to_comparison)
14339*67e74705SXin Li       << FixItHint::CreateReplacement(Loc, "==");
14340*67e74705SXin Li }
14341*67e74705SXin Li 
14342*67e74705SXin Li /// \brief Redundant parentheses over an equality comparison can indicate
14343*67e74705SXin Li /// that the user intended an assignment used as condition.
DiagnoseEqualityWithExtraParens(ParenExpr * ParenE)14344*67e74705SXin Li void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14345*67e74705SXin Li   // Don't warn if the parens came from a macro.
14346*67e74705SXin Li   SourceLocation parenLoc = ParenE->getLocStart();
14347*67e74705SXin Li   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14348*67e74705SXin Li     return;
14349*67e74705SXin Li   // Don't warn for dependent expressions.
14350*67e74705SXin Li   if (ParenE->isTypeDependent())
14351*67e74705SXin Li     return;
14352*67e74705SXin Li 
14353*67e74705SXin Li   Expr *E = ParenE->IgnoreParens();
14354*67e74705SXin Li 
14355*67e74705SXin Li   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14356*67e74705SXin Li     if (opE->getOpcode() == BO_EQ &&
14357*67e74705SXin Li         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14358*67e74705SXin Li                                                            == Expr::MLV_Valid) {
14359*67e74705SXin Li       SourceLocation Loc = opE->getOperatorLoc();
14360*67e74705SXin Li 
14361*67e74705SXin Li       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14362*67e74705SXin Li       SourceRange ParenERange = ParenE->getSourceRange();
14363*67e74705SXin Li       Diag(Loc, diag::note_equality_comparison_silence)
14364*67e74705SXin Li         << FixItHint::CreateRemoval(ParenERange.getBegin())
14365*67e74705SXin Li         << FixItHint::CreateRemoval(ParenERange.getEnd());
14366*67e74705SXin Li       Diag(Loc, diag::note_equality_comparison_to_assign)
14367*67e74705SXin Li         << FixItHint::CreateReplacement(Loc, "=");
14368*67e74705SXin Li     }
14369*67e74705SXin Li }
14370*67e74705SXin Li 
CheckBooleanCondition(SourceLocation Loc,Expr * E,bool IsConstexpr)14371*67e74705SXin Li ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14372*67e74705SXin Li                                        bool IsConstexpr) {
14373*67e74705SXin Li   DiagnoseAssignmentAsCondition(E);
14374*67e74705SXin Li   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14375*67e74705SXin Li     DiagnoseEqualityWithExtraParens(parenE);
14376*67e74705SXin Li 
14377*67e74705SXin Li   ExprResult result = CheckPlaceholderExpr(E);
14378*67e74705SXin Li   if (result.isInvalid()) return ExprError();
14379*67e74705SXin Li   E = result.get();
14380*67e74705SXin Li 
14381*67e74705SXin Li   if (!E->isTypeDependent()) {
14382*67e74705SXin Li     if (getLangOpts().CPlusPlus)
14383*67e74705SXin Li       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14384*67e74705SXin Li 
14385*67e74705SXin Li     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14386*67e74705SXin Li     if (ERes.isInvalid())
14387*67e74705SXin Li       return ExprError();
14388*67e74705SXin Li     E = ERes.get();
14389*67e74705SXin Li 
14390*67e74705SXin Li     QualType T = E->getType();
14391*67e74705SXin Li     if (!T->isScalarType()) { // C99 6.8.4.1p1
14392*67e74705SXin Li       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14393*67e74705SXin Li         << T << E->getSourceRange();
14394*67e74705SXin Li       return ExprError();
14395*67e74705SXin Li     }
14396*67e74705SXin Li     CheckBoolLikeConversion(E, Loc);
14397*67e74705SXin Li   }
14398*67e74705SXin Li 
14399*67e74705SXin Li   return E;
14400*67e74705SXin Li }
14401*67e74705SXin Li 
ActOnCondition(Scope * S,SourceLocation Loc,Expr * SubExpr,ConditionKind CK)14402*67e74705SXin Li Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14403*67e74705SXin Li                                            Expr *SubExpr, ConditionKind CK) {
14404*67e74705SXin Li   // Empty conditions are valid in for-statements.
14405*67e74705SXin Li   if (!SubExpr)
14406*67e74705SXin Li     return ConditionResult();
14407*67e74705SXin Li 
14408*67e74705SXin Li   ExprResult Cond;
14409*67e74705SXin Li   switch (CK) {
14410*67e74705SXin Li   case ConditionKind::Boolean:
14411*67e74705SXin Li     Cond = CheckBooleanCondition(Loc, SubExpr);
14412*67e74705SXin Li     break;
14413*67e74705SXin Li 
14414*67e74705SXin Li   case ConditionKind::ConstexprIf:
14415*67e74705SXin Li     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14416*67e74705SXin Li     break;
14417*67e74705SXin Li 
14418*67e74705SXin Li   case ConditionKind::Switch:
14419*67e74705SXin Li     Cond = CheckSwitchCondition(Loc, SubExpr);
14420*67e74705SXin Li     break;
14421*67e74705SXin Li   }
14422*67e74705SXin Li   if (Cond.isInvalid())
14423*67e74705SXin Li     return ConditionError();
14424*67e74705SXin Li 
14425*67e74705SXin Li   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14426*67e74705SXin Li   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14427*67e74705SXin Li   if (!FullExpr.get())
14428*67e74705SXin Li     return ConditionError();
14429*67e74705SXin Li 
14430*67e74705SXin Li   return ConditionResult(*this, nullptr, FullExpr,
14431*67e74705SXin Li                          CK == ConditionKind::ConstexprIf);
14432*67e74705SXin Li }
14433*67e74705SXin Li 
14434*67e74705SXin Li namespace {
14435*67e74705SXin Li   /// A visitor for rebuilding a call to an __unknown_any expression
14436*67e74705SXin Li   /// to have an appropriate type.
14437*67e74705SXin Li   struct RebuildUnknownAnyFunction
14438*67e74705SXin Li     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14439*67e74705SXin Li 
14440*67e74705SXin Li     Sema &S;
14441*67e74705SXin Li 
RebuildUnknownAnyFunction__anon3c1752cc0b11::RebuildUnknownAnyFunction14442*67e74705SXin Li     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14443*67e74705SXin Li 
VisitStmt__anon3c1752cc0b11::RebuildUnknownAnyFunction14444*67e74705SXin Li     ExprResult VisitStmt(Stmt *S) {
14445*67e74705SXin Li       llvm_unreachable("unexpected statement!");
14446*67e74705SXin Li     }
14447*67e74705SXin Li 
VisitExpr__anon3c1752cc0b11::RebuildUnknownAnyFunction14448*67e74705SXin Li     ExprResult VisitExpr(Expr *E) {
14449*67e74705SXin Li       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14450*67e74705SXin Li         << E->getSourceRange();
14451*67e74705SXin Li       return ExprError();
14452*67e74705SXin Li     }
14453*67e74705SXin Li 
14454*67e74705SXin Li     /// Rebuild an expression which simply semantically wraps another
14455*67e74705SXin Li     /// expression which it shares the type and value kind of.
rebuildSugarExpr__anon3c1752cc0b11::RebuildUnknownAnyFunction14456*67e74705SXin Li     template <class T> ExprResult rebuildSugarExpr(T *E) {
14457*67e74705SXin Li       ExprResult SubResult = Visit(E->getSubExpr());
14458*67e74705SXin Li       if (SubResult.isInvalid()) return ExprError();
14459*67e74705SXin Li 
14460*67e74705SXin Li       Expr *SubExpr = SubResult.get();
14461*67e74705SXin Li       E->setSubExpr(SubExpr);
14462*67e74705SXin Li       E->setType(SubExpr->getType());
14463*67e74705SXin Li       E->setValueKind(SubExpr->getValueKind());
14464*67e74705SXin Li       assert(E->getObjectKind() == OK_Ordinary);
14465*67e74705SXin Li       return E;
14466*67e74705SXin Li     }
14467*67e74705SXin Li 
VisitParenExpr__anon3c1752cc0b11::RebuildUnknownAnyFunction14468*67e74705SXin Li     ExprResult VisitParenExpr(ParenExpr *E) {
14469*67e74705SXin Li       return rebuildSugarExpr(E);
14470*67e74705SXin Li     }
14471*67e74705SXin Li 
VisitUnaryExtension__anon3c1752cc0b11::RebuildUnknownAnyFunction14472*67e74705SXin Li     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14473*67e74705SXin Li       return rebuildSugarExpr(E);
14474*67e74705SXin Li     }
14475*67e74705SXin Li 
VisitUnaryAddrOf__anon3c1752cc0b11::RebuildUnknownAnyFunction14476*67e74705SXin Li     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14477*67e74705SXin Li       ExprResult SubResult = Visit(E->getSubExpr());
14478*67e74705SXin Li       if (SubResult.isInvalid()) return ExprError();
14479*67e74705SXin Li 
14480*67e74705SXin Li       Expr *SubExpr = SubResult.get();
14481*67e74705SXin Li       E->setSubExpr(SubExpr);
14482*67e74705SXin Li       E->setType(S.Context.getPointerType(SubExpr->getType()));
14483*67e74705SXin Li       assert(E->getValueKind() == VK_RValue);
14484*67e74705SXin Li       assert(E->getObjectKind() == OK_Ordinary);
14485*67e74705SXin Li       return E;
14486*67e74705SXin Li     }
14487*67e74705SXin Li 
resolveDecl__anon3c1752cc0b11::RebuildUnknownAnyFunction14488*67e74705SXin Li     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14489*67e74705SXin Li       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14490*67e74705SXin Li 
14491*67e74705SXin Li       E->setType(VD->getType());
14492*67e74705SXin Li 
14493*67e74705SXin Li       assert(E->getValueKind() == VK_RValue);
14494*67e74705SXin Li       if (S.getLangOpts().CPlusPlus &&
14495*67e74705SXin Li           !(isa<CXXMethodDecl>(VD) &&
14496*67e74705SXin Li             cast<CXXMethodDecl>(VD)->isInstance()))
14497*67e74705SXin Li         E->setValueKind(VK_LValue);
14498*67e74705SXin Li 
14499*67e74705SXin Li       return E;
14500*67e74705SXin Li     }
14501*67e74705SXin Li 
VisitMemberExpr__anon3c1752cc0b11::RebuildUnknownAnyFunction14502*67e74705SXin Li     ExprResult VisitMemberExpr(MemberExpr *E) {
14503*67e74705SXin Li       return resolveDecl(E, E->getMemberDecl());
14504*67e74705SXin Li     }
14505*67e74705SXin Li 
VisitDeclRefExpr__anon3c1752cc0b11::RebuildUnknownAnyFunction14506*67e74705SXin Li     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14507*67e74705SXin Li       return resolveDecl(E, E->getDecl());
14508*67e74705SXin Li     }
14509*67e74705SXin Li   };
14510*67e74705SXin Li }
14511*67e74705SXin Li 
14512*67e74705SXin Li /// Given a function expression of unknown-any type, try to rebuild it
14513*67e74705SXin Li /// to have a function type.
rebuildUnknownAnyFunction(Sema & S,Expr * FunctionExpr)14514*67e74705SXin Li static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14515*67e74705SXin Li   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14516*67e74705SXin Li   if (Result.isInvalid()) return ExprError();
14517*67e74705SXin Li   return S.DefaultFunctionArrayConversion(Result.get());
14518*67e74705SXin Li }
14519*67e74705SXin Li 
14520*67e74705SXin Li namespace {
14521*67e74705SXin Li   /// A visitor for rebuilding an expression of type __unknown_anytype
14522*67e74705SXin Li   /// into one which resolves the type directly on the referring
14523*67e74705SXin Li   /// expression.  Strict preservation of the original source
14524*67e74705SXin Li   /// structure is not a goal.
14525*67e74705SXin Li   struct RebuildUnknownAnyExpr
14526*67e74705SXin Li     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14527*67e74705SXin Li 
14528*67e74705SXin Li     Sema &S;
14529*67e74705SXin Li 
14530*67e74705SXin Li     /// The current destination type.
14531*67e74705SXin Li     QualType DestType;
14532*67e74705SXin Li 
RebuildUnknownAnyExpr__anon3c1752cc0c11::RebuildUnknownAnyExpr14533*67e74705SXin Li     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14534*67e74705SXin Li       : S(S), DestType(CastType) {}
14535*67e74705SXin Li 
VisitStmt__anon3c1752cc0c11::RebuildUnknownAnyExpr14536*67e74705SXin Li     ExprResult VisitStmt(Stmt *S) {
14537*67e74705SXin Li       llvm_unreachable("unexpected statement!");
14538*67e74705SXin Li     }
14539*67e74705SXin Li 
VisitExpr__anon3c1752cc0c11::RebuildUnknownAnyExpr14540*67e74705SXin Li     ExprResult VisitExpr(Expr *E) {
14541*67e74705SXin Li       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14542*67e74705SXin Li         << E->getSourceRange();
14543*67e74705SXin Li       return ExprError();
14544*67e74705SXin Li     }
14545*67e74705SXin Li 
14546*67e74705SXin Li     ExprResult VisitCallExpr(CallExpr *E);
14547*67e74705SXin Li     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14548*67e74705SXin Li 
14549*67e74705SXin Li     /// Rebuild an expression which simply semantically wraps another
14550*67e74705SXin Li     /// expression which it shares the type and value kind of.
rebuildSugarExpr__anon3c1752cc0c11::RebuildUnknownAnyExpr14551*67e74705SXin Li     template <class T> ExprResult rebuildSugarExpr(T *E) {
14552*67e74705SXin Li       ExprResult SubResult = Visit(E->getSubExpr());
14553*67e74705SXin Li       if (SubResult.isInvalid()) return ExprError();
14554*67e74705SXin Li       Expr *SubExpr = SubResult.get();
14555*67e74705SXin Li       E->setSubExpr(SubExpr);
14556*67e74705SXin Li       E->setType(SubExpr->getType());
14557*67e74705SXin Li       E->setValueKind(SubExpr->getValueKind());
14558*67e74705SXin Li       assert(E->getObjectKind() == OK_Ordinary);
14559*67e74705SXin Li       return E;
14560*67e74705SXin Li     }
14561*67e74705SXin Li 
VisitParenExpr__anon3c1752cc0c11::RebuildUnknownAnyExpr14562*67e74705SXin Li     ExprResult VisitParenExpr(ParenExpr *E) {
14563*67e74705SXin Li       return rebuildSugarExpr(E);
14564*67e74705SXin Li     }
14565*67e74705SXin Li 
VisitUnaryExtension__anon3c1752cc0c11::RebuildUnknownAnyExpr14566*67e74705SXin Li     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14567*67e74705SXin Li       return rebuildSugarExpr(E);
14568*67e74705SXin Li     }
14569*67e74705SXin Li 
VisitUnaryAddrOf__anon3c1752cc0c11::RebuildUnknownAnyExpr14570*67e74705SXin Li     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14571*67e74705SXin Li       const PointerType *Ptr = DestType->getAs<PointerType>();
14572*67e74705SXin Li       if (!Ptr) {
14573*67e74705SXin Li         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14574*67e74705SXin Li           << E->getSourceRange();
14575*67e74705SXin Li         return ExprError();
14576*67e74705SXin Li       }
14577*67e74705SXin Li       assert(E->getValueKind() == VK_RValue);
14578*67e74705SXin Li       assert(E->getObjectKind() == OK_Ordinary);
14579*67e74705SXin Li       E->setType(DestType);
14580*67e74705SXin Li 
14581*67e74705SXin Li       // Build the sub-expression as if it were an object of the pointee type.
14582*67e74705SXin Li       DestType = Ptr->getPointeeType();
14583*67e74705SXin Li       ExprResult SubResult = Visit(E->getSubExpr());
14584*67e74705SXin Li       if (SubResult.isInvalid()) return ExprError();
14585*67e74705SXin Li       E->setSubExpr(SubResult.get());
14586*67e74705SXin Li       return E;
14587*67e74705SXin Li     }
14588*67e74705SXin Li 
14589*67e74705SXin Li     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14590*67e74705SXin Li 
14591*67e74705SXin Li     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14592*67e74705SXin Li 
VisitMemberExpr__anon3c1752cc0c11::RebuildUnknownAnyExpr14593*67e74705SXin Li     ExprResult VisitMemberExpr(MemberExpr *E) {
14594*67e74705SXin Li       return resolveDecl(E, E->getMemberDecl());
14595*67e74705SXin Li     }
14596*67e74705SXin Li 
VisitDeclRefExpr__anon3c1752cc0c11::RebuildUnknownAnyExpr14597*67e74705SXin Li     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14598*67e74705SXin Li       return resolveDecl(E, E->getDecl());
14599*67e74705SXin Li     }
14600*67e74705SXin Li   };
14601*67e74705SXin Li }
14602*67e74705SXin Li 
14603*67e74705SXin Li /// Rebuilds a call expression which yielded __unknown_anytype.
VisitCallExpr(CallExpr * E)14604*67e74705SXin Li ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14605*67e74705SXin Li   Expr *CalleeExpr = E->getCallee();
14606*67e74705SXin Li 
14607*67e74705SXin Li   enum FnKind {
14608*67e74705SXin Li     FK_MemberFunction,
14609*67e74705SXin Li     FK_FunctionPointer,
14610*67e74705SXin Li     FK_BlockPointer
14611*67e74705SXin Li   };
14612*67e74705SXin Li 
14613*67e74705SXin Li   FnKind Kind;
14614*67e74705SXin Li   QualType CalleeType = CalleeExpr->getType();
14615*67e74705SXin Li   if (CalleeType == S.Context.BoundMemberTy) {
14616*67e74705SXin Li     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14617*67e74705SXin Li     Kind = FK_MemberFunction;
14618*67e74705SXin Li     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14619*67e74705SXin Li   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14620*67e74705SXin Li     CalleeType = Ptr->getPointeeType();
14621*67e74705SXin Li     Kind = FK_FunctionPointer;
14622*67e74705SXin Li   } else {
14623*67e74705SXin Li     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14624*67e74705SXin Li     Kind = FK_BlockPointer;
14625*67e74705SXin Li   }
14626*67e74705SXin Li   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14627*67e74705SXin Li 
14628*67e74705SXin Li   // Verify that this is a legal result type of a function.
14629*67e74705SXin Li   if (DestType->isArrayType() || DestType->isFunctionType()) {
14630*67e74705SXin Li     unsigned diagID = diag::err_func_returning_array_function;
14631*67e74705SXin Li     if (Kind == FK_BlockPointer)
14632*67e74705SXin Li       diagID = diag::err_block_returning_array_function;
14633*67e74705SXin Li 
14634*67e74705SXin Li     S.Diag(E->getExprLoc(), diagID)
14635*67e74705SXin Li       << DestType->isFunctionType() << DestType;
14636*67e74705SXin Li     return ExprError();
14637*67e74705SXin Li   }
14638*67e74705SXin Li 
14639*67e74705SXin Li   // Otherwise, go ahead and set DestType as the call's result.
14640*67e74705SXin Li   E->setType(DestType.getNonLValueExprType(S.Context));
14641*67e74705SXin Li   E->setValueKind(Expr::getValueKindForType(DestType));
14642*67e74705SXin Li   assert(E->getObjectKind() == OK_Ordinary);
14643*67e74705SXin Li 
14644*67e74705SXin Li   // Rebuild the function type, replacing the result type with DestType.
14645*67e74705SXin Li   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14646*67e74705SXin Li   if (Proto) {
14647*67e74705SXin Li     // __unknown_anytype(...) is a special case used by the debugger when
14648*67e74705SXin Li     // it has no idea what a function's signature is.
14649*67e74705SXin Li     //
14650*67e74705SXin Li     // We want to build this call essentially under the K&R
14651*67e74705SXin Li     // unprototyped rules, but making a FunctionNoProtoType in C++
14652*67e74705SXin Li     // would foul up all sorts of assumptions.  However, we cannot
14653*67e74705SXin Li     // simply pass all arguments as variadic arguments, nor can we
14654*67e74705SXin Li     // portably just call the function under a non-variadic type; see
14655*67e74705SXin Li     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14656*67e74705SXin Li     // However, it turns out that in practice it is generally safe to
14657*67e74705SXin Li     // call a function declared as "A foo(B,C,D);" under the prototype
14658*67e74705SXin Li     // "A foo(B,C,D,...);".  The only known exception is with the
14659*67e74705SXin Li     // Windows ABI, where any variadic function is implicitly cdecl
14660*67e74705SXin Li     // regardless of its normal CC.  Therefore we change the parameter
14661*67e74705SXin Li     // types to match the types of the arguments.
14662*67e74705SXin Li     //
14663*67e74705SXin Li     // This is a hack, but it is far superior to moving the
14664*67e74705SXin Li     // corresponding target-specific code from IR-gen to Sema/AST.
14665*67e74705SXin Li 
14666*67e74705SXin Li     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14667*67e74705SXin Li     SmallVector<QualType, 8> ArgTypes;
14668*67e74705SXin Li     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14669*67e74705SXin Li       ArgTypes.reserve(E->getNumArgs());
14670*67e74705SXin Li       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14671*67e74705SXin Li         Expr *Arg = E->getArg(i);
14672*67e74705SXin Li         QualType ArgType = Arg->getType();
14673*67e74705SXin Li         if (E->isLValue()) {
14674*67e74705SXin Li           ArgType = S.Context.getLValueReferenceType(ArgType);
14675*67e74705SXin Li         } else if (E->isXValue()) {
14676*67e74705SXin Li           ArgType = S.Context.getRValueReferenceType(ArgType);
14677*67e74705SXin Li         }
14678*67e74705SXin Li         ArgTypes.push_back(ArgType);
14679*67e74705SXin Li       }
14680*67e74705SXin Li       ParamTypes = ArgTypes;
14681*67e74705SXin Li     }
14682*67e74705SXin Li     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14683*67e74705SXin Li                                          Proto->getExtProtoInfo());
14684*67e74705SXin Li   } else {
14685*67e74705SXin Li     DestType = S.Context.getFunctionNoProtoType(DestType,
14686*67e74705SXin Li                                                 FnType->getExtInfo());
14687*67e74705SXin Li   }
14688*67e74705SXin Li 
14689*67e74705SXin Li   // Rebuild the appropriate pointer-to-function type.
14690*67e74705SXin Li   switch (Kind) {
14691*67e74705SXin Li   case FK_MemberFunction:
14692*67e74705SXin Li     // Nothing to do.
14693*67e74705SXin Li     break;
14694*67e74705SXin Li 
14695*67e74705SXin Li   case FK_FunctionPointer:
14696*67e74705SXin Li     DestType = S.Context.getPointerType(DestType);
14697*67e74705SXin Li     break;
14698*67e74705SXin Li 
14699*67e74705SXin Li   case FK_BlockPointer:
14700*67e74705SXin Li     DestType = S.Context.getBlockPointerType(DestType);
14701*67e74705SXin Li     break;
14702*67e74705SXin Li   }
14703*67e74705SXin Li 
14704*67e74705SXin Li   // Finally, we can recurse.
14705*67e74705SXin Li   ExprResult CalleeResult = Visit(CalleeExpr);
14706*67e74705SXin Li   if (!CalleeResult.isUsable()) return ExprError();
14707*67e74705SXin Li   E->setCallee(CalleeResult.get());
14708*67e74705SXin Li 
14709*67e74705SXin Li   // Bind a temporary if necessary.
14710*67e74705SXin Li   return S.MaybeBindToTemporary(E);
14711*67e74705SXin Li }
14712*67e74705SXin Li 
VisitObjCMessageExpr(ObjCMessageExpr * E)14713*67e74705SXin Li ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14714*67e74705SXin Li   // Verify that this is a legal result type of a call.
14715*67e74705SXin Li   if (DestType->isArrayType() || DestType->isFunctionType()) {
14716*67e74705SXin Li     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14717*67e74705SXin Li       << DestType->isFunctionType() << DestType;
14718*67e74705SXin Li     return ExprError();
14719*67e74705SXin Li   }
14720*67e74705SXin Li 
14721*67e74705SXin Li   // Rewrite the method result type if available.
14722*67e74705SXin Li   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14723*67e74705SXin Li     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14724*67e74705SXin Li     Method->setReturnType(DestType);
14725*67e74705SXin Li   }
14726*67e74705SXin Li 
14727*67e74705SXin Li   // Change the type of the message.
14728*67e74705SXin Li   E->setType(DestType.getNonReferenceType());
14729*67e74705SXin Li   E->setValueKind(Expr::getValueKindForType(DestType));
14730*67e74705SXin Li 
14731*67e74705SXin Li   return S.MaybeBindToTemporary(E);
14732*67e74705SXin Li }
14733*67e74705SXin Li 
VisitImplicitCastExpr(ImplicitCastExpr * E)14734*67e74705SXin Li ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14735*67e74705SXin Li   // The only case we should ever see here is a function-to-pointer decay.
14736*67e74705SXin Li   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14737*67e74705SXin Li     assert(E->getValueKind() == VK_RValue);
14738*67e74705SXin Li     assert(E->getObjectKind() == OK_Ordinary);
14739*67e74705SXin Li 
14740*67e74705SXin Li     E->setType(DestType);
14741*67e74705SXin Li 
14742*67e74705SXin Li     // Rebuild the sub-expression as the pointee (function) type.
14743*67e74705SXin Li     DestType = DestType->castAs<PointerType>()->getPointeeType();
14744*67e74705SXin Li 
14745*67e74705SXin Li     ExprResult Result = Visit(E->getSubExpr());
14746*67e74705SXin Li     if (!Result.isUsable()) return ExprError();
14747*67e74705SXin Li 
14748*67e74705SXin Li     E->setSubExpr(Result.get());
14749*67e74705SXin Li     return E;
14750*67e74705SXin Li   } else if (E->getCastKind() == CK_LValueToRValue) {
14751*67e74705SXin Li     assert(E->getValueKind() == VK_RValue);
14752*67e74705SXin Li     assert(E->getObjectKind() == OK_Ordinary);
14753*67e74705SXin Li 
14754*67e74705SXin Li     assert(isa<BlockPointerType>(E->getType()));
14755*67e74705SXin Li 
14756*67e74705SXin Li     E->setType(DestType);
14757*67e74705SXin Li 
14758*67e74705SXin Li     // The sub-expression has to be a lvalue reference, so rebuild it as such.
14759*67e74705SXin Li     DestType = S.Context.getLValueReferenceType(DestType);
14760*67e74705SXin Li 
14761*67e74705SXin Li     ExprResult Result = Visit(E->getSubExpr());
14762*67e74705SXin Li     if (!Result.isUsable()) return ExprError();
14763*67e74705SXin Li 
14764*67e74705SXin Li     E->setSubExpr(Result.get());
14765*67e74705SXin Li     return E;
14766*67e74705SXin Li   } else {
14767*67e74705SXin Li     llvm_unreachable("Unhandled cast type!");
14768*67e74705SXin Li   }
14769*67e74705SXin Li }
14770*67e74705SXin Li 
resolveDecl(Expr * E,ValueDecl * VD)14771*67e74705SXin Li ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14772*67e74705SXin Li   ExprValueKind ValueKind = VK_LValue;
14773*67e74705SXin Li   QualType Type = DestType;
14774*67e74705SXin Li 
14775*67e74705SXin Li   // We know how to make this work for certain kinds of decls:
14776*67e74705SXin Li 
14777*67e74705SXin Li   //  - functions
14778*67e74705SXin Li   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14779*67e74705SXin Li     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14780*67e74705SXin Li       DestType = Ptr->getPointeeType();
14781*67e74705SXin Li       ExprResult Result = resolveDecl(E, VD);
14782*67e74705SXin Li       if (Result.isInvalid()) return ExprError();
14783*67e74705SXin Li       return S.ImpCastExprToType(Result.get(), Type,
14784*67e74705SXin Li                                  CK_FunctionToPointerDecay, VK_RValue);
14785*67e74705SXin Li     }
14786*67e74705SXin Li 
14787*67e74705SXin Li     if (!Type->isFunctionType()) {
14788*67e74705SXin Li       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14789*67e74705SXin Li         << VD << E->getSourceRange();
14790*67e74705SXin Li       return ExprError();
14791*67e74705SXin Li     }
14792*67e74705SXin Li     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14793*67e74705SXin Li       // We must match the FunctionDecl's type to the hack introduced in
14794*67e74705SXin Li       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14795*67e74705SXin Li       // type. See the lengthy commentary in that routine.
14796*67e74705SXin Li       QualType FDT = FD->getType();
14797*67e74705SXin Li       const FunctionType *FnType = FDT->castAs<FunctionType>();
14798*67e74705SXin Li       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14799*67e74705SXin Li       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14800*67e74705SXin Li       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14801*67e74705SXin Li         SourceLocation Loc = FD->getLocation();
14802*67e74705SXin Li         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14803*67e74705SXin Li                                       FD->getDeclContext(),
14804*67e74705SXin Li                                       Loc, Loc, FD->getNameInfo().getName(),
14805*67e74705SXin Li                                       DestType, FD->getTypeSourceInfo(),
14806*67e74705SXin Li                                       SC_None, false/*isInlineSpecified*/,
14807*67e74705SXin Li                                       FD->hasPrototype(),
14808*67e74705SXin Li                                       false/*isConstexprSpecified*/);
14809*67e74705SXin Li 
14810*67e74705SXin Li         if (FD->getQualifier())
14811*67e74705SXin Li           NewFD->setQualifierInfo(FD->getQualifierLoc());
14812*67e74705SXin Li 
14813*67e74705SXin Li         SmallVector<ParmVarDecl*, 16> Params;
14814*67e74705SXin Li         for (const auto &AI : FT->param_types()) {
14815*67e74705SXin Li           ParmVarDecl *Param =
14816*67e74705SXin Li             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14817*67e74705SXin Li           Param->setScopeInfo(0, Params.size());
14818*67e74705SXin Li           Params.push_back(Param);
14819*67e74705SXin Li         }
14820*67e74705SXin Li         NewFD->setParams(Params);
14821*67e74705SXin Li         DRE->setDecl(NewFD);
14822*67e74705SXin Li         VD = DRE->getDecl();
14823*67e74705SXin Li       }
14824*67e74705SXin Li     }
14825*67e74705SXin Li 
14826*67e74705SXin Li     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14827*67e74705SXin Li       if (MD->isInstance()) {
14828*67e74705SXin Li         ValueKind = VK_RValue;
14829*67e74705SXin Li         Type = S.Context.BoundMemberTy;
14830*67e74705SXin Li       }
14831*67e74705SXin Li 
14832*67e74705SXin Li     // Function references aren't l-values in C.
14833*67e74705SXin Li     if (!S.getLangOpts().CPlusPlus)
14834*67e74705SXin Li       ValueKind = VK_RValue;
14835*67e74705SXin Li 
14836*67e74705SXin Li   //  - variables
14837*67e74705SXin Li   } else if (isa<VarDecl>(VD)) {
14838*67e74705SXin Li     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14839*67e74705SXin Li       Type = RefTy->getPointeeType();
14840*67e74705SXin Li     } else if (Type->isFunctionType()) {
14841*67e74705SXin Li       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14842*67e74705SXin Li         << VD << E->getSourceRange();
14843*67e74705SXin Li       return ExprError();
14844*67e74705SXin Li     }
14845*67e74705SXin Li 
14846*67e74705SXin Li   //  - nothing else
14847*67e74705SXin Li   } else {
14848*67e74705SXin Li     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14849*67e74705SXin Li       << VD << E->getSourceRange();
14850*67e74705SXin Li     return ExprError();
14851*67e74705SXin Li   }
14852*67e74705SXin Li 
14853*67e74705SXin Li   // Modifying the declaration like this is friendly to IR-gen but
14854*67e74705SXin Li   // also really dangerous.
14855*67e74705SXin Li   VD->setType(DestType);
14856*67e74705SXin Li   E->setType(Type);
14857*67e74705SXin Li   E->setValueKind(ValueKind);
14858*67e74705SXin Li   return E;
14859*67e74705SXin Li }
14860*67e74705SXin Li 
14861*67e74705SXin Li /// Check a cast of an unknown-any type.  We intentionally only
14862*67e74705SXin Li /// trigger this for C-style casts.
checkUnknownAnyCast(SourceRange TypeRange,QualType CastType,Expr * CastExpr,CastKind & CastKind,ExprValueKind & VK,CXXCastPath & Path)14863*67e74705SXin Li ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14864*67e74705SXin Li                                      Expr *CastExpr, CastKind &CastKind,
14865*67e74705SXin Li                                      ExprValueKind &VK, CXXCastPath &Path) {
14866*67e74705SXin Li   // The type we're casting to must be either void or complete.
14867*67e74705SXin Li   if (!CastType->isVoidType() &&
14868*67e74705SXin Li       RequireCompleteType(TypeRange.getBegin(), CastType,
14869*67e74705SXin Li                           diag::err_typecheck_cast_to_incomplete))
14870*67e74705SXin Li     return ExprError();
14871*67e74705SXin Li 
14872*67e74705SXin Li   // Rewrite the casted expression from scratch.
14873*67e74705SXin Li   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14874*67e74705SXin Li   if (!result.isUsable()) return ExprError();
14875*67e74705SXin Li 
14876*67e74705SXin Li   CastExpr = result.get();
14877*67e74705SXin Li   VK = CastExpr->getValueKind();
14878*67e74705SXin Li   CastKind = CK_NoOp;
14879*67e74705SXin Li 
14880*67e74705SXin Li   return CastExpr;
14881*67e74705SXin Li }
14882*67e74705SXin Li 
forceUnknownAnyToType(Expr * E,QualType ToType)14883*67e74705SXin Li ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14884*67e74705SXin Li   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14885*67e74705SXin Li }
14886*67e74705SXin Li 
checkUnknownAnyArg(SourceLocation callLoc,Expr * arg,QualType & paramType)14887*67e74705SXin Li ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14888*67e74705SXin Li                                     Expr *arg, QualType &paramType) {
14889*67e74705SXin Li   // If the syntactic form of the argument is not an explicit cast of
14890*67e74705SXin Li   // any sort, just do default argument promotion.
14891*67e74705SXin Li   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14892*67e74705SXin Li   if (!castArg) {
14893*67e74705SXin Li     ExprResult result = DefaultArgumentPromotion(arg);
14894*67e74705SXin Li     if (result.isInvalid()) return ExprError();
14895*67e74705SXin Li     paramType = result.get()->getType();
14896*67e74705SXin Li     return result;
14897*67e74705SXin Li   }
14898*67e74705SXin Li 
14899*67e74705SXin Li   // Otherwise, use the type that was written in the explicit cast.
14900*67e74705SXin Li   assert(!arg->hasPlaceholderType());
14901*67e74705SXin Li   paramType = castArg->getTypeAsWritten();
14902*67e74705SXin Li 
14903*67e74705SXin Li   // Copy-initialize a parameter of that type.
14904*67e74705SXin Li   InitializedEntity entity =
14905*67e74705SXin Li     InitializedEntity::InitializeParameter(Context, paramType,
14906*67e74705SXin Li                                            /*consumed*/ false);
14907*67e74705SXin Li   return PerformCopyInitialization(entity, callLoc, arg);
14908*67e74705SXin Li }
14909*67e74705SXin Li 
diagnoseUnknownAnyExpr(Sema & S,Expr * E)14910*67e74705SXin Li static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14911*67e74705SXin Li   Expr *orig = E;
14912*67e74705SXin Li   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
14913*67e74705SXin Li   while (true) {
14914*67e74705SXin Li     E = E->IgnoreParenImpCasts();
14915*67e74705SXin Li     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14916*67e74705SXin Li       E = call->getCallee();
14917*67e74705SXin Li       diagID = diag::err_uncasted_call_of_unknown_any;
14918*67e74705SXin Li     } else {
14919*67e74705SXin Li       break;
14920*67e74705SXin Li     }
14921*67e74705SXin Li   }
14922*67e74705SXin Li 
14923*67e74705SXin Li   SourceLocation loc;
14924*67e74705SXin Li   NamedDecl *d;
14925*67e74705SXin Li   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
14926*67e74705SXin Li     loc = ref->getLocation();
14927*67e74705SXin Li     d = ref->getDecl();
14928*67e74705SXin Li   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
14929*67e74705SXin Li     loc = mem->getMemberLoc();
14930*67e74705SXin Li     d = mem->getMemberDecl();
14931*67e74705SXin Li   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
14932*67e74705SXin Li     diagID = diag::err_uncasted_call_of_unknown_any;
14933*67e74705SXin Li     loc = msg->getSelectorStartLoc();
14934*67e74705SXin Li     d = msg->getMethodDecl();
14935*67e74705SXin Li     if (!d) {
14936*67e74705SXin Li       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14937*67e74705SXin Li         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14938*67e74705SXin Li         << orig->getSourceRange();
14939*67e74705SXin Li       return ExprError();
14940*67e74705SXin Li     }
14941*67e74705SXin Li   } else {
14942*67e74705SXin Li     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14943*67e74705SXin Li       << E->getSourceRange();
14944*67e74705SXin Li     return ExprError();
14945*67e74705SXin Li   }
14946*67e74705SXin Li 
14947*67e74705SXin Li   S.Diag(loc, diagID) << d << orig->getSourceRange();
14948*67e74705SXin Li 
14949*67e74705SXin Li   // Never recoverable.
14950*67e74705SXin Li   return ExprError();
14951*67e74705SXin Li }
14952*67e74705SXin Li 
14953*67e74705SXin Li /// Check for operands with placeholder types and complain if found.
14954*67e74705SXin Li /// Returns true if there was an error and no recovery was possible.
CheckPlaceholderExpr(Expr * E)14955*67e74705SXin Li ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
14956*67e74705SXin Li   if (!getLangOpts().CPlusPlus) {
14957*67e74705SXin Li     // C cannot handle TypoExpr nodes on either side of a binop because it
14958*67e74705SXin Li     // doesn't handle dependent types properly, so make sure any TypoExprs have
14959*67e74705SXin Li     // been dealt with before checking the operands.
14960*67e74705SXin Li     ExprResult Result = CorrectDelayedTyposInExpr(E);
14961*67e74705SXin Li     if (!Result.isUsable()) return ExprError();
14962*67e74705SXin Li     E = Result.get();
14963*67e74705SXin Li   }
14964*67e74705SXin Li 
14965*67e74705SXin Li   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
14966*67e74705SXin Li   if (!placeholderType) return E;
14967*67e74705SXin Li 
14968*67e74705SXin Li   switch (placeholderType->getKind()) {
14969*67e74705SXin Li 
14970*67e74705SXin Li   // Overloaded expressions.
14971*67e74705SXin Li   case BuiltinType::Overload: {
14972*67e74705SXin Li     // Try to resolve a single function template specialization.
14973*67e74705SXin Li     // This is obligatory.
14974*67e74705SXin Li     ExprResult Result = E;
14975*67e74705SXin Li     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
14976*67e74705SXin Li       return Result;
14977*67e74705SXin Li 
14978*67e74705SXin Li     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
14979*67e74705SXin Li     // leaves Result unchanged on failure.
14980*67e74705SXin Li     Result = E;
14981*67e74705SXin Li     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
14982*67e74705SXin Li       return Result;
14983*67e74705SXin Li 
14984*67e74705SXin Li     // If that failed, try to recover with a call.
14985*67e74705SXin Li     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
14986*67e74705SXin Li                          /*complain*/ true);
14987*67e74705SXin Li     return Result;
14988*67e74705SXin Li   }
14989*67e74705SXin Li 
14990*67e74705SXin Li   // Bound member functions.
14991*67e74705SXin Li   case BuiltinType::BoundMember: {
14992*67e74705SXin Li     ExprResult result = E;
14993*67e74705SXin Li     const Expr *BME = E->IgnoreParens();
14994*67e74705SXin Li     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
14995*67e74705SXin Li     // Try to give a nicer diagnostic if it is a bound member that we recognize.
14996*67e74705SXin Li     if (isa<CXXPseudoDestructorExpr>(BME)) {
14997*67e74705SXin Li       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
14998*67e74705SXin Li     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
14999*67e74705SXin Li       if (ME->getMemberNameInfo().getName().getNameKind() ==
15000*67e74705SXin Li           DeclarationName::CXXDestructorName)
15001*67e74705SXin Li         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15002*67e74705SXin Li     }
15003*67e74705SXin Li     tryToRecoverWithCall(result, PD,
15004*67e74705SXin Li                          /*complain*/ true);
15005*67e74705SXin Li     return result;
15006*67e74705SXin Li   }
15007*67e74705SXin Li 
15008*67e74705SXin Li   // ARC unbridged casts.
15009*67e74705SXin Li   case BuiltinType::ARCUnbridgedCast: {
15010*67e74705SXin Li     Expr *realCast = stripARCUnbridgedCast(E);
15011*67e74705SXin Li     diagnoseARCUnbridgedCast(realCast);
15012*67e74705SXin Li     return realCast;
15013*67e74705SXin Li   }
15014*67e74705SXin Li 
15015*67e74705SXin Li   // Expressions of unknown type.
15016*67e74705SXin Li   case BuiltinType::UnknownAny:
15017*67e74705SXin Li     return diagnoseUnknownAnyExpr(*this, E);
15018*67e74705SXin Li 
15019*67e74705SXin Li   // Pseudo-objects.
15020*67e74705SXin Li   case BuiltinType::PseudoObject:
15021*67e74705SXin Li     return checkPseudoObjectRValue(E);
15022*67e74705SXin Li 
15023*67e74705SXin Li   case BuiltinType::BuiltinFn: {
15024*67e74705SXin Li     // Accept __noop without parens by implicitly converting it to a call expr.
15025*67e74705SXin Li     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15026*67e74705SXin Li     if (DRE) {
15027*67e74705SXin Li       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15028*67e74705SXin Li       if (FD->getBuiltinID() == Builtin::BI__noop) {
15029*67e74705SXin Li         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15030*67e74705SXin Li                               CK_BuiltinFnToFnPtr).get();
15031*67e74705SXin Li         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15032*67e74705SXin Li                                       VK_RValue, SourceLocation());
15033*67e74705SXin Li       }
15034*67e74705SXin Li     }
15035*67e74705SXin Li 
15036*67e74705SXin Li     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15037*67e74705SXin Li     return ExprError();
15038*67e74705SXin Li   }
15039*67e74705SXin Li 
15040*67e74705SXin Li   // Expressions of unknown type.
15041*67e74705SXin Li   case BuiltinType::OMPArraySection:
15042*67e74705SXin Li     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15043*67e74705SXin Li     return ExprError();
15044*67e74705SXin Li 
15045*67e74705SXin Li   // Everything else should be impossible.
15046*67e74705SXin Li #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15047*67e74705SXin Li   case BuiltinType::Id:
15048*67e74705SXin Li #include "clang/Basic/OpenCLImageTypes.def"
15049*67e74705SXin Li #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15050*67e74705SXin Li #define PLACEHOLDER_TYPE(Id, SingletonId)
15051*67e74705SXin Li #include "clang/AST/BuiltinTypes.def"
15052*67e74705SXin Li     break;
15053*67e74705SXin Li   }
15054*67e74705SXin Li 
15055*67e74705SXin Li   llvm_unreachable("invalid placeholder type!");
15056*67e74705SXin Li }
15057*67e74705SXin Li 
CheckCaseExpression(Expr * E)15058*67e74705SXin Li bool Sema::CheckCaseExpression(Expr *E) {
15059*67e74705SXin Li   if (E->isTypeDependent())
15060*67e74705SXin Li     return true;
15061*67e74705SXin Li   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15062*67e74705SXin Li     return E->getType()->isIntegralOrEnumerationType();
15063*67e74705SXin Li   return false;
15064*67e74705SXin Li }
15065*67e74705SXin Li 
15066*67e74705SXin Li /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15067*67e74705SXin Li ExprResult
ActOnObjCBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)15068*67e74705SXin Li Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15069*67e74705SXin Li   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15070*67e74705SXin Li          "Unknown Objective-C Boolean value!");
15071*67e74705SXin Li   QualType BoolT = Context.ObjCBuiltinBoolTy;
15072*67e74705SXin Li   if (!Context.getBOOLDecl()) {
15073*67e74705SXin Li     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15074*67e74705SXin Li                         Sema::LookupOrdinaryName);
15075*67e74705SXin Li     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15076*67e74705SXin Li       NamedDecl *ND = Result.getFoundDecl();
15077*67e74705SXin Li       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15078*67e74705SXin Li         Context.setBOOLDecl(TD);
15079*67e74705SXin Li     }
15080*67e74705SXin Li   }
15081*67e74705SXin Li   if (Context.getBOOLDecl())
15082*67e74705SXin Li     BoolT = Context.getBOOLType();
15083*67e74705SXin Li   return new (Context)
15084*67e74705SXin Li       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15085*67e74705SXin Li }
15086