• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/Template.h"
45 using namespace clang;
46 using namespace sema;
47 
48 /// \brief Determine whether the use of this declaration is valid, without
49 /// emitting diagnostics.
CanUseDecl(NamedDecl * D)50 bool Sema::CanUseDecl(NamedDecl *D) {
51   // See if this is an auto-typed variable whose initializer we are parsing.
52   if (ParsingInitForAutoVars.count(D))
53     return false;
54 
55   // See if this is a deleted function.
56   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57     if (FD->isDeleted())
58       return false;
59 
60     // If the function has a deduced return type, and we can't deduce it,
61     // then we can't use it either.
62     if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() &&
63         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
64       return false;
65   }
66 
67   // See if this function is unavailable.
68   if (D->getAvailability() == AR_Unavailable &&
69       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
70     return false;
71 
72   return true;
73 }
74 
DiagnoseUnusedOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc)75 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
76   // Warn if this is used but marked unused.
77   if (D->hasAttr<UnusedAttr>()) {
78     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
79     if (!DC->hasAttr<UnusedAttr>())
80       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
81   }
82 }
83 
DiagnoseAvailabilityOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess)84 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
85                               NamedDecl *D, SourceLocation Loc,
86                               const ObjCInterfaceDecl *UnknownObjCClass,
87                               bool ObjCPropertyAccess) {
88   // See if this declaration is unavailable or deprecated.
89   std::string Message;
90 
91   // Forward class declarations get their attributes from their definition.
92   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
93     if (IDecl->getDefinition())
94       D = IDecl->getDefinition();
95   }
96   AvailabilityResult Result = D->getAvailability(&Message);
97   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
98     if (Result == AR_Available) {
99       const DeclContext *DC = ECD->getDeclContext();
100       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
101         Result = TheEnumDecl->getAvailability(&Message);
102     }
103 
104   const ObjCPropertyDecl *ObjCPDecl = nullptr;
105   if (Result == AR_Deprecated || Result == AR_Unavailable) {
106     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
107       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
108         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
109         if (PDeclResult == Result)
110           ObjCPDecl = PD;
111       }
112     }
113   }
114 
115   switch (Result) {
116     case AR_Available:
117     case AR_NotYetIntroduced:
118       break;
119 
120     case AR_Deprecated:
121       if (S.getCurContextAvailability() != AR_Deprecated)
122         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
123                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
124                                   ObjCPropertyAccess);
125       break;
126 
127     case AR_Unavailable:
128       if (S.getCurContextAvailability() != AR_Unavailable)
129         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
130                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
131                                   ObjCPropertyAccess);
132       break;
133 
134     }
135     return Result;
136 }
137 
138 /// \brief Emit a note explaining that this function is deleted.
NoteDeletedFunction(FunctionDecl * Decl)139 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
140   assert(Decl->isDeleted());
141 
142   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
143 
144   if (Method && Method->isDeleted() && Method->isDefaulted()) {
145     // If the method was explicitly defaulted, point at that declaration.
146     if (!Method->isImplicit())
147       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
148 
149     // Try to diagnose why this special member function was implicitly
150     // deleted. This might fail, if that reason no longer applies.
151     CXXSpecialMember CSM = getSpecialMember(Method);
152     if (CSM != CXXInvalid)
153       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
154 
155     return;
156   }
157 
158   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
159     if (CXXConstructorDecl *BaseCD =
160             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
161       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
162       if (BaseCD->isDeleted()) {
163         NoteDeletedFunction(BaseCD);
164       } else {
165         // FIXME: An explanation of why exactly it can't be inherited
166         // would be nice.
167         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
168       }
169       return;
170     }
171   }
172 
173   Diag(Decl->getLocation(), diag::note_availability_specified_here)
174     << Decl << true;
175 }
176 
177 /// \brief Determine whether a FunctionDecl was ever declared with an
178 /// explicit storage class.
hasAnyExplicitStorageClass(const FunctionDecl * D)179 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
180   for (auto I : D->redecls()) {
181     if (I->getStorageClass() != SC_None)
182       return true;
183   }
184   return false;
185 }
186 
187 /// \brief Check whether we're in an extern inline function and referring to a
188 /// variable or function with internal linkage (C11 6.7.4p3).
189 ///
190 /// This is only a warning because we used to silently accept this code, but
191 /// in many cases it will not behave correctly. This is not enabled in C++ mode
192 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
193 /// and so while there may still be user mistakes, most of the time we can't
194 /// prove that there are errors.
diagnoseUseOfInternalDeclInInlineFunction(Sema & S,const NamedDecl * D,SourceLocation Loc)195 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
196                                                       const NamedDecl *D,
197                                                       SourceLocation Loc) {
198   // This is disabled under C++; there are too many ways for this to fire in
199   // contexts where the warning is a false positive, or where it is technically
200   // correct but benign.
201   if (S.getLangOpts().CPlusPlus)
202     return;
203 
204   // Check if this is an inlined function or method.
205   FunctionDecl *Current = S.getCurFunctionDecl();
206   if (!Current)
207     return;
208   if (!Current->isInlined())
209     return;
210   if (!Current->isExternallyVisible())
211     return;
212 
213   // Check if the decl has internal linkage.
214   if (D->getFormalLinkage() != InternalLinkage)
215     return;
216 
217   // Downgrade from ExtWarn to Extension if
218   //  (1) the supposedly external inline function is in the main file,
219   //      and probably won't be included anywhere else.
220   //  (2) the thing we're referencing is a pure function.
221   //  (3) the thing we're referencing is another inline function.
222   // This last can give us false negatives, but it's better than warning on
223   // wrappers for simple C library functions.
224   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
225   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
226   if (!DowngradeWarning && UsedFn)
227     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
228 
229   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
230                                : diag::warn_internal_in_extern_inline)
231     << /*IsVar=*/!UsedFn << D;
232 
233   S.MaybeSuggestAddingStaticToDecl(Current);
234 
235   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
236       << D;
237 }
238 
MaybeSuggestAddingStaticToDecl(const FunctionDecl * Cur)239 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
240   const FunctionDecl *First = Cur->getFirstDecl();
241 
242   // Suggest "static" on the function, if possible.
243   if (!hasAnyExplicitStorageClass(First)) {
244     SourceLocation DeclBegin = First->getSourceRange().getBegin();
245     Diag(DeclBegin, diag::note_convert_inline_to_static)
246       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
247   }
248 }
249 
250 /// \brief Determine whether the use of this declaration is valid, and
251 /// emit any corresponding diagnostics.
252 ///
253 /// This routine diagnoses various problems with referencing
254 /// declarations that can occur when using a declaration. For example,
255 /// it might warn if a deprecated or unavailable declaration is being
256 /// used, or produce an error (and return true) if a C++0x deleted
257 /// function is being used.
258 ///
259 /// \returns true if there was an error (this declaration cannot be
260 /// referenced), false otherwise.
261 ///
DiagnoseUseOfDecl(NamedDecl * D,SourceLocation Loc,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess)262 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
263                              const ObjCInterfaceDecl *UnknownObjCClass,
264                              bool ObjCPropertyAccess) {
265   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
266     // If there were any diagnostics suppressed by template argument deduction,
267     // emit them now.
268     SuppressedDiagnosticsMap::iterator
269       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
270     if (Pos != SuppressedDiagnostics.end()) {
271       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
272       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
273         Diag(Suppressed[I].first, Suppressed[I].second);
274 
275       // Clear out the list of suppressed diagnostics, so that we don't emit
276       // them again for this specialization. However, we don't obsolete this
277       // entry from the table, because we want to avoid ever emitting these
278       // diagnostics again.
279       Suppressed.clear();
280     }
281 
282     // C++ [basic.start.main]p3:
283     //   The function 'main' shall not be used within a program.
284     if (cast<FunctionDecl>(D)->isMain())
285       Diag(Loc, diag::ext_main_used);
286   }
287 
288   // See if this is an auto-typed variable whose initializer we are parsing.
289   if (ParsingInitForAutoVars.count(D)) {
290     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
291       << D->getDeclName();
292     return true;
293   }
294 
295   // See if this is a deleted function.
296   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
297     if (FD->isDeleted()) {
298       Diag(Loc, diag::err_deleted_function_use);
299       NoteDeletedFunction(FD);
300       return true;
301     }
302 
303     // If the function has a deduced return type, and we can't deduce it,
304     // then we can't use it either.
305     if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() &&
306         DeduceReturnType(FD, Loc))
307       return true;
308   }
309   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, ObjCPropertyAccess);
310 
311   DiagnoseUnusedOfDecl(*this, D, Loc);
312 
313   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
314 
315   return false;
316 }
317 
318 /// \brief Retrieve the message suffix that should be added to a
319 /// diagnostic complaining about the given function being deleted or
320 /// unavailable.
getDeletedOrUnavailableSuffix(const FunctionDecl * FD)321 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
322   std::string Message;
323   if (FD->getAvailability(&Message))
324     return ": " + Message;
325 
326   return std::string();
327 }
328 
329 /// DiagnoseSentinelCalls - This routine checks whether a call or
330 /// message-send is to a declaration with the sentinel attribute, and
331 /// if so, it checks that the requirements of the sentinel are
332 /// satisfied.
DiagnoseSentinelCalls(NamedDecl * D,SourceLocation Loc,ArrayRef<Expr * > Args)333 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
334                                  ArrayRef<Expr *> Args) {
335   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
336   if (!attr)
337     return;
338 
339   // The number of formal parameters of the declaration.
340   unsigned numFormalParams;
341 
342   // The kind of declaration.  This is also an index into a %select in
343   // the diagnostic.
344   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
345 
346   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
347     numFormalParams = MD->param_size();
348     calleeType = CT_Method;
349   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
350     numFormalParams = FD->param_size();
351     calleeType = CT_Function;
352   } else if (isa<VarDecl>(D)) {
353     QualType type = cast<ValueDecl>(D)->getType();
354     const FunctionType *fn = nullptr;
355     if (const PointerType *ptr = type->getAs<PointerType>()) {
356       fn = ptr->getPointeeType()->getAs<FunctionType>();
357       if (!fn) return;
358       calleeType = CT_Function;
359     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
360       fn = ptr->getPointeeType()->castAs<FunctionType>();
361       calleeType = CT_Block;
362     } else {
363       return;
364     }
365 
366     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
367       numFormalParams = proto->getNumParams();
368     } else {
369       numFormalParams = 0;
370     }
371   } else {
372     return;
373   }
374 
375   // "nullPos" is the number of formal parameters at the end which
376   // effectively count as part of the variadic arguments.  This is
377   // useful if you would prefer to not have *any* formal parameters,
378   // but the language forces you to have at least one.
379   unsigned nullPos = attr->getNullPos();
380   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
381   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
382 
383   // The number of arguments which should follow the sentinel.
384   unsigned numArgsAfterSentinel = attr->getSentinel();
385 
386   // If there aren't enough arguments for all the formal parameters,
387   // the sentinel, and the args after the sentinel, complain.
388   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
389     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
390     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
391     return;
392   }
393 
394   // Otherwise, find the sentinel expression.
395   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
396   if (!sentinelExpr) return;
397   if (sentinelExpr->isValueDependent()) return;
398   if (Context.isSentinelNullExpr(sentinelExpr)) return;
399 
400   // Pick a reasonable string to insert.  Optimistically use 'nil' or
401   // 'NULL' if those are actually defined in the context.  Only use
402   // 'nil' for ObjC methods, where it's much more likely that the
403   // variadic arguments form a list of object pointers.
404   SourceLocation MissingNilLoc
405     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
406   std::string NullValue;
407   if (calleeType == CT_Method &&
408       PP.getIdentifierInfo("nil")->hasMacroDefinition())
409     NullValue = "nil";
410   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
411     NullValue = "NULL";
412   else
413     NullValue = "(void*) 0";
414 
415   if (MissingNilLoc.isInvalid())
416     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
417   else
418     Diag(MissingNilLoc, diag::warn_missing_sentinel)
419       << int(calleeType)
420       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
421   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
422 }
423 
getExprRange(Expr * E) const424 SourceRange Sema::getExprRange(Expr *E) const {
425   return E ? E->getSourceRange() : SourceRange();
426 }
427 
428 //===----------------------------------------------------------------------===//
429 //  Standard Promotions and Conversions
430 //===----------------------------------------------------------------------===//
431 
432 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
DefaultFunctionArrayConversion(Expr * E)433 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
434   // Handle any placeholder expressions which made it here.
435   if (E->getType()->isPlaceholderType()) {
436     ExprResult result = CheckPlaceholderExpr(E);
437     if (result.isInvalid()) return ExprError();
438     E = result.get();
439   }
440 
441   QualType Ty = E->getType();
442   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
443 
444   if (Ty->isFunctionType()) {
445     // If we are here, we are not calling a function but taking
446     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
447     if (getLangOpts().OpenCL) {
448       Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
449       return ExprError();
450     }
451     E = ImpCastExprToType(E, Context.getPointerType(Ty),
452                           CK_FunctionToPointerDecay).get();
453   } else if (Ty->isArrayType()) {
454     // In C90 mode, arrays only promote to pointers if the array expression is
455     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
456     // type 'array of type' is converted to an expression that has type 'pointer
457     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
458     // that has type 'array of type' ...".  The relevant change is "an lvalue"
459     // (C90) to "an expression" (C99).
460     //
461     // C++ 4.2p1:
462     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
463     // T" can be converted to an rvalue of type "pointer to T".
464     //
465     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
466       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
467                             CK_ArrayToPointerDecay).get();
468   }
469   return E;
470 }
471 
CheckForNullPointerDereference(Sema & S,Expr * E)472 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
473   // Check to see if we are dereferencing a null pointer.  If so,
474   // and if not volatile-qualified, this is undefined behavior that the
475   // optimizer will delete, so warn about it.  People sometimes try to use this
476   // to get a deterministic trap and are surprised by clang's behavior.  This
477   // only handles the pattern "*null", which is a very syntactic check.
478   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
479     if (UO->getOpcode() == UO_Deref &&
480         UO->getSubExpr()->IgnoreParenCasts()->
481           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
482         !UO->getType().isVolatileQualified()) {
483     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
484                           S.PDiag(diag::warn_indirection_through_null)
485                             << UO->getSubExpr()->getSourceRange());
486     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
487                         S.PDiag(diag::note_indirection_through_null));
488   }
489 }
490 
DiagnoseDirectIsaAccess(Sema & S,const ObjCIvarRefExpr * OIRE,SourceLocation AssignLoc,const Expr * RHS)491 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
492                                     SourceLocation AssignLoc,
493                                     const Expr* RHS) {
494   const ObjCIvarDecl *IV = OIRE->getDecl();
495   if (!IV)
496     return;
497 
498   DeclarationName MemberName = IV->getDeclName();
499   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
500   if (!Member || !Member->isStr("isa"))
501     return;
502 
503   const Expr *Base = OIRE->getBase();
504   QualType BaseType = Base->getType();
505   if (OIRE->isArrow())
506     BaseType = BaseType->getPointeeType();
507   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
508     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
509       ObjCInterfaceDecl *ClassDeclared = nullptr;
510       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
511       if (!ClassDeclared->getSuperClass()
512           && (*ClassDeclared->ivar_begin()) == IV) {
513         if (RHS) {
514           NamedDecl *ObjectSetClass =
515             S.LookupSingleName(S.TUScope,
516                                &S.Context.Idents.get("object_setClass"),
517                                SourceLocation(), S.LookupOrdinaryName);
518           if (ObjectSetClass) {
519             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
520             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
521             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
522             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
523                                                      AssignLoc), ",") <<
524             FixItHint::CreateInsertion(RHSLocEnd, ")");
525           }
526           else
527             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
528         } else {
529           NamedDecl *ObjectGetClass =
530             S.LookupSingleName(S.TUScope,
531                                &S.Context.Idents.get("object_getClass"),
532                                SourceLocation(), S.LookupOrdinaryName);
533           if (ObjectGetClass)
534             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
535             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
536             FixItHint::CreateReplacement(
537                                          SourceRange(OIRE->getOpLoc(),
538                                                      OIRE->getLocEnd()), ")");
539           else
540             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
541         }
542         S.Diag(IV->getLocation(), diag::note_ivar_decl);
543       }
544     }
545 }
546 
DefaultLvalueConversion(Expr * E)547 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
548   // Handle any placeholder expressions which made it here.
549   if (E->getType()->isPlaceholderType()) {
550     ExprResult result = CheckPlaceholderExpr(E);
551     if (result.isInvalid()) return ExprError();
552     E = result.get();
553   }
554 
555   // C++ [conv.lval]p1:
556   //   A glvalue of a non-function, non-array type T can be
557   //   converted to a prvalue.
558   if (!E->isGLValue()) return E;
559 
560   QualType T = E->getType();
561   assert(!T.isNull() && "r-value conversion on typeless expression?");
562 
563   // We don't want to throw lvalue-to-rvalue casts on top of
564   // expressions of certain types in C++.
565   if (getLangOpts().CPlusPlus &&
566       (E->getType() == Context.OverloadTy ||
567        T->isDependentType() ||
568        T->isRecordType()))
569     return E;
570 
571   // The C standard is actually really unclear on this point, and
572   // DR106 tells us what the result should be but not why.  It's
573   // generally best to say that void types just doesn't undergo
574   // lvalue-to-rvalue at all.  Note that expressions of unqualified
575   // 'void' type are never l-values, but qualified void can be.
576   if (T->isVoidType())
577     return E;
578 
579   // OpenCL usually rejects direct accesses to values of 'half' type.
580   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
581       T->isHalfType()) {
582     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
583       << 0 << T;
584     return ExprError();
585   }
586 
587   CheckForNullPointerDereference(*this, E);
588   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
589     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
590                                      &Context.Idents.get("object_getClass"),
591                                      SourceLocation(), LookupOrdinaryName);
592     if (ObjectGetClass)
593       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
594         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
595         FixItHint::CreateReplacement(
596                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
597     else
598       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
599   }
600   else if (const ObjCIvarRefExpr *OIRE =
601             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
602     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
603 
604   // C++ [conv.lval]p1:
605   //   [...] If T is a non-class type, the type of the prvalue is the
606   //   cv-unqualified version of T. Otherwise, the type of the
607   //   rvalue is T.
608   //
609   // C99 6.3.2.1p2:
610   //   If the lvalue has qualified type, the value has the unqualified
611   //   version of the type of the lvalue; otherwise, the value has the
612   //   type of the lvalue.
613   if (T.hasQualifiers())
614     T = T.getUnqualifiedType();
615 
616   UpdateMarkingForLValueToRValue(E);
617 
618   // Loading a __weak object implicitly retains the value, so we need a cleanup to
619   // balance that.
620   if (getLangOpts().ObjCAutoRefCount &&
621       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
622     ExprNeedsCleanups = true;
623 
624   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
625                                             nullptr, VK_RValue);
626 
627   // C11 6.3.2.1p2:
628   //   ... if the lvalue has atomic type, the value has the non-atomic version
629   //   of the type of the lvalue ...
630   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
631     T = Atomic->getValueType().getUnqualifiedType();
632     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
633                                    nullptr, VK_RValue);
634   }
635 
636   return Res;
637 }
638 
DefaultFunctionArrayLvalueConversion(Expr * E)639 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
640   ExprResult Res = DefaultFunctionArrayConversion(E);
641   if (Res.isInvalid())
642     return ExprError();
643   Res = DefaultLvalueConversion(Res.get());
644   if (Res.isInvalid())
645     return ExprError();
646   return Res;
647 }
648 
649 /// CallExprUnaryConversions - a special case of an unary conversion
650 /// performed on a function designator of a call expression.
CallExprUnaryConversions(Expr * E)651 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
652   QualType Ty = E->getType();
653   ExprResult Res = E;
654   // Only do implicit cast for a function type, but not for a pointer
655   // to function type.
656   if (Ty->isFunctionType()) {
657     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
658                             CK_FunctionToPointerDecay).get();
659     if (Res.isInvalid())
660       return ExprError();
661   }
662   Res = DefaultLvalueConversion(Res.get());
663   if (Res.isInvalid())
664     return ExprError();
665   return Res.get();
666 }
667 
668 /// UsualUnaryConversions - Performs various conversions that are common to most
669 /// operators (C99 6.3). The conversions of array and function types are
670 /// sometimes suppressed. For example, the array->pointer conversion doesn't
671 /// apply if the array is an argument to the sizeof or address (&) operators.
672 /// In these instances, this routine should *not* be called.
UsualUnaryConversions(Expr * E)673 ExprResult Sema::UsualUnaryConversions(Expr *E) {
674   // First, convert to an r-value.
675   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
676   if (Res.isInvalid())
677     return ExprError();
678   E = Res.get();
679 
680   QualType Ty = E->getType();
681   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
682 
683   // Half FP have to be promoted to float unless it is natively supported
684   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
685     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
686 
687   // Try to perform integral promotions if the object has a theoretically
688   // promotable type.
689   if (Ty->isIntegralOrUnscopedEnumerationType()) {
690     // C99 6.3.1.1p2:
691     //
692     //   The following may be used in an expression wherever an int or
693     //   unsigned int may be used:
694     //     - an object or expression with an integer type whose integer
695     //       conversion rank is less than or equal to the rank of int
696     //       and unsigned int.
697     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
698     //
699     //   If an int can represent all values of the original type, the
700     //   value is converted to an int; otherwise, it is converted to an
701     //   unsigned int. These are called the integer promotions. All
702     //   other types are unchanged by the integer promotions.
703 
704     QualType PTy = Context.isPromotableBitField(E);
705     if (!PTy.isNull()) {
706       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
707       return E;
708     }
709     if (Ty->isPromotableIntegerType()) {
710       QualType PT = Context.getPromotedIntegerType(Ty);
711       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
712       return E;
713     }
714   }
715   return E;
716 }
717 
718 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
719 /// do not have a prototype. Arguments that have type float or __fp16
720 /// are promoted to double. All other argument types are converted by
721 /// UsualUnaryConversions().
DefaultArgumentPromotion(Expr * E)722 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
723   QualType Ty = E->getType();
724   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
725 
726   ExprResult Res = UsualUnaryConversions(E);
727   if (Res.isInvalid())
728     return ExprError();
729   E = Res.get();
730 
731   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
732   // double.
733   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
734   if (BTy && (BTy->getKind() == BuiltinType::Half ||
735               BTy->getKind() == BuiltinType::Float))
736     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
737 
738   // C++ performs lvalue-to-rvalue conversion as a default argument
739   // promotion, even on class types, but note:
740   //   C++11 [conv.lval]p2:
741   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
742   //     operand or a subexpression thereof the value contained in the
743   //     referenced object is not accessed. Otherwise, if the glvalue
744   //     has a class type, the conversion copy-initializes a temporary
745   //     of type T from the glvalue and the result of the conversion
746   //     is a prvalue for the temporary.
747   // FIXME: add some way to gate this entire thing for correctness in
748   // potentially potentially evaluated contexts.
749   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
750     ExprResult Temp = PerformCopyInitialization(
751                        InitializedEntity::InitializeTemporary(E->getType()),
752                                                 E->getExprLoc(), E);
753     if (Temp.isInvalid())
754       return ExprError();
755     E = Temp.get();
756   }
757 
758   return E;
759 }
760 
761 /// Determine the degree of POD-ness for an expression.
762 /// Incomplete types are considered POD, since this check can be performed
763 /// when we're in an unevaluated context.
isValidVarArgType(const QualType & Ty)764 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
765   if (Ty->isIncompleteType()) {
766     // C++11 [expr.call]p7:
767     //   After these conversions, if the argument does not have arithmetic,
768     //   enumeration, pointer, pointer to member, or class type, the program
769     //   is ill-formed.
770     //
771     // Since we've already performed array-to-pointer and function-to-pointer
772     // decay, the only such type in C++ is cv void. This also handles
773     // initializer lists as variadic arguments.
774     if (Ty->isVoidType())
775       return VAK_Invalid;
776 
777     if (Ty->isObjCObjectType())
778       return VAK_Invalid;
779     return VAK_Valid;
780   }
781 
782   if (Ty.isCXX98PODType(Context))
783     return VAK_Valid;
784 
785   // C++11 [expr.call]p7:
786   //   Passing a potentially-evaluated argument of class type (Clause 9)
787   //   having a non-trivial copy constructor, a non-trivial move constructor,
788   //   or a non-trivial destructor, with no corresponding parameter,
789   //   is conditionally-supported with implementation-defined semantics.
790   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
791     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
792       if (!Record->hasNonTrivialCopyConstructor() &&
793           !Record->hasNonTrivialMoveConstructor() &&
794           !Record->hasNonTrivialDestructor())
795         return VAK_ValidInCXX11;
796 
797   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
798     return VAK_Valid;
799 
800   if (Ty->isObjCObjectType())
801     return VAK_Invalid;
802 
803   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
804   // permitted to reject them. We should consider doing so.
805   return VAK_Undefined;
806 }
807 
checkVariadicArgument(const Expr * E,VariadicCallType CT)808 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
809   // Don't allow one to pass an Objective-C interface to a vararg.
810   const QualType &Ty = E->getType();
811   VarArgKind VAK = isValidVarArgType(Ty);
812 
813   // Complain about passing non-POD types through varargs.
814   switch (VAK) {
815   case VAK_ValidInCXX11:
816     DiagRuntimeBehavior(
817         E->getLocStart(), nullptr,
818         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
819           << Ty << CT);
820     // Fall through.
821   case VAK_Valid:
822     if (Ty->isRecordType()) {
823       // This is unlikely to be what the user intended. If the class has a
824       // 'c_str' member function, the user probably meant to call that.
825       DiagRuntimeBehavior(E->getLocStart(), nullptr,
826                           PDiag(diag::warn_pass_class_arg_to_vararg)
827                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
828     }
829     break;
830 
831   case VAK_Undefined:
832     DiagRuntimeBehavior(
833         E->getLocStart(), nullptr,
834         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
835           << getLangOpts().CPlusPlus11 << Ty << CT);
836     break;
837 
838   case VAK_Invalid:
839     if (Ty->isObjCObjectType())
840       DiagRuntimeBehavior(
841           E->getLocStart(), nullptr,
842           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
843             << Ty << CT);
844     else
845       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
846         << isa<InitListExpr>(E) << Ty << CT;
847     break;
848   }
849 }
850 
851 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
852 /// will create a trap if the resulting type is not a POD type.
DefaultVariadicArgumentPromotion(Expr * E,VariadicCallType CT,FunctionDecl * FDecl)853 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
854                                                   FunctionDecl *FDecl) {
855   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
856     // Strip the unbridged-cast placeholder expression off, if applicable.
857     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
858         (CT == VariadicMethod ||
859          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
860       E = stripARCUnbridgedCast(E);
861 
862     // Otherwise, do normal placeholder checking.
863     } else {
864       ExprResult ExprRes = CheckPlaceholderExpr(E);
865       if (ExprRes.isInvalid())
866         return ExprError();
867       E = ExprRes.get();
868     }
869   }
870 
871   ExprResult ExprRes = DefaultArgumentPromotion(E);
872   if (ExprRes.isInvalid())
873     return ExprError();
874   E = ExprRes.get();
875 
876   // Diagnostics regarding non-POD argument types are
877   // emitted along with format string checking in Sema::CheckFunctionCall().
878   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
879     // Turn this into a trap.
880     CXXScopeSpec SS;
881     SourceLocation TemplateKWLoc;
882     UnqualifiedId Name;
883     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
884                        E->getLocStart());
885     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
886                                           Name, true, false);
887     if (TrapFn.isInvalid())
888       return ExprError();
889 
890     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
891                                     E->getLocStart(), None,
892                                     E->getLocEnd());
893     if (Call.isInvalid())
894       return ExprError();
895 
896     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
897                                   Call.get(), E);
898     if (Comma.isInvalid())
899       return ExprError();
900     return Comma.get();
901   }
902 
903   if (!getLangOpts().CPlusPlus &&
904       RequireCompleteType(E->getExprLoc(), E->getType(),
905                           diag::err_call_incomplete_argument))
906     return ExprError();
907 
908   return E;
909 }
910 
911 /// \brief Converts an integer to complex float type.  Helper function of
912 /// UsualArithmeticConversions()
913 ///
914 /// \return false if the integer expression is an integer type and is
915 /// successfully converted to the complex type.
handleIntegerToComplexFloatConversion(Sema & S,ExprResult & IntExpr,ExprResult & ComplexExpr,QualType IntTy,QualType ComplexTy,bool SkipCast)916 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
917                                                   ExprResult &ComplexExpr,
918                                                   QualType IntTy,
919                                                   QualType ComplexTy,
920                                                   bool SkipCast) {
921   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
922   if (SkipCast) return false;
923   if (IntTy->isIntegerType()) {
924     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
925     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
926     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
927                                   CK_FloatingRealToComplex);
928   } else {
929     assert(IntTy->isComplexIntegerType());
930     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
931                                   CK_IntegralComplexToFloatingComplex);
932   }
933   return false;
934 }
935 
936 /// \brief Takes two complex float types and converts them to the same type.
937 /// Helper function of UsualArithmeticConversions()
938 static QualType
handleComplexFloatToComplexFloatConverstion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)939 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
940                                             ExprResult &RHS, QualType LHSType,
941                                             QualType RHSType,
942                                             bool IsCompAssign) {
943   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
944 
945   if (order < 0) {
946     // _Complex float -> _Complex double
947     if (!IsCompAssign)
948       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingComplexCast);
949     return RHSType;
950   }
951   if (order > 0)
952     // _Complex float -> _Complex double
953     RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingComplexCast);
954   return LHSType;
955 }
956 
957 /// \brief Converts otherExpr to complex float and promotes complexExpr if
958 /// necessary.  Helper function of UsualArithmeticConversions()
handleOtherComplexFloatConversion(Sema & S,ExprResult & ComplexExpr,ExprResult & OtherExpr,QualType ComplexTy,QualType OtherTy,bool ConvertComplexExpr,bool ConvertOtherExpr)959 static QualType handleOtherComplexFloatConversion(Sema &S,
960                                                   ExprResult &ComplexExpr,
961                                                   ExprResult &OtherExpr,
962                                                   QualType ComplexTy,
963                                                   QualType OtherTy,
964                                                   bool ConvertComplexExpr,
965                                                   bool ConvertOtherExpr) {
966   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
967 
968   // If just the complexExpr is complex, the otherExpr needs to be converted,
969   // and the complexExpr might need to be promoted.
970   if (order > 0) { // complexExpr is wider
971     // float -> _Complex double
972     if (ConvertOtherExpr) {
973       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
974       OtherExpr = S.ImpCastExprToType(OtherExpr.get(), fp, CK_FloatingCast);
975       OtherExpr = S.ImpCastExprToType(OtherExpr.get(), ComplexTy,
976                                       CK_FloatingRealToComplex);
977     }
978     return ComplexTy;
979   }
980 
981   // otherTy is at least as wide.  Find its corresponding complex type.
982   QualType result = (order == 0 ? ComplexTy :
983                                   S.Context.getComplexType(OtherTy));
984 
985   // double -> _Complex double
986   if (ConvertOtherExpr)
987     OtherExpr = S.ImpCastExprToType(OtherExpr.get(), result,
988                                     CK_FloatingRealToComplex);
989 
990   // _Complex float -> _Complex double
991   if (ConvertComplexExpr && order < 0)
992     ComplexExpr = S.ImpCastExprToType(ComplexExpr.get(), result,
993                                       CK_FloatingComplexCast);
994 
995   return result;
996 }
997 
998 /// \brief Handle arithmetic conversion with complex types.  Helper function of
999 /// UsualArithmeticConversions()
handleComplexFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1000 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1001                                              ExprResult &RHS, QualType LHSType,
1002                                              QualType RHSType,
1003                                              bool IsCompAssign) {
1004   // if we have an integer operand, the result is the complex type.
1005   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1006                                              /*skipCast*/false))
1007     return LHSType;
1008   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1009                                              /*skipCast*/IsCompAssign))
1010     return RHSType;
1011 
1012   // This handles complex/complex, complex/float, or float/complex.
1013   // When both operands are complex, the shorter operand is converted to the
1014   // type of the longer, and that is the type of the result. This corresponds
1015   // to what is done when combining two real floating-point operands.
1016   // The fun begins when size promotion occur across type domains.
1017   // From H&S 6.3.4: When one operand is complex and the other is a real
1018   // floating-point type, the less precise type is converted, within it's
1019   // real or complex domain, to the precision of the other type. For example,
1020   // when combining a "long double" with a "double _Complex", the
1021   // "double _Complex" is promoted to "long double _Complex".
1022 
1023   bool LHSComplexFloat = LHSType->isComplexType();
1024   bool RHSComplexFloat = RHSType->isComplexType();
1025 
1026   // If both are complex, just cast to the more precise type.
1027   if (LHSComplexFloat && RHSComplexFloat)
1028     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
1029                                                        LHSType, RHSType,
1030                                                        IsCompAssign);
1031 
1032   // If only one operand is complex, promote it if necessary and convert the
1033   // other operand to complex.
1034   if (LHSComplexFloat)
1035     return handleOtherComplexFloatConversion(
1036         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1037         /*convertOtherExpr*/ true);
1038 
1039   assert(RHSComplexFloat);
1040   return handleOtherComplexFloatConversion(
1041       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1042       /*convertOtherExpr*/ !IsCompAssign);
1043 }
1044 
1045 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1046 /// of UsualArithmeticConversions()
handleIntToFloatConversion(Sema & S,ExprResult & FloatExpr,ExprResult & IntExpr,QualType FloatTy,QualType IntTy,bool ConvertFloat,bool ConvertInt)1047 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1048                                            ExprResult &IntExpr,
1049                                            QualType FloatTy, QualType IntTy,
1050                                            bool ConvertFloat, bool ConvertInt) {
1051   if (IntTy->isIntegerType()) {
1052     if (ConvertInt)
1053       // Convert intExpr to the lhs floating point type.
1054       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1055                                     CK_IntegralToFloating);
1056     return FloatTy;
1057   }
1058 
1059   // Convert both sides to the appropriate complex float.
1060   assert(IntTy->isComplexIntegerType());
1061   QualType result = S.Context.getComplexType(FloatTy);
1062 
1063   // _Complex int -> _Complex float
1064   if (ConvertInt)
1065     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1066                                   CK_IntegralComplexToFloatingComplex);
1067 
1068   // float -> _Complex float
1069   if (ConvertFloat)
1070     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1071                                     CK_FloatingRealToComplex);
1072 
1073   return result;
1074 }
1075 
1076 /// \brief Handle arithmethic conversion with floating point types.  Helper
1077 /// function of UsualArithmeticConversions()
handleFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1078 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1079                                       ExprResult &RHS, QualType LHSType,
1080                                       QualType RHSType, bool IsCompAssign) {
1081   bool LHSFloat = LHSType->isRealFloatingType();
1082   bool RHSFloat = RHSType->isRealFloatingType();
1083 
1084   // If we have two real floating types, convert the smaller operand
1085   // to the bigger result.
1086   if (LHSFloat && RHSFloat) {
1087     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1088     if (order > 0) {
1089       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1090       return LHSType;
1091     }
1092 
1093     assert(order < 0 && "illegal float comparison");
1094     if (!IsCompAssign)
1095       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1096     return RHSType;
1097   }
1098 
1099   if (LHSFloat)
1100     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1101                                       /*convertFloat=*/!IsCompAssign,
1102                                       /*convertInt=*/ true);
1103   assert(RHSFloat);
1104   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1105                                     /*convertInt=*/ true,
1106                                     /*convertFloat=*/!IsCompAssign);
1107 }
1108 
1109 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1110 
1111 namespace {
1112 /// These helper callbacks are placed in an anonymous namespace to
1113 /// permit their use as function template parameters.
doIntegralCast(Sema & S,Expr * op,QualType toType)1114 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1115   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1116 }
1117 
doComplexIntegralCast(Sema & S,Expr * op,QualType toType)1118 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1119   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1120                              CK_IntegralComplexCast);
1121 }
1122 }
1123 
1124 /// \brief Handle integer arithmetic conversions.  Helper function of
1125 /// UsualArithmeticConversions()
1126 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
handleIntegerConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1127 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1128                                         ExprResult &RHS, QualType LHSType,
1129                                         QualType RHSType, bool IsCompAssign) {
1130   // The rules for this case are in C99 6.3.1.8
1131   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1132   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1133   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1134   if (LHSSigned == RHSSigned) {
1135     // Same signedness; use the higher-ranked type
1136     if (order >= 0) {
1137       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1138       return LHSType;
1139     } else if (!IsCompAssign)
1140       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1141     return RHSType;
1142   } else if (order != (LHSSigned ? 1 : -1)) {
1143     // The unsigned type has greater than or equal rank to the
1144     // signed type, so use the unsigned type
1145     if (RHSSigned) {
1146       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1147       return LHSType;
1148     } else if (!IsCompAssign)
1149       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1150     return RHSType;
1151   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1152     // The two types are different widths; if we are here, that
1153     // means the signed type is larger than the unsigned type, so
1154     // use the signed type.
1155     if (LHSSigned) {
1156       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1157       return LHSType;
1158     } else if (!IsCompAssign)
1159       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1160     return RHSType;
1161   } else {
1162     // The signed type is higher-ranked than the unsigned type,
1163     // but isn't actually any bigger (like unsigned int and long
1164     // on most 32-bit systems).  Use the unsigned type corresponding
1165     // to the signed type.
1166     QualType result =
1167       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1168     RHS = (*doRHSCast)(S, RHS.get(), result);
1169     if (!IsCompAssign)
1170       LHS = (*doLHSCast)(S, LHS.get(), result);
1171     return result;
1172   }
1173 }
1174 
1175 /// \brief Handle conversions with GCC complex int extension.  Helper function
1176 /// of UsualArithmeticConversions()
handleComplexIntConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1177 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1178                                            ExprResult &RHS, QualType LHSType,
1179                                            QualType RHSType,
1180                                            bool IsCompAssign) {
1181   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1182   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1183 
1184   if (LHSComplexInt && RHSComplexInt) {
1185     QualType LHSEltType = LHSComplexInt->getElementType();
1186     QualType RHSEltType = RHSComplexInt->getElementType();
1187     QualType ScalarType =
1188       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1189         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1190 
1191     return S.Context.getComplexType(ScalarType);
1192   }
1193 
1194   if (LHSComplexInt) {
1195     QualType LHSEltType = LHSComplexInt->getElementType();
1196     QualType ScalarType =
1197       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1198         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1199     QualType ComplexType = S.Context.getComplexType(ScalarType);
1200     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1201                               CK_IntegralRealToComplex);
1202 
1203     return ComplexType;
1204   }
1205 
1206   assert(RHSComplexInt);
1207 
1208   QualType RHSEltType = RHSComplexInt->getElementType();
1209   QualType ScalarType =
1210     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1211       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1212   QualType ComplexType = S.Context.getComplexType(ScalarType);
1213 
1214   if (!IsCompAssign)
1215     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1216                               CK_IntegralRealToComplex);
1217   return ComplexType;
1218 }
1219 
1220 /// UsualArithmeticConversions - Performs various conversions that are common to
1221 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1222 /// routine returns the first non-arithmetic type found. The client is
1223 /// responsible for emitting appropriate error diagnostics.
UsualArithmeticConversions(ExprResult & LHS,ExprResult & RHS,bool IsCompAssign)1224 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1225                                           bool IsCompAssign) {
1226   if (!IsCompAssign) {
1227     LHS = UsualUnaryConversions(LHS.get());
1228     if (LHS.isInvalid())
1229       return QualType();
1230   }
1231 
1232   RHS = UsualUnaryConversions(RHS.get());
1233   if (RHS.isInvalid())
1234     return QualType();
1235 
1236   // For conversion purposes, we ignore any qualifiers.
1237   // For example, "const float" and "float" are equivalent.
1238   QualType LHSType =
1239     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1240   QualType RHSType =
1241     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1242 
1243   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1244   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1245     LHSType = AtomicLHS->getValueType();
1246 
1247   // If both types are identical, no conversion is needed.
1248   if (LHSType == RHSType)
1249     return LHSType;
1250 
1251   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1252   // The caller can deal with this (e.g. pointer + int).
1253   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1254     return QualType();
1255 
1256   // Apply unary and bitfield promotions to the LHS's type.
1257   QualType LHSUnpromotedType = LHSType;
1258   if (LHSType->isPromotableIntegerType())
1259     LHSType = Context.getPromotedIntegerType(LHSType);
1260   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1261   if (!LHSBitfieldPromoteTy.isNull())
1262     LHSType = LHSBitfieldPromoteTy;
1263   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1264     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1265 
1266   // If both types are identical, no conversion is needed.
1267   if (LHSType == RHSType)
1268     return LHSType;
1269 
1270   // At this point, we have two different arithmetic types.
1271 
1272   // Handle complex types first (C99 6.3.1.8p1).
1273   if (LHSType->isComplexType() || RHSType->isComplexType())
1274     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1275                                         IsCompAssign);
1276 
1277   // Now handle "real" floating types (i.e. float, double, long double).
1278   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1279     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1280                                  IsCompAssign);
1281 
1282   // Handle GCC complex int extension.
1283   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1284     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1285                                       IsCompAssign);
1286 
1287   // Finally, we have two differing integer types.
1288   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1289            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1290 }
1291 
1292 
1293 //===----------------------------------------------------------------------===//
1294 //  Semantic Analysis for various Expression Types
1295 //===----------------------------------------------------------------------===//
1296 
1297 
1298 ExprResult
ActOnGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<ParsedType> ArgTypes,ArrayRef<Expr * > ArgExprs)1299 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1300                                 SourceLocation DefaultLoc,
1301                                 SourceLocation RParenLoc,
1302                                 Expr *ControllingExpr,
1303                                 ArrayRef<ParsedType> ArgTypes,
1304                                 ArrayRef<Expr *> ArgExprs) {
1305   unsigned NumAssocs = ArgTypes.size();
1306   assert(NumAssocs == ArgExprs.size());
1307 
1308   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1309   for (unsigned i = 0; i < NumAssocs; ++i) {
1310     if (ArgTypes[i])
1311       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1312     else
1313       Types[i] = nullptr;
1314   }
1315 
1316   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1317                                              ControllingExpr,
1318                                              llvm::makeArrayRef(Types, NumAssocs),
1319                                              ArgExprs);
1320   delete [] Types;
1321   return ER;
1322 }
1323 
1324 ExprResult
CreateGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > Types,ArrayRef<Expr * > Exprs)1325 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1326                                  SourceLocation DefaultLoc,
1327                                  SourceLocation RParenLoc,
1328                                  Expr *ControllingExpr,
1329                                  ArrayRef<TypeSourceInfo *> Types,
1330                                  ArrayRef<Expr *> Exprs) {
1331   unsigned NumAssocs = Types.size();
1332   assert(NumAssocs == Exprs.size());
1333   if (ControllingExpr->getType()->isPlaceholderType()) {
1334     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1335     if (result.isInvalid()) return ExprError();
1336     ControllingExpr = result.get();
1337   }
1338 
1339   bool TypeErrorFound = false,
1340        IsResultDependent = ControllingExpr->isTypeDependent(),
1341        ContainsUnexpandedParameterPack
1342          = ControllingExpr->containsUnexpandedParameterPack();
1343 
1344   for (unsigned i = 0; i < NumAssocs; ++i) {
1345     if (Exprs[i]->containsUnexpandedParameterPack())
1346       ContainsUnexpandedParameterPack = true;
1347 
1348     if (Types[i]) {
1349       if (Types[i]->getType()->containsUnexpandedParameterPack())
1350         ContainsUnexpandedParameterPack = true;
1351 
1352       if (Types[i]->getType()->isDependentType()) {
1353         IsResultDependent = true;
1354       } else {
1355         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1356         // complete object type other than a variably modified type."
1357         unsigned D = 0;
1358         if (Types[i]->getType()->isIncompleteType())
1359           D = diag::err_assoc_type_incomplete;
1360         else if (!Types[i]->getType()->isObjectType())
1361           D = diag::err_assoc_type_nonobject;
1362         else if (Types[i]->getType()->isVariablyModifiedType())
1363           D = diag::err_assoc_type_variably_modified;
1364 
1365         if (D != 0) {
1366           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1367             << Types[i]->getTypeLoc().getSourceRange()
1368             << Types[i]->getType();
1369           TypeErrorFound = true;
1370         }
1371 
1372         // C11 6.5.1.1p2 "No two generic associations in the same generic
1373         // selection shall specify compatible types."
1374         for (unsigned j = i+1; j < NumAssocs; ++j)
1375           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1376               Context.typesAreCompatible(Types[i]->getType(),
1377                                          Types[j]->getType())) {
1378             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1379                  diag::err_assoc_compatible_types)
1380               << Types[j]->getTypeLoc().getSourceRange()
1381               << Types[j]->getType()
1382               << Types[i]->getType();
1383             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1384                  diag::note_compat_assoc)
1385               << Types[i]->getTypeLoc().getSourceRange()
1386               << Types[i]->getType();
1387             TypeErrorFound = true;
1388           }
1389       }
1390     }
1391   }
1392   if (TypeErrorFound)
1393     return ExprError();
1394 
1395   // If we determined that the generic selection is result-dependent, don't
1396   // try to compute the result expression.
1397   if (IsResultDependent)
1398     return new (Context) GenericSelectionExpr(
1399         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1400         ContainsUnexpandedParameterPack);
1401 
1402   SmallVector<unsigned, 1> CompatIndices;
1403   unsigned DefaultIndex = -1U;
1404   for (unsigned i = 0; i < NumAssocs; ++i) {
1405     if (!Types[i])
1406       DefaultIndex = i;
1407     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1408                                         Types[i]->getType()))
1409       CompatIndices.push_back(i);
1410   }
1411 
1412   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1413   // type compatible with at most one of the types named in its generic
1414   // association list."
1415   if (CompatIndices.size() > 1) {
1416     // We strip parens here because the controlling expression is typically
1417     // parenthesized in macro definitions.
1418     ControllingExpr = ControllingExpr->IgnoreParens();
1419     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1420       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1421       << (unsigned) CompatIndices.size();
1422     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1423          E = CompatIndices.end(); I != E; ++I) {
1424       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1425            diag::note_compat_assoc)
1426         << Types[*I]->getTypeLoc().getSourceRange()
1427         << Types[*I]->getType();
1428     }
1429     return ExprError();
1430   }
1431 
1432   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1433   // its controlling expression shall have type compatible with exactly one of
1434   // the types named in its generic association list."
1435   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1436     // We strip parens here because the controlling expression is typically
1437     // parenthesized in macro definitions.
1438     ControllingExpr = ControllingExpr->IgnoreParens();
1439     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1440       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1441     return ExprError();
1442   }
1443 
1444   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1445   // type name that is compatible with the type of the controlling expression,
1446   // then the result expression of the generic selection is the expression
1447   // in that generic association. Otherwise, the result expression of the
1448   // generic selection is the expression in the default generic association."
1449   unsigned ResultIndex =
1450     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1451 
1452   return new (Context) GenericSelectionExpr(
1453       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1454       ContainsUnexpandedParameterPack, ResultIndex);
1455 }
1456 
1457 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1458 /// location of the token and the offset of the ud-suffix within it.
getUDSuffixLoc(Sema & S,SourceLocation TokLoc,unsigned Offset)1459 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1460                                      unsigned Offset) {
1461   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1462                                         S.getLangOpts());
1463 }
1464 
1465 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1466 /// 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)1467 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1468                                                  IdentifierInfo *UDSuffix,
1469                                                  SourceLocation UDSuffixLoc,
1470                                                  ArrayRef<Expr*> Args,
1471                                                  SourceLocation LitEndLoc) {
1472   assert(Args.size() <= 2 && "too many arguments for literal operator");
1473 
1474   QualType ArgTy[2];
1475   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1476     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1477     if (ArgTy[ArgIdx]->isArrayType())
1478       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1479   }
1480 
1481   DeclarationName OpName =
1482     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1483   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1484   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1485 
1486   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1487   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1488                               /*AllowRaw*/false, /*AllowTemplate*/false,
1489                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1490     return ExprError();
1491 
1492   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1493 }
1494 
1495 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1496 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1497 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1498 /// multiple tokens.  However, the common case is that StringToks points to one
1499 /// string.
1500 ///
1501 ExprResult
ActOnStringLiteral(ArrayRef<Token> StringToks,Scope * UDLScope)1502 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1503   assert(!StringToks.empty() && "Must have at least one string!");
1504 
1505   StringLiteralParser Literal(StringToks, PP);
1506   if (Literal.hadError)
1507     return ExprError();
1508 
1509   SmallVector<SourceLocation, 4> StringTokLocs;
1510   for (unsigned i = 0; i != StringToks.size(); ++i)
1511     StringTokLocs.push_back(StringToks[i].getLocation());
1512 
1513   QualType CharTy = Context.CharTy;
1514   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1515   if (Literal.isWide()) {
1516     CharTy = Context.getWideCharType();
1517     Kind = StringLiteral::Wide;
1518   } else if (Literal.isUTF8()) {
1519     Kind = StringLiteral::UTF8;
1520   } else if (Literal.isUTF16()) {
1521     CharTy = Context.Char16Ty;
1522     Kind = StringLiteral::UTF16;
1523   } else if (Literal.isUTF32()) {
1524     CharTy = Context.Char32Ty;
1525     Kind = StringLiteral::UTF32;
1526   } else if (Literal.isPascal()) {
1527     CharTy = Context.UnsignedCharTy;
1528   }
1529 
1530   QualType CharTyConst = CharTy;
1531   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1532   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1533     CharTyConst.addConst();
1534 
1535   // Get an array type for the string, according to C99 6.4.5.  This includes
1536   // the nul terminator character as well as the string length for pascal
1537   // strings.
1538   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1539                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1540                                  ArrayType::Normal, 0);
1541 
1542   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1543   if (getLangOpts().OpenCL) {
1544     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1545   }
1546 
1547   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1548   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1549                                              Kind, Literal.Pascal, StrTy,
1550                                              &StringTokLocs[0],
1551                                              StringTokLocs.size());
1552   if (Literal.getUDSuffix().empty())
1553     return Lit;
1554 
1555   // We're building a user-defined literal.
1556   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1557   SourceLocation UDSuffixLoc =
1558     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1559                    Literal.getUDSuffixOffset());
1560 
1561   // Make sure we're allowed user-defined literals here.
1562   if (!UDLScope)
1563     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1564 
1565   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1566   //   operator "" X (str, len)
1567   QualType SizeType = Context.getSizeType();
1568 
1569   DeclarationName OpName =
1570     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1571   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1572   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1573 
1574   QualType ArgTy[] = {
1575     Context.getArrayDecayedType(StrTy), SizeType
1576   };
1577 
1578   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1579   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1580                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1581                                 /*AllowStringTemplate*/true)) {
1582 
1583   case LOLR_Cooked: {
1584     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1585     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1586                                                     StringTokLocs[0]);
1587     Expr *Args[] = { Lit, LenArg };
1588 
1589     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1590   }
1591 
1592   case LOLR_StringTemplate: {
1593     TemplateArgumentListInfo ExplicitArgs;
1594 
1595     unsigned CharBits = Context.getIntWidth(CharTy);
1596     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1597     llvm::APSInt Value(CharBits, CharIsUnsigned);
1598 
1599     TemplateArgument TypeArg(CharTy);
1600     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1601     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1602 
1603     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1604       Value = Lit->getCodeUnit(I);
1605       TemplateArgument Arg(Context, Value, CharTy);
1606       TemplateArgumentLocInfo ArgInfo;
1607       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1608     }
1609     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1610                                     &ExplicitArgs);
1611   }
1612   case LOLR_Raw:
1613   case LOLR_Template:
1614     llvm_unreachable("unexpected literal operator lookup result");
1615   case LOLR_Error:
1616     return ExprError();
1617   }
1618   llvm_unreachable("unexpected literal operator lookup result");
1619 }
1620 
1621 ExprResult
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,SourceLocation Loc,const CXXScopeSpec * SS)1622 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1623                        SourceLocation Loc,
1624                        const CXXScopeSpec *SS) {
1625   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1626   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1627 }
1628 
1629 /// BuildDeclRefExpr - Build an expression that references a
1630 /// declaration that does not require a closure capture.
1631 ExprResult
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,const DeclarationNameInfo & NameInfo,const CXXScopeSpec * SS,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs)1632 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1633                        const DeclarationNameInfo &NameInfo,
1634                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1635                        const TemplateArgumentListInfo *TemplateArgs) {
1636   if (getLangOpts().CUDA)
1637     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1638       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1639         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1640                            CalleeTarget = IdentifyCUDATarget(Callee);
1641         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1642           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1643             << CalleeTarget << D->getIdentifier() << CallerTarget;
1644           Diag(D->getLocation(), diag::note_previous_decl)
1645             << D->getIdentifier();
1646           return ExprError();
1647         }
1648       }
1649 
1650   bool refersToEnclosingScope =
1651     (CurContext != D->getDeclContext() &&
1652      D->getDeclContext()->isFunctionOrMethod()) ||
1653     (isa<VarDecl>(D) &&
1654      cast<VarDecl>(D)->isInitCapture());
1655 
1656   DeclRefExpr *E;
1657   if (isa<VarTemplateSpecializationDecl>(D)) {
1658     VarTemplateSpecializationDecl *VarSpec =
1659         cast<VarTemplateSpecializationDecl>(D);
1660 
1661     E = DeclRefExpr::Create(
1662         Context,
1663         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1664         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1665         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1666   } else {
1667     assert(!TemplateArgs && "No template arguments for non-variable"
1668                             " template specialization references");
1669     E = DeclRefExpr::Create(
1670         Context,
1671         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1672         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1673   }
1674 
1675   MarkDeclRefReferenced(E);
1676 
1677   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1678       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1679       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1680       recordUseOfEvaluatedWeak(E);
1681 
1682   // Just in case we're building an illegal pointer-to-member.
1683   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1684   if (FD && FD->isBitField())
1685     E->setObjectKind(OK_BitField);
1686 
1687   return E;
1688 }
1689 
1690 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1691 /// possibly a list of template arguments.
1692 ///
1693 /// If this produces template arguments, it is permitted to call
1694 /// DecomposeTemplateName.
1695 ///
1696 /// This actually loses a lot of source location information for
1697 /// non-standard name kinds; we should consider preserving that in
1698 /// some way.
1699 void
DecomposeUnqualifiedId(const UnqualifiedId & Id,TemplateArgumentListInfo & Buffer,DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * & TemplateArgs)1700 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1701                              TemplateArgumentListInfo &Buffer,
1702                              DeclarationNameInfo &NameInfo,
1703                              const TemplateArgumentListInfo *&TemplateArgs) {
1704   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1705     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1706     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1707 
1708     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1709                                        Id.TemplateId->NumArgs);
1710     translateTemplateArguments(TemplateArgsPtr, Buffer);
1711 
1712     TemplateName TName = Id.TemplateId->Template.get();
1713     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1714     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1715     TemplateArgs = &Buffer;
1716   } else {
1717     NameInfo = GetNameFromUnqualifiedId(Id);
1718     TemplateArgs = nullptr;
1719   }
1720 }
1721 
1722 /// Diagnose an empty lookup.
1723 ///
1724 /// \return false if new lookup candidates were found
DiagnoseEmptyLookup(Scope * S,CXXScopeSpec & SS,LookupResult & R,CorrectionCandidateCallback & CCC,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args)1725 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1726                                CorrectionCandidateCallback &CCC,
1727                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1728                                ArrayRef<Expr *> Args) {
1729   DeclarationName Name = R.getLookupName();
1730 
1731   unsigned diagnostic = diag::err_undeclared_var_use;
1732   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1733   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1734       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1735       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1736     diagnostic = diag::err_undeclared_use;
1737     diagnostic_suggest = diag::err_undeclared_use_suggest;
1738   }
1739 
1740   // If the original lookup was an unqualified lookup, fake an
1741   // unqualified lookup.  This is useful when (for example) the
1742   // original lookup would not have found something because it was a
1743   // dependent name.
1744   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1745     ? CurContext : nullptr;
1746   while (DC) {
1747     if (isa<CXXRecordDecl>(DC)) {
1748       LookupQualifiedName(R, DC);
1749 
1750       if (!R.empty()) {
1751         // Don't give errors about ambiguities in this lookup.
1752         R.suppressDiagnostics();
1753 
1754         // During a default argument instantiation the CurContext points
1755         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1756         // function parameter list, hence add an explicit check.
1757         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1758                               ActiveTemplateInstantiations.back().Kind ==
1759             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1760         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1761         bool isInstance = CurMethod &&
1762                           CurMethod->isInstance() &&
1763                           DC == CurMethod->getParent() && !isDefaultArgument;
1764 
1765 
1766         // Give a code modification hint to insert 'this->'.
1767         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1768         // Actually quite difficult!
1769         if (getLangOpts().MSVCCompat)
1770           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1771         if (isInstance) {
1772           Diag(R.getNameLoc(), diagnostic) << Name
1773             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1774           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1775               CallsUndergoingInstantiation.back()->getCallee());
1776 
1777           CXXMethodDecl *DepMethod;
1778           if (CurMethod->isDependentContext())
1779             DepMethod = CurMethod;
1780           else if (CurMethod->getTemplatedKind() ==
1781               FunctionDecl::TK_FunctionTemplateSpecialization)
1782             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1783                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1784           else
1785             DepMethod = cast<CXXMethodDecl>(
1786                 CurMethod->getInstantiatedFromMemberFunction());
1787           assert(DepMethod && "No template pattern found");
1788 
1789           QualType DepThisType = DepMethod->getThisType(Context);
1790           CheckCXXThisCapture(R.getNameLoc());
1791           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1792                                      R.getNameLoc(), DepThisType, false);
1793           TemplateArgumentListInfo TList;
1794           if (ULE->hasExplicitTemplateArgs())
1795             ULE->copyTemplateArgumentsInto(TList);
1796 
1797           CXXScopeSpec SS;
1798           SS.Adopt(ULE->getQualifierLoc());
1799           CXXDependentScopeMemberExpr *DepExpr =
1800               CXXDependentScopeMemberExpr::Create(
1801                   Context, DepThis, DepThisType, true, SourceLocation(),
1802                   SS.getWithLocInContext(Context),
1803                   ULE->getTemplateKeywordLoc(), nullptr,
1804                   R.getLookupNameInfo(),
1805                   ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
1806           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1807         } else {
1808           Diag(R.getNameLoc(), diagnostic) << Name;
1809         }
1810 
1811         // Do we really want to note all of these?
1812         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1813           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1814 
1815         // Return true if we are inside a default argument instantiation
1816         // and the found name refers to an instance member function, otherwise
1817         // the function calling DiagnoseEmptyLookup will try to create an
1818         // implicit member call and this is wrong for default argument.
1819         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1820           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1821           return true;
1822         }
1823 
1824         // Tell the callee to try to recover.
1825         return false;
1826       }
1827 
1828       R.clear();
1829     }
1830 
1831     // In Microsoft mode, if we are performing lookup from within a friend
1832     // function definition declared at class scope then we must set
1833     // DC to the lexical parent to be able to search into the parent
1834     // class.
1835     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1836         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1837         DC->getLexicalParent()->isRecord())
1838       DC = DC->getLexicalParent();
1839     else
1840       DC = DC->getParent();
1841   }
1842 
1843   // We didn't find anything, so try to correct for a typo.
1844   TypoCorrection Corrected;
1845   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1846                                     S, &SS, CCC, CTK_ErrorRecovery))) {
1847     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1848     bool DroppedSpecifier =
1849         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1850     R.setLookupName(Corrected.getCorrection());
1851 
1852     bool AcceptableWithRecovery = false;
1853     bool AcceptableWithoutRecovery = false;
1854     NamedDecl *ND = Corrected.getCorrectionDecl();
1855     if (ND) {
1856       if (Corrected.isOverloaded()) {
1857         OverloadCandidateSet OCS(R.getNameLoc(),
1858                                  OverloadCandidateSet::CSK_Normal);
1859         OverloadCandidateSet::iterator Best;
1860         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1861                                         CDEnd = Corrected.end();
1862              CD != CDEnd; ++CD) {
1863           if (FunctionTemplateDecl *FTD =
1864                    dyn_cast<FunctionTemplateDecl>(*CD))
1865             AddTemplateOverloadCandidate(
1866                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1867                 Args, OCS);
1868           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1869             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1870               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1871                                    Args, OCS);
1872         }
1873         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1874         case OR_Success:
1875           ND = Best->Function;
1876           Corrected.setCorrectionDecl(ND);
1877           break;
1878         default:
1879           // FIXME: Arbitrarily pick the first declaration for the note.
1880           Corrected.setCorrectionDecl(ND);
1881           break;
1882         }
1883       }
1884       R.addDecl(ND);
1885       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1886         CXXRecordDecl *Record = nullptr;
1887         if (Corrected.getCorrectionSpecifier()) {
1888           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1889           Record = Ty->getAsCXXRecordDecl();
1890         }
1891         if (!Record)
1892           Record = cast<CXXRecordDecl>(
1893               ND->getDeclContext()->getRedeclContext());
1894         R.setNamingClass(Record);
1895       }
1896 
1897       AcceptableWithRecovery =
1898           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1899       // FIXME: If we ended up with a typo for a type name or
1900       // Objective-C class name, we're in trouble because the parser
1901       // is in the wrong place to recover. Suggest the typo
1902       // correction, but don't make it a fix-it since we're not going
1903       // to recover well anyway.
1904       AcceptableWithoutRecovery =
1905           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1906     } else {
1907       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1908       // because we aren't able to recover.
1909       AcceptableWithoutRecovery = true;
1910     }
1911 
1912     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1913       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1914                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1915                             ? diag::note_implicit_param_decl
1916                             : diag::note_previous_decl;
1917       if (SS.isEmpty())
1918         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1919                      PDiag(NoteID), AcceptableWithRecovery);
1920       else
1921         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1922                                   << Name << computeDeclContext(SS, false)
1923                                   << DroppedSpecifier << SS.getRange(),
1924                      PDiag(NoteID), AcceptableWithRecovery);
1925 
1926       // Tell the callee whether to try to recover.
1927       return !AcceptableWithRecovery;
1928     }
1929   }
1930   R.clear();
1931 
1932   // Emit a special diagnostic for failed member lookups.
1933   // FIXME: computing the declaration context might fail here (?)
1934   if (!SS.isEmpty()) {
1935     Diag(R.getNameLoc(), diag::err_no_member)
1936       << Name << computeDeclContext(SS, false)
1937       << SS.getRange();
1938     return true;
1939   }
1940 
1941   // Give up, we can't recover.
1942   Diag(R.getNameLoc(), diagnostic) << Name;
1943   return true;
1944 }
1945 
1946 /// In Microsoft mode, if we are inside a template class whose parent class has
1947 /// dependent base classes, and we can't resolve an unqualified identifier, then
1948 /// assume the identifier is a member of a dependent base class.  We can only
1949 /// recover successfully in static methods, instance methods, and other contexts
1950 /// where 'this' is available.  This doesn't precisely match MSVC's
1951 /// instantiation model, but it's close enough.
1952 static Expr *
recoverFromMSUnqualifiedLookup(Sema & S,ASTContext & Context,DeclarationNameInfo & NameInfo,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)1953 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1954                                DeclarationNameInfo &NameInfo,
1955                                SourceLocation TemplateKWLoc,
1956                                const TemplateArgumentListInfo *TemplateArgs) {
1957   // Only try to recover from lookup into dependent bases in static methods or
1958   // contexts where 'this' is available.
1959   QualType ThisType = S.getCurrentThisType();
1960   const CXXRecordDecl *RD = nullptr;
1961   if (!ThisType.isNull())
1962     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1963   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1964     RD = MD->getParent();
1965   if (!RD || !RD->hasAnyDependentBases())
1966     return nullptr;
1967 
1968   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1969   // is available, suggest inserting 'this->' as a fixit.
1970   SourceLocation Loc = NameInfo.getLoc();
1971   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
1972   DB << NameInfo.getName() << RD;
1973 
1974   if (!ThisType.isNull()) {
1975     DB << FixItHint::CreateInsertion(Loc, "this->");
1976     return CXXDependentScopeMemberExpr::Create(
1977         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
1978         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
1979         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
1980   }
1981 
1982   // Synthesize a fake NNS that points to the derived class.  This will
1983   // perform name lookup during template instantiation.
1984   CXXScopeSpec SS;
1985   auto *NNS =
1986       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
1987   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
1988   return DependentScopeDeclRefExpr::Create(
1989       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
1990       TemplateArgs);
1991 }
1992 
ActOnIdExpression(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Id,bool HasTrailingLParen,bool IsAddressOfOperand,CorrectionCandidateCallback * CCC,bool IsInlineAsmIdentifier)1993 ExprResult Sema::ActOnIdExpression(Scope *S,
1994                                    CXXScopeSpec &SS,
1995                                    SourceLocation TemplateKWLoc,
1996                                    UnqualifiedId &Id,
1997                                    bool HasTrailingLParen,
1998                                    bool IsAddressOfOperand,
1999                                    CorrectionCandidateCallback *CCC,
2000                                    bool IsInlineAsmIdentifier) {
2001   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2002          "cannot be direct & operand and have a trailing lparen");
2003   if (SS.isInvalid())
2004     return ExprError();
2005 
2006   TemplateArgumentListInfo TemplateArgsBuffer;
2007 
2008   // Decompose the UnqualifiedId into the following data.
2009   DeclarationNameInfo NameInfo;
2010   const TemplateArgumentListInfo *TemplateArgs;
2011   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2012 
2013   DeclarationName Name = NameInfo.getName();
2014   IdentifierInfo *II = Name.getAsIdentifierInfo();
2015   SourceLocation NameLoc = NameInfo.getLoc();
2016 
2017   // C++ [temp.dep.expr]p3:
2018   //   An id-expression is type-dependent if it contains:
2019   //     -- an identifier that was declared with a dependent type,
2020   //        (note: handled after lookup)
2021   //     -- a template-id that is dependent,
2022   //        (note: handled in BuildTemplateIdExpr)
2023   //     -- a conversion-function-id that specifies a dependent type,
2024   //     -- a nested-name-specifier that contains a class-name that
2025   //        names a dependent type.
2026   // Determine whether this is a member of an unknown specialization;
2027   // we need to handle these differently.
2028   bool DependentID = false;
2029   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2030       Name.getCXXNameType()->isDependentType()) {
2031     DependentID = true;
2032   } else if (SS.isSet()) {
2033     if (DeclContext *DC = computeDeclContext(SS, false)) {
2034       if (RequireCompleteDeclContext(SS, DC))
2035         return ExprError();
2036     } else {
2037       DependentID = true;
2038     }
2039   }
2040 
2041   if (DependentID)
2042     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2043                                       IsAddressOfOperand, TemplateArgs);
2044 
2045   // Perform the required lookup.
2046   LookupResult R(*this, NameInfo,
2047                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2048                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2049   if (TemplateArgs) {
2050     // Lookup the template name again to correctly establish the context in
2051     // which it was found. This is really unfortunate as we already did the
2052     // lookup to determine that it was a template name in the first place. If
2053     // this becomes a performance hit, we can work harder to preserve those
2054     // results until we get here but it's likely not worth it.
2055     bool MemberOfUnknownSpecialization;
2056     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2057                        MemberOfUnknownSpecialization);
2058 
2059     if (MemberOfUnknownSpecialization ||
2060         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2061       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2062                                         IsAddressOfOperand, TemplateArgs);
2063   } else {
2064     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2065     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2066 
2067     // If the result might be in a dependent base class, this is a dependent
2068     // id-expression.
2069     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2070       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2071                                         IsAddressOfOperand, TemplateArgs);
2072 
2073     // If this reference is in an Objective-C method, then we need to do
2074     // some special Objective-C lookup, too.
2075     if (IvarLookupFollowUp) {
2076       ExprResult E(LookupInObjCMethod(R, S, II, true));
2077       if (E.isInvalid())
2078         return ExprError();
2079 
2080       if (Expr *Ex = E.getAs<Expr>())
2081         return Ex;
2082     }
2083   }
2084 
2085   if (R.isAmbiguous())
2086     return ExprError();
2087 
2088   // This could be an implicitly declared function reference (legal in C90,
2089   // extension in C99, forbidden in C++).
2090   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2091     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2092     if (D) R.addDecl(D);
2093   }
2094 
2095   // Determine whether this name might be a candidate for
2096   // argument-dependent lookup.
2097   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2098 
2099   if (R.empty() && !ADL) {
2100     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2101       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2102                                                    TemplateKWLoc, TemplateArgs))
2103         return E;
2104     }
2105 
2106     // Don't diagnose an empty lookup for inline assembly.
2107     if (IsInlineAsmIdentifier)
2108       return ExprError();
2109 
2110     // If this name wasn't predeclared and if this is not a function
2111     // call, diagnose the problem.
2112     CorrectionCandidateCallback DefaultValidator;
2113     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2114     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2115            "Typo correction callback misconfigured");
2116     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2117       return ExprError();
2118 
2119     assert(!R.empty() &&
2120            "DiagnoseEmptyLookup returned false but added no results");
2121 
2122     // If we found an Objective-C instance variable, let
2123     // LookupInObjCMethod build the appropriate expression to
2124     // reference the ivar.
2125     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2126       R.clear();
2127       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2128       // In a hopelessly buggy code, Objective-C instance variable
2129       // lookup fails and no expression will be built to reference it.
2130       if (!E.isInvalid() && !E.get())
2131         return ExprError();
2132       return E;
2133     }
2134   }
2135 
2136   // This is guaranteed from this point on.
2137   assert(!R.empty() || ADL);
2138 
2139   // Check whether this might be a C++ implicit instance member access.
2140   // C++ [class.mfct.non-static]p3:
2141   //   When an id-expression that is not part of a class member access
2142   //   syntax and not used to form a pointer to member is used in the
2143   //   body of a non-static member function of class X, if name lookup
2144   //   resolves the name in the id-expression to a non-static non-type
2145   //   member of some class C, the id-expression is transformed into a
2146   //   class member access expression using (*this) as the
2147   //   postfix-expression to the left of the . operator.
2148   //
2149   // But we don't actually need to do this for '&' operands if R
2150   // resolved to a function or overloaded function set, because the
2151   // expression is ill-formed if it actually works out to be a
2152   // non-static member function:
2153   //
2154   // C++ [expr.ref]p4:
2155   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2156   //   [t]he expression can be used only as the left-hand operand of a
2157   //   member function call.
2158   //
2159   // There are other safeguards against such uses, but it's important
2160   // to get this right here so that we don't end up making a
2161   // spuriously dependent expression if we're inside a dependent
2162   // instance method.
2163   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2164     bool MightBeImplicitMember;
2165     if (!IsAddressOfOperand)
2166       MightBeImplicitMember = true;
2167     else if (!SS.isEmpty())
2168       MightBeImplicitMember = false;
2169     else if (R.isOverloadedResult())
2170       MightBeImplicitMember = false;
2171     else if (R.isUnresolvableResult())
2172       MightBeImplicitMember = true;
2173     else
2174       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2175                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2176                               isa<MSPropertyDecl>(R.getFoundDecl());
2177 
2178     if (MightBeImplicitMember)
2179       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2180                                              R, TemplateArgs);
2181   }
2182 
2183   if (TemplateArgs || TemplateKWLoc.isValid()) {
2184 
2185     // In C++1y, if this is a variable template id, then check it
2186     // in BuildTemplateIdExpr().
2187     // The single lookup result must be a variable template declaration.
2188     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2189         Id.TemplateId->Kind == TNK_Var_template) {
2190       assert(R.getAsSingle<VarTemplateDecl>() &&
2191              "There should only be one declaration found.");
2192     }
2193 
2194     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2195   }
2196 
2197   return BuildDeclarationNameExpr(SS, R, ADL);
2198 }
2199 
2200 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2201 /// declaration name, generally during template instantiation.
2202 /// There's a large number of things which don't need to be done along
2203 /// this path.
2204 ExprResult
BuildQualifiedDeclarationNameExpr(CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,bool IsAddressOfOperand,TypeSourceInfo ** RecoveryTSI)2205 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2206                                         const DeclarationNameInfo &NameInfo,
2207                                         bool IsAddressOfOperand,
2208                                         TypeSourceInfo **RecoveryTSI) {
2209   DeclContext *DC = computeDeclContext(SS, false);
2210   if (!DC)
2211     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2212                                      NameInfo, /*TemplateArgs=*/nullptr);
2213 
2214   if (RequireCompleteDeclContext(SS, DC))
2215     return ExprError();
2216 
2217   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2218   LookupQualifiedName(R, DC);
2219 
2220   if (R.isAmbiguous())
2221     return ExprError();
2222 
2223   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2224     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2225                                      NameInfo, /*TemplateArgs=*/nullptr);
2226 
2227   if (R.empty()) {
2228     Diag(NameInfo.getLoc(), diag::err_no_member)
2229       << NameInfo.getName() << DC << SS.getRange();
2230     return ExprError();
2231   }
2232 
2233   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2234     // Diagnose a missing typename if this resolved unambiguously to a type in
2235     // a dependent context.  If we can recover with a type, downgrade this to
2236     // a warning in Microsoft compatibility mode.
2237     unsigned DiagID = diag::err_typename_missing;
2238     if (RecoveryTSI && getLangOpts().MSVCCompat)
2239       DiagID = diag::ext_typename_missing;
2240     SourceLocation Loc = SS.getBeginLoc();
2241     auto D = Diag(Loc, DiagID);
2242     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2243       << SourceRange(Loc, NameInfo.getEndLoc());
2244 
2245     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2246     // context.
2247     if (!RecoveryTSI)
2248       return ExprError();
2249 
2250     // Only issue the fixit if we're prepared to recover.
2251     D << FixItHint::CreateInsertion(Loc, "typename ");
2252 
2253     // Recover by pretending this was an elaborated type.
2254     QualType Ty = Context.getTypeDeclType(TD);
2255     TypeLocBuilder TLB;
2256     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2257 
2258     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2259     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2260     QTL.setElaboratedKeywordLoc(SourceLocation());
2261     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2262 
2263     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2264 
2265     return ExprEmpty();
2266   }
2267 
2268   // Defend against this resolving to an implicit member access. We usually
2269   // won't get here if this might be a legitimate a class member (we end up in
2270   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2271   // a pointer-to-member or in an unevaluated context in C++11.
2272   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2273     return BuildPossibleImplicitMemberExpr(SS,
2274                                            /*TemplateKWLoc=*/SourceLocation(),
2275                                            R, /*TemplateArgs=*/nullptr);
2276 
2277   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2278 }
2279 
2280 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2281 /// detected that we're currently inside an ObjC method.  Perform some
2282 /// additional lookup.
2283 ///
2284 /// Ideally, most of this would be done by lookup, but there's
2285 /// actually quite a lot of extra work involved.
2286 ///
2287 /// Returns a null sentinel to indicate trivial success.
2288 ExprResult
LookupInObjCMethod(LookupResult & Lookup,Scope * S,IdentifierInfo * II,bool AllowBuiltinCreation)2289 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2290                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2291   SourceLocation Loc = Lookup.getNameLoc();
2292   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2293 
2294   // Check for error condition which is already reported.
2295   if (!CurMethod)
2296     return ExprError();
2297 
2298   // There are two cases to handle here.  1) scoped lookup could have failed,
2299   // in which case we should look for an ivar.  2) scoped lookup could have
2300   // found a decl, but that decl is outside the current instance method (i.e.
2301   // a global variable).  In these two cases, we do a lookup for an ivar with
2302   // this name, if the lookup sucedes, we replace it our current decl.
2303 
2304   // If we're in a class method, we don't normally want to look for
2305   // ivars.  But if we don't find anything else, and there's an
2306   // ivar, that's an error.
2307   bool IsClassMethod = CurMethod->isClassMethod();
2308 
2309   bool LookForIvars;
2310   if (Lookup.empty())
2311     LookForIvars = true;
2312   else if (IsClassMethod)
2313     LookForIvars = false;
2314   else
2315     LookForIvars = (Lookup.isSingleResult() &&
2316                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2317   ObjCInterfaceDecl *IFace = nullptr;
2318   if (LookForIvars) {
2319     IFace = CurMethod->getClassInterface();
2320     ObjCInterfaceDecl *ClassDeclared;
2321     ObjCIvarDecl *IV = nullptr;
2322     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2323       // Diagnose using an ivar in a class method.
2324       if (IsClassMethod)
2325         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2326                          << IV->getDeclName());
2327 
2328       // If we're referencing an invalid decl, just return this as a silent
2329       // error node.  The error diagnostic was already emitted on the decl.
2330       if (IV->isInvalidDecl())
2331         return ExprError();
2332 
2333       // Check if referencing a field with __attribute__((deprecated)).
2334       if (DiagnoseUseOfDecl(IV, Loc))
2335         return ExprError();
2336 
2337       // Diagnose the use of an ivar outside of the declaring class.
2338       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2339           !declaresSameEntity(ClassDeclared, IFace) &&
2340           !getLangOpts().DebuggerSupport)
2341         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2342 
2343       // FIXME: This should use a new expr for a direct reference, don't
2344       // turn this into Self->ivar, just return a BareIVarExpr or something.
2345       IdentifierInfo &II = Context.Idents.get("self");
2346       UnqualifiedId SelfName;
2347       SelfName.setIdentifier(&II, SourceLocation());
2348       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2349       CXXScopeSpec SelfScopeSpec;
2350       SourceLocation TemplateKWLoc;
2351       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2352                                               SelfName, false, false);
2353       if (SelfExpr.isInvalid())
2354         return ExprError();
2355 
2356       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2357       if (SelfExpr.isInvalid())
2358         return ExprError();
2359 
2360       MarkAnyDeclReferenced(Loc, IV, true);
2361 
2362       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2363       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2364           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2365         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2366 
2367       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2368                                                               Loc, IV->getLocation(),
2369                                                               SelfExpr.get(),
2370                                                               true, true);
2371 
2372       if (getLangOpts().ObjCAutoRefCount) {
2373         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2374           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2375             recordUseOfEvaluatedWeak(Result);
2376         }
2377         if (CurContext->isClosure())
2378           Diag(Loc, diag::warn_implicitly_retains_self)
2379             << FixItHint::CreateInsertion(Loc, "self->");
2380       }
2381 
2382       return Result;
2383     }
2384   } else if (CurMethod->isInstanceMethod()) {
2385     // We should warn if a local variable hides an ivar.
2386     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2387       ObjCInterfaceDecl *ClassDeclared;
2388       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2389         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2390             declaresSameEntity(IFace, ClassDeclared))
2391           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2392       }
2393     }
2394   } else if (Lookup.isSingleResult() &&
2395              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2396     // If accessing a stand-alone ivar in a class method, this is an error.
2397     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2398       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2399                        << IV->getDeclName());
2400   }
2401 
2402   if (Lookup.empty() && II && AllowBuiltinCreation) {
2403     // FIXME. Consolidate this with similar code in LookupName.
2404     if (unsigned BuiltinID = II->getBuiltinID()) {
2405       if (!(getLangOpts().CPlusPlus &&
2406             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2407         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2408                                            S, Lookup.isForRedeclaration(),
2409                                            Lookup.getNameLoc());
2410         if (D) Lookup.addDecl(D);
2411       }
2412     }
2413   }
2414   // Sentinel value saying that we didn't do anything special.
2415   return ExprResult((Expr *)nullptr);
2416 }
2417 
2418 /// \brief Cast a base object to a member's actual type.
2419 ///
2420 /// Logically this happens in three phases:
2421 ///
2422 /// * First we cast from the base type to the naming class.
2423 ///   The naming class is the class into which we were looking
2424 ///   when we found the member;  it's the qualifier type if a
2425 ///   qualifier was provided, and otherwise it's the base type.
2426 ///
2427 /// * Next we cast from the naming class to the declaring class.
2428 ///   If the member we found was brought into a class's scope by
2429 ///   a using declaration, this is that class;  otherwise it's
2430 ///   the class declaring the member.
2431 ///
2432 /// * Finally we cast from the declaring class to the "true"
2433 ///   declaring class of the member.  This conversion does not
2434 ///   obey access control.
2435 ExprResult
PerformObjectMemberConversion(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,NamedDecl * Member)2436 Sema::PerformObjectMemberConversion(Expr *From,
2437                                     NestedNameSpecifier *Qualifier,
2438                                     NamedDecl *FoundDecl,
2439                                     NamedDecl *Member) {
2440   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2441   if (!RD)
2442     return From;
2443 
2444   QualType DestRecordType;
2445   QualType DestType;
2446   QualType FromRecordType;
2447   QualType FromType = From->getType();
2448   bool PointerConversions = false;
2449   if (isa<FieldDecl>(Member)) {
2450     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2451 
2452     if (FromType->getAs<PointerType>()) {
2453       DestType = Context.getPointerType(DestRecordType);
2454       FromRecordType = FromType->getPointeeType();
2455       PointerConversions = true;
2456     } else {
2457       DestType = DestRecordType;
2458       FromRecordType = FromType;
2459     }
2460   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2461     if (Method->isStatic())
2462       return From;
2463 
2464     DestType = Method->getThisType(Context);
2465     DestRecordType = DestType->getPointeeType();
2466 
2467     if (FromType->getAs<PointerType>()) {
2468       FromRecordType = FromType->getPointeeType();
2469       PointerConversions = true;
2470     } else {
2471       FromRecordType = FromType;
2472       DestType = DestRecordType;
2473     }
2474   } else {
2475     // No conversion necessary.
2476     return From;
2477   }
2478 
2479   if (DestType->isDependentType() || FromType->isDependentType())
2480     return From;
2481 
2482   // If the unqualified types are the same, no conversion is necessary.
2483   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2484     return From;
2485 
2486   SourceRange FromRange = From->getSourceRange();
2487   SourceLocation FromLoc = FromRange.getBegin();
2488 
2489   ExprValueKind VK = From->getValueKind();
2490 
2491   // C++ [class.member.lookup]p8:
2492   //   [...] Ambiguities can often be resolved by qualifying a name with its
2493   //   class name.
2494   //
2495   // If the member was a qualified name and the qualified referred to a
2496   // specific base subobject type, we'll cast to that intermediate type
2497   // first and then to the object in which the member is declared. That allows
2498   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2499   //
2500   //   class Base { public: int x; };
2501   //   class Derived1 : public Base { };
2502   //   class Derived2 : public Base { };
2503   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2504   //
2505   //   void VeryDerived::f() {
2506   //     x = 17; // error: ambiguous base subobjects
2507   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2508   //   }
2509   if (Qualifier && Qualifier->getAsType()) {
2510     QualType QType = QualType(Qualifier->getAsType(), 0);
2511     assert(QType->isRecordType() && "lookup done with non-record type");
2512 
2513     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2514 
2515     // In C++98, the qualifier type doesn't actually have to be a base
2516     // type of the object type, in which case we just ignore it.
2517     // Otherwise build the appropriate casts.
2518     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2519       CXXCastPath BasePath;
2520       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2521                                        FromLoc, FromRange, &BasePath))
2522         return ExprError();
2523 
2524       if (PointerConversions)
2525         QType = Context.getPointerType(QType);
2526       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2527                                VK, &BasePath).get();
2528 
2529       FromType = QType;
2530       FromRecordType = QRecordType;
2531 
2532       // If the qualifier type was the same as the destination type,
2533       // we're done.
2534       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2535         return From;
2536     }
2537   }
2538 
2539   bool IgnoreAccess = false;
2540 
2541   // If we actually found the member through a using declaration, cast
2542   // down to the using declaration's type.
2543   //
2544   // Pointer equality is fine here because only one declaration of a
2545   // class ever has member declarations.
2546   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2547     assert(isa<UsingShadowDecl>(FoundDecl));
2548     QualType URecordType = Context.getTypeDeclType(
2549                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2550 
2551     // We only need to do this if the naming-class to declaring-class
2552     // conversion is non-trivial.
2553     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2554       assert(IsDerivedFrom(FromRecordType, URecordType));
2555       CXXCastPath BasePath;
2556       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2557                                        FromLoc, FromRange, &BasePath))
2558         return ExprError();
2559 
2560       QualType UType = URecordType;
2561       if (PointerConversions)
2562         UType = Context.getPointerType(UType);
2563       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2564                                VK, &BasePath).get();
2565       FromType = UType;
2566       FromRecordType = URecordType;
2567     }
2568 
2569     // We don't do access control for the conversion from the
2570     // declaring class to the true declaring class.
2571     IgnoreAccess = true;
2572   }
2573 
2574   CXXCastPath BasePath;
2575   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2576                                    FromLoc, FromRange, &BasePath,
2577                                    IgnoreAccess))
2578     return ExprError();
2579 
2580   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2581                            VK, &BasePath);
2582 }
2583 
UseArgumentDependentLookup(const CXXScopeSpec & SS,const LookupResult & R,bool HasTrailingLParen)2584 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2585                                       const LookupResult &R,
2586                                       bool HasTrailingLParen) {
2587   // Only when used directly as the postfix-expression of a call.
2588   if (!HasTrailingLParen)
2589     return false;
2590 
2591   // Never if a scope specifier was provided.
2592   if (SS.isSet())
2593     return false;
2594 
2595   // Only in C++ or ObjC++.
2596   if (!getLangOpts().CPlusPlus)
2597     return false;
2598 
2599   // Turn off ADL when we find certain kinds of declarations during
2600   // normal lookup:
2601   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2602     NamedDecl *D = *I;
2603 
2604     // C++0x [basic.lookup.argdep]p3:
2605     //     -- a declaration of a class member
2606     // Since using decls preserve this property, we check this on the
2607     // original decl.
2608     if (D->isCXXClassMember())
2609       return false;
2610 
2611     // C++0x [basic.lookup.argdep]p3:
2612     //     -- a block-scope function declaration that is not a
2613     //        using-declaration
2614     // NOTE: we also trigger this for function templates (in fact, we
2615     // don't check the decl type at all, since all other decl types
2616     // turn off ADL anyway).
2617     if (isa<UsingShadowDecl>(D))
2618       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2619     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2620       return false;
2621 
2622     // C++0x [basic.lookup.argdep]p3:
2623     //     -- a declaration that is neither a function or a function
2624     //        template
2625     // And also for builtin functions.
2626     if (isa<FunctionDecl>(D)) {
2627       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2628 
2629       // But also builtin functions.
2630       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2631         return false;
2632     } else if (!isa<FunctionTemplateDecl>(D))
2633       return false;
2634   }
2635 
2636   return true;
2637 }
2638 
2639 
2640 /// Diagnoses obvious problems with the use of the given declaration
2641 /// as an expression.  This is only actually called for lookups that
2642 /// were not overloaded, and it doesn't promise that the declaration
2643 /// will in fact be used.
CheckDeclInExpr(Sema & S,SourceLocation Loc,NamedDecl * D)2644 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2645   if (isa<TypedefNameDecl>(D)) {
2646     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2647     return true;
2648   }
2649 
2650   if (isa<ObjCInterfaceDecl>(D)) {
2651     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2652     return true;
2653   }
2654 
2655   if (isa<NamespaceDecl>(D)) {
2656     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2657     return true;
2658   }
2659 
2660   return false;
2661 }
2662 
2663 ExprResult
BuildDeclarationNameExpr(const CXXScopeSpec & SS,LookupResult & R,bool NeedsADL)2664 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2665                                LookupResult &R,
2666                                bool NeedsADL) {
2667   // If this is a single, fully-resolved result and we don't need ADL,
2668   // just build an ordinary singleton decl ref.
2669   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2670     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2671                                     R.getRepresentativeDecl());
2672 
2673   // We only need to check the declaration if there's exactly one
2674   // result, because in the overloaded case the results can only be
2675   // functions and function templates.
2676   if (R.isSingleResult() &&
2677       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2678     return ExprError();
2679 
2680   // Otherwise, just build an unresolved lookup expression.  Suppress
2681   // any lookup-related diagnostics; we'll hash these out later, when
2682   // we've picked a target.
2683   R.suppressDiagnostics();
2684 
2685   UnresolvedLookupExpr *ULE
2686     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2687                                    SS.getWithLocInContext(Context),
2688                                    R.getLookupNameInfo(),
2689                                    NeedsADL, R.isOverloadedResult(),
2690                                    R.begin(), R.end());
2691 
2692   return ULE;
2693 }
2694 
2695 /// \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)2696 ExprResult Sema::BuildDeclarationNameExpr(
2697     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2698     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2699   assert(D && "Cannot refer to a NULL declaration");
2700   assert(!isa<FunctionTemplateDecl>(D) &&
2701          "Cannot refer unambiguously to a function template");
2702 
2703   SourceLocation Loc = NameInfo.getLoc();
2704   if (CheckDeclInExpr(*this, Loc, D))
2705     return ExprError();
2706 
2707   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2708     // Specifically diagnose references to class templates that are missing
2709     // a template argument list.
2710     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2711                                            << Template << SS.getRange();
2712     Diag(Template->getLocation(), diag::note_template_decl_here);
2713     return ExprError();
2714   }
2715 
2716   // Make sure that we're referring to a value.
2717   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2718   if (!VD) {
2719     Diag(Loc, diag::err_ref_non_value)
2720       << D << SS.getRange();
2721     Diag(D->getLocation(), diag::note_declared_at);
2722     return ExprError();
2723   }
2724 
2725   // Check whether this declaration can be used. Note that we suppress
2726   // this check when we're going to perform argument-dependent lookup
2727   // on this function name, because this might not be the function
2728   // that overload resolution actually selects.
2729   if (DiagnoseUseOfDecl(VD, Loc))
2730     return ExprError();
2731 
2732   // Only create DeclRefExpr's for valid Decl's.
2733   if (VD->isInvalidDecl())
2734     return ExprError();
2735 
2736   // Handle members of anonymous structs and unions.  If we got here,
2737   // and the reference is to a class member indirect field, then this
2738   // must be the subject of a pointer-to-member expression.
2739   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2740     if (!indirectField->isCXXClassMember())
2741       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2742                                                       indirectField);
2743 
2744   {
2745     QualType type = VD->getType();
2746     ExprValueKind valueKind = VK_RValue;
2747 
2748     switch (D->getKind()) {
2749     // Ignore all the non-ValueDecl kinds.
2750 #define ABSTRACT_DECL(kind)
2751 #define VALUE(type, base)
2752 #define DECL(type, base) \
2753     case Decl::type:
2754 #include "clang/AST/DeclNodes.inc"
2755       llvm_unreachable("invalid value decl kind");
2756 
2757     // These shouldn't make it here.
2758     case Decl::ObjCAtDefsField:
2759     case Decl::ObjCIvar:
2760       llvm_unreachable("forming non-member reference to ivar?");
2761 
2762     // Enum constants are always r-values and never references.
2763     // Unresolved using declarations are dependent.
2764     case Decl::EnumConstant:
2765     case Decl::UnresolvedUsingValue:
2766       valueKind = VK_RValue;
2767       break;
2768 
2769     // Fields and indirect fields that got here must be for
2770     // pointer-to-member expressions; we just call them l-values for
2771     // internal consistency, because this subexpression doesn't really
2772     // exist in the high-level semantics.
2773     case Decl::Field:
2774     case Decl::IndirectField:
2775       assert(getLangOpts().CPlusPlus &&
2776              "building reference to field in C?");
2777 
2778       // These can't have reference type in well-formed programs, but
2779       // for internal consistency we do this anyway.
2780       type = type.getNonReferenceType();
2781       valueKind = VK_LValue;
2782       break;
2783 
2784     // Non-type template parameters are either l-values or r-values
2785     // depending on the type.
2786     case Decl::NonTypeTemplateParm: {
2787       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2788         type = reftype->getPointeeType();
2789         valueKind = VK_LValue; // even if the parameter is an r-value reference
2790         break;
2791       }
2792 
2793       // For non-references, we need to strip qualifiers just in case
2794       // the template parameter was declared as 'const int' or whatever.
2795       valueKind = VK_RValue;
2796       type = type.getUnqualifiedType();
2797       break;
2798     }
2799 
2800     case Decl::Var:
2801     case Decl::VarTemplateSpecialization:
2802     case Decl::VarTemplatePartialSpecialization:
2803       // In C, "extern void blah;" is valid and is an r-value.
2804       if (!getLangOpts().CPlusPlus &&
2805           !type.hasQualifiers() &&
2806           type->isVoidType()) {
2807         valueKind = VK_RValue;
2808         break;
2809       }
2810       // fallthrough
2811 
2812     case Decl::ImplicitParam:
2813     case Decl::ParmVar: {
2814       // These are always l-values.
2815       valueKind = VK_LValue;
2816       type = type.getNonReferenceType();
2817 
2818       // FIXME: Does the addition of const really only apply in
2819       // potentially-evaluated contexts? Since the variable isn't actually
2820       // captured in an unevaluated context, it seems that the answer is no.
2821       if (!isUnevaluatedContext()) {
2822         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2823         if (!CapturedType.isNull())
2824           type = CapturedType;
2825       }
2826 
2827       break;
2828     }
2829 
2830     case Decl::Function: {
2831       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2832         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2833           type = Context.BuiltinFnTy;
2834           valueKind = VK_RValue;
2835           break;
2836         }
2837       }
2838 
2839       const FunctionType *fty = type->castAs<FunctionType>();
2840 
2841       // If we're referring to a function with an __unknown_anytype
2842       // result type, make the entire expression __unknown_anytype.
2843       if (fty->getReturnType() == Context.UnknownAnyTy) {
2844         type = Context.UnknownAnyTy;
2845         valueKind = VK_RValue;
2846         break;
2847       }
2848 
2849       // Functions are l-values in C++.
2850       if (getLangOpts().CPlusPlus) {
2851         valueKind = VK_LValue;
2852         break;
2853       }
2854 
2855       // C99 DR 316 says that, if a function type comes from a
2856       // function definition (without a prototype), that type is only
2857       // used for checking compatibility. Therefore, when referencing
2858       // the function, we pretend that we don't have the full function
2859       // type.
2860       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2861           isa<FunctionProtoType>(fty))
2862         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2863                                               fty->getExtInfo());
2864 
2865       // Functions are r-values in C.
2866       valueKind = VK_RValue;
2867       break;
2868     }
2869 
2870     case Decl::MSProperty:
2871       valueKind = VK_LValue;
2872       break;
2873 
2874     case Decl::CXXMethod:
2875       // If we're referring to a method with an __unknown_anytype
2876       // result type, make the entire expression __unknown_anytype.
2877       // This should only be possible with a type written directly.
2878       if (const FunctionProtoType *proto
2879             = dyn_cast<FunctionProtoType>(VD->getType()))
2880         if (proto->getReturnType() == Context.UnknownAnyTy) {
2881           type = Context.UnknownAnyTy;
2882           valueKind = VK_RValue;
2883           break;
2884         }
2885 
2886       // C++ methods are l-values if static, r-values if non-static.
2887       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2888         valueKind = VK_LValue;
2889         break;
2890       }
2891       // fallthrough
2892 
2893     case Decl::CXXConversion:
2894     case Decl::CXXDestructor:
2895     case Decl::CXXConstructor:
2896       valueKind = VK_RValue;
2897       break;
2898     }
2899 
2900     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2901                             TemplateArgs);
2902   }
2903 }
2904 
BuildPredefinedExpr(SourceLocation Loc,PredefinedExpr::IdentType IT)2905 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2906                                      PredefinedExpr::IdentType IT) {
2907   // Pick the current block, lambda, captured statement or function.
2908   Decl *currentDecl = nullptr;
2909   if (const BlockScopeInfo *BSI = getCurBlock())
2910     currentDecl = BSI->TheDecl;
2911   else if (const LambdaScopeInfo *LSI = getCurLambda())
2912     currentDecl = LSI->CallOperator;
2913   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2914     currentDecl = CSI->TheCapturedDecl;
2915   else
2916     currentDecl = getCurFunctionOrMethodDecl();
2917 
2918   if (!currentDecl) {
2919     Diag(Loc, diag::ext_predef_outside_function);
2920     currentDecl = Context.getTranslationUnitDecl();
2921   }
2922 
2923   QualType ResTy;
2924   if (cast<DeclContext>(currentDecl)->isDependentContext())
2925     ResTy = Context.DependentTy;
2926   else {
2927     // Pre-defined identifiers are of type char[x], where x is the length of
2928     // the string.
2929     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2930 
2931     llvm::APInt LengthI(32, Length + 1);
2932     if (IT == PredefinedExpr::LFunction)
2933       ResTy = Context.WideCharTy.withConst();
2934     else
2935       ResTy = Context.CharTy.withConst();
2936     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2937   }
2938 
2939   return new (Context) PredefinedExpr(Loc, ResTy, IT);
2940 }
2941 
ActOnPredefinedExpr(SourceLocation Loc,tok::TokenKind Kind)2942 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2943   PredefinedExpr::IdentType IT;
2944 
2945   switch (Kind) {
2946   default: llvm_unreachable("Unknown simple primary expr!");
2947   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2948   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2949   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
2950   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
2951   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2952   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2953   }
2954 
2955   return BuildPredefinedExpr(Loc, IT);
2956 }
2957 
ActOnCharacterConstant(const Token & Tok,Scope * UDLScope)2958 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2959   SmallString<16> CharBuffer;
2960   bool Invalid = false;
2961   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2962   if (Invalid)
2963     return ExprError();
2964 
2965   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2966                             PP, Tok.getKind());
2967   if (Literal.hadError())
2968     return ExprError();
2969 
2970   QualType Ty;
2971   if (Literal.isWide())
2972     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2973   else if (Literal.isUTF16())
2974     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2975   else if (Literal.isUTF32())
2976     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2977   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2978     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2979   else
2980     Ty = Context.CharTy;  // 'x' -> char in C++
2981 
2982   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2983   if (Literal.isWide())
2984     Kind = CharacterLiteral::Wide;
2985   else if (Literal.isUTF16())
2986     Kind = CharacterLiteral::UTF16;
2987   else if (Literal.isUTF32())
2988     Kind = CharacterLiteral::UTF32;
2989 
2990   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2991                                              Tok.getLocation());
2992 
2993   if (Literal.getUDSuffix().empty())
2994     return Lit;
2995 
2996   // We're building a user-defined literal.
2997   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2998   SourceLocation UDSuffixLoc =
2999     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3000 
3001   // Make sure we're allowed user-defined literals here.
3002   if (!UDLScope)
3003     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3004 
3005   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3006   //   operator "" X (ch)
3007   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3008                                         Lit, Tok.getLocation());
3009 }
3010 
ActOnIntegerConstant(SourceLocation Loc,uint64_t Val)3011 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3012   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3013   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3014                                 Context.IntTy, Loc);
3015 }
3016 
BuildFloatingLiteral(Sema & S,NumericLiteralParser & Literal,QualType Ty,SourceLocation Loc)3017 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3018                                   QualType Ty, SourceLocation Loc) {
3019   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3020 
3021   using llvm::APFloat;
3022   APFloat Val(Format);
3023 
3024   APFloat::opStatus result = Literal.GetFloatValue(Val);
3025 
3026   // Overflow is always an error, but underflow is only an error if
3027   // we underflowed to zero (APFloat reports denormals as underflow).
3028   if ((result & APFloat::opOverflow) ||
3029       ((result & APFloat::opUnderflow) && Val.isZero())) {
3030     unsigned diagnostic;
3031     SmallString<20> buffer;
3032     if (result & APFloat::opOverflow) {
3033       diagnostic = diag::warn_float_overflow;
3034       APFloat::getLargest(Format).toString(buffer);
3035     } else {
3036       diagnostic = diag::warn_float_underflow;
3037       APFloat::getSmallest(Format).toString(buffer);
3038     }
3039 
3040     S.Diag(Loc, diagnostic)
3041       << Ty
3042       << StringRef(buffer.data(), buffer.size());
3043   }
3044 
3045   bool isExact = (result == APFloat::opOK);
3046   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3047 }
3048 
ActOnNumericConstant(const Token & Tok,Scope * UDLScope)3049 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3050   // Fast path for a single digit (which is quite common).  A single digit
3051   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3052   if (Tok.getLength() == 1) {
3053     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3054     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3055   }
3056 
3057   SmallString<128> SpellingBuffer;
3058   // NumericLiteralParser wants to overread by one character.  Add padding to
3059   // the buffer in case the token is copied to the buffer.  If getSpelling()
3060   // returns a StringRef to the memory buffer, it should have a null char at
3061   // the EOF, so it is also safe.
3062   SpellingBuffer.resize(Tok.getLength() + 1);
3063 
3064   // Get the spelling of the token, which eliminates trigraphs, etc.
3065   bool Invalid = false;
3066   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3067   if (Invalid)
3068     return ExprError();
3069 
3070   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3071   if (Literal.hadError)
3072     return ExprError();
3073 
3074   if (Literal.hasUDSuffix()) {
3075     // We're building a user-defined literal.
3076     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3077     SourceLocation UDSuffixLoc =
3078       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3079 
3080     // Make sure we're allowed user-defined literals here.
3081     if (!UDLScope)
3082       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3083 
3084     QualType CookedTy;
3085     if (Literal.isFloatingLiteral()) {
3086       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3087       // long double, the literal is treated as a call of the form
3088       //   operator "" X (f L)
3089       CookedTy = Context.LongDoubleTy;
3090     } else {
3091       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3092       // unsigned long long, the literal is treated as a call of the form
3093       //   operator "" X (n ULL)
3094       CookedTy = Context.UnsignedLongLongTy;
3095     }
3096 
3097     DeclarationName OpName =
3098       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3099     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3100     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3101 
3102     SourceLocation TokLoc = Tok.getLocation();
3103 
3104     // Perform literal operator lookup to determine if we're building a raw
3105     // literal or a cooked one.
3106     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3107     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3108                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3109                                   /*AllowStringTemplate*/false)) {
3110     case LOLR_Error:
3111       return ExprError();
3112 
3113     case LOLR_Cooked: {
3114       Expr *Lit;
3115       if (Literal.isFloatingLiteral()) {
3116         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3117       } else {
3118         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3119         if (Literal.GetIntegerValue(ResultVal))
3120           Diag(Tok.getLocation(), diag::err_integer_too_large);
3121         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3122                                      Tok.getLocation());
3123       }
3124       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3125     }
3126 
3127     case LOLR_Raw: {
3128       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3129       // literal is treated as a call of the form
3130       //   operator "" X ("n")
3131       unsigned Length = Literal.getUDSuffixOffset();
3132       QualType StrTy = Context.getConstantArrayType(
3133           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3134           ArrayType::Normal, 0);
3135       Expr *Lit = StringLiteral::Create(
3136           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3137           /*Pascal*/false, StrTy, &TokLoc, 1);
3138       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3139     }
3140 
3141     case LOLR_Template: {
3142       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3143       // template), L is treated as a call fo the form
3144       //   operator "" X <'c1', 'c2', ... 'ck'>()
3145       // where n is the source character sequence c1 c2 ... ck.
3146       TemplateArgumentListInfo ExplicitArgs;
3147       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3148       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3149       llvm::APSInt Value(CharBits, CharIsUnsigned);
3150       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3151         Value = TokSpelling[I];
3152         TemplateArgument Arg(Context, Value, Context.CharTy);
3153         TemplateArgumentLocInfo ArgInfo;
3154         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3155       }
3156       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3157                                       &ExplicitArgs);
3158     }
3159     case LOLR_StringTemplate:
3160       llvm_unreachable("unexpected literal operator lookup result");
3161     }
3162   }
3163 
3164   Expr *Res;
3165 
3166   if (Literal.isFloatingLiteral()) {
3167     QualType Ty;
3168     if (Literal.isFloat)
3169       Ty = Context.FloatTy;
3170     else if (!Literal.isLong)
3171       Ty = Context.DoubleTy;
3172     else
3173       Ty = Context.LongDoubleTy;
3174 
3175     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3176 
3177     if (Ty == Context.DoubleTy) {
3178       if (getLangOpts().SinglePrecisionConstants) {
3179         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3180       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3181         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3182         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3183       }
3184     }
3185   } else if (!Literal.isIntegerLiteral()) {
3186     return ExprError();
3187   } else {
3188     QualType Ty;
3189 
3190     // 'long long' is a C99 or C++11 feature.
3191     if (!getLangOpts().C99 && Literal.isLongLong) {
3192       if (getLangOpts().CPlusPlus)
3193         Diag(Tok.getLocation(),
3194              getLangOpts().CPlusPlus11 ?
3195              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3196       else
3197         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3198     }
3199 
3200     // Get the value in the widest-possible width.
3201     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3202     // The microsoft literal suffix extensions support 128-bit literals, which
3203     // may be wider than [u]intmax_t.
3204     // FIXME: Actually, they don't. We seem to have accidentally invented the
3205     //        i128 suffix.
3206     if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
3207         Context.getTargetInfo().hasInt128Type())
3208       MaxWidth = 128;
3209     llvm::APInt ResultVal(MaxWidth, 0);
3210 
3211     if (Literal.GetIntegerValue(ResultVal)) {
3212       // If this value didn't fit into uintmax_t, error and force to ull.
3213       Diag(Tok.getLocation(), diag::err_integer_too_large);
3214       Ty = Context.UnsignedLongLongTy;
3215       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3216              "long long is not intmax_t?");
3217     } else {
3218       // If this value fits into a ULL, try to figure out what else it fits into
3219       // according to the rules of C99 6.4.4.1p5.
3220 
3221       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3222       // be an unsigned int.
3223       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3224 
3225       // Check from smallest to largest, picking the smallest type we can.
3226       unsigned Width = 0;
3227 
3228       // Microsoft specific integer suffixes are explicitly sized.
3229       if (Literal.MicrosoftInteger) {
3230         if (Literal.MicrosoftInteger > MaxWidth) {
3231           // If this target doesn't support __int128, error and force to ull.
3232           Diag(Tok.getLocation(), diag::err_int128_unsupported);
3233           Width = MaxWidth;
3234           Ty = Context.getIntMaxType();
3235         } else {
3236           Width = Literal.MicrosoftInteger;
3237           Ty = Context.getIntTypeForBitwidth(Width,
3238                                              /*Signed=*/!Literal.isUnsigned);
3239         }
3240       }
3241 
3242       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3243         // Are int/unsigned possibilities?
3244         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3245 
3246         // Does it fit in a unsigned int?
3247         if (ResultVal.isIntN(IntSize)) {
3248           // Does it fit in a signed int?
3249           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3250             Ty = Context.IntTy;
3251           else if (AllowUnsigned)
3252             Ty = Context.UnsignedIntTy;
3253           Width = IntSize;
3254         }
3255       }
3256 
3257       // Are long/unsigned long possibilities?
3258       if (Ty.isNull() && !Literal.isLongLong) {
3259         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3260 
3261         // Does it fit in a unsigned long?
3262         if (ResultVal.isIntN(LongSize)) {
3263           // Does it fit in a signed long?
3264           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3265             Ty = Context.LongTy;
3266           else if (AllowUnsigned)
3267             Ty = Context.UnsignedLongTy;
3268           Width = LongSize;
3269         }
3270       }
3271 
3272       // Check long long if needed.
3273       if (Ty.isNull()) {
3274         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3275 
3276         // Does it fit in a unsigned long long?
3277         if (ResultVal.isIntN(LongLongSize)) {
3278           // Does it fit in a signed long long?
3279           // To be compatible with MSVC, hex integer literals ending with the
3280           // LL or i64 suffix are always signed in Microsoft mode.
3281           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3282               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3283             Ty = Context.LongLongTy;
3284           else if (AllowUnsigned)
3285             Ty = Context.UnsignedLongLongTy;
3286           Width = LongLongSize;
3287         }
3288       }
3289 
3290       // If we still couldn't decide a type, we probably have something that
3291       // does not fit in a signed long long, but has no U suffix.
3292       if (Ty.isNull()) {
3293         Diag(Tok.getLocation(), diag::ext_integer_too_large_for_signed);
3294         Ty = Context.UnsignedLongLongTy;
3295         Width = Context.getTargetInfo().getLongLongWidth();
3296       }
3297 
3298       if (ResultVal.getBitWidth() != Width)
3299         ResultVal = ResultVal.trunc(Width);
3300     }
3301     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3302   }
3303 
3304   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3305   if (Literal.isImaginary)
3306     Res = new (Context) ImaginaryLiteral(Res,
3307                                         Context.getComplexType(Res->getType()));
3308 
3309   return Res;
3310 }
3311 
ActOnParenExpr(SourceLocation L,SourceLocation R,Expr * E)3312 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3313   assert(E && "ActOnParenExpr() missing expr");
3314   return new (Context) ParenExpr(L, R, E);
3315 }
3316 
CheckVecStepTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange)3317 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3318                                          SourceLocation Loc,
3319                                          SourceRange ArgRange) {
3320   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3321   // scalar or vector data type argument..."
3322   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3323   // type (C99 6.2.5p18) or void.
3324   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3325     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3326       << T << ArgRange;
3327     return true;
3328   }
3329 
3330   assert((T->isVoidType() || !T->isIncompleteType()) &&
3331          "Scalar types should always be complete");
3332   return false;
3333 }
3334 
CheckExtensionTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)3335 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3336                                            SourceLocation Loc,
3337                                            SourceRange ArgRange,
3338                                            UnaryExprOrTypeTrait TraitKind) {
3339   // Invalid types must be hard errors for SFINAE in C++.
3340   if (S.LangOpts.CPlusPlus)
3341     return true;
3342 
3343   // C99 6.5.3.4p1:
3344   if (T->isFunctionType() &&
3345       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3346     // sizeof(function)/alignof(function) is allowed as an extension.
3347     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3348       << TraitKind << ArgRange;
3349     return false;
3350   }
3351 
3352   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3353   // this is an error (OpenCL v1.1 s6.3.k)
3354   if (T->isVoidType()) {
3355     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3356                                         : diag::ext_sizeof_alignof_void_type;
3357     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3358     return false;
3359   }
3360 
3361   return true;
3362 }
3363 
CheckObjCTraitOperandConstraints(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)3364 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3365                                              SourceLocation Loc,
3366                                              SourceRange ArgRange,
3367                                              UnaryExprOrTypeTrait TraitKind) {
3368   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3369   // runtime doesn't allow it.
3370   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3371     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3372       << T << (TraitKind == UETT_SizeOf)
3373       << ArgRange;
3374     return true;
3375   }
3376 
3377   return false;
3378 }
3379 
3380 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3381 /// pointer type is equal to T) and emit a warning if it is.
warnOnSizeofOnArrayDecay(Sema & S,SourceLocation Loc,QualType T,Expr * E)3382 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3383                                      Expr *E) {
3384   // Don't warn if the operation changed the type.
3385   if (T != E->getType())
3386     return;
3387 
3388   // Now look for array decays.
3389   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3390   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3391     return;
3392 
3393   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3394                                              << ICE->getType()
3395                                              << ICE->getSubExpr()->getType();
3396 }
3397 
3398 /// \brief Check the constraints on expression operands to unary type expression
3399 /// and type traits.
3400 ///
3401 /// Completes any types necessary and validates the constraints on the operand
3402 /// expression. The logic mostly mirrors the type-based overload, but may modify
3403 /// the expression as it completes the type for that expression through template
3404 /// instantiation, etc.
CheckUnaryExprOrTypeTraitOperand(Expr * E,UnaryExprOrTypeTrait ExprKind)3405 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3406                                             UnaryExprOrTypeTrait ExprKind) {
3407   QualType ExprTy = E->getType();
3408   assert(!ExprTy->isReferenceType());
3409 
3410   if (ExprKind == UETT_VecStep)
3411     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3412                                         E->getSourceRange());
3413 
3414   // Whitelist some types as extensions
3415   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3416                                       E->getSourceRange(), ExprKind))
3417     return false;
3418 
3419   // 'alignof' applied to an expression only requires the base element type of
3420   // the expression to be complete. 'sizeof' requires the expression's type to
3421   // be complete (and will attempt to complete it if it's an array of unknown
3422   // bound).
3423   if (ExprKind == UETT_AlignOf) {
3424     if (RequireCompleteType(E->getExprLoc(),
3425                             Context.getBaseElementType(E->getType()),
3426                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3427                             E->getSourceRange()))
3428       return true;
3429   } else {
3430     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3431                                 ExprKind, E->getSourceRange()))
3432       return true;
3433   }
3434 
3435   // Completing the expression's type may have changed it.
3436   ExprTy = E->getType();
3437   assert(!ExprTy->isReferenceType());
3438 
3439   if (ExprTy->isFunctionType()) {
3440     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3441       << ExprKind << E->getSourceRange();
3442     return true;
3443   }
3444 
3445   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3446                                        E->getSourceRange(), ExprKind))
3447     return true;
3448 
3449   if (ExprKind == UETT_SizeOf) {
3450     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3451       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3452         QualType OType = PVD->getOriginalType();
3453         QualType Type = PVD->getType();
3454         if (Type->isPointerType() && OType->isArrayType()) {
3455           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3456             << Type << OType;
3457           Diag(PVD->getLocation(), diag::note_declared_at);
3458         }
3459       }
3460     }
3461 
3462     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3463     // decays into a pointer and returns an unintended result. This is most
3464     // likely a typo for "sizeof(array) op x".
3465     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3466       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3467                                BO->getLHS());
3468       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3469                                BO->getRHS());
3470     }
3471   }
3472 
3473   return false;
3474 }
3475 
3476 /// \brief Check the constraints on operands to unary expression and type
3477 /// traits.
3478 ///
3479 /// This will complete any types necessary, and validate the various constraints
3480 /// on those operands.
3481 ///
3482 /// The UsualUnaryConversions() function is *not* called by this routine.
3483 /// C99 6.3.2.1p[2-4] all state:
3484 ///   Except when it is the operand of the sizeof operator ...
3485 ///
3486 /// C++ [expr.sizeof]p4
3487 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3488 ///   standard conversions are not applied to the operand of sizeof.
3489 ///
3490 /// This policy is followed for all of the unary trait expressions.
CheckUnaryExprOrTypeTraitOperand(QualType ExprType,SourceLocation OpLoc,SourceRange ExprRange,UnaryExprOrTypeTrait ExprKind)3491 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3492                                             SourceLocation OpLoc,
3493                                             SourceRange ExprRange,
3494                                             UnaryExprOrTypeTrait ExprKind) {
3495   if (ExprType->isDependentType())
3496     return false;
3497 
3498   // C++ [expr.sizeof]p2:
3499   //     When applied to a reference or a reference type, the result
3500   //     is the size of the referenced type.
3501   // C++11 [expr.alignof]p3:
3502   //     When alignof is applied to a reference type, the result
3503   //     shall be the alignment of the referenced type.
3504   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3505     ExprType = Ref->getPointeeType();
3506 
3507   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3508   //   When alignof or _Alignof is applied to an array type, the result
3509   //   is the alignment of the element type.
3510   if (ExprKind == UETT_AlignOf)
3511     ExprType = Context.getBaseElementType(ExprType);
3512 
3513   if (ExprKind == UETT_VecStep)
3514     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3515 
3516   // Whitelist some types as extensions
3517   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3518                                       ExprKind))
3519     return false;
3520 
3521   if (RequireCompleteType(OpLoc, ExprType,
3522                           diag::err_sizeof_alignof_incomplete_type,
3523                           ExprKind, ExprRange))
3524     return true;
3525 
3526   if (ExprType->isFunctionType()) {
3527     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3528       << ExprKind << ExprRange;
3529     return true;
3530   }
3531 
3532   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3533                                        ExprKind))
3534     return true;
3535 
3536   return false;
3537 }
3538 
CheckAlignOfExpr(Sema & S,Expr * E)3539 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3540   E = E->IgnoreParens();
3541 
3542   // Cannot know anything else if the expression is dependent.
3543   if (E->isTypeDependent())
3544     return false;
3545 
3546   if (E->getObjectKind() == OK_BitField) {
3547     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3548        << 1 << E->getSourceRange();
3549     return true;
3550   }
3551 
3552   ValueDecl *D = nullptr;
3553   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3554     D = DRE->getDecl();
3555   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3556     D = ME->getMemberDecl();
3557   }
3558 
3559   // If it's a field, require the containing struct to have a
3560   // complete definition so that we can compute the layout.
3561   //
3562   // This can happen in C++11 onwards, either by naming the member
3563   // in a way that is not transformed into a member access expression
3564   // (in an unevaluated operand, for instance), or by naming the member
3565   // in a trailing-return-type.
3566   //
3567   // For the record, since __alignof__ on expressions is a GCC
3568   // extension, GCC seems to permit this but always gives the
3569   // nonsensical answer 0.
3570   //
3571   // We don't really need the layout here --- we could instead just
3572   // directly check for all the appropriate alignment-lowing
3573   // attributes --- but that would require duplicating a lot of
3574   // logic that just isn't worth duplicating for such a marginal
3575   // use-case.
3576   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3577     // Fast path this check, since we at least know the record has a
3578     // definition if we can find a member of it.
3579     if (!FD->getParent()->isCompleteDefinition()) {
3580       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3581         << E->getSourceRange();
3582       return true;
3583     }
3584 
3585     // Otherwise, if it's a field, and the field doesn't have
3586     // reference type, then it must have a complete type (or be a
3587     // flexible array member, which we explicitly want to
3588     // white-list anyway), which makes the following checks trivial.
3589     if (!FD->getType()->isReferenceType())
3590       return false;
3591   }
3592 
3593   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3594 }
3595 
CheckVecStepExpr(Expr * E)3596 bool Sema::CheckVecStepExpr(Expr *E) {
3597   E = E->IgnoreParens();
3598 
3599   // Cannot know anything else if the expression is dependent.
3600   if (E->isTypeDependent())
3601     return false;
3602 
3603   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3604 }
3605 
3606 /// \brief Build a sizeof or alignof expression given a type operand.
3607 ExprResult
CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo * TInfo,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,SourceRange R)3608 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3609                                      SourceLocation OpLoc,
3610                                      UnaryExprOrTypeTrait ExprKind,
3611                                      SourceRange R) {
3612   if (!TInfo)
3613     return ExprError();
3614 
3615   QualType T = TInfo->getType();
3616 
3617   if (!T->isDependentType() &&
3618       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3619     return ExprError();
3620 
3621   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3622   return new (Context) UnaryExprOrTypeTraitExpr(
3623       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3624 }
3625 
3626 /// \brief Build a sizeof or alignof expression given an expression
3627 /// operand.
3628 ExprResult
CreateUnaryExprOrTypeTraitExpr(Expr * E,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind)3629 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3630                                      UnaryExprOrTypeTrait ExprKind) {
3631   ExprResult PE = CheckPlaceholderExpr(E);
3632   if (PE.isInvalid())
3633     return ExprError();
3634 
3635   E = PE.get();
3636 
3637   // Verify that the operand is valid.
3638   bool isInvalid = false;
3639   if (E->isTypeDependent()) {
3640     // Delay type-checking for type-dependent expressions.
3641   } else if (ExprKind == UETT_AlignOf) {
3642     isInvalid = CheckAlignOfExpr(*this, E);
3643   } else if (ExprKind == UETT_VecStep) {
3644     isInvalid = CheckVecStepExpr(E);
3645   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3646     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3647     isInvalid = true;
3648   } else {
3649     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3650   }
3651 
3652   if (isInvalid)
3653     return ExprError();
3654 
3655   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3656     PE = TransformToPotentiallyEvaluated(E);
3657     if (PE.isInvalid()) return ExprError();
3658     E = PE.get();
3659   }
3660 
3661   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3662   return new (Context) UnaryExprOrTypeTraitExpr(
3663       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3664 }
3665 
3666 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3667 /// expr and the same for @c alignof and @c __alignof
3668 /// Note that the ArgRange is invalid if isType is false.
3669 ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,bool IsType,void * TyOrEx,const SourceRange & ArgRange)3670 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3671                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3672                                     void *TyOrEx, const SourceRange &ArgRange) {
3673   // If error parsing type, ignore.
3674   if (!TyOrEx) return ExprError();
3675 
3676   if (IsType) {
3677     TypeSourceInfo *TInfo;
3678     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3679     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3680   }
3681 
3682   Expr *ArgEx = (Expr *)TyOrEx;
3683   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3684   return Result;
3685 }
3686 
CheckRealImagOperand(Sema & S,ExprResult & V,SourceLocation Loc,bool IsReal)3687 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3688                                      bool IsReal) {
3689   if (V.get()->isTypeDependent())
3690     return S.Context.DependentTy;
3691 
3692   // _Real and _Imag are only l-values for normal l-values.
3693   if (V.get()->getObjectKind() != OK_Ordinary) {
3694     V = S.DefaultLvalueConversion(V.get());
3695     if (V.isInvalid())
3696       return QualType();
3697   }
3698 
3699   // These operators return the element type of a complex type.
3700   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3701     return CT->getElementType();
3702 
3703   // Otherwise they pass through real integer and floating point types here.
3704   if (V.get()->getType()->isArithmeticType())
3705     return V.get()->getType();
3706 
3707   // Test for placeholders.
3708   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3709   if (PR.isInvalid()) return QualType();
3710   if (PR.get() != V.get()) {
3711     V = PR;
3712     return CheckRealImagOperand(S, V, Loc, IsReal);
3713   }
3714 
3715   // Reject anything else.
3716   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3717     << (IsReal ? "__real" : "__imag");
3718   return QualType();
3719 }
3720 
3721 
3722 
3723 ExprResult
ActOnPostfixUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Kind,Expr * Input)3724 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3725                           tok::TokenKind Kind, Expr *Input) {
3726   UnaryOperatorKind Opc;
3727   switch (Kind) {
3728   default: llvm_unreachable("Unknown unary op!");
3729   case tok::plusplus:   Opc = UO_PostInc; break;
3730   case tok::minusminus: Opc = UO_PostDec; break;
3731   }
3732 
3733   // Since this might is a postfix expression, get rid of ParenListExprs.
3734   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3735   if (Result.isInvalid()) return ExprError();
3736   Input = Result.get();
3737 
3738   return BuildUnaryOp(S, OpLoc, Opc, Input);
3739 }
3740 
3741 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3742 ///
3743 /// \return true on error
checkArithmeticOnObjCPointer(Sema & S,SourceLocation opLoc,Expr * op)3744 static bool checkArithmeticOnObjCPointer(Sema &S,
3745                                          SourceLocation opLoc,
3746                                          Expr *op) {
3747   assert(op->getType()->isObjCObjectPointerType());
3748   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3749       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3750     return false;
3751 
3752   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3753     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3754     << op->getSourceRange();
3755   return true;
3756 }
3757 
3758 ExprResult
ActOnArraySubscriptExpr(Scope * S,Expr * base,SourceLocation lbLoc,Expr * idx,SourceLocation rbLoc)3759 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3760                               Expr *idx, SourceLocation rbLoc) {
3761   // Since this might be a postfix expression, get rid of ParenListExprs.
3762   if (isa<ParenListExpr>(base)) {
3763     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3764     if (result.isInvalid()) return ExprError();
3765     base = result.get();
3766   }
3767 
3768   // Handle any non-overload placeholder types in the base and index
3769   // expressions.  We can't handle overloads here because the other
3770   // operand might be an overloadable type, in which case the overload
3771   // resolution for the operator overload should get the first crack
3772   // at the overload.
3773   if (base->getType()->isNonOverloadPlaceholderType()) {
3774     ExprResult result = CheckPlaceholderExpr(base);
3775     if (result.isInvalid()) return ExprError();
3776     base = result.get();
3777   }
3778   if (idx->getType()->isNonOverloadPlaceholderType()) {
3779     ExprResult result = CheckPlaceholderExpr(idx);
3780     if (result.isInvalid()) return ExprError();
3781     idx = result.get();
3782   }
3783 
3784   // Build an unanalyzed expression if either operand is type-dependent.
3785   if (getLangOpts().CPlusPlus &&
3786       (base->isTypeDependent() || idx->isTypeDependent())) {
3787     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3788                                             VK_LValue, OK_Ordinary, rbLoc);
3789   }
3790 
3791   // Use C++ overloaded-operator rules if either operand has record
3792   // type.  The spec says to do this if either type is *overloadable*,
3793   // but enum types can't declare subscript operators or conversion
3794   // operators, so there's nothing interesting for overload resolution
3795   // to do if there aren't any record types involved.
3796   //
3797   // ObjC pointers have their own subscripting logic that is not tied
3798   // to overload resolution and so should not take this path.
3799   if (getLangOpts().CPlusPlus &&
3800       (base->getType()->isRecordType() ||
3801        (!base->getType()->isObjCObjectPointerType() &&
3802         idx->getType()->isRecordType()))) {
3803     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3804   }
3805 
3806   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3807 }
3808 
3809 ExprResult
CreateBuiltinArraySubscriptExpr(Expr * Base,SourceLocation LLoc,Expr * Idx,SourceLocation RLoc)3810 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3811                                       Expr *Idx, SourceLocation RLoc) {
3812   Expr *LHSExp = Base;
3813   Expr *RHSExp = Idx;
3814 
3815   // Perform default conversions.
3816   if (!LHSExp->getType()->getAs<VectorType>()) {
3817     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3818     if (Result.isInvalid())
3819       return ExprError();
3820     LHSExp = Result.get();
3821   }
3822   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3823   if (Result.isInvalid())
3824     return ExprError();
3825   RHSExp = Result.get();
3826 
3827   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3828   ExprValueKind VK = VK_LValue;
3829   ExprObjectKind OK = OK_Ordinary;
3830 
3831   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3832   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3833   // in the subscript position. As a result, we need to derive the array base
3834   // and index from the expression types.
3835   Expr *BaseExpr, *IndexExpr;
3836   QualType ResultType;
3837   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3838     BaseExpr = LHSExp;
3839     IndexExpr = RHSExp;
3840     ResultType = Context.DependentTy;
3841   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3842     BaseExpr = LHSExp;
3843     IndexExpr = RHSExp;
3844     ResultType = PTy->getPointeeType();
3845   } else if (const ObjCObjectPointerType *PTy =
3846                LHSTy->getAs<ObjCObjectPointerType>()) {
3847     BaseExpr = LHSExp;
3848     IndexExpr = RHSExp;
3849 
3850     // Use custom logic if this should be the pseudo-object subscript
3851     // expression.
3852     if (!LangOpts.isSubscriptPointerArithmetic())
3853       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
3854                                           nullptr);
3855 
3856     ResultType = PTy->getPointeeType();
3857   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3858      // Handle the uncommon case of "123[Ptr]".
3859     BaseExpr = RHSExp;
3860     IndexExpr = LHSExp;
3861     ResultType = PTy->getPointeeType();
3862   } else if (const ObjCObjectPointerType *PTy =
3863                RHSTy->getAs<ObjCObjectPointerType>()) {
3864      // Handle the uncommon case of "123[Ptr]".
3865     BaseExpr = RHSExp;
3866     IndexExpr = LHSExp;
3867     ResultType = PTy->getPointeeType();
3868     if (!LangOpts.isSubscriptPointerArithmetic()) {
3869       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3870         << ResultType << BaseExpr->getSourceRange();
3871       return ExprError();
3872     }
3873   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3874     BaseExpr = LHSExp;    // vectors: V[123]
3875     IndexExpr = RHSExp;
3876     VK = LHSExp->getValueKind();
3877     if (VK != VK_RValue)
3878       OK = OK_VectorComponent;
3879 
3880     // FIXME: need to deal with const...
3881     ResultType = VTy->getElementType();
3882   } else if (LHSTy->isArrayType()) {
3883     // If we see an array that wasn't promoted by
3884     // DefaultFunctionArrayLvalueConversion, it must be an array that
3885     // wasn't promoted because of the C90 rule that doesn't
3886     // allow promoting non-lvalue arrays.  Warn, then
3887     // force the promotion here.
3888     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3889         LHSExp->getSourceRange();
3890     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3891                                CK_ArrayToPointerDecay).get();
3892     LHSTy = LHSExp->getType();
3893 
3894     BaseExpr = LHSExp;
3895     IndexExpr = RHSExp;
3896     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3897   } else if (RHSTy->isArrayType()) {
3898     // Same as previous, except for 123[f().a] case
3899     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3900         RHSExp->getSourceRange();
3901     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3902                                CK_ArrayToPointerDecay).get();
3903     RHSTy = RHSExp->getType();
3904 
3905     BaseExpr = RHSExp;
3906     IndexExpr = LHSExp;
3907     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3908   } else {
3909     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3910        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3911   }
3912   // C99 6.5.2.1p1
3913   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3914     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3915                      << IndexExpr->getSourceRange());
3916 
3917   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3918        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3919          && !IndexExpr->isTypeDependent())
3920     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3921 
3922   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3923   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3924   // type. Note that Functions are not objects, and that (in C99 parlance)
3925   // incomplete types are not object types.
3926   if (ResultType->isFunctionType()) {
3927     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3928       << ResultType << BaseExpr->getSourceRange();
3929     return ExprError();
3930   }
3931 
3932   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3933     // GNU extension: subscripting on pointer to void
3934     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3935       << BaseExpr->getSourceRange();
3936 
3937     // C forbids expressions of unqualified void type from being l-values.
3938     // See IsCForbiddenLValueType.
3939     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3940   } else if (!ResultType->isDependentType() &&
3941       RequireCompleteType(LLoc, ResultType,
3942                           diag::err_subscript_incomplete_type, BaseExpr))
3943     return ExprError();
3944 
3945   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3946          !ResultType.isCForbiddenLValueType());
3947 
3948   return new (Context)
3949       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
3950 }
3951 
BuildCXXDefaultArgExpr(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)3952 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3953                                         FunctionDecl *FD,
3954                                         ParmVarDecl *Param) {
3955   if (Param->hasUnparsedDefaultArg()) {
3956     Diag(CallLoc,
3957          diag::err_use_of_default_argument_to_function_declared_later) <<
3958       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3959     Diag(UnparsedDefaultArgLocs[Param],
3960          diag::note_default_argument_declared_here);
3961     return ExprError();
3962   }
3963 
3964   if (Param->hasUninstantiatedDefaultArg()) {
3965     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3966 
3967     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3968                                                  Param);
3969 
3970     // Instantiate the expression.
3971     MultiLevelTemplateArgumentList MutiLevelArgList
3972       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
3973 
3974     InstantiatingTemplate Inst(*this, CallLoc, Param,
3975                                MutiLevelArgList.getInnermost());
3976     if (Inst.isInvalid())
3977       return ExprError();
3978 
3979     ExprResult Result;
3980     {
3981       // C++ [dcl.fct.default]p5:
3982       //   The names in the [default argument] expression are bound, and
3983       //   the semantic constraints are checked, at the point where the
3984       //   default argument expression appears.
3985       ContextRAII SavedContext(*this, FD);
3986       LocalInstantiationScope Local(*this);
3987       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3988     }
3989     if (Result.isInvalid())
3990       return ExprError();
3991 
3992     // Check the expression as an initializer for the parameter.
3993     InitializedEntity Entity
3994       = InitializedEntity::InitializeParameter(Context, Param);
3995     InitializationKind Kind
3996       = InitializationKind::CreateCopy(Param->getLocation(),
3997              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3998     Expr *ResultE = Result.getAs<Expr>();
3999 
4000     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4001     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4002     if (Result.isInvalid())
4003       return ExprError();
4004 
4005     Expr *Arg = Result.getAs<Expr>();
4006     CheckCompletedExpr(Arg, Param->getOuterLocStart());
4007     // Build the default argument expression.
4008     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
4009   }
4010 
4011   // If the default expression creates temporaries, we need to
4012   // push them to the current stack of expression temporaries so they'll
4013   // be properly destroyed.
4014   // FIXME: We should really be rebuilding the default argument with new
4015   // bound temporaries; see the comment in PR5810.
4016   // We don't need to do that with block decls, though, because
4017   // blocks in default argument expression can never capture anything.
4018   if (isa<ExprWithCleanups>(Param->getInit())) {
4019     // Set the "needs cleanups" bit regardless of whether there are
4020     // any explicit objects.
4021     ExprNeedsCleanups = true;
4022 
4023     // Append all the objects to the cleanup list.  Right now, this
4024     // should always be a no-op, because blocks in default argument
4025     // expressions should never be able to capture anything.
4026     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4027            "default argument expression has capturing blocks?");
4028   }
4029 
4030   // We already type-checked the argument, so we know it works.
4031   // Just mark all of the declarations in this potentially-evaluated expression
4032   // as being "referenced".
4033   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4034                                    /*SkipLocalVariables=*/true);
4035   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4036 }
4037 
4038 
4039 Sema::VariadicCallType
getVariadicCallType(FunctionDecl * FDecl,const FunctionProtoType * Proto,Expr * Fn)4040 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4041                           Expr *Fn) {
4042   if (Proto && Proto->isVariadic()) {
4043     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4044       return VariadicConstructor;
4045     else if (Fn && Fn->getType()->isBlockPointerType())
4046       return VariadicBlock;
4047     else if (FDecl) {
4048       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4049         if (Method->isInstance())
4050           return VariadicMethod;
4051     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4052       return VariadicMethod;
4053     return VariadicFunction;
4054   }
4055   return VariadicDoesNotApply;
4056 }
4057 
4058 namespace {
4059 class FunctionCallCCC : public FunctionCallFilterCCC {
4060 public:
FunctionCallCCC(Sema & SemaRef,const IdentifierInfo * FuncName,unsigned NumArgs,MemberExpr * ME)4061   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4062                   unsigned NumArgs, MemberExpr *ME)
4063       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4064         FunctionName(FuncName) {}
4065 
ValidateCandidate(const TypoCorrection & candidate)4066   bool ValidateCandidate(const TypoCorrection &candidate) override {
4067     if (!candidate.getCorrectionSpecifier() ||
4068         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4069       return false;
4070     }
4071 
4072     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4073   }
4074 
4075 private:
4076   const IdentifierInfo *const FunctionName;
4077 };
4078 }
4079 
TryTypoCorrectionForCall(Sema & S,Expr * Fn,FunctionDecl * FDecl,ArrayRef<Expr * > Args)4080 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4081                                                FunctionDecl *FDecl,
4082                                                ArrayRef<Expr *> Args) {
4083   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4084   DeclarationName FuncName = FDecl->getDeclName();
4085   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4086   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4087 
4088   if (TypoCorrection Corrected = S.CorrectTypo(
4089           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4090           S.getScopeForContext(S.CurContext), nullptr, CCC,
4091           Sema::CTK_ErrorRecovery)) {
4092     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4093       if (Corrected.isOverloaded()) {
4094         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4095         OverloadCandidateSet::iterator Best;
4096         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4097                                            CDEnd = Corrected.end();
4098              CD != CDEnd; ++CD) {
4099           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4100             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4101                                    OCS);
4102         }
4103         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4104         case OR_Success:
4105           ND = Best->Function;
4106           Corrected.setCorrectionDecl(ND);
4107           break;
4108         default:
4109           break;
4110         }
4111       }
4112       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4113         return Corrected;
4114       }
4115     }
4116   }
4117   return TypoCorrection();
4118 }
4119 
4120 /// ConvertArgumentsForCall - Converts the arguments specified in
4121 /// Args/NumArgs to the parameter types of the function FDecl with
4122 /// function prototype Proto. Call is the call expression itself, and
4123 /// Fn is the function expression. For a C++ member function, this
4124 /// routine does not attempt to convert the object argument. Returns
4125 /// true if the call is ill-formed.
4126 bool
ConvertArgumentsForCall(CallExpr * Call,Expr * Fn,FunctionDecl * FDecl,const FunctionProtoType * Proto,ArrayRef<Expr * > Args,SourceLocation RParenLoc,bool IsExecConfig)4127 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4128                               FunctionDecl *FDecl,
4129                               const FunctionProtoType *Proto,
4130                               ArrayRef<Expr *> Args,
4131                               SourceLocation RParenLoc,
4132                               bool IsExecConfig) {
4133   // Bail out early if calling a builtin with custom typechecking.
4134   // We don't need to do this in the
4135   if (FDecl)
4136     if (unsigned ID = FDecl->getBuiltinID())
4137       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4138         return false;
4139 
4140   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4141   // assignment, to the types of the corresponding parameter, ...
4142   unsigned NumParams = Proto->getNumParams();
4143   bool Invalid = false;
4144   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4145   unsigned FnKind = Fn->getType()->isBlockPointerType()
4146                        ? 1 /* block */
4147                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4148                                        : 0 /* function */);
4149 
4150   // If too few arguments are available (and we don't have default
4151   // arguments for the remaining parameters), don't make the call.
4152   if (Args.size() < NumParams) {
4153     if (Args.size() < MinArgs) {
4154       TypoCorrection TC;
4155       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4156         unsigned diag_id =
4157             MinArgs == NumParams && !Proto->isVariadic()
4158                 ? diag::err_typecheck_call_too_few_args_suggest
4159                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4160         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4161                                         << static_cast<unsigned>(Args.size())
4162                                         << TC.getCorrectionRange());
4163       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4164         Diag(RParenLoc,
4165              MinArgs == NumParams && !Proto->isVariadic()
4166                  ? diag::err_typecheck_call_too_few_args_one
4167                  : diag::err_typecheck_call_too_few_args_at_least_one)
4168             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4169       else
4170         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4171                             ? diag::err_typecheck_call_too_few_args
4172                             : diag::err_typecheck_call_too_few_args_at_least)
4173             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4174             << Fn->getSourceRange();
4175 
4176       // Emit the location of the prototype.
4177       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4178         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4179           << FDecl;
4180 
4181       return true;
4182     }
4183     Call->setNumArgs(Context, NumParams);
4184   }
4185 
4186   // If too many are passed and not variadic, error on the extras and drop
4187   // them.
4188   if (Args.size() > NumParams) {
4189     if (!Proto->isVariadic()) {
4190       TypoCorrection TC;
4191       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4192         unsigned diag_id =
4193             MinArgs == NumParams && !Proto->isVariadic()
4194                 ? diag::err_typecheck_call_too_many_args_suggest
4195                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4196         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4197                                         << static_cast<unsigned>(Args.size())
4198                                         << TC.getCorrectionRange());
4199       } else if (NumParams == 1 && FDecl &&
4200                  FDecl->getParamDecl(0)->getDeclName())
4201         Diag(Args[NumParams]->getLocStart(),
4202              MinArgs == NumParams
4203                  ? diag::err_typecheck_call_too_many_args_one
4204                  : diag::err_typecheck_call_too_many_args_at_most_one)
4205             << FnKind << FDecl->getParamDecl(0)
4206             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4207             << SourceRange(Args[NumParams]->getLocStart(),
4208                            Args.back()->getLocEnd());
4209       else
4210         Diag(Args[NumParams]->getLocStart(),
4211              MinArgs == NumParams
4212                  ? diag::err_typecheck_call_too_many_args
4213                  : diag::err_typecheck_call_too_many_args_at_most)
4214             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4215             << Fn->getSourceRange()
4216             << SourceRange(Args[NumParams]->getLocStart(),
4217                            Args.back()->getLocEnd());
4218 
4219       // Emit the location of the prototype.
4220       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4221         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4222           << FDecl;
4223 
4224       // This deletes the extra arguments.
4225       Call->setNumArgs(Context, NumParams);
4226       return true;
4227     }
4228   }
4229   SmallVector<Expr *, 8> AllArgs;
4230   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4231 
4232   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4233                                    Proto, 0, Args, AllArgs, CallType);
4234   if (Invalid)
4235     return true;
4236   unsigned TotalNumArgs = AllArgs.size();
4237   for (unsigned i = 0; i < TotalNumArgs; ++i)
4238     Call->setArg(i, AllArgs[i]);
4239 
4240   return false;
4241 }
4242 
GatherArgumentsForCall(SourceLocation CallLoc,FunctionDecl * FDecl,const FunctionProtoType * Proto,unsigned FirstParam,ArrayRef<Expr * > Args,SmallVectorImpl<Expr * > & AllArgs,VariadicCallType CallType,bool AllowExplicit,bool IsListInitialization)4243 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4244                                   const FunctionProtoType *Proto,
4245                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4246                                   SmallVectorImpl<Expr *> &AllArgs,
4247                                   VariadicCallType CallType, bool AllowExplicit,
4248                                   bool IsListInitialization) {
4249   unsigned NumParams = Proto->getNumParams();
4250   bool Invalid = false;
4251   unsigned ArgIx = 0;
4252   // Continue to check argument types (even if we have too few/many args).
4253   for (unsigned i = FirstParam; i < NumParams; i++) {
4254     QualType ProtoArgType = Proto->getParamType(i);
4255 
4256     Expr *Arg;
4257     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4258     if (ArgIx < Args.size()) {
4259       Arg = Args[ArgIx++];
4260 
4261       if (RequireCompleteType(Arg->getLocStart(),
4262                               ProtoArgType,
4263                               diag::err_call_incomplete_argument, Arg))
4264         return true;
4265 
4266       // Strip the unbridged-cast placeholder expression off, if applicable.
4267       bool CFAudited = false;
4268       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4269           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4270           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4271         Arg = stripARCUnbridgedCast(Arg);
4272       else if (getLangOpts().ObjCAutoRefCount &&
4273                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4274                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4275         CFAudited = true;
4276 
4277       InitializedEntity Entity =
4278           Param ? InitializedEntity::InitializeParameter(Context, Param,
4279                                                          ProtoArgType)
4280                 : InitializedEntity::InitializeParameter(
4281                       Context, ProtoArgType, Proto->isParamConsumed(i));
4282 
4283       // Remember that parameter belongs to a CF audited API.
4284       if (CFAudited)
4285         Entity.setParameterCFAudited();
4286 
4287       ExprResult ArgE = PerformCopyInitialization(
4288           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4289       if (ArgE.isInvalid())
4290         return true;
4291 
4292       Arg = ArgE.getAs<Expr>();
4293     } else {
4294       assert(Param && "can't use default arguments without a known callee");
4295 
4296       ExprResult ArgExpr =
4297         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4298       if (ArgExpr.isInvalid())
4299         return true;
4300 
4301       Arg = ArgExpr.getAs<Expr>();
4302     }
4303 
4304     // Check for array bounds violations for each argument to the call. This
4305     // check only triggers warnings when the argument isn't a more complex Expr
4306     // with its own checking, such as a BinaryOperator.
4307     CheckArrayAccess(Arg);
4308 
4309     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4310     CheckStaticArrayArgument(CallLoc, Param, Arg);
4311 
4312     AllArgs.push_back(Arg);
4313   }
4314 
4315   // If this is a variadic call, handle args passed through "...".
4316   if (CallType != VariadicDoesNotApply) {
4317     // Assume that extern "C" functions with variadic arguments that
4318     // return __unknown_anytype aren't *really* variadic.
4319     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4320         FDecl->isExternC()) {
4321       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4322         QualType paramType; // ignored
4323         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4324         Invalid |= arg.isInvalid();
4325         AllArgs.push_back(arg.get());
4326       }
4327 
4328     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4329     } else {
4330       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4331         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4332                                                           FDecl);
4333         Invalid |= Arg.isInvalid();
4334         AllArgs.push_back(Arg.get());
4335       }
4336     }
4337 
4338     // Check for array bounds violations.
4339     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4340       CheckArrayAccess(Args[i]);
4341   }
4342   return Invalid;
4343 }
4344 
DiagnoseCalleeStaticArrayParam(Sema & S,ParmVarDecl * PVD)4345 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4346   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4347   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4348     TL = DTL.getOriginalLoc();
4349   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4350     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4351       << ATL.getLocalSourceRange();
4352 }
4353 
4354 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4355 /// array parameter, check that it is non-null, and that if it is formed by
4356 /// array-to-pointer decay, the underlying array is sufficiently large.
4357 ///
4358 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4359 /// array type derivation, then for each call to the function, the value of the
4360 /// corresponding actual argument shall provide access to the first element of
4361 /// an array with at least as many elements as specified by the size expression.
4362 void
CheckStaticArrayArgument(SourceLocation CallLoc,ParmVarDecl * Param,const Expr * ArgExpr)4363 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4364                                ParmVarDecl *Param,
4365                                const Expr *ArgExpr) {
4366   // Static array parameters are not supported in C++.
4367   if (!Param || getLangOpts().CPlusPlus)
4368     return;
4369 
4370   QualType OrigTy = Param->getOriginalType();
4371 
4372   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4373   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4374     return;
4375 
4376   if (ArgExpr->isNullPointerConstant(Context,
4377                                      Expr::NPC_NeverValueDependent)) {
4378     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4379     DiagnoseCalleeStaticArrayParam(*this, Param);
4380     return;
4381   }
4382 
4383   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4384   if (!CAT)
4385     return;
4386 
4387   const ConstantArrayType *ArgCAT =
4388     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4389   if (!ArgCAT)
4390     return;
4391 
4392   if (ArgCAT->getSize().ult(CAT->getSize())) {
4393     Diag(CallLoc, diag::warn_static_array_too_small)
4394       << ArgExpr->getSourceRange()
4395       << (unsigned) ArgCAT->getSize().getZExtValue()
4396       << (unsigned) CAT->getSize().getZExtValue();
4397     DiagnoseCalleeStaticArrayParam(*this, Param);
4398   }
4399 }
4400 
4401 /// Given a function expression of unknown-any type, try to rebuild it
4402 /// to have a function type.
4403 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4404 
4405 /// Is the given type a placeholder that we need to lower out
4406 /// immediately during argument processing?
isPlaceholderToRemoveAsArg(QualType type)4407 static bool isPlaceholderToRemoveAsArg(QualType type) {
4408   // Placeholders are never sugared.
4409   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4410   if (!placeholder) return false;
4411 
4412   switch (placeholder->getKind()) {
4413   // Ignore all the non-placeholder types.
4414 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4415 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4416 #include "clang/AST/BuiltinTypes.def"
4417     return false;
4418 
4419   // We cannot lower out overload sets; they might validly be resolved
4420   // by the call machinery.
4421   case BuiltinType::Overload:
4422     return false;
4423 
4424   // Unbridged casts in ARC can be handled in some call positions and
4425   // should be left in place.
4426   case BuiltinType::ARCUnbridgedCast:
4427     return false;
4428 
4429   // Pseudo-objects should be converted as soon as possible.
4430   case BuiltinType::PseudoObject:
4431     return true;
4432 
4433   // The debugger mode could theoretically but currently does not try
4434   // to resolve unknown-typed arguments based on known parameter types.
4435   case BuiltinType::UnknownAny:
4436     return true;
4437 
4438   // These are always invalid as call arguments and should be reported.
4439   case BuiltinType::BoundMember:
4440   case BuiltinType::BuiltinFn:
4441     return true;
4442   }
4443   llvm_unreachable("bad builtin type kind");
4444 }
4445 
4446 /// Check an argument list for placeholders that we won't try to
4447 /// handle later.
checkArgsForPlaceholders(Sema & S,MultiExprArg args)4448 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4449   // Apply this processing to all the arguments at once instead of
4450   // dying at the first failure.
4451   bool hasInvalid = false;
4452   for (size_t i = 0, e = args.size(); i != e; i++) {
4453     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4454       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4455       if (result.isInvalid()) hasInvalid = true;
4456       else args[i] = result.get();
4457     }
4458   }
4459   return hasInvalid;
4460 }
4461 
4462 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4463 /// This provides the location of the left/right parens and a list of comma
4464 /// locations.
4465 ExprResult
ActOnCallExpr(Scope * S,Expr * Fn,SourceLocation LParenLoc,MultiExprArg ArgExprs,SourceLocation RParenLoc,Expr * ExecConfig,bool IsExecConfig)4466 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4467                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4468                     Expr *ExecConfig, bool IsExecConfig) {
4469   // Since this might be a postfix expression, get rid of ParenListExprs.
4470   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4471   if (Result.isInvalid()) return ExprError();
4472   Fn = Result.get();
4473 
4474   if (checkArgsForPlaceholders(*this, ArgExprs))
4475     return ExprError();
4476 
4477   if (getLangOpts().CPlusPlus) {
4478     // If this is a pseudo-destructor expression, build the call immediately.
4479     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4480       if (!ArgExprs.empty()) {
4481         // Pseudo-destructor calls should not have any arguments.
4482         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4483           << FixItHint::CreateRemoval(
4484                                     SourceRange(ArgExprs[0]->getLocStart(),
4485                                                 ArgExprs.back()->getLocEnd()));
4486       }
4487 
4488       return new (Context)
4489           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4490     }
4491     if (Fn->getType() == Context.PseudoObjectTy) {
4492       ExprResult result = CheckPlaceholderExpr(Fn);
4493       if (result.isInvalid()) return ExprError();
4494       Fn = result.get();
4495     }
4496 
4497     // Determine whether this is a dependent call inside a C++ template,
4498     // in which case we won't do any semantic analysis now.
4499     // FIXME: Will need to cache the results of name lookup (including ADL) in
4500     // Fn.
4501     bool Dependent = false;
4502     if (Fn->isTypeDependent())
4503       Dependent = true;
4504     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4505       Dependent = true;
4506 
4507     if (Dependent) {
4508       if (ExecConfig) {
4509         return new (Context) CUDAKernelCallExpr(
4510             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4511             Context.DependentTy, VK_RValue, RParenLoc);
4512       } else {
4513         return new (Context) CallExpr(
4514             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4515       }
4516     }
4517 
4518     // Determine whether this is a call to an object (C++ [over.call.object]).
4519     if (Fn->getType()->isRecordType())
4520       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4521                                           RParenLoc);
4522 
4523     if (Fn->getType() == Context.UnknownAnyTy) {
4524       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4525       if (result.isInvalid()) return ExprError();
4526       Fn = result.get();
4527     }
4528 
4529     if (Fn->getType() == Context.BoundMemberTy) {
4530       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4531     }
4532   }
4533 
4534   // Check for overloaded calls.  This can happen even in C due to extensions.
4535   if (Fn->getType() == Context.OverloadTy) {
4536     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4537 
4538     // We aren't supposed to apply this logic for if there's an '&' involved.
4539     if (!find.HasFormOfMemberPointer) {
4540       OverloadExpr *ovl = find.Expression;
4541       if (isa<UnresolvedLookupExpr>(ovl)) {
4542         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4543         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4544                                        RParenLoc, ExecConfig);
4545       } else {
4546         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4547                                          RParenLoc);
4548       }
4549     }
4550   }
4551 
4552   // If we're directly calling a function, get the appropriate declaration.
4553   if (Fn->getType() == Context.UnknownAnyTy) {
4554     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4555     if (result.isInvalid()) return ExprError();
4556     Fn = result.get();
4557   }
4558 
4559   Expr *NakedFn = Fn->IgnoreParens();
4560 
4561   NamedDecl *NDecl = nullptr;
4562   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4563     if (UnOp->getOpcode() == UO_AddrOf)
4564       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4565 
4566   if (isa<DeclRefExpr>(NakedFn))
4567     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4568   else if (isa<MemberExpr>(NakedFn))
4569     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4570 
4571   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4572     if (FD->hasAttr<EnableIfAttr>()) {
4573       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4574         Diag(Fn->getLocStart(),
4575              isa<CXXMethodDecl>(FD) ?
4576                  diag::err_ovl_no_viable_member_function_in_call :
4577                  diag::err_ovl_no_viable_function_in_call)
4578           << FD << FD->getSourceRange();
4579         Diag(FD->getLocation(),
4580              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4581             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4582       }
4583     }
4584   }
4585 
4586   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4587                                ExecConfig, IsExecConfig);
4588 }
4589 
4590 ExprResult
ActOnCUDAExecConfigExpr(Scope * S,SourceLocation LLLLoc,MultiExprArg ExecConfig,SourceLocation GGGLoc)4591 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4592                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4593   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4594   if (!ConfigDecl)
4595     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4596                           << "cudaConfigureCall");
4597   QualType ConfigQTy = ConfigDecl->getType();
4598 
4599   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4600       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4601   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4602 
4603   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
4604                        /*IsExecConfig=*/true);
4605 }
4606 
4607 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4608 ///
4609 /// __builtin_astype( value, dst type )
4610 ///
ActOnAsTypeExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)4611 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4612                                  SourceLocation BuiltinLoc,
4613                                  SourceLocation RParenLoc) {
4614   ExprValueKind VK = VK_RValue;
4615   ExprObjectKind OK = OK_Ordinary;
4616   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4617   QualType SrcTy = E->getType();
4618   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4619     return ExprError(Diag(BuiltinLoc,
4620                           diag::err_invalid_astype_of_different_size)
4621                      << DstTy
4622                      << SrcTy
4623                      << E->getSourceRange());
4624   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4625 }
4626 
4627 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4628 /// provided arguments.
4629 ///
4630 /// __builtin_convertvector( value, dst type )
4631 ///
ActOnConvertVectorExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)4632 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4633                                         SourceLocation BuiltinLoc,
4634                                         SourceLocation RParenLoc) {
4635   TypeSourceInfo *TInfo;
4636   GetTypeFromParser(ParsedDestTy, &TInfo);
4637   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4638 }
4639 
4640 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4641 /// i.e. an expression not of \p OverloadTy.  The expression should
4642 /// unary-convert to an expression of function-pointer or
4643 /// block-pointer type.
4644 ///
4645 /// \param NDecl the declaration being called, if available
4646 ExprResult
BuildResolvedCallExpr(Expr * Fn,NamedDecl * NDecl,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc,Expr * Config,bool IsExecConfig)4647 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4648                             SourceLocation LParenLoc,
4649                             ArrayRef<Expr *> Args,
4650                             SourceLocation RParenLoc,
4651                             Expr *Config, bool IsExecConfig) {
4652   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4653   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4654 
4655   // Promote the function operand.
4656   // We special-case function promotion here because we only allow promoting
4657   // builtin functions to function pointers in the callee of a call.
4658   ExprResult Result;
4659   if (BuiltinID &&
4660       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4661     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4662                                CK_BuiltinFnToFnPtr).get();
4663   } else {
4664     Result = CallExprUnaryConversions(Fn);
4665   }
4666   if (Result.isInvalid())
4667     return ExprError();
4668   Fn = Result.get();
4669 
4670   // Make the call expr early, before semantic checks.  This guarantees cleanup
4671   // of arguments and function on error.
4672   CallExpr *TheCall;
4673   if (Config)
4674     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4675                                                cast<CallExpr>(Config), Args,
4676                                                Context.BoolTy, VK_RValue,
4677                                                RParenLoc);
4678   else
4679     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4680                                      VK_RValue, RParenLoc);
4681 
4682   // Bail out early if calling a builtin with custom typechecking.
4683   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4684     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4685 
4686  retry:
4687   const FunctionType *FuncT;
4688   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4689     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4690     // have type pointer to function".
4691     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4692     if (!FuncT)
4693       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4694                          << Fn->getType() << Fn->getSourceRange());
4695   } else if (const BlockPointerType *BPT =
4696                Fn->getType()->getAs<BlockPointerType>()) {
4697     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4698   } else {
4699     // Handle calls to expressions of unknown-any type.
4700     if (Fn->getType() == Context.UnknownAnyTy) {
4701       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4702       if (rewrite.isInvalid()) return ExprError();
4703       Fn = rewrite.get();
4704       TheCall->setCallee(Fn);
4705       goto retry;
4706     }
4707 
4708     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4709       << Fn->getType() << Fn->getSourceRange());
4710   }
4711 
4712   if (getLangOpts().CUDA) {
4713     if (Config) {
4714       // CUDA: Kernel calls must be to global functions
4715       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4716         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4717             << FDecl->getName() << Fn->getSourceRange());
4718 
4719       // CUDA: Kernel function must have 'void' return type
4720       if (!FuncT->getReturnType()->isVoidType())
4721         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4722             << Fn->getType() << Fn->getSourceRange());
4723     } else {
4724       // CUDA: Calls to global functions must be configured
4725       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4726         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4727             << FDecl->getName() << Fn->getSourceRange());
4728     }
4729   }
4730 
4731   // Check for a valid return type
4732   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4733                           FDecl))
4734     return ExprError();
4735 
4736   // We know the result type of the call, set it.
4737   TheCall->setType(FuncT->getCallResultType(Context));
4738   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4739 
4740   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4741   if (Proto) {
4742     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4743                                 IsExecConfig))
4744       return ExprError();
4745   } else {
4746     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4747 
4748     if (FDecl) {
4749       // Check if we have too few/too many template arguments, based
4750       // on our knowledge of the function definition.
4751       const FunctionDecl *Def = nullptr;
4752       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4753         Proto = Def->getType()->getAs<FunctionProtoType>();
4754        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4755           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4756           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4757       }
4758 
4759       // If the function we're calling isn't a function prototype, but we have
4760       // a function prototype from a prior declaratiom, use that prototype.
4761       if (!FDecl->hasPrototype())
4762         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4763     }
4764 
4765     // Promote the arguments (C99 6.5.2.2p6).
4766     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4767       Expr *Arg = Args[i];
4768 
4769       if (Proto && i < Proto->getNumParams()) {
4770         InitializedEntity Entity = InitializedEntity::InitializeParameter(
4771             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
4772         ExprResult ArgE =
4773             PerformCopyInitialization(Entity, SourceLocation(), Arg);
4774         if (ArgE.isInvalid())
4775           return true;
4776 
4777         Arg = ArgE.getAs<Expr>();
4778 
4779       } else {
4780         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4781 
4782         if (ArgE.isInvalid())
4783           return true;
4784 
4785         Arg = ArgE.getAs<Expr>();
4786       }
4787 
4788       if (RequireCompleteType(Arg->getLocStart(),
4789                               Arg->getType(),
4790                               diag::err_call_incomplete_argument, Arg))
4791         return ExprError();
4792 
4793       TheCall->setArg(i, Arg);
4794     }
4795   }
4796 
4797   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4798     if (!Method->isStatic())
4799       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4800         << Fn->getSourceRange());
4801 
4802   // Check for sentinels
4803   if (NDecl)
4804     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4805 
4806   // Do special checking on direct calls to functions.
4807   if (FDecl) {
4808     if (CheckFunctionCall(FDecl, TheCall, Proto))
4809       return ExprError();
4810 
4811     if (BuiltinID)
4812       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4813   } else if (NDecl) {
4814     if (CheckPointerCall(NDecl, TheCall, Proto))
4815       return ExprError();
4816   } else {
4817     if (CheckOtherCall(TheCall, Proto))
4818       return ExprError();
4819   }
4820 
4821   return MaybeBindToTemporary(TheCall);
4822 }
4823 
4824 ExprResult
ActOnCompoundLiteral(SourceLocation LParenLoc,ParsedType Ty,SourceLocation RParenLoc,Expr * InitExpr)4825 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4826                            SourceLocation RParenLoc, Expr *InitExpr) {
4827   assert(Ty && "ActOnCompoundLiteral(): missing type");
4828   // FIXME: put back this assert when initializers are worked out.
4829   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4830 
4831   TypeSourceInfo *TInfo;
4832   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4833   if (!TInfo)
4834     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4835 
4836   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4837 }
4838 
4839 ExprResult
BuildCompoundLiteralExpr(SourceLocation LParenLoc,TypeSourceInfo * TInfo,SourceLocation RParenLoc,Expr * LiteralExpr)4840 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4841                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4842   QualType literalType = TInfo->getType();
4843 
4844   if (literalType->isArrayType()) {
4845     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4846           diag::err_illegal_decl_array_incomplete_type,
4847           SourceRange(LParenLoc,
4848                       LiteralExpr->getSourceRange().getEnd())))
4849       return ExprError();
4850     if (literalType->isVariableArrayType())
4851       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4852         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4853   } else if (!literalType->isDependentType() &&
4854              RequireCompleteType(LParenLoc, literalType,
4855                diag::err_typecheck_decl_incomplete_type,
4856                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4857     return ExprError();
4858 
4859   InitializedEntity Entity
4860     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4861   InitializationKind Kind
4862     = InitializationKind::CreateCStyleCast(LParenLoc,
4863                                            SourceRange(LParenLoc, RParenLoc),
4864                                            /*InitList=*/true);
4865   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4866   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4867                                       &literalType);
4868   if (Result.isInvalid())
4869     return ExprError();
4870   LiteralExpr = Result.get();
4871 
4872   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
4873   if (isFileScope &&
4874       !LiteralExpr->isTypeDependent() &&
4875       !LiteralExpr->isValueDependent() &&
4876       !literalType->isDependentType()) { // 6.5.2.5p3
4877     if (CheckForConstantInitializer(LiteralExpr, literalType))
4878       return ExprError();
4879   }
4880 
4881   // In C, compound literals are l-values for some reason.
4882   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4883 
4884   return MaybeBindToTemporary(
4885            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4886                                              VK, LiteralExpr, isFileScope));
4887 }
4888 
4889 ExprResult
ActOnInitList(SourceLocation LBraceLoc,MultiExprArg InitArgList,SourceLocation RBraceLoc)4890 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4891                     SourceLocation RBraceLoc) {
4892   // Immediately handle non-overload placeholders.  Overloads can be
4893   // resolved contextually, but everything else here can't.
4894   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4895     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4896       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4897 
4898       // Ignore failures; dropping the entire initializer list because
4899       // of one failure would be terrible for indexing/etc.
4900       if (result.isInvalid()) continue;
4901 
4902       InitArgList[I] = result.get();
4903     }
4904   }
4905 
4906   // Semantic analysis for initializers is done by ActOnDeclarator() and
4907   // CheckInitializer() - it requires knowledge of the object being intialized.
4908 
4909   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4910                                                RBraceLoc);
4911   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4912   return E;
4913 }
4914 
4915 /// Do an explicit extend of the given block pointer if we're in ARC.
maybeExtendBlockObject(Sema & S,ExprResult & E)4916 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4917   assert(E.get()->getType()->isBlockPointerType());
4918   assert(E.get()->isRValue());
4919 
4920   // Only do this in an r-value context.
4921   if (!S.getLangOpts().ObjCAutoRefCount) return;
4922 
4923   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4924                                CK_ARCExtendBlockObject, E.get(),
4925                                /*base path*/ nullptr, VK_RValue);
4926   S.ExprNeedsCleanups = true;
4927 }
4928 
4929 /// Prepare a conversion of the given expression to an ObjC object
4930 /// pointer type.
PrepareCastToObjCObjectPointer(ExprResult & E)4931 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4932   QualType type = E.get()->getType();
4933   if (type->isObjCObjectPointerType()) {
4934     return CK_BitCast;
4935   } else if (type->isBlockPointerType()) {
4936     maybeExtendBlockObject(*this, E);
4937     return CK_BlockPointerToObjCPointerCast;
4938   } else {
4939     assert(type->isPointerType());
4940     return CK_CPointerToObjCPointerCast;
4941   }
4942 }
4943 
4944 /// Prepares for a scalar cast, performing all the necessary stages
4945 /// except the final cast and returning the kind required.
PrepareScalarCast(ExprResult & Src,QualType DestTy)4946 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4947   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4948   // Also, callers should have filtered out the invalid cases with
4949   // pointers.  Everything else should be possible.
4950 
4951   QualType SrcTy = Src.get()->getType();
4952   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4953     return CK_NoOp;
4954 
4955   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4956   case Type::STK_MemberPointer:
4957     llvm_unreachable("member pointer type in C");
4958 
4959   case Type::STK_CPointer:
4960   case Type::STK_BlockPointer:
4961   case Type::STK_ObjCObjectPointer:
4962     switch (DestTy->getScalarTypeKind()) {
4963     case Type::STK_CPointer: {
4964       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
4965       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
4966       if (SrcAS != DestAS)
4967         return CK_AddressSpaceConversion;
4968       return CK_BitCast;
4969     }
4970     case Type::STK_BlockPointer:
4971       return (SrcKind == Type::STK_BlockPointer
4972                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4973     case Type::STK_ObjCObjectPointer:
4974       if (SrcKind == Type::STK_ObjCObjectPointer)
4975         return CK_BitCast;
4976       if (SrcKind == Type::STK_CPointer)
4977         return CK_CPointerToObjCPointerCast;
4978       maybeExtendBlockObject(*this, Src);
4979       return CK_BlockPointerToObjCPointerCast;
4980     case Type::STK_Bool:
4981       return CK_PointerToBoolean;
4982     case Type::STK_Integral:
4983       return CK_PointerToIntegral;
4984     case Type::STK_Floating:
4985     case Type::STK_FloatingComplex:
4986     case Type::STK_IntegralComplex:
4987     case Type::STK_MemberPointer:
4988       llvm_unreachable("illegal cast from pointer");
4989     }
4990     llvm_unreachable("Should have returned before this");
4991 
4992   case Type::STK_Bool: // casting from bool is like casting from an integer
4993   case Type::STK_Integral:
4994     switch (DestTy->getScalarTypeKind()) {
4995     case Type::STK_CPointer:
4996     case Type::STK_ObjCObjectPointer:
4997     case Type::STK_BlockPointer:
4998       if (Src.get()->isNullPointerConstant(Context,
4999                                            Expr::NPC_ValueDependentIsNull))
5000         return CK_NullToPointer;
5001       return CK_IntegralToPointer;
5002     case Type::STK_Bool:
5003       return CK_IntegralToBoolean;
5004     case Type::STK_Integral:
5005       return CK_IntegralCast;
5006     case Type::STK_Floating:
5007       return CK_IntegralToFloating;
5008     case Type::STK_IntegralComplex:
5009       Src = ImpCastExprToType(Src.get(),
5010                               DestTy->castAs<ComplexType>()->getElementType(),
5011                               CK_IntegralCast);
5012       return CK_IntegralRealToComplex;
5013     case Type::STK_FloatingComplex:
5014       Src = ImpCastExprToType(Src.get(),
5015                               DestTy->castAs<ComplexType>()->getElementType(),
5016                               CK_IntegralToFloating);
5017       return CK_FloatingRealToComplex;
5018     case Type::STK_MemberPointer:
5019       llvm_unreachable("member pointer type in C");
5020     }
5021     llvm_unreachable("Should have returned before this");
5022 
5023   case Type::STK_Floating:
5024     switch (DestTy->getScalarTypeKind()) {
5025     case Type::STK_Floating:
5026       return CK_FloatingCast;
5027     case Type::STK_Bool:
5028       return CK_FloatingToBoolean;
5029     case Type::STK_Integral:
5030       return CK_FloatingToIntegral;
5031     case Type::STK_FloatingComplex:
5032       Src = ImpCastExprToType(Src.get(),
5033                               DestTy->castAs<ComplexType>()->getElementType(),
5034                               CK_FloatingCast);
5035       return CK_FloatingRealToComplex;
5036     case Type::STK_IntegralComplex:
5037       Src = ImpCastExprToType(Src.get(),
5038                               DestTy->castAs<ComplexType>()->getElementType(),
5039                               CK_FloatingToIntegral);
5040       return CK_IntegralRealToComplex;
5041     case Type::STK_CPointer:
5042     case Type::STK_ObjCObjectPointer:
5043     case Type::STK_BlockPointer:
5044       llvm_unreachable("valid float->pointer cast?");
5045     case Type::STK_MemberPointer:
5046       llvm_unreachable("member pointer type in C");
5047     }
5048     llvm_unreachable("Should have returned before this");
5049 
5050   case Type::STK_FloatingComplex:
5051     switch (DestTy->getScalarTypeKind()) {
5052     case Type::STK_FloatingComplex:
5053       return CK_FloatingComplexCast;
5054     case Type::STK_IntegralComplex:
5055       return CK_FloatingComplexToIntegralComplex;
5056     case Type::STK_Floating: {
5057       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5058       if (Context.hasSameType(ET, DestTy))
5059         return CK_FloatingComplexToReal;
5060       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5061       return CK_FloatingCast;
5062     }
5063     case Type::STK_Bool:
5064       return CK_FloatingComplexToBoolean;
5065     case Type::STK_Integral:
5066       Src = ImpCastExprToType(Src.get(),
5067                               SrcTy->castAs<ComplexType>()->getElementType(),
5068                               CK_FloatingComplexToReal);
5069       return CK_FloatingToIntegral;
5070     case Type::STK_CPointer:
5071     case Type::STK_ObjCObjectPointer:
5072     case Type::STK_BlockPointer:
5073       llvm_unreachable("valid complex float->pointer cast?");
5074     case Type::STK_MemberPointer:
5075       llvm_unreachable("member pointer type in C");
5076     }
5077     llvm_unreachable("Should have returned before this");
5078 
5079   case Type::STK_IntegralComplex:
5080     switch (DestTy->getScalarTypeKind()) {
5081     case Type::STK_FloatingComplex:
5082       return CK_IntegralComplexToFloatingComplex;
5083     case Type::STK_IntegralComplex:
5084       return CK_IntegralComplexCast;
5085     case Type::STK_Integral: {
5086       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5087       if (Context.hasSameType(ET, DestTy))
5088         return CK_IntegralComplexToReal;
5089       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5090       return CK_IntegralCast;
5091     }
5092     case Type::STK_Bool:
5093       return CK_IntegralComplexToBoolean;
5094     case Type::STK_Floating:
5095       Src = ImpCastExprToType(Src.get(),
5096                               SrcTy->castAs<ComplexType>()->getElementType(),
5097                               CK_IntegralComplexToReal);
5098       return CK_IntegralToFloating;
5099     case Type::STK_CPointer:
5100     case Type::STK_ObjCObjectPointer:
5101     case Type::STK_BlockPointer:
5102       llvm_unreachable("valid complex int->pointer cast?");
5103     case Type::STK_MemberPointer:
5104       llvm_unreachable("member pointer type in C");
5105     }
5106     llvm_unreachable("Should have returned before this");
5107   }
5108 
5109   llvm_unreachable("Unhandled scalar cast");
5110 }
5111 
breakDownVectorType(QualType type,uint64_t & len,QualType & eltType)5112 static bool breakDownVectorType(QualType type, uint64_t &len,
5113                                 QualType &eltType) {
5114   // Vectors are simple.
5115   if (const VectorType *vecType = type->getAs<VectorType>()) {
5116     len = vecType->getNumElements();
5117     eltType = vecType->getElementType();
5118     assert(eltType->isScalarType());
5119     return true;
5120   }
5121 
5122   // We allow lax conversion to and from non-vector types, but only if
5123   // they're real types (i.e. non-complex, non-pointer scalar types).
5124   if (!type->isRealType()) return false;
5125 
5126   len = 1;
5127   eltType = type;
5128   return true;
5129 }
5130 
VectorTypesMatch(Sema & S,QualType srcTy,QualType destTy)5131 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5132   uint64_t srcLen, destLen;
5133   QualType srcElt, destElt;
5134   if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5135   if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5136 
5137   // ASTContext::getTypeSize will return the size rounded up to a
5138   // power of 2, so instead of using that, we need to use the raw
5139   // element size multiplied by the element count.
5140   uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5141   uint64_t destEltSize = S.Context.getTypeSize(destElt);
5142 
5143   return (srcLen * srcEltSize == destLen * destEltSize);
5144 }
5145 
5146 /// Is this a legal conversion between two known vector types?
isLaxVectorConversion(QualType srcTy,QualType destTy)5147 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5148   assert(destTy->isVectorType() || srcTy->isVectorType());
5149 
5150   if (!Context.getLangOpts().LaxVectorConversions)
5151     return false;
5152   return VectorTypesMatch(*this, srcTy, destTy);
5153 }
5154 
CheckVectorCast(SourceRange R,QualType VectorTy,QualType Ty,CastKind & Kind)5155 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5156                            CastKind &Kind) {
5157   assert(VectorTy->isVectorType() && "Not a vector type!");
5158 
5159   if (Ty->isVectorType() || Ty->isIntegerType()) {
5160     if (!VectorTypesMatch(*this, Ty, VectorTy))
5161       return Diag(R.getBegin(),
5162                   Ty->isVectorType() ?
5163                   diag::err_invalid_conversion_between_vectors :
5164                   diag::err_invalid_conversion_between_vector_and_integer)
5165         << VectorTy << Ty << R;
5166   } else
5167     return Diag(R.getBegin(),
5168                 diag::err_invalid_conversion_between_vector_and_scalar)
5169       << VectorTy << Ty << R;
5170 
5171   Kind = CK_BitCast;
5172   return false;
5173 }
5174 
CheckExtVectorCast(SourceRange R,QualType DestTy,Expr * CastExpr,CastKind & Kind)5175 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5176                                     Expr *CastExpr, CastKind &Kind) {
5177   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5178 
5179   QualType SrcTy = CastExpr->getType();
5180 
5181   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5182   // an ExtVectorType.
5183   // In OpenCL, casts between vectors of different types are not allowed.
5184   // (See OpenCL 6.2).
5185   if (SrcTy->isVectorType()) {
5186     if (!VectorTypesMatch(*this, SrcTy, DestTy)
5187         || (getLangOpts().OpenCL &&
5188             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5189       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5190         << DestTy << SrcTy << R;
5191       return ExprError();
5192     }
5193     Kind = CK_BitCast;
5194     return CastExpr;
5195   }
5196 
5197   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5198   // conversion will take place first from scalar to elt type, and then
5199   // splat from elt type to vector.
5200   if (SrcTy->isPointerType())
5201     return Diag(R.getBegin(),
5202                 diag::err_invalid_conversion_between_vector_and_scalar)
5203       << DestTy << SrcTy << R;
5204 
5205   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5206   ExprResult CastExprRes = CastExpr;
5207   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5208   if (CastExprRes.isInvalid())
5209     return ExprError();
5210   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5211 
5212   Kind = CK_VectorSplat;
5213   return CastExpr;
5214 }
5215 
5216 ExprResult
ActOnCastExpr(Scope * S,SourceLocation LParenLoc,Declarator & D,ParsedType & Ty,SourceLocation RParenLoc,Expr * CastExpr)5217 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5218                     Declarator &D, ParsedType &Ty,
5219                     SourceLocation RParenLoc, Expr *CastExpr) {
5220   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5221          "ActOnCastExpr(): missing type or expr");
5222 
5223   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5224   if (D.isInvalidType())
5225     return ExprError();
5226 
5227   if (getLangOpts().CPlusPlus) {
5228     // Check that there are no default arguments (C++ only).
5229     CheckExtraCXXDefaultArguments(D);
5230   }
5231 
5232   checkUnusedDeclAttributes(D);
5233 
5234   QualType castType = castTInfo->getType();
5235   Ty = CreateParsedType(castType, castTInfo);
5236 
5237   bool isVectorLiteral = false;
5238 
5239   // Check for an altivec or OpenCL literal,
5240   // i.e. all the elements are integer constants.
5241   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5242   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5243   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5244        && castType->isVectorType() && (PE || PLE)) {
5245     if (PLE && PLE->getNumExprs() == 0) {
5246       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5247       return ExprError();
5248     }
5249     if (PE || PLE->getNumExprs() == 1) {
5250       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5251       if (!E->getType()->isVectorType())
5252         isVectorLiteral = true;
5253     }
5254     else
5255       isVectorLiteral = true;
5256   }
5257 
5258   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5259   // then handle it as such.
5260   if (isVectorLiteral)
5261     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5262 
5263   // If the Expr being casted is a ParenListExpr, handle it specially.
5264   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5265   // sequence of BinOp comma operators.
5266   if (isa<ParenListExpr>(CastExpr)) {
5267     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5268     if (Result.isInvalid()) return ExprError();
5269     CastExpr = Result.get();
5270   }
5271 
5272   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5273       !getSourceManager().isInSystemMacro(LParenLoc))
5274     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5275 
5276   CheckTollFreeBridgeCast(castType, CastExpr);
5277 
5278   CheckObjCBridgeRelatedCast(castType, CastExpr);
5279 
5280   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5281 }
5282 
BuildVectorLiteral(SourceLocation LParenLoc,SourceLocation RParenLoc,Expr * E,TypeSourceInfo * TInfo)5283 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5284                                     SourceLocation RParenLoc, Expr *E,
5285                                     TypeSourceInfo *TInfo) {
5286   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5287          "Expected paren or paren list expression");
5288 
5289   Expr **exprs;
5290   unsigned numExprs;
5291   Expr *subExpr;
5292   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5293   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5294     LiteralLParenLoc = PE->getLParenLoc();
5295     LiteralRParenLoc = PE->getRParenLoc();
5296     exprs = PE->getExprs();
5297     numExprs = PE->getNumExprs();
5298   } else { // isa<ParenExpr> by assertion at function entrance
5299     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5300     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5301     subExpr = cast<ParenExpr>(E)->getSubExpr();
5302     exprs = &subExpr;
5303     numExprs = 1;
5304   }
5305 
5306   QualType Ty = TInfo->getType();
5307   assert(Ty->isVectorType() && "Expected vector type");
5308 
5309   SmallVector<Expr *, 8> initExprs;
5310   const VectorType *VTy = Ty->getAs<VectorType>();
5311   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5312 
5313   // '(...)' form of vector initialization in AltiVec: the number of
5314   // initializers must be one or must match the size of the vector.
5315   // If a single value is specified in the initializer then it will be
5316   // replicated to all the components of the vector
5317   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5318     // The number of initializers must be one or must match the size of the
5319     // vector. If a single value is specified in the initializer then it will
5320     // be replicated to all the components of the vector
5321     if (numExprs == 1) {
5322       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5323       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5324       if (Literal.isInvalid())
5325         return ExprError();
5326       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5327                                   PrepareScalarCast(Literal, ElemTy));
5328       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5329     }
5330     else if (numExprs < numElems) {
5331       Diag(E->getExprLoc(),
5332            diag::err_incorrect_number_of_vector_initializers);
5333       return ExprError();
5334     }
5335     else
5336       initExprs.append(exprs, exprs + numExprs);
5337   }
5338   else {
5339     // For OpenCL, when the number of initializers is a single value,
5340     // it will be replicated to all components of the vector.
5341     if (getLangOpts().OpenCL &&
5342         VTy->getVectorKind() == VectorType::GenericVector &&
5343         numExprs == 1) {
5344         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5345         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5346         if (Literal.isInvalid())
5347           return ExprError();
5348         Literal = ImpCastExprToType(Literal.get(), ElemTy,
5349                                     PrepareScalarCast(Literal, ElemTy));
5350         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5351     }
5352 
5353     initExprs.append(exprs, exprs + numExprs);
5354   }
5355   // FIXME: This means that pretty-printing the final AST will produce curly
5356   // braces instead of the original commas.
5357   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5358                                                    initExprs, LiteralRParenLoc);
5359   initE->setType(Ty);
5360   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5361 }
5362 
5363 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5364 /// the ParenListExpr into a sequence of comma binary operators.
5365 ExprResult
MaybeConvertParenListExprToParenExpr(Scope * S,Expr * OrigExpr)5366 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5367   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5368   if (!E)
5369     return OrigExpr;
5370 
5371   ExprResult Result(E->getExpr(0));
5372 
5373   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5374     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5375                         E->getExpr(i));
5376 
5377   if (Result.isInvalid()) return ExprError();
5378 
5379   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5380 }
5381 
ActOnParenListExpr(SourceLocation L,SourceLocation R,MultiExprArg Val)5382 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5383                                     SourceLocation R,
5384                                     MultiExprArg Val) {
5385   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5386   return expr;
5387 }
5388 
5389 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5390 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5391 /// emitted.
DiagnoseConditionalForNull(Expr * LHSExpr,Expr * RHSExpr,SourceLocation QuestionLoc)5392 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5393                                       SourceLocation QuestionLoc) {
5394   Expr *NullExpr = LHSExpr;
5395   Expr *NonPointerExpr = RHSExpr;
5396   Expr::NullPointerConstantKind NullKind =
5397       NullExpr->isNullPointerConstant(Context,
5398                                       Expr::NPC_ValueDependentIsNotNull);
5399 
5400   if (NullKind == Expr::NPCK_NotNull) {
5401     NullExpr = RHSExpr;
5402     NonPointerExpr = LHSExpr;
5403     NullKind =
5404         NullExpr->isNullPointerConstant(Context,
5405                                         Expr::NPC_ValueDependentIsNotNull);
5406   }
5407 
5408   if (NullKind == Expr::NPCK_NotNull)
5409     return false;
5410 
5411   if (NullKind == Expr::NPCK_ZeroExpression)
5412     return false;
5413 
5414   if (NullKind == Expr::NPCK_ZeroLiteral) {
5415     // In this case, check to make sure that we got here from a "NULL"
5416     // string in the source code.
5417     NullExpr = NullExpr->IgnoreParenImpCasts();
5418     SourceLocation loc = NullExpr->getExprLoc();
5419     if (!findMacroSpelling(loc, "NULL"))
5420       return false;
5421   }
5422 
5423   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5424   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5425       << NonPointerExpr->getType() << DiagType
5426       << NonPointerExpr->getSourceRange();
5427   return true;
5428 }
5429 
5430 /// \brief Return false if the condition expression is valid, true otherwise.
checkCondition(Sema & S,Expr * Cond)5431 static bool checkCondition(Sema &S, Expr *Cond) {
5432   QualType CondTy = Cond->getType();
5433 
5434   // C99 6.5.15p2
5435   if (CondTy->isScalarType()) return false;
5436 
5437   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5438   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5439     return false;
5440 
5441   // Emit the proper error message.
5442   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5443                               diag::err_typecheck_cond_expect_scalar :
5444                               diag::err_typecheck_cond_expect_scalar_or_vector)
5445     << CondTy;
5446   return true;
5447 }
5448 
5449 /// \brief Return false if the two expressions can be converted to a vector,
5450 /// true otherwise
checkConditionalConvertScalarsToVectors(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType CondTy)5451 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5452                                                     ExprResult &RHS,
5453                                                     QualType CondTy) {
5454   // Both operands should be of scalar type.
5455   if (!LHS.get()->getType()->isScalarType()) {
5456     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5457       << CondTy;
5458     return true;
5459   }
5460   if (!RHS.get()->getType()->isScalarType()) {
5461     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5462       << CondTy;
5463     return true;
5464   }
5465 
5466   // Implicity convert these scalars to the type of the condition.
5467   LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast);
5468   RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast);
5469   return false;
5470 }
5471 
5472 /// \brief Handle when one or both operands are void type.
checkConditionalVoidType(Sema & S,ExprResult & LHS,ExprResult & RHS)5473 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5474                                          ExprResult &RHS) {
5475     Expr *LHSExpr = LHS.get();
5476     Expr *RHSExpr = RHS.get();
5477 
5478     if (!LHSExpr->getType()->isVoidType())
5479       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5480         << RHSExpr->getSourceRange();
5481     if (!RHSExpr->getType()->isVoidType())
5482       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5483         << LHSExpr->getSourceRange();
5484     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5485     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5486     return S.Context.VoidTy;
5487 }
5488 
5489 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5490 /// true otherwise.
checkConditionalNullPointer(Sema & S,ExprResult & NullExpr,QualType PointerTy)5491 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5492                                         QualType PointerTy) {
5493   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5494       !NullExpr.get()->isNullPointerConstant(S.Context,
5495                                             Expr::NPC_ValueDependentIsNull))
5496     return true;
5497 
5498   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5499   return false;
5500 }
5501 
5502 /// \brief Checks compatibility between two pointers and return the resulting
5503 /// type.
checkConditionalPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)5504 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5505                                                      ExprResult &RHS,
5506                                                      SourceLocation Loc) {
5507   QualType LHSTy = LHS.get()->getType();
5508   QualType RHSTy = RHS.get()->getType();
5509 
5510   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5511     // Two identical pointers types are always compatible.
5512     return LHSTy;
5513   }
5514 
5515   QualType lhptee, rhptee;
5516 
5517   // Get the pointee types.
5518   bool IsBlockPointer = false;
5519   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5520     lhptee = LHSBTy->getPointeeType();
5521     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5522     IsBlockPointer = true;
5523   } else {
5524     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5525     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5526   }
5527 
5528   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5529   // differently qualified versions of compatible types, the result type is
5530   // a pointer to an appropriately qualified version of the composite
5531   // type.
5532 
5533   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5534   // clause doesn't make sense for our extensions. E.g. address space 2 should
5535   // be incompatible with address space 3: they may live on different devices or
5536   // anything.
5537   Qualifiers lhQual = lhptee.getQualifiers();
5538   Qualifiers rhQual = rhptee.getQualifiers();
5539 
5540   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5541   lhQual.removeCVRQualifiers();
5542   rhQual.removeCVRQualifiers();
5543 
5544   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5545   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5546 
5547   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5548 
5549   if (CompositeTy.isNull()) {
5550     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5551       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5552       << RHS.get()->getSourceRange();
5553     // In this situation, we assume void* type. No especially good
5554     // reason, but this is what gcc does, and we do have to pick
5555     // to get a consistent AST.
5556     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5557     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5558     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5559     return incompatTy;
5560   }
5561 
5562   // The pointer types are compatible.
5563   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5564   if (IsBlockPointer)
5565     ResultTy = S.Context.getBlockPointerType(ResultTy);
5566   else
5567     ResultTy = S.Context.getPointerType(ResultTy);
5568 
5569   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5570   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5571   return ResultTy;
5572 }
5573 
5574 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
5575 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
5576 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
isObjCPtrBlockCompatible(Sema & S,ASTContext & C,QualType QT)5577 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
5578   if (QT->isObjCIdType())
5579     return true;
5580 
5581   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
5582   if (!OPT)
5583     return false;
5584 
5585   if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
5586     if (ID->getIdentifier() != &C.Idents.get("NSObject"))
5587       return false;
5588 
5589   ObjCProtocolDecl* PNSCopying =
5590     S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
5591   ObjCProtocolDecl* PNSObject =
5592     S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
5593 
5594   for (auto *Proto : OPT->quals()) {
5595     if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
5596         (PNSObject && declaresSameEntity(Proto, PNSObject)))
5597       ;
5598     else
5599       return false;
5600   }
5601   return true;
5602 }
5603 
5604 /// \brief Return the resulting type when the operands are both block pointers.
checkConditionalBlockPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)5605 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5606                                                           ExprResult &LHS,
5607                                                           ExprResult &RHS,
5608                                                           SourceLocation Loc) {
5609   QualType LHSTy = LHS.get()->getType();
5610   QualType RHSTy = RHS.get()->getType();
5611 
5612   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5613     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5614       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5615       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5616       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5617       return destType;
5618     }
5619     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5620       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5621       << RHS.get()->getSourceRange();
5622     return QualType();
5623   }
5624 
5625   // We have 2 block pointer types.
5626   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5627 }
5628 
5629 /// \brief Return the resulting type when the operands are both pointers.
5630 static QualType
checkConditionalObjectPointersCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)5631 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5632                                             ExprResult &RHS,
5633                                             SourceLocation Loc) {
5634   // get the pointer types
5635   QualType LHSTy = LHS.get()->getType();
5636   QualType RHSTy = RHS.get()->getType();
5637 
5638   // get the "pointed to" types
5639   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5640   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5641 
5642   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5643   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5644     // Figure out necessary qualifiers (C99 6.5.15p6)
5645     QualType destPointee
5646       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5647     QualType destType = S.Context.getPointerType(destPointee);
5648     // Add qualifiers if necessary.
5649     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5650     // Promote to void*.
5651     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5652     return destType;
5653   }
5654   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5655     QualType destPointee
5656       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5657     QualType destType = S.Context.getPointerType(destPointee);
5658     // Add qualifiers if necessary.
5659     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5660     // Promote to void*.
5661     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5662     return destType;
5663   }
5664 
5665   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5666 }
5667 
5668 /// \brief Return false if the first expression is not an integer and the second
5669 /// expression is not a pointer, true otherwise.
checkPointerIntegerMismatch(Sema & S,ExprResult & Int,Expr * PointerExpr,SourceLocation Loc,bool IsIntFirstExpr)5670 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5671                                         Expr* PointerExpr, SourceLocation Loc,
5672                                         bool IsIntFirstExpr) {
5673   if (!PointerExpr->getType()->isPointerType() ||
5674       !Int.get()->getType()->isIntegerType())
5675     return false;
5676 
5677   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5678   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5679 
5680   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5681     << Expr1->getType() << Expr2->getType()
5682     << Expr1->getSourceRange() << Expr2->getSourceRange();
5683   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
5684                             CK_IntegralToPointer);
5685   return true;
5686 }
5687 
5688 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5689 /// In that case, LHS = cond.
5690 /// C99 6.5.15
CheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)5691 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5692                                         ExprResult &RHS, ExprValueKind &VK,
5693                                         ExprObjectKind &OK,
5694                                         SourceLocation QuestionLoc) {
5695 
5696   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5697   if (!LHSResult.isUsable()) return QualType();
5698   LHS = LHSResult;
5699 
5700   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5701   if (!RHSResult.isUsable()) return QualType();
5702   RHS = RHSResult;
5703 
5704   // C++ is sufficiently different to merit its own checker.
5705   if (getLangOpts().CPlusPlus)
5706     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5707 
5708   VK = VK_RValue;
5709   OK = OK_Ordinary;
5710 
5711   // First, check the condition.
5712   Cond = UsualUnaryConversions(Cond.get());
5713   if (Cond.isInvalid())
5714     return QualType();
5715   if (checkCondition(*this, Cond.get()))
5716     return QualType();
5717 
5718   // Now check the two expressions.
5719   if (LHS.get()->getType()->isVectorType() ||
5720       RHS.get()->getType()->isVectorType())
5721     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5722 
5723   UsualArithmeticConversions(LHS, RHS);
5724   if (LHS.isInvalid() || RHS.isInvalid())
5725     return QualType();
5726 
5727   QualType CondTy = Cond.get()->getType();
5728   QualType LHSTy = LHS.get()->getType();
5729   QualType RHSTy = RHS.get()->getType();
5730 
5731   // If the condition is a vector, and both operands are scalar,
5732   // attempt to implicity convert them to the vector type to act like the
5733   // built in select. (OpenCL v1.1 s6.3.i)
5734   if (getLangOpts().OpenCL && CondTy->isVectorType())
5735     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5736       return QualType();
5737 
5738   // If both operands have arithmetic type, do the usual arithmetic conversions
5739   // to find a common type: C99 6.5.15p3,5.
5740   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5741     return LHS.get()->getType();
5742 
5743   // If both operands are the same structure or union type, the result is that
5744   // type.
5745   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5746     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5747       if (LHSRT->getDecl() == RHSRT->getDecl())
5748         // "If both the operands have structure or union type, the result has
5749         // that type."  This implies that CV qualifiers are dropped.
5750         return LHSTy.getUnqualifiedType();
5751     // FIXME: Type of conditional expression must be complete in C mode.
5752   }
5753 
5754   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5755   // The following || allows only one side to be void (a GCC-ism).
5756   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5757     return checkConditionalVoidType(*this, LHS, RHS);
5758   }
5759 
5760   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5761   // the type of the other operand."
5762   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5763   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5764 
5765   // All objective-c pointer type analysis is done here.
5766   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5767                                                         QuestionLoc);
5768   if (LHS.isInvalid() || RHS.isInvalid())
5769     return QualType();
5770   if (!compositeType.isNull())
5771     return compositeType;
5772 
5773 
5774   // Handle block pointer types.
5775   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5776     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5777                                                      QuestionLoc);
5778 
5779   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5780   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5781     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5782                                                        QuestionLoc);
5783 
5784   // GCC compatibility: soften pointer/integer mismatch.  Note that
5785   // null pointers have been filtered out by this point.
5786   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5787       /*isIntFirstExpr=*/true))
5788     return RHSTy;
5789   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5790       /*isIntFirstExpr=*/false))
5791     return LHSTy;
5792 
5793   // Emit a better diagnostic if one of the expressions is a null pointer
5794   // constant and the other is not a pointer type. In this case, the user most
5795   // likely forgot to take the address of the other expression.
5796   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5797     return QualType();
5798 
5799   // Otherwise, the operands are not compatible.
5800   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5801     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5802     << RHS.get()->getSourceRange();
5803   return QualType();
5804 }
5805 
5806 /// FindCompositeObjCPointerType - Helper method to find composite type of
5807 /// two objective-c pointer types of the two input expressions.
FindCompositeObjCPointerType(ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)5808 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5809                                             SourceLocation QuestionLoc) {
5810   QualType LHSTy = LHS.get()->getType();
5811   QualType RHSTy = RHS.get()->getType();
5812 
5813   // Handle things like Class and struct objc_class*.  Here we case the result
5814   // to the pseudo-builtin, because that will be implicitly cast back to the
5815   // redefinition type if an attempt is made to access its fields.
5816   if (LHSTy->isObjCClassType() &&
5817       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5818     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5819     return LHSTy;
5820   }
5821   if (RHSTy->isObjCClassType() &&
5822       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5823     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5824     return RHSTy;
5825   }
5826   // And the same for struct objc_object* / id
5827   if (LHSTy->isObjCIdType() &&
5828       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5829     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5830     return LHSTy;
5831   }
5832   if (RHSTy->isObjCIdType() &&
5833       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5834     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5835     return RHSTy;
5836   }
5837   // And the same for struct objc_selector* / SEL
5838   if (Context.isObjCSelType(LHSTy) &&
5839       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5840     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
5841     return LHSTy;
5842   }
5843   if (Context.isObjCSelType(RHSTy) &&
5844       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5845     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
5846     return RHSTy;
5847   }
5848   // Check constraints for Objective-C object pointers types.
5849   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5850 
5851     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5852       // Two identical object pointer types are always compatible.
5853       return LHSTy;
5854     }
5855     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5856     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5857     QualType compositeType = LHSTy;
5858 
5859     // If both operands are interfaces and either operand can be
5860     // assigned to the other, use that type as the composite
5861     // type. This allows
5862     //   xxx ? (A*) a : (B*) b
5863     // where B is a subclass of A.
5864     //
5865     // Additionally, as for assignment, if either type is 'id'
5866     // allow silent coercion. Finally, if the types are
5867     // incompatible then make sure to use 'id' as the composite
5868     // type so the result is acceptable for sending messages to.
5869 
5870     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5871     // It could return the composite type.
5872     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5873       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5874     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5875       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5876     } else if ((LHSTy->isObjCQualifiedIdType() ||
5877                 RHSTy->isObjCQualifiedIdType()) &&
5878                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5879       // Need to handle "id<xx>" explicitly.
5880       // GCC allows qualified id and any Objective-C type to devolve to
5881       // id. Currently localizing to here until clear this should be
5882       // part of ObjCQualifiedIdTypesAreCompatible.
5883       compositeType = Context.getObjCIdType();
5884     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5885       compositeType = Context.getObjCIdType();
5886     } else if (!(compositeType =
5887                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5888       ;
5889     else {
5890       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5891       << LHSTy << RHSTy
5892       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5893       QualType incompatTy = Context.getObjCIdType();
5894       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5895       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5896       return incompatTy;
5897     }
5898     // The object pointer types are compatible.
5899     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
5900     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
5901     return compositeType;
5902   }
5903   // Check Objective-C object pointer types and 'void *'
5904   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5905     if (getLangOpts().ObjCAutoRefCount) {
5906       // ARC forbids the implicit conversion of object pointers to 'void *',
5907       // so these types are not compatible.
5908       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5909           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5910       LHS = RHS = true;
5911       return QualType();
5912     }
5913     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5914     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5915     QualType destPointee
5916     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5917     QualType destType = Context.getPointerType(destPointee);
5918     // Add qualifiers if necessary.
5919     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5920     // Promote to void*.
5921     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5922     return destType;
5923   }
5924   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5925     if (getLangOpts().ObjCAutoRefCount) {
5926       // ARC forbids the implicit conversion of object pointers to 'void *',
5927       // so these types are not compatible.
5928       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5929           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5930       LHS = RHS = true;
5931       return QualType();
5932     }
5933     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5934     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5935     QualType destPointee
5936     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5937     QualType destType = Context.getPointerType(destPointee);
5938     // Add qualifiers if necessary.
5939     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5940     // Promote to void*.
5941     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5942     return destType;
5943   }
5944   return QualType();
5945 }
5946 
5947 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5948 /// ParenRange in parentheses.
SuggestParentheses(Sema & Self,SourceLocation Loc,const PartialDiagnostic & Note,SourceRange ParenRange)5949 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5950                                const PartialDiagnostic &Note,
5951                                SourceRange ParenRange) {
5952   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5953   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5954       EndLoc.isValid()) {
5955     Self.Diag(Loc, Note)
5956       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5957       << FixItHint::CreateInsertion(EndLoc, ")");
5958   } else {
5959     // We can't display the parentheses, so just show the bare note.
5960     Self.Diag(Loc, Note) << ParenRange;
5961   }
5962 }
5963 
IsArithmeticOp(BinaryOperatorKind Opc)5964 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5965   return Opc >= BO_Mul && Opc <= BO_Shr;
5966 }
5967 
5968 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5969 /// expression, either using a built-in or overloaded operator,
5970 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5971 /// expression.
IsArithmeticBinaryExpr(Expr * E,BinaryOperatorKind * Opcode,Expr ** RHSExprs)5972 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5973                                    Expr **RHSExprs) {
5974   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5975   E = E->IgnoreImpCasts();
5976   E = E->IgnoreConversionOperator();
5977   E = E->IgnoreImpCasts();
5978 
5979   // Built-in binary operator.
5980   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5981     if (IsArithmeticOp(OP->getOpcode())) {
5982       *Opcode = OP->getOpcode();
5983       *RHSExprs = OP->getRHS();
5984       return true;
5985     }
5986   }
5987 
5988   // Overloaded operator.
5989   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5990     if (Call->getNumArgs() != 2)
5991       return false;
5992 
5993     // Make sure this is really a binary operator that is safe to pass into
5994     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5995     OverloadedOperatorKind OO = Call->getOperator();
5996     if (OO < OO_Plus || OO > OO_Arrow ||
5997         OO == OO_PlusPlus || OO == OO_MinusMinus)
5998       return false;
5999 
6000     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6001     if (IsArithmeticOp(OpKind)) {
6002       *Opcode = OpKind;
6003       *RHSExprs = Call->getArg(1);
6004       return true;
6005     }
6006   }
6007 
6008   return false;
6009 }
6010 
IsLogicOp(BinaryOperatorKind Opc)6011 static bool IsLogicOp(BinaryOperatorKind Opc) {
6012   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6013 }
6014 
6015 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6016 /// or is a logical expression such as (x==y) which has int type, but is
6017 /// commonly interpreted as boolean.
ExprLooksBoolean(Expr * E)6018 static bool ExprLooksBoolean(Expr *E) {
6019   E = E->IgnoreParenImpCasts();
6020 
6021   if (E->getType()->isBooleanType())
6022     return true;
6023   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6024     return IsLogicOp(OP->getOpcode());
6025   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6026     return OP->getOpcode() == UO_LNot;
6027 
6028   return false;
6029 }
6030 
6031 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6032 /// and binary operator are mixed in a way that suggests the programmer assumed
6033 /// the conditional operator has higher precedence, for example:
6034 /// "int x = a + someBinaryCondition ? 1 : 2".
DiagnoseConditionalPrecedence(Sema & Self,SourceLocation OpLoc,Expr * Condition,Expr * LHSExpr,Expr * RHSExpr)6035 static void DiagnoseConditionalPrecedence(Sema &Self,
6036                                           SourceLocation OpLoc,
6037                                           Expr *Condition,
6038                                           Expr *LHSExpr,
6039                                           Expr *RHSExpr) {
6040   BinaryOperatorKind CondOpcode;
6041   Expr *CondRHS;
6042 
6043   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6044     return;
6045   if (!ExprLooksBoolean(CondRHS))
6046     return;
6047 
6048   // The condition is an arithmetic binary expression, with a right-
6049   // hand side that looks boolean, so warn.
6050 
6051   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6052       << Condition->getSourceRange()
6053       << BinaryOperator::getOpcodeStr(CondOpcode);
6054 
6055   SuggestParentheses(Self, OpLoc,
6056     Self.PDiag(diag::note_precedence_silence)
6057       << BinaryOperator::getOpcodeStr(CondOpcode),
6058     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6059 
6060   SuggestParentheses(Self, OpLoc,
6061     Self.PDiag(diag::note_precedence_conditional_first),
6062     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6063 }
6064 
6065 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6066 /// in the case of a the GNU conditional expr extension.
ActOnConditionalOp(SourceLocation QuestionLoc,SourceLocation ColonLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr)6067 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6068                                     SourceLocation ColonLoc,
6069                                     Expr *CondExpr, Expr *LHSExpr,
6070                                     Expr *RHSExpr) {
6071   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6072   // was the condition.
6073   OpaqueValueExpr *opaqueValue = nullptr;
6074   Expr *commonExpr = nullptr;
6075   if (!LHSExpr) {
6076     commonExpr = CondExpr;
6077     // Lower out placeholder types first.  This is important so that we don't
6078     // try to capture a placeholder. This happens in few cases in C++; such
6079     // as Objective-C++'s dictionary subscripting syntax.
6080     if (commonExpr->hasPlaceholderType()) {
6081       ExprResult result = CheckPlaceholderExpr(commonExpr);
6082       if (!result.isUsable()) return ExprError();
6083       commonExpr = result.get();
6084     }
6085     // We usually want to apply unary conversions *before* saving, except
6086     // in the special case of a C++ l-value conditional.
6087     if (!(getLangOpts().CPlusPlus
6088           && !commonExpr->isTypeDependent()
6089           && commonExpr->getValueKind() == RHSExpr->getValueKind()
6090           && commonExpr->isGLValue()
6091           && commonExpr->isOrdinaryOrBitFieldObject()
6092           && RHSExpr->isOrdinaryOrBitFieldObject()
6093           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6094       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6095       if (commonRes.isInvalid())
6096         return ExprError();
6097       commonExpr = commonRes.get();
6098     }
6099 
6100     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6101                                                 commonExpr->getType(),
6102                                                 commonExpr->getValueKind(),
6103                                                 commonExpr->getObjectKind(),
6104                                                 commonExpr);
6105     LHSExpr = CondExpr = opaqueValue;
6106   }
6107 
6108   ExprValueKind VK = VK_RValue;
6109   ExprObjectKind OK = OK_Ordinary;
6110   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6111   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6112                                              VK, OK, QuestionLoc);
6113   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6114       RHS.isInvalid())
6115     return ExprError();
6116 
6117   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6118                                 RHS.get());
6119 
6120   if (!commonExpr)
6121     return new (Context)
6122         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6123                             RHS.get(), result, VK, OK);
6124 
6125   return new (Context) BinaryConditionalOperator(
6126       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6127       ColonLoc, result, VK, OK);
6128 }
6129 
6130 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6131 // being closely modeled after the C99 spec:-). The odd characteristic of this
6132 // routine is it effectively iqnores the qualifiers on the top level pointee.
6133 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6134 // FIXME: add a couple examples in this comment.
6135 static Sema::AssignConvertType
checkPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)6136 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6137   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6138   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6139 
6140   // get the "pointed to" type (ignoring qualifiers at the top level)
6141   const Type *lhptee, *rhptee;
6142   Qualifiers lhq, rhq;
6143   std::tie(lhptee, lhq) =
6144       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6145   std::tie(rhptee, rhq) =
6146       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6147 
6148   Sema::AssignConvertType ConvTy = Sema::Compatible;
6149 
6150   // C99 6.5.16.1p1: This following citation is common to constraints
6151   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6152   // qualifiers of the type *pointed to* by the right;
6153 
6154   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6155   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6156       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6157     // Ignore lifetime for further calculation.
6158     lhq.removeObjCLifetime();
6159     rhq.removeObjCLifetime();
6160   }
6161 
6162   if (!lhq.compatiblyIncludes(rhq)) {
6163     // Treat address-space mismatches as fatal.  TODO: address subspaces
6164     if (lhq.getAddressSpace() != rhq.getAddressSpace())
6165       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6166 
6167     // It's okay to add or remove GC or lifetime qualifiers when converting to
6168     // and from void*.
6169     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6170                         .compatiblyIncludes(
6171                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6172              && (lhptee->isVoidType() || rhptee->isVoidType()))
6173       ; // keep old
6174 
6175     // Treat lifetime mismatches as fatal.
6176     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6177       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6178 
6179     // For GCC compatibility, other qualifier mismatches are treated
6180     // as still compatible in C.
6181     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6182   }
6183 
6184   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6185   // incomplete type and the other is a pointer to a qualified or unqualified
6186   // version of void...
6187   if (lhptee->isVoidType()) {
6188     if (rhptee->isIncompleteOrObjectType())
6189       return ConvTy;
6190 
6191     // As an extension, we allow cast to/from void* to function pointer.
6192     assert(rhptee->isFunctionType());
6193     return Sema::FunctionVoidPointer;
6194   }
6195 
6196   if (rhptee->isVoidType()) {
6197     if (lhptee->isIncompleteOrObjectType())
6198       return ConvTy;
6199 
6200     // As an extension, we allow cast to/from void* to function pointer.
6201     assert(lhptee->isFunctionType());
6202     return Sema::FunctionVoidPointer;
6203   }
6204 
6205   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6206   // unqualified versions of compatible types, ...
6207   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6208   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6209     // Check if the pointee types are compatible ignoring the sign.
6210     // We explicitly check for char so that we catch "char" vs
6211     // "unsigned char" on systems where "char" is unsigned.
6212     if (lhptee->isCharType())
6213       ltrans = S.Context.UnsignedCharTy;
6214     else if (lhptee->hasSignedIntegerRepresentation())
6215       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6216 
6217     if (rhptee->isCharType())
6218       rtrans = S.Context.UnsignedCharTy;
6219     else if (rhptee->hasSignedIntegerRepresentation())
6220       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6221 
6222     if (ltrans == rtrans) {
6223       // Types are compatible ignoring the sign. Qualifier incompatibility
6224       // takes priority over sign incompatibility because the sign
6225       // warning can be disabled.
6226       if (ConvTy != Sema::Compatible)
6227         return ConvTy;
6228 
6229       return Sema::IncompatiblePointerSign;
6230     }
6231 
6232     // If we are a multi-level pointer, it's possible that our issue is simply
6233     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6234     // the eventual target type is the same and the pointers have the same
6235     // level of indirection, this must be the issue.
6236     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6237       do {
6238         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6239         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6240       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6241 
6242       if (lhptee == rhptee)
6243         return Sema::IncompatibleNestedPointerQualifiers;
6244     }
6245 
6246     // General pointer incompatibility takes priority over qualifiers.
6247     return Sema::IncompatiblePointer;
6248   }
6249   if (!S.getLangOpts().CPlusPlus &&
6250       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6251     return Sema::IncompatiblePointer;
6252   return ConvTy;
6253 }
6254 
6255 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6256 /// block pointer types are compatible or whether a block and normal pointer
6257 /// are compatible. It is more restrict than comparing two function pointer
6258 // types.
6259 static Sema::AssignConvertType
checkBlockPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)6260 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6261                                     QualType RHSType) {
6262   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6263   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6264 
6265   QualType lhptee, rhptee;
6266 
6267   // get the "pointed to" type (ignoring qualifiers at the top level)
6268   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6269   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6270 
6271   // In C++, the types have to match exactly.
6272   if (S.getLangOpts().CPlusPlus)
6273     return Sema::IncompatibleBlockPointer;
6274 
6275   Sema::AssignConvertType ConvTy = Sema::Compatible;
6276 
6277   // For blocks we enforce that qualifiers are identical.
6278   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6279     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6280 
6281   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6282     return Sema::IncompatibleBlockPointer;
6283 
6284   return ConvTy;
6285 }
6286 
6287 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6288 /// for assignment compatibility.
6289 static Sema::AssignConvertType
checkObjCPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)6290 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6291                                    QualType RHSType) {
6292   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6293   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6294 
6295   if (LHSType->isObjCBuiltinType()) {
6296     // Class is not compatible with ObjC object pointers.
6297     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6298         !RHSType->isObjCQualifiedClassType())
6299       return Sema::IncompatiblePointer;
6300     return Sema::Compatible;
6301   }
6302   if (RHSType->isObjCBuiltinType()) {
6303     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6304         !LHSType->isObjCQualifiedClassType())
6305       return Sema::IncompatiblePointer;
6306     return Sema::Compatible;
6307   }
6308   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6309   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6310 
6311   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6312       // make an exception for id<P>
6313       !LHSType->isObjCQualifiedIdType())
6314     return Sema::CompatiblePointerDiscardsQualifiers;
6315 
6316   if (S.Context.typesAreCompatible(LHSType, RHSType))
6317     return Sema::Compatible;
6318   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6319     return Sema::IncompatibleObjCQualifiedId;
6320   return Sema::IncompatiblePointer;
6321 }
6322 
6323 Sema::AssignConvertType
CheckAssignmentConstraints(SourceLocation Loc,QualType LHSType,QualType RHSType)6324 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6325                                  QualType LHSType, QualType RHSType) {
6326   // Fake up an opaque expression.  We don't actually care about what
6327   // cast operations are required, so if CheckAssignmentConstraints
6328   // adds casts to this they'll be wasted, but fortunately that doesn't
6329   // usually happen on valid code.
6330   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6331   ExprResult RHSPtr = &RHSExpr;
6332   CastKind K = CK_Invalid;
6333 
6334   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6335 }
6336 
6337 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6338 /// has code to accommodate several GCC extensions when type checking
6339 /// pointers. Here are some objectionable examples that GCC considers warnings:
6340 ///
6341 ///  int a, *pint;
6342 ///  short *pshort;
6343 ///  struct foo *pfoo;
6344 ///
6345 ///  pint = pshort; // warning: assignment from incompatible pointer type
6346 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6347 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6348 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6349 ///
6350 /// As a result, the code for dealing with pointers is more complex than the
6351 /// C99 spec dictates.
6352 ///
6353 /// Sets 'Kind' for any result kind except Incompatible.
6354 Sema::AssignConvertType
CheckAssignmentConstraints(QualType LHSType,ExprResult & RHS,CastKind & Kind)6355 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6356                                  CastKind &Kind) {
6357   QualType RHSType = RHS.get()->getType();
6358   QualType OrigLHSType = LHSType;
6359 
6360   // Get canonical types.  We're not formatting these types, just comparing
6361   // them.
6362   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6363   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6364 
6365   // Common case: no conversion required.
6366   if (LHSType == RHSType) {
6367     Kind = CK_NoOp;
6368     return Compatible;
6369   }
6370 
6371   // If we have an atomic type, try a non-atomic assignment, then just add an
6372   // atomic qualification step.
6373   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6374     Sema::AssignConvertType result =
6375       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6376     if (result != Compatible)
6377       return result;
6378     if (Kind != CK_NoOp)
6379       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6380     Kind = CK_NonAtomicToAtomic;
6381     return Compatible;
6382   }
6383 
6384   // If the left-hand side is a reference type, then we are in a
6385   // (rare!) case where we've allowed the use of references in C,
6386   // e.g., as a parameter type in a built-in function. In this case,
6387   // just make sure that the type referenced is compatible with the
6388   // right-hand side type. The caller is responsible for adjusting
6389   // LHSType so that the resulting expression does not have reference
6390   // type.
6391   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6392     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6393       Kind = CK_LValueBitCast;
6394       return Compatible;
6395     }
6396     return Incompatible;
6397   }
6398 
6399   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6400   // to the same ExtVector type.
6401   if (LHSType->isExtVectorType()) {
6402     if (RHSType->isExtVectorType())
6403       return Incompatible;
6404     if (RHSType->isArithmeticType()) {
6405       // CK_VectorSplat does T -> vector T, so first cast to the
6406       // element type.
6407       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6408       if (elType != RHSType) {
6409         Kind = PrepareScalarCast(RHS, elType);
6410         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6411       }
6412       Kind = CK_VectorSplat;
6413       return Compatible;
6414     }
6415   }
6416 
6417   // Conversions to or from vector type.
6418   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6419     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6420       // Allow assignments of an AltiVec vector type to an equivalent GCC
6421       // vector type and vice versa
6422       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6423         Kind = CK_BitCast;
6424         return Compatible;
6425       }
6426 
6427       // If we are allowing lax vector conversions, and LHS and RHS are both
6428       // vectors, the total size only needs to be the same. This is a bitcast;
6429       // no bits are changed but the result type is different.
6430       if (isLaxVectorConversion(RHSType, LHSType)) {
6431         Kind = CK_BitCast;
6432         return IncompatibleVectors;
6433       }
6434     }
6435     return Incompatible;
6436   }
6437 
6438   // Arithmetic conversions.
6439   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6440       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6441     Kind = PrepareScalarCast(RHS, LHSType);
6442     return Compatible;
6443   }
6444 
6445   // Conversions to normal pointers.
6446   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6447     // U* -> T*
6448     if (isa<PointerType>(RHSType)) {
6449       Kind = CK_BitCast;
6450       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6451     }
6452 
6453     // int -> T*
6454     if (RHSType->isIntegerType()) {
6455       Kind = CK_IntegralToPointer; // FIXME: null?
6456       return IntToPointer;
6457     }
6458 
6459     // C pointers are not compatible with ObjC object pointers,
6460     // with two exceptions:
6461     if (isa<ObjCObjectPointerType>(RHSType)) {
6462       //  - conversions to void*
6463       if (LHSPointer->getPointeeType()->isVoidType()) {
6464         Kind = CK_BitCast;
6465         return Compatible;
6466       }
6467 
6468       //  - conversions from 'Class' to the redefinition type
6469       if (RHSType->isObjCClassType() &&
6470           Context.hasSameType(LHSType,
6471                               Context.getObjCClassRedefinitionType())) {
6472         Kind = CK_BitCast;
6473         return Compatible;
6474       }
6475 
6476       Kind = CK_BitCast;
6477       return IncompatiblePointer;
6478     }
6479 
6480     // U^ -> void*
6481     if (RHSType->getAs<BlockPointerType>()) {
6482       if (LHSPointer->getPointeeType()->isVoidType()) {
6483         Kind = CK_BitCast;
6484         return Compatible;
6485       }
6486     }
6487 
6488     return Incompatible;
6489   }
6490 
6491   // Conversions to block pointers.
6492   if (isa<BlockPointerType>(LHSType)) {
6493     // U^ -> T^
6494     if (RHSType->isBlockPointerType()) {
6495       Kind = CK_BitCast;
6496       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6497     }
6498 
6499     // int or null -> T^
6500     if (RHSType->isIntegerType()) {
6501       Kind = CK_IntegralToPointer; // FIXME: null
6502       return IntToBlockPointer;
6503     }
6504 
6505     // id -> T^
6506     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6507       Kind = CK_AnyPointerToBlockPointerCast;
6508       return Compatible;
6509     }
6510 
6511     // void* -> T^
6512     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6513       if (RHSPT->getPointeeType()->isVoidType()) {
6514         Kind = CK_AnyPointerToBlockPointerCast;
6515         return Compatible;
6516       }
6517 
6518     return Incompatible;
6519   }
6520 
6521   // Conversions to Objective-C pointers.
6522   if (isa<ObjCObjectPointerType>(LHSType)) {
6523     // A* -> B*
6524     if (RHSType->isObjCObjectPointerType()) {
6525       Kind = CK_BitCast;
6526       Sema::AssignConvertType result =
6527         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6528       if (getLangOpts().ObjCAutoRefCount &&
6529           result == Compatible &&
6530           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6531         result = IncompatibleObjCWeakRef;
6532       return result;
6533     }
6534 
6535     // int or null -> A*
6536     if (RHSType->isIntegerType()) {
6537       Kind = CK_IntegralToPointer; // FIXME: null
6538       return IntToPointer;
6539     }
6540 
6541     // In general, C pointers are not compatible with ObjC object pointers,
6542     // with two exceptions:
6543     if (isa<PointerType>(RHSType)) {
6544       Kind = CK_CPointerToObjCPointerCast;
6545 
6546       //  - conversions from 'void*'
6547       if (RHSType->isVoidPointerType()) {
6548         return Compatible;
6549       }
6550 
6551       //  - conversions to 'Class' from its redefinition type
6552       if (LHSType->isObjCClassType() &&
6553           Context.hasSameType(RHSType,
6554                               Context.getObjCClassRedefinitionType())) {
6555         return Compatible;
6556       }
6557 
6558       return IncompatiblePointer;
6559     }
6560 
6561     // Only under strict condition T^ is compatible with an Objective-C pointer.
6562     if (RHSType->isBlockPointerType() &&
6563         isObjCPtrBlockCompatible(*this, Context, LHSType)) {
6564       maybeExtendBlockObject(*this, RHS);
6565       Kind = CK_BlockPointerToObjCPointerCast;
6566       return Compatible;
6567     }
6568 
6569     return Incompatible;
6570   }
6571 
6572   // Conversions from pointers that are not covered by the above.
6573   if (isa<PointerType>(RHSType)) {
6574     // T* -> _Bool
6575     if (LHSType == Context.BoolTy) {
6576       Kind = CK_PointerToBoolean;
6577       return Compatible;
6578     }
6579 
6580     // T* -> int
6581     if (LHSType->isIntegerType()) {
6582       Kind = CK_PointerToIntegral;
6583       return PointerToInt;
6584     }
6585 
6586     return Incompatible;
6587   }
6588 
6589   // Conversions from Objective-C pointers that are not covered by the above.
6590   if (isa<ObjCObjectPointerType>(RHSType)) {
6591     // T* -> _Bool
6592     if (LHSType == Context.BoolTy) {
6593       Kind = CK_PointerToBoolean;
6594       return Compatible;
6595     }
6596 
6597     // T* -> int
6598     if (LHSType->isIntegerType()) {
6599       Kind = CK_PointerToIntegral;
6600       return PointerToInt;
6601     }
6602 
6603     return Incompatible;
6604   }
6605 
6606   // struct A -> struct B
6607   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6608     if (Context.typesAreCompatible(LHSType, RHSType)) {
6609       Kind = CK_NoOp;
6610       return Compatible;
6611     }
6612   }
6613 
6614   return Incompatible;
6615 }
6616 
6617 /// \brief Constructs a transparent union from an expression that is
6618 /// used to initialize the transparent union.
ConstructTransparentUnion(Sema & S,ASTContext & C,ExprResult & EResult,QualType UnionType,FieldDecl * Field)6619 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6620                                       ExprResult &EResult, QualType UnionType,
6621                                       FieldDecl *Field) {
6622   // Build an initializer list that designates the appropriate member
6623   // of the transparent union.
6624   Expr *E = EResult.get();
6625   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6626                                                    E, SourceLocation());
6627   Initializer->setType(UnionType);
6628   Initializer->setInitializedFieldInUnion(Field);
6629 
6630   // Build a compound literal constructing a value of the transparent
6631   // union type from this initializer list.
6632   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6633   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6634                                         VK_RValue, Initializer, false);
6635 }
6636 
6637 Sema::AssignConvertType
CheckTransparentUnionArgumentConstraints(QualType ArgType,ExprResult & RHS)6638 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6639                                                ExprResult &RHS) {
6640   QualType RHSType = RHS.get()->getType();
6641 
6642   // If the ArgType is a Union type, we want to handle a potential
6643   // transparent_union GCC extension.
6644   const RecordType *UT = ArgType->getAsUnionType();
6645   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6646     return Incompatible;
6647 
6648   // The field to initialize within the transparent union.
6649   RecordDecl *UD = UT->getDecl();
6650   FieldDecl *InitField = nullptr;
6651   // It's compatible if the expression matches any of the fields.
6652   for (auto *it : UD->fields()) {
6653     if (it->getType()->isPointerType()) {
6654       // If the transparent union contains a pointer type, we allow:
6655       // 1) void pointer
6656       // 2) null pointer constant
6657       if (RHSType->isPointerType())
6658         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6659           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
6660           InitField = it;
6661           break;
6662         }
6663 
6664       if (RHS.get()->isNullPointerConstant(Context,
6665                                            Expr::NPC_ValueDependentIsNull)) {
6666         RHS = ImpCastExprToType(RHS.get(), it->getType(),
6667                                 CK_NullToPointer);
6668         InitField = it;
6669         break;
6670       }
6671     }
6672 
6673     CastKind Kind = CK_Invalid;
6674     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6675           == Compatible) {
6676       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
6677       InitField = it;
6678       break;
6679     }
6680   }
6681 
6682   if (!InitField)
6683     return Incompatible;
6684 
6685   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6686   return Compatible;
6687 }
6688 
6689 Sema::AssignConvertType
CheckSingleAssignmentConstraints(QualType LHSType,ExprResult & RHS,bool Diagnose,bool DiagnoseCFAudited)6690 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6691                                        bool Diagnose,
6692                                        bool DiagnoseCFAudited) {
6693   if (getLangOpts().CPlusPlus) {
6694     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6695       // C++ 5.17p3: If the left operand is not of class type, the
6696       // expression is implicitly converted (C++ 4) to the
6697       // cv-unqualified type of the left operand.
6698       ExprResult Res;
6699       if (Diagnose) {
6700         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6701                                         AA_Assigning);
6702       } else {
6703         ImplicitConversionSequence ICS =
6704             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6705                                   /*SuppressUserConversions=*/false,
6706                                   /*AllowExplicit=*/false,
6707                                   /*InOverloadResolution=*/false,
6708                                   /*CStyle=*/false,
6709                                   /*AllowObjCWritebackConversion=*/false);
6710         if (ICS.isFailure())
6711           return Incompatible;
6712         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6713                                         ICS, AA_Assigning);
6714       }
6715       if (Res.isInvalid())
6716         return Incompatible;
6717       Sema::AssignConvertType result = Compatible;
6718       if (getLangOpts().ObjCAutoRefCount &&
6719           !CheckObjCARCUnavailableWeakConversion(LHSType,
6720                                                  RHS.get()->getType()))
6721         result = IncompatibleObjCWeakRef;
6722       RHS = Res;
6723       return result;
6724     }
6725 
6726     // FIXME: Currently, we fall through and treat C++ classes like C
6727     // structures.
6728     // FIXME: We also fall through for atomics; not sure what should
6729     // happen there, though.
6730   }
6731 
6732   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6733   // a null pointer constant.
6734   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6735        LHSType->isBlockPointerType()) &&
6736       RHS.get()->isNullPointerConstant(Context,
6737                                        Expr::NPC_ValueDependentIsNull)) {
6738     CastKind Kind;
6739     CXXCastPath Path;
6740     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6741     RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
6742     return Compatible;
6743   }
6744 
6745   // This check seems unnatural, however it is necessary to ensure the proper
6746   // conversion of functions/arrays. If the conversion were done for all
6747   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6748   // expressions that suppress this implicit conversion (&, sizeof).
6749   //
6750   // Suppress this for references: C++ 8.5.3p5.
6751   if (!LHSType->isReferenceType()) {
6752     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6753     if (RHS.isInvalid())
6754       return Incompatible;
6755   }
6756 
6757   CastKind Kind = CK_Invalid;
6758   Sema::AssignConvertType result =
6759     CheckAssignmentConstraints(LHSType, RHS, Kind);
6760 
6761   // C99 6.5.16.1p2: The value of the right operand is converted to the
6762   // type of the assignment expression.
6763   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6764   // so that we can use references in built-in functions even in C.
6765   // The getNonReferenceType() call makes sure that the resulting expression
6766   // does not have reference type.
6767   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6768     QualType Ty = LHSType.getNonLValueExprType(Context);
6769     Expr *E = RHS.get();
6770     if (getLangOpts().ObjCAutoRefCount)
6771       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6772                              DiagnoseCFAudited);
6773     if (getLangOpts().ObjC1 &&
6774         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
6775                                           LHSType, E->getType(), E) ||
6776          ConversionToObjCStringLiteralCheck(LHSType, E))) {
6777       RHS = E;
6778       return Compatible;
6779     }
6780 
6781     RHS = ImpCastExprToType(E, Ty, Kind);
6782   }
6783   return result;
6784 }
6785 
InvalidOperands(SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)6786 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6787                                ExprResult &RHS) {
6788   Diag(Loc, diag::err_typecheck_invalid_operands)
6789     << LHS.get()->getType() << RHS.get()->getType()
6790     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6791   return QualType();
6792 }
6793 
6794 /// Try to convert a value of non-vector type to a vector type by converting
6795 /// the type to the element type of the vector and then performing a splat.
6796 /// If the language is OpenCL, we only use conversions that promote scalar
6797 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
6798 /// for float->int.
6799 ///
6800 /// \param scalar - if non-null, actually perform the conversions
6801 /// \return true if the operation fails (but without diagnosing the failure)
tryVectorConvertAndSplat(Sema & S,ExprResult * scalar,QualType scalarTy,QualType vectorEltTy,QualType vectorTy)6802 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
6803                                      QualType scalarTy,
6804                                      QualType vectorEltTy,
6805                                      QualType vectorTy) {
6806   // The conversion to apply to the scalar before splatting it,
6807   // if necessary.
6808   CastKind scalarCast = CK_Invalid;
6809 
6810   if (vectorEltTy->isIntegralType(S.Context)) {
6811     if (!scalarTy->isIntegralType(S.Context))
6812       return true;
6813     if (S.getLangOpts().OpenCL &&
6814         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
6815       return true;
6816     scalarCast = CK_IntegralCast;
6817   } else if (vectorEltTy->isRealFloatingType()) {
6818     if (scalarTy->isRealFloatingType()) {
6819       if (S.getLangOpts().OpenCL &&
6820           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
6821         return true;
6822       scalarCast = CK_FloatingCast;
6823     }
6824     else if (scalarTy->isIntegralType(S.Context))
6825       scalarCast = CK_IntegralToFloating;
6826     else
6827       return true;
6828   } else {
6829     return true;
6830   }
6831 
6832   // Adjust scalar if desired.
6833   if (scalar) {
6834     if (scalarCast != CK_Invalid)
6835       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
6836     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
6837   }
6838   return false;
6839 }
6840 
CheckVectorOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)6841 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6842                                    SourceLocation Loc, bool IsCompAssign) {
6843   if (!IsCompAssign) {
6844     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6845     if (LHS.isInvalid())
6846       return QualType();
6847   }
6848   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6849   if (RHS.isInvalid())
6850     return QualType();
6851 
6852   // For conversion purposes, we ignore any qualifiers.
6853   // For example, "const float" and "float" are equivalent.
6854   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
6855   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
6856 
6857   // If the vector types are identical, return.
6858   if (Context.hasSameType(LHSType, RHSType))
6859     return LHSType;
6860 
6861   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
6862   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
6863   assert(LHSVecType || RHSVecType);
6864 
6865   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
6866   if (LHSVecType && RHSVecType &&
6867       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6868     if (isa<ExtVectorType>(LHSVecType)) {
6869       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
6870       return LHSType;
6871     }
6872 
6873     if (!IsCompAssign)
6874       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
6875     return RHSType;
6876   }
6877 
6878   // If there's an ext-vector type and a scalar, try to convert the scalar to
6879   // the vector element type and splat.
6880   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
6881     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
6882                                   LHSVecType->getElementType(), LHSType))
6883       return LHSType;
6884   }
6885   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
6886     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
6887                                   LHSType, RHSVecType->getElementType(),
6888                                   RHSType))
6889       return RHSType;
6890   }
6891 
6892   // If we're allowing lax vector conversions, only the total (data) size
6893   // needs to be the same.
6894   // FIXME: Should we really be allowing this?
6895   // FIXME: We really just pick the LHS type arbitrarily?
6896   if (isLaxVectorConversion(RHSType, LHSType)) {
6897     QualType resultType = LHSType;
6898     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
6899     return resultType;
6900   }
6901 
6902   // Okay, the expression is invalid.
6903 
6904   // If there's a non-vector, non-real operand, diagnose that.
6905   if ((!RHSVecType && !RHSType->isRealType()) ||
6906       (!LHSVecType && !LHSType->isRealType())) {
6907     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
6908       << LHSType << RHSType
6909       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6910     return QualType();
6911   }
6912 
6913   // Otherwise, use the generic diagnostic.
6914   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6915     << LHSType << RHSType
6916     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6917   return QualType();
6918 }
6919 
6920 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6921 // expression.  These are mainly cases where the null pointer is used as an
6922 // integer instead of a pointer.
checkArithmeticNull(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompare)6923 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6924                                 SourceLocation Loc, bool IsCompare) {
6925   // The canonical way to check for a GNU null is with isNullPointerConstant,
6926   // but we use a bit of a hack here for speed; this is a relatively
6927   // hot path, and isNullPointerConstant is slow.
6928   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6929   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6930 
6931   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6932 
6933   // Avoid analyzing cases where the result will either be invalid (and
6934   // diagnosed as such) or entirely valid and not something to warn about.
6935   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6936       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6937     return;
6938 
6939   // Comparison operations would not make sense with a null pointer no matter
6940   // what the other expression is.
6941   if (!IsCompare) {
6942     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6943         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6944         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6945     return;
6946   }
6947 
6948   // The rest of the operations only make sense with a null pointer
6949   // if the other expression is a pointer.
6950   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6951       NonNullType->canDecayToPointerType())
6952     return;
6953 
6954   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6955       << LHSNull /* LHS is NULL */ << NonNullType
6956       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6957 }
6958 
CheckMultiplyDivideOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool IsDiv)6959 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6960                                            SourceLocation Loc,
6961                                            bool IsCompAssign, bool IsDiv) {
6962   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6963 
6964   if (LHS.get()->getType()->isVectorType() ||
6965       RHS.get()->getType()->isVectorType())
6966     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6967 
6968   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6969   if (LHS.isInvalid() || RHS.isInvalid())
6970     return QualType();
6971 
6972 
6973   if (compType.isNull() || !compType->isArithmeticType())
6974     return InvalidOperands(Loc, LHS, RHS);
6975 
6976   // Check for division by zero.
6977   llvm::APSInt RHSValue;
6978   if (IsDiv && !RHS.get()->isValueDependent() &&
6979       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6980     DiagRuntimeBehavior(Loc, RHS.get(),
6981                         PDiag(diag::warn_division_by_zero)
6982                           << RHS.get()->getSourceRange());
6983 
6984   return compType;
6985 }
6986 
CheckRemainderOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)6987 QualType Sema::CheckRemainderOperands(
6988   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6989   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6990 
6991   if (LHS.get()->getType()->isVectorType() ||
6992       RHS.get()->getType()->isVectorType()) {
6993     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6994         RHS.get()->getType()->hasIntegerRepresentation())
6995       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6996     return InvalidOperands(Loc, LHS, RHS);
6997   }
6998 
6999   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7000   if (LHS.isInvalid() || RHS.isInvalid())
7001     return QualType();
7002 
7003   if (compType.isNull() || !compType->isIntegerType())
7004     return InvalidOperands(Loc, LHS, RHS);
7005 
7006   // Check for remainder by zero.
7007   llvm::APSInt RHSValue;
7008   if (!RHS.get()->isValueDependent() &&
7009       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7010     DiagRuntimeBehavior(Loc, RHS.get(),
7011                         PDiag(diag::warn_remainder_by_zero)
7012                           << RHS.get()->getSourceRange());
7013 
7014   return compType;
7015 }
7016 
7017 /// \brief Diagnose invalid arithmetic on two void pointers.
diagnoseArithmeticOnTwoVoidPointers(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)7018 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7019                                                 Expr *LHSExpr, Expr *RHSExpr) {
7020   S.Diag(Loc, S.getLangOpts().CPlusPlus
7021                 ? diag::err_typecheck_pointer_arith_void_type
7022                 : diag::ext_gnu_void_ptr)
7023     << 1 /* two pointers */ << LHSExpr->getSourceRange()
7024                             << RHSExpr->getSourceRange();
7025 }
7026 
7027 /// \brief Diagnose invalid arithmetic on a void pointer.
diagnoseArithmeticOnVoidPointer(Sema & S,SourceLocation Loc,Expr * Pointer)7028 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7029                                             Expr *Pointer) {
7030   S.Diag(Loc, S.getLangOpts().CPlusPlus
7031                 ? diag::err_typecheck_pointer_arith_void_type
7032                 : diag::ext_gnu_void_ptr)
7033     << 0 /* one pointer */ << Pointer->getSourceRange();
7034 }
7035 
7036 /// \brief Diagnose invalid arithmetic on two function pointers.
diagnoseArithmeticOnTwoFunctionPointers(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)7037 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7038                                                     Expr *LHS, Expr *RHS) {
7039   assert(LHS->getType()->isAnyPointerType());
7040   assert(RHS->getType()->isAnyPointerType());
7041   S.Diag(Loc, S.getLangOpts().CPlusPlus
7042                 ? diag::err_typecheck_pointer_arith_function_type
7043                 : diag::ext_gnu_ptr_func_arith)
7044     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7045     // We only show the second type if it differs from the first.
7046     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7047                                                    RHS->getType())
7048     << RHS->getType()->getPointeeType()
7049     << LHS->getSourceRange() << RHS->getSourceRange();
7050 }
7051 
7052 /// \brief Diagnose invalid arithmetic on a function pointer.
diagnoseArithmeticOnFunctionPointer(Sema & S,SourceLocation Loc,Expr * Pointer)7053 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7054                                                 Expr *Pointer) {
7055   assert(Pointer->getType()->isAnyPointerType());
7056   S.Diag(Loc, S.getLangOpts().CPlusPlus
7057                 ? diag::err_typecheck_pointer_arith_function_type
7058                 : diag::ext_gnu_ptr_func_arith)
7059     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7060     << 0 /* one pointer, so only one type */
7061     << Pointer->getSourceRange();
7062 }
7063 
7064 /// \brief Emit error if Operand is incomplete pointer type
7065 ///
7066 /// \returns True if pointer has incomplete type
checkArithmeticIncompletePointerType(Sema & S,SourceLocation Loc,Expr * Operand)7067 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7068                                                  Expr *Operand) {
7069   assert(Operand->getType()->isAnyPointerType() &&
7070          !Operand->getType()->isDependentType());
7071   QualType PointeeTy = Operand->getType()->getPointeeType();
7072   return S.RequireCompleteType(Loc, PointeeTy,
7073                                diag::err_typecheck_arithmetic_incomplete_type,
7074                                PointeeTy, Operand->getSourceRange());
7075 }
7076 
7077 /// \brief Check the validity of an arithmetic pointer operand.
7078 ///
7079 /// If the operand has pointer type, this code will check for pointer types
7080 /// which are invalid in arithmetic operations. These will be diagnosed
7081 /// appropriately, including whether or not the use is supported as an
7082 /// extension.
7083 ///
7084 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticOpPointerOperand(Sema & S,SourceLocation Loc,Expr * Operand)7085 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7086                                             Expr *Operand) {
7087   if (!Operand->getType()->isAnyPointerType()) return true;
7088 
7089   QualType PointeeTy = Operand->getType()->getPointeeType();
7090   if (PointeeTy->isVoidType()) {
7091     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
7092     return !S.getLangOpts().CPlusPlus;
7093   }
7094   if (PointeeTy->isFunctionType()) {
7095     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7096     return !S.getLangOpts().CPlusPlus;
7097   }
7098 
7099   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7100 
7101   return true;
7102 }
7103 
7104 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7105 /// operands.
7106 ///
7107 /// This routine will diagnose any invalid arithmetic on pointer operands much
7108 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7109 /// for emitting a single diagnostic even for operations where both LHS and RHS
7110 /// are (potentially problematic) pointers.
7111 ///
7112 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticBinOpPointerOperands(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)7113 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7114                                                 Expr *LHSExpr, Expr *RHSExpr) {
7115   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7116   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7117   if (!isLHSPointer && !isRHSPointer) return true;
7118 
7119   QualType LHSPointeeTy, RHSPointeeTy;
7120   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7121   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7122 
7123   // Check for arithmetic on pointers to incomplete types.
7124   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7125   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7126   if (isLHSVoidPtr || isRHSVoidPtr) {
7127     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7128     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7129     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7130 
7131     return !S.getLangOpts().CPlusPlus;
7132   }
7133 
7134   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7135   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7136   if (isLHSFuncPtr || isRHSFuncPtr) {
7137     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7138     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7139                                                                 RHSExpr);
7140     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7141 
7142     return !S.getLangOpts().CPlusPlus;
7143   }
7144 
7145   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7146     return false;
7147   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7148     return false;
7149 
7150   return true;
7151 }
7152 
7153 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7154 /// literal.
diagnoseStringPlusInt(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)7155 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7156                                   Expr *LHSExpr, Expr *RHSExpr) {
7157   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7158   Expr* IndexExpr = RHSExpr;
7159   if (!StrExpr) {
7160     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7161     IndexExpr = LHSExpr;
7162   }
7163 
7164   bool IsStringPlusInt = StrExpr &&
7165       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7166   if (!IsStringPlusInt)
7167     return;
7168 
7169   llvm::APSInt index;
7170   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7171     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7172     if (index.isNonNegative() &&
7173         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7174                               index.isUnsigned()))
7175       return;
7176   }
7177 
7178   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7179   Self.Diag(OpLoc, diag::warn_string_plus_int)
7180       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7181 
7182   // Only print a fixit for "str" + int, not for int + "str".
7183   if (IndexExpr == RHSExpr) {
7184     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7185     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7186         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7187         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7188         << FixItHint::CreateInsertion(EndLoc, "]");
7189   } else
7190     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7191 }
7192 
7193 /// \brief Emit a warning when adding a char literal to a string.
diagnoseStringPlusChar(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)7194 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7195                                    Expr *LHSExpr, Expr *RHSExpr) {
7196   const DeclRefExpr *StringRefExpr =
7197       dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
7198   const CharacterLiteral *CharExpr =
7199       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7200   if (!StringRefExpr) {
7201     StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
7202     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7203   }
7204 
7205   if (!CharExpr || !StringRefExpr)
7206     return;
7207 
7208   const QualType StringType = StringRefExpr->getType();
7209 
7210   // Return if not a PointerType.
7211   if (!StringType->isAnyPointerType())
7212     return;
7213 
7214   // Return if not a CharacterType.
7215   if (!StringType->getPointeeType()->isAnyCharacterType())
7216     return;
7217 
7218   ASTContext &Ctx = Self.getASTContext();
7219   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7220 
7221   const QualType CharType = CharExpr->getType();
7222   if (!CharType->isAnyCharacterType() &&
7223       CharType->isIntegerType() &&
7224       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7225     Self.Diag(OpLoc, diag::warn_string_plus_char)
7226         << DiagRange << Ctx.CharTy;
7227   } else {
7228     Self.Diag(OpLoc, diag::warn_string_plus_char)
7229         << DiagRange << CharExpr->getType();
7230   }
7231 
7232   // Only print a fixit for str + char, not for char + str.
7233   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7234     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7235     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7236         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7237         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7238         << FixItHint::CreateInsertion(EndLoc, "]");
7239   } else {
7240     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7241   }
7242 }
7243 
7244 /// \brief Emit error when two pointers are incompatible.
diagnosePointerIncompatibility(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)7245 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7246                                            Expr *LHSExpr, Expr *RHSExpr) {
7247   assert(LHSExpr->getType()->isAnyPointerType());
7248   assert(RHSExpr->getType()->isAnyPointerType());
7249   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7250     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7251     << RHSExpr->getSourceRange();
7252 }
7253 
CheckAdditionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,unsigned Opc,QualType * CompLHSTy)7254 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7255     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7256     QualType* CompLHSTy) {
7257   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7258 
7259   if (LHS.get()->getType()->isVectorType() ||
7260       RHS.get()->getType()->isVectorType()) {
7261     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7262     if (CompLHSTy) *CompLHSTy = compType;
7263     return compType;
7264   }
7265 
7266   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7267   if (LHS.isInvalid() || RHS.isInvalid())
7268     return QualType();
7269 
7270   // Diagnose "string literal" '+' int and string '+' "char literal".
7271   if (Opc == BO_Add) {
7272     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7273     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7274   }
7275 
7276   // handle the common case first (both operands are arithmetic).
7277   if (!compType.isNull() && compType->isArithmeticType()) {
7278     if (CompLHSTy) *CompLHSTy = compType;
7279     return compType;
7280   }
7281 
7282   // Type-checking.  Ultimately the pointer's going to be in PExp;
7283   // note that we bias towards the LHS being the pointer.
7284   Expr *PExp = LHS.get(), *IExp = RHS.get();
7285 
7286   bool isObjCPointer;
7287   if (PExp->getType()->isPointerType()) {
7288     isObjCPointer = false;
7289   } else if (PExp->getType()->isObjCObjectPointerType()) {
7290     isObjCPointer = true;
7291   } else {
7292     std::swap(PExp, IExp);
7293     if (PExp->getType()->isPointerType()) {
7294       isObjCPointer = false;
7295     } else if (PExp->getType()->isObjCObjectPointerType()) {
7296       isObjCPointer = true;
7297     } else {
7298       return InvalidOperands(Loc, LHS, RHS);
7299     }
7300   }
7301   assert(PExp->getType()->isAnyPointerType());
7302 
7303   if (!IExp->getType()->isIntegerType())
7304     return InvalidOperands(Loc, LHS, RHS);
7305 
7306   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7307     return QualType();
7308 
7309   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7310     return QualType();
7311 
7312   // Check array bounds for pointer arithemtic
7313   CheckArrayAccess(PExp, IExp);
7314 
7315   if (CompLHSTy) {
7316     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7317     if (LHSTy.isNull()) {
7318       LHSTy = LHS.get()->getType();
7319       if (LHSTy->isPromotableIntegerType())
7320         LHSTy = Context.getPromotedIntegerType(LHSTy);
7321     }
7322     *CompLHSTy = LHSTy;
7323   }
7324 
7325   return PExp->getType();
7326 }
7327 
7328 // C99 6.5.6
CheckSubtractionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,QualType * CompLHSTy)7329 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7330                                         SourceLocation Loc,
7331                                         QualType* CompLHSTy) {
7332   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7333 
7334   if (LHS.get()->getType()->isVectorType() ||
7335       RHS.get()->getType()->isVectorType()) {
7336     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7337     if (CompLHSTy) *CompLHSTy = compType;
7338     return compType;
7339   }
7340 
7341   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7342   if (LHS.isInvalid() || RHS.isInvalid())
7343     return QualType();
7344 
7345   // Enforce type constraints: C99 6.5.6p3.
7346 
7347   // Handle the common case first (both operands are arithmetic).
7348   if (!compType.isNull() && compType->isArithmeticType()) {
7349     if (CompLHSTy) *CompLHSTy = compType;
7350     return compType;
7351   }
7352 
7353   // Either ptr - int   or   ptr - ptr.
7354   if (LHS.get()->getType()->isAnyPointerType()) {
7355     QualType lpointee = LHS.get()->getType()->getPointeeType();
7356 
7357     // Diagnose bad cases where we step over interface counts.
7358     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7359         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7360       return QualType();
7361 
7362     // The result type of a pointer-int computation is the pointer type.
7363     if (RHS.get()->getType()->isIntegerType()) {
7364       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7365         return QualType();
7366 
7367       // Check array bounds for pointer arithemtic
7368       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
7369                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7370 
7371       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7372       return LHS.get()->getType();
7373     }
7374 
7375     // Handle pointer-pointer subtractions.
7376     if (const PointerType *RHSPTy
7377           = RHS.get()->getType()->getAs<PointerType>()) {
7378       QualType rpointee = RHSPTy->getPointeeType();
7379 
7380       if (getLangOpts().CPlusPlus) {
7381         // Pointee types must be the same: C++ [expr.add]
7382         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7383           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7384         }
7385       } else {
7386         // Pointee types must be compatible C99 6.5.6p3
7387         if (!Context.typesAreCompatible(
7388                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7389                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7390           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7391           return QualType();
7392         }
7393       }
7394 
7395       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7396                                                LHS.get(), RHS.get()))
7397         return QualType();
7398 
7399       // The pointee type may have zero size.  As an extension, a structure or
7400       // union may have zero size or an array may have zero length.  In this
7401       // case subtraction does not make sense.
7402       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7403         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7404         if (ElementSize.isZero()) {
7405           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7406             << rpointee.getUnqualifiedType()
7407             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7408         }
7409       }
7410 
7411       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7412       return Context.getPointerDiffType();
7413     }
7414   }
7415 
7416   return InvalidOperands(Loc, LHS, RHS);
7417 }
7418 
isScopedEnumerationType(QualType T)7419 static bool isScopedEnumerationType(QualType T) {
7420   if (const EnumType *ET = dyn_cast<EnumType>(T))
7421     return ET->getDecl()->isScoped();
7422   return false;
7423 }
7424 
DiagnoseBadShiftValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,unsigned Opc,QualType LHSType)7425 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7426                                    SourceLocation Loc, unsigned Opc,
7427                                    QualType LHSType) {
7428   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7429   // so skip remaining warnings as we don't want to modify values within Sema.
7430   if (S.getLangOpts().OpenCL)
7431     return;
7432 
7433   llvm::APSInt Right;
7434   // Check right/shifter operand
7435   if (RHS.get()->isValueDependent() ||
7436       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7437     return;
7438 
7439   if (Right.isNegative()) {
7440     S.DiagRuntimeBehavior(Loc, RHS.get(),
7441                           S.PDiag(diag::warn_shift_negative)
7442                             << RHS.get()->getSourceRange());
7443     return;
7444   }
7445   llvm::APInt LeftBits(Right.getBitWidth(),
7446                        S.Context.getTypeSize(LHS.get()->getType()));
7447   if (Right.uge(LeftBits)) {
7448     S.DiagRuntimeBehavior(Loc, RHS.get(),
7449                           S.PDiag(diag::warn_shift_gt_typewidth)
7450                             << RHS.get()->getSourceRange());
7451     return;
7452   }
7453   if (Opc != BO_Shl)
7454     return;
7455 
7456   // When left shifting an ICE which is signed, we can check for overflow which
7457   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7458   // integers have defined behavior modulo one more than the maximum value
7459   // representable in the result type, so never warn for those.
7460   llvm::APSInt Left;
7461   if (LHS.get()->isValueDependent() ||
7462       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7463       LHSType->hasUnsignedIntegerRepresentation())
7464     return;
7465   llvm::APInt ResultBits =
7466       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7467   if (LeftBits.uge(ResultBits))
7468     return;
7469   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7470   Result = Result.shl(Right);
7471 
7472   // Print the bit representation of the signed integer as an unsigned
7473   // hexadecimal number.
7474   SmallString<40> HexResult;
7475   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7476 
7477   // If we are only missing a sign bit, this is less likely to result in actual
7478   // bugs -- if the result is cast back to an unsigned type, it will have the
7479   // expected value. Thus we place this behind a different warning that can be
7480   // turned off separately if needed.
7481   if (LeftBits == ResultBits - 1) {
7482     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7483         << HexResult.str() << LHSType
7484         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7485     return;
7486   }
7487 
7488   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7489     << HexResult.str() << Result.getMinSignedBits() << LHSType
7490     << Left.getBitWidth() << LHS.get()->getSourceRange()
7491     << RHS.get()->getSourceRange();
7492 }
7493 
7494 // C99 6.5.7
CheckShiftOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,unsigned Opc,bool IsCompAssign)7495 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7496                                   SourceLocation Loc, unsigned Opc,
7497                                   bool IsCompAssign) {
7498   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7499 
7500   // Vector shifts promote their scalar inputs to vector type.
7501   if (LHS.get()->getType()->isVectorType() ||
7502       RHS.get()->getType()->isVectorType())
7503     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7504 
7505   // Shifts don't perform usual arithmetic conversions, they just do integer
7506   // promotions on each operand. C99 6.5.7p3
7507 
7508   // For the LHS, do usual unary conversions, but then reset them away
7509   // if this is a compound assignment.
7510   ExprResult OldLHS = LHS;
7511   LHS = UsualUnaryConversions(LHS.get());
7512   if (LHS.isInvalid())
7513     return QualType();
7514   QualType LHSType = LHS.get()->getType();
7515   if (IsCompAssign) LHS = OldLHS;
7516 
7517   // The RHS is simpler.
7518   RHS = UsualUnaryConversions(RHS.get());
7519   if (RHS.isInvalid())
7520     return QualType();
7521   QualType RHSType = RHS.get()->getType();
7522 
7523   // C99 6.5.7p2: Each of the operands shall have integer type.
7524   if (!LHSType->hasIntegerRepresentation() ||
7525       !RHSType->hasIntegerRepresentation())
7526     return InvalidOperands(Loc, LHS, RHS);
7527 
7528   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7529   // hasIntegerRepresentation() above instead of this.
7530   if (isScopedEnumerationType(LHSType) ||
7531       isScopedEnumerationType(RHSType)) {
7532     return InvalidOperands(Loc, LHS, RHS);
7533   }
7534   // Sanity-check shift operands
7535   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7536 
7537   // "The type of the result is that of the promoted left operand."
7538   return LHSType;
7539 }
7540 
IsWithinTemplateSpecialization(Decl * D)7541 static bool IsWithinTemplateSpecialization(Decl *D) {
7542   if (DeclContext *DC = D->getDeclContext()) {
7543     if (isa<ClassTemplateSpecializationDecl>(DC))
7544       return true;
7545     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7546       return FD->isFunctionTemplateSpecialization();
7547   }
7548   return false;
7549 }
7550 
7551 /// If two different enums are compared, raise a warning.
checkEnumComparison(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)7552 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7553                                 Expr *RHS) {
7554   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7555   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7556 
7557   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7558   if (!LHSEnumType)
7559     return;
7560   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7561   if (!RHSEnumType)
7562     return;
7563 
7564   // Ignore anonymous enums.
7565   if (!LHSEnumType->getDecl()->getIdentifier())
7566     return;
7567   if (!RHSEnumType->getDecl()->getIdentifier())
7568     return;
7569 
7570   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7571     return;
7572 
7573   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7574       << LHSStrippedType << RHSStrippedType
7575       << LHS->getSourceRange() << RHS->getSourceRange();
7576 }
7577 
7578 /// \brief Diagnose bad pointer comparisons.
diagnoseDistinctPointerComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)7579 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7580                                               ExprResult &LHS, ExprResult &RHS,
7581                                               bool IsError) {
7582   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7583                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7584     << LHS.get()->getType() << RHS.get()->getType()
7585     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7586 }
7587 
7588 /// \brief Returns false if the pointers are converted to a composite type,
7589 /// true otherwise.
convertPointersToCompositeType(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)7590 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7591                                            ExprResult &LHS, ExprResult &RHS) {
7592   // C++ [expr.rel]p2:
7593   //   [...] Pointer conversions (4.10) and qualification
7594   //   conversions (4.4) are performed on pointer operands (or on
7595   //   a pointer operand and a null pointer constant) to bring
7596   //   them to their composite pointer type. [...]
7597   //
7598   // C++ [expr.eq]p1 uses the same notion for (in)equality
7599   // comparisons of pointers.
7600 
7601   // C++ [expr.eq]p2:
7602   //   In addition, pointers to members can be compared, or a pointer to
7603   //   member and a null pointer constant. Pointer to member conversions
7604   //   (4.11) and qualification conversions (4.4) are performed to bring
7605   //   them to a common type. If one operand is a null pointer constant,
7606   //   the common type is the type of the other operand. Otherwise, the
7607   //   common type is a pointer to member type similar (4.4) to the type
7608   //   of one of the operands, with a cv-qualification signature (4.4)
7609   //   that is the union of the cv-qualification signatures of the operand
7610   //   types.
7611 
7612   QualType LHSType = LHS.get()->getType();
7613   QualType RHSType = RHS.get()->getType();
7614   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7615          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7616 
7617   bool NonStandardCompositeType = false;
7618   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
7619   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7620   if (T.isNull()) {
7621     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7622     return true;
7623   }
7624 
7625   if (NonStandardCompositeType)
7626     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7627       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7628       << RHS.get()->getSourceRange();
7629 
7630   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
7631   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
7632   return false;
7633 }
7634 
diagnoseFunctionPointerToVoidComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)7635 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7636                                                     ExprResult &LHS,
7637                                                     ExprResult &RHS,
7638                                                     bool IsError) {
7639   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7640                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7641     << LHS.get()->getType() << RHS.get()->getType()
7642     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7643 }
7644 
isObjCObjectLiteral(ExprResult & E)7645 static bool isObjCObjectLiteral(ExprResult &E) {
7646   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7647   case Stmt::ObjCArrayLiteralClass:
7648   case Stmt::ObjCDictionaryLiteralClass:
7649   case Stmt::ObjCStringLiteralClass:
7650   case Stmt::ObjCBoxedExprClass:
7651     return true;
7652   default:
7653     // Note that ObjCBoolLiteral is NOT an object literal!
7654     return false;
7655   }
7656 }
7657 
hasIsEqualMethod(Sema & S,const Expr * LHS,const Expr * RHS)7658 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7659   const ObjCObjectPointerType *Type =
7660     LHS->getType()->getAs<ObjCObjectPointerType>();
7661 
7662   // If this is not actually an Objective-C object, bail out.
7663   if (!Type)
7664     return false;
7665 
7666   // Get the LHS object's interface type.
7667   QualType InterfaceType = Type->getPointeeType();
7668   if (const ObjCObjectType *iQFaceTy =
7669       InterfaceType->getAsObjCQualifiedInterfaceType())
7670     InterfaceType = iQFaceTy->getBaseType();
7671 
7672   // If the RHS isn't an Objective-C object, bail out.
7673   if (!RHS->getType()->isObjCObjectPointerType())
7674     return false;
7675 
7676   // Try to find the -isEqual: method.
7677   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7678   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7679                                                       InterfaceType,
7680                                                       /*instance=*/true);
7681   if (!Method) {
7682     if (Type->isObjCIdType()) {
7683       // For 'id', just check the global pool.
7684       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7685                                                   /*receiverId=*/true,
7686                                                   /*warn=*/false);
7687     } else {
7688       // Check protocols.
7689       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7690                                              /*instance=*/true);
7691     }
7692   }
7693 
7694   if (!Method)
7695     return false;
7696 
7697   QualType T = Method->parameters()[0]->getType();
7698   if (!T->isObjCObjectPointerType())
7699     return false;
7700 
7701   QualType R = Method->getReturnType();
7702   if (!R->isScalarType())
7703     return false;
7704 
7705   return true;
7706 }
7707 
CheckLiteralKind(Expr * FromE)7708 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7709   FromE = FromE->IgnoreParenImpCasts();
7710   switch (FromE->getStmtClass()) {
7711     default:
7712       break;
7713     case Stmt::ObjCStringLiteralClass:
7714       // "string literal"
7715       return LK_String;
7716     case Stmt::ObjCArrayLiteralClass:
7717       // "array literal"
7718       return LK_Array;
7719     case Stmt::ObjCDictionaryLiteralClass:
7720       // "dictionary literal"
7721       return LK_Dictionary;
7722     case Stmt::BlockExprClass:
7723       return LK_Block;
7724     case Stmt::ObjCBoxedExprClass: {
7725       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7726       switch (Inner->getStmtClass()) {
7727         case Stmt::IntegerLiteralClass:
7728         case Stmt::FloatingLiteralClass:
7729         case Stmt::CharacterLiteralClass:
7730         case Stmt::ObjCBoolLiteralExprClass:
7731         case Stmt::CXXBoolLiteralExprClass:
7732           // "numeric literal"
7733           return LK_Numeric;
7734         case Stmt::ImplicitCastExprClass: {
7735           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7736           // Boolean literals can be represented by implicit casts.
7737           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7738             return LK_Numeric;
7739           break;
7740         }
7741         default:
7742           break;
7743       }
7744       return LK_Boxed;
7745     }
7746   }
7747   return LK_None;
7748 }
7749 
diagnoseObjCLiteralComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,BinaryOperator::Opcode Opc)7750 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7751                                           ExprResult &LHS, ExprResult &RHS,
7752                                           BinaryOperator::Opcode Opc){
7753   Expr *Literal;
7754   Expr *Other;
7755   if (isObjCObjectLiteral(LHS)) {
7756     Literal = LHS.get();
7757     Other = RHS.get();
7758   } else {
7759     Literal = RHS.get();
7760     Other = LHS.get();
7761   }
7762 
7763   // Don't warn on comparisons against nil.
7764   Other = Other->IgnoreParenCasts();
7765   if (Other->isNullPointerConstant(S.getASTContext(),
7766                                    Expr::NPC_ValueDependentIsNotNull))
7767     return;
7768 
7769   // This should be kept in sync with warn_objc_literal_comparison.
7770   // LK_String should always be after the other literals, since it has its own
7771   // warning flag.
7772   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7773   assert(LiteralKind != Sema::LK_Block);
7774   if (LiteralKind == Sema::LK_None) {
7775     llvm_unreachable("Unknown Objective-C object literal kind");
7776   }
7777 
7778   if (LiteralKind == Sema::LK_String)
7779     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7780       << Literal->getSourceRange();
7781   else
7782     S.Diag(Loc, diag::warn_objc_literal_comparison)
7783       << LiteralKind << Literal->getSourceRange();
7784 
7785   if (BinaryOperator::isEqualityOp(Opc) &&
7786       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7787     SourceLocation Start = LHS.get()->getLocStart();
7788     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7789     CharSourceRange OpRange =
7790       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7791 
7792     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7793       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7794       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7795       << FixItHint::CreateInsertion(End, "]");
7796   }
7797 }
7798 
diagnoseLogicalNotOnLHSofComparison(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,unsigned OpaqueOpc)7799 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7800                                                 ExprResult &RHS,
7801                                                 SourceLocation Loc,
7802                                                 unsigned OpaqueOpc) {
7803   // This checking requires bools.
7804   if (!S.getLangOpts().Bool) return;
7805 
7806   // Check that left hand side is !something.
7807   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7808   if (!UO || UO->getOpcode() != UO_LNot) return;
7809 
7810   // Only check if the right hand side is non-bool arithmetic type.
7811   if (RHS.get()->getType()->isBooleanType()) return;
7812 
7813   // Make sure that the something in !something is not bool.
7814   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7815   if (SubExpr->getType()->isBooleanType()) return;
7816 
7817   // Emit warning.
7818   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7819       << Loc;
7820 
7821   // First note suggest !(x < y)
7822   SourceLocation FirstOpen = SubExpr->getLocStart();
7823   SourceLocation FirstClose = RHS.get()->getLocEnd();
7824   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7825   if (FirstClose.isInvalid())
7826     FirstOpen = SourceLocation();
7827   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7828       << FixItHint::CreateInsertion(FirstOpen, "(")
7829       << FixItHint::CreateInsertion(FirstClose, ")");
7830 
7831   // Second note suggests (!x) < y
7832   SourceLocation SecondOpen = LHS.get()->getLocStart();
7833   SourceLocation SecondClose = LHS.get()->getLocEnd();
7834   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7835   if (SecondClose.isInvalid())
7836     SecondOpen = SourceLocation();
7837   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7838       << FixItHint::CreateInsertion(SecondOpen, "(")
7839       << FixItHint::CreateInsertion(SecondClose, ")");
7840 }
7841 
7842 // Get the decl for a simple expression: a reference to a variable,
7843 // an implicit C++ field reference, or an implicit ObjC ivar reference.
getCompareDecl(Expr * E)7844 static ValueDecl *getCompareDecl(Expr *E) {
7845   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7846     return DR->getDecl();
7847   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7848     if (Ivar->isFreeIvar())
7849       return Ivar->getDecl();
7850   }
7851   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7852     if (Mem->isImplicitAccess())
7853       return Mem->getMemberDecl();
7854   }
7855   return nullptr;
7856 }
7857 
7858 // C99 6.5.8, C++ [expr.rel]
CheckCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,unsigned OpaqueOpc,bool IsRelational)7859 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7860                                     SourceLocation Loc, unsigned OpaqueOpc,
7861                                     bool IsRelational) {
7862   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7863 
7864   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7865 
7866   // Handle vector comparisons separately.
7867   if (LHS.get()->getType()->isVectorType() ||
7868       RHS.get()->getType()->isVectorType())
7869     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7870 
7871   QualType LHSType = LHS.get()->getType();
7872   QualType RHSType = RHS.get()->getType();
7873 
7874   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7875   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7876 
7877   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7878   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7879 
7880   if (!LHSType->hasFloatingRepresentation() &&
7881       !(LHSType->isBlockPointerType() && IsRelational) &&
7882       !LHS.get()->getLocStart().isMacroID() &&
7883       !RHS.get()->getLocStart().isMacroID() &&
7884       ActiveTemplateInstantiations.empty()) {
7885     // For non-floating point types, check for self-comparisons of the form
7886     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7887     // often indicate logic errors in the program.
7888     //
7889     // NOTE: Don't warn about comparison expressions resulting from macro
7890     // expansion. Also don't warn about comparisons which are only self
7891     // comparisons within a template specialization. The warnings should catch
7892     // obvious cases in the definition of the template anyways. The idea is to
7893     // warn when the typed comparison operator will always evaluate to the same
7894     // result.
7895     ValueDecl *DL = getCompareDecl(LHSStripped);
7896     ValueDecl *DR = getCompareDecl(RHSStripped);
7897     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7898       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
7899                           << 0 // self-
7900                           << (Opc == BO_EQ
7901                               || Opc == BO_LE
7902                               || Opc == BO_GE));
7903     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7904                !DL->getType()->isReferenceType() &&
7905                !DR->getType()->isReferenceType()) {
7906         // what is it always going to eval to?
7907         char always_evals_to;
7908         switch(Opc) {
7909         case BO_EQ: // e.g. array1 == array2
7910           always_evals_to = 0; // false
7911           break;
7912         case BO_NE: // e.g. array1 != array2
7913           always_evals_to = 1; // true
7914           break;
7915         default:
7916           // best we can say is 'a constant'
7917           always_evals_to = 2; // e.g. array1 <= array2
7918           break;
7919         }
7920         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
7921                             << 1 // array
7922                             << always_evals_to);
7923     }
7924 
7925     if (isa<CastExpr>(LHSStripped))
7926       LHSStripped = LHSStripped->IgnoreParenCasts();
7927     if (isa<CastExpr>(RHSStripped))
7928       RHSStripped = RHSStripped->IgnoreParenCasts();
7929 
7930     // Warn about comparisons against a string constant (unless the other
7931     // operand is null), the user probably wants strcmp.
7932     Expr *literalString = nullptr;
7933     Expr *literalStringStripped = nullptr;
7934     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7935         !RHSStripped->isNullPointerConstant(Context,
7936                                             Expr::NPC_ValueDependentIsNull)) {
7937       literalString = LHS.get();
7938       literalStringStripped = LHSStripped;
7939     } else if ((isa<StringLiteral>(RHSStripped) ||
7940                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7941                !LHSStripped->isNullPointerConstant(Context,
7942                                             Expr::NPC_ValueDependentIsNull)) {
7943       literalString = RHS.get();
7944       literalStringStripped = RHSStripped;
7945     }
7946 
7947     if (literalString) {
7948       DiagRuntimeBehavior(Loc, nullptr,
7949         PDiag(diag::warn_stringcompare)
7950           << isa<ObjCEncodeExpr>(literalStringStripped)
7951           << literalString->getSourceRange());
7952     }
7953   }
7954 
7955   // C99 6.5.8p3 / C99 6.5.9p4
7956   UsualArithmeticConversions(LHS, RHS);
7957   if (LHS.isInvalid() || RHS.isInvalid())
7958     return QualType();
7959 
7960   LHSType = LHS.get()->getType();
7961   RHSType = RHS.get()->getType();
7962 
7963   // The result of comparisons is 'bool' in C++, 'int' in C.
7964   QualType ResultTy = Context.getLogicalOperationType();
7965 
7966   if (IsRelational) {
7967     if (LHSType->isRealType() && RHSType->isRealType())
7968       return ResultTy;
7969   } else {
7970     // Check for comparisons of floating point operands using != and ==.
7971     if (LHSType->hasFloatingRepresentation())
7972       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7973 
7974     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7975       return ResultTy;
7976   }
7977 
7978   const Expr::NullPointerConstantKind LHSNullKind =
7979       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7980   const Expr::NullPointerConstantKind RHSNullKind =
7981       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7982   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
7983   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
7984 
7985   if (!IsRelational && LHSIsNull != RHSIsNull) {
7986     bool IsEquality = Opc == BO_EQ;
7987     if (RHSIsNull)
7988       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
7989                                    RHS.get()->getSourceRange());
7990     else
7991       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
7992                                    LHS.get()->getSourceRange());
7993   }
7994 
7995   // All of the following pointer-related warnings are GCC extensions, except
7996   // when handling null pointer constants.
7997   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7998     QualType LCanPointeeTy =
7999       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8000     QualType RCanPointeeTy =
8001       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8002 
8003     if (getLangOpts().CPlusPlus) {
8004       if (LCanPointeeTy == RCanPointeeTy)
8005         return ResultTy;
8006       if (!IsRelational &&
8007           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8008         // Valid unless comparison between non-null pointer and function pointer
8009         // This is a gcc extension compatibility comparison.
8010         // In a SFINAE context, we treat this as a hard error to maintain
8011         // conformance with the C++ standard.
8012         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8013             && !LHSIsNull && !RHSIsNull) {
8014           diagnoseFunctionPointerToVoidComparison(
8015               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
8016 
8017           if (isSFINAEContext())
8018             return QualType();
8019 
8020           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8021           return ResultTy;
8022         }
8023       }
8024 
8025       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8026         return QualType();
8027       else
8028         return ResultTy;
8029     }
8030     // C99 6.5.9p2 and C99 6.5.8p2
8031     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8032                                    RCanPointeeTy.getUnqualifiedType())) {
8033       // Valid unless a relational comparison of function pointers
8034       if (IsRelational && LCanPointeeTy->isFunctionType()) {
8035         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
8036           << LHSType << RHSType << LHS.get()->getSourceRange()
8037           << RHS.get()->getSourceRange();
8038       }
8039     } else if (!IsRelational &&
8040                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8041       // Valid unless comparison between non-null pointer and function pointer
8042       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8043           && !LHSIsNull && !RHSIsNull)
8044         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
8045                                                 /*isError*/false);
8046     } else {
8047       // Invalid
8048       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
8049     }
8050     if (LCanPointeeTy != RCanPointeeTy) {
8051       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8052       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8053       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8054                                                : CK_BitCast;
8055       if (LHSIsNull && !RHSIsNull)
8056         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
8057       else
8058         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
8059     }
8060     return ResultTy;
8061   }
8062 
8063   if (getLangOpts().CPlusPlus) {
8064     // Comparison of nullptr_t with itself.
8065     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
8066       return ResultTy;
8067 
8068     // Comparison of pointers with null pointer constants and equality
8069     // comparisons of member pointers to null pointer constants.
8070     if (RHSIsNull &&
8071         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
8072          (!IsRelational &&
8073           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
8074       RHS = ImpCastExprToType(RHS.get(), LHSType,
8075                         LHSType->isMemberPointerType()
8076                           ? CK_NullToMemberPointer
8077                           : CK_NullToPointer);
8078       return ResultTy;
8079     }
8080     if (LHSIsNull &&
8081         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
8082          (!IsRelational &&
8083           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
8084       LHS = ImpCastExprToType(LHS.get(), RHSType,
8085                         RHSType->isMemberPointerType()
8086                           ? CK_NullToMemberPointer
8087                           : CK_NullToPointer);
8088       return ResultTy;
8089     }
8090 
8091     // Comparison of member pointers.
8092     if (!IsRelational &&
8093         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8094       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8095         return QualType();
8096       else
8097         return ResultTy;
8098     }
8099 
8100     // Handle scoped enumeration types specifically, since they don't promote
8101     // to integers.
8102     if (LHS.get()->getType()->isEnumeralType() &&
8103         Context.hasSameUnqualifiedType(LHS.get()->getType(),
8104                                        RHS.get()->getType()))
8105       return ResultTy;
8106   }
8107 
8108   // Handle block pointer types.
8109   if (!IsRelational && LHSType->isBlockPointerType() &&
8110       RHSType->isBlockPointerType()) {
8111     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8112     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8113 
8114     if (!LHSIsNull && !RHSIsNull &&
8115         !Context.typesAreCompatible(lpointee, rpointee)) {
8116       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8117         << LHSType << RHSType << LHS.get()->getSourceRange()
8118         << RHS.get()->getSourceRange();
8119     }
8120     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8121     return ResultTy;
8122   }
8123 
8124   // Allow block pointers to be compared with null pointer constants.
8125   if (!IsRelational
8126       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8127           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8128     if (!LHSIsNull && !RHSIsNull) {
8129       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8130              ->getPointeeType()->isVoidType())
8131             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8132                 ->getPointeeType()->isVoidType())))
8133         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8134           << LHSType << RHSType << LHS.get()->getSourceRange()
8135           << RHS.get()->getSourceRange();
8136     }
8137     if (LHSIsNull && !RHSIsNull)
8138       LHS = ImpCastExprToType(LHS.get(), RHSType,
8139                               RHSType->isPointerType() ? CK_BitCast
8140                                 : CK_AnyPointerToBlockPointerCast);
8141     else
8142       RHS = ImpCastExprToType(RHS.get(), LHSType,
8143                               LHSType->isPointerType() ? CK_BitCast
8144                                 : CK_AnyPointerToBlockPointerCast);
8145     return ResultTy;
8146   }
8147 
8148   if (LHSType->isObjCObjectPointerType() ||
8149       RHSType->isObjCObjectPointerType()) {
8150     const PointerType *LPT = LHSType->getAs<PointerType>();
8151     const PointerType *RPT = RHSType->getAs<PointerType>();
8152     if (LPT || RPT) {
8153       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8154       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8155 
8156       if (!LPtrToVoid && !RPtrToVoid &&
8157           !Context.typesAreCompatible(LHSType, RHSType)) {
8158         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8159                                           /*isError*/false);
8160       }
8161       if (LHSIsNull && !RHSIsNull) {
8162         Expr *E = LHS.get();
8163         if (getLangOpts().ObjCAutoRefCount)
8164           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8165         LHS = ImpCastExprToType(E, RHSType,
8166                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8167       }
8168       else {
8169         Expr *E = RHS.get();
8170         if (getLangOpts().ObjCAutoRefCount)
8171           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8172                                  Opc);
8173         RHS = ImpCastExprToType(E, LHSType,
8174                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8175       }
8176       return ResultTy;
8177     }
8178     if (LHSType->isObjCObjectPointerType() &&
8179         RHSType->isObjCObjectPointerType()) {
8180       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8181         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8182                                           /*isError*/false);
8183       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8184         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8185 
8186       if (LHSIsNull && !RHSIsNull)
8187         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8188       else
8189         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8190       return ResultTy;
8191     }
8192   }
8193   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8194       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8195     unsigned DiagID = 0;
8196     bool isError = false;
8197     if (LangOpts.DebuggerSupport) {
8198       // Under a debugger, allow the comparison of pointers to integers,
8199       // since users tend to want to compare addresses.
8200     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8201         (RHSIsNull && RHSType->isIntegerType())) {
8202       if (IsRelational && !getLangOpts().CPlusPlus)
8203         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8204     } else if (IsRelational && !getLangOpts().CPlusPlus)
8205       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8206     else if (getLangOpts().CPlusPlus) {
8207       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8208       isError = true;
8209     } else
8210       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8211 
8212     if (DiagID) {
8213       Diag(Loc, DiagID)
8214         << LHSType << RHSType << LHS.get()->getSourceRange()
8215         << RHS.get()->getSourceRange();
8216       if (isError)
8217         return QualType();
8218     }
8219 
8220     if (LHSType->isIntegerType())
8221       LHS = ImpCastExprToType(LHS.get(), RHSType,
8222                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8223     else
8224       RHS = ImpCastExprToType(RHS.get(), LHSType,
8225                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8226     return ResultTy;
8227   }
8228 
8229   // Handle block pointers.
8230   if (!IsRelational && RHSIsNull
8231       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8232     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8233     return ResultTy;
8234   }
8235   if (!IsRelational && LHSIsNull
8236       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8237     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
8238     return ResultTy;
8239   }
8240 
8241   return InvalidOperands(Loc, LHS, RHS);
8242 }
8243 
8244 
8245 // Return a signed type that is of identical size and number of elements.
8246 // For floating point vectors, return an integer type of identical size
8247 // and number of elements.
GetSignedVectorType(QualType V)8248 QualType Sema::GetSignedVectorType(QualType V) {
8249   const VectorType *VTy = V->getAs<VectorType>();
8250   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8251   if (TypeSize == Context.getTypeSize(Context.CharTy))
8252     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8253   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8254     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8255   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8256     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8257   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8258     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8259   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8260          "Unhandled vector element size in vector compare");
8261   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8262 }
8263 
8264 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8265 /// operates on extended vector types.  Instead of producing an IntTy result,
8266 /// like a scalar comparison, a vector comparison produces a vector of integer
8267 /// types.
CheckVectorCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsRelational)8268 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8269                                           SourceLocation Loc,
8270                                           bool IsRelational) {
8271   // Check to make sure we're operating on vectors of the same type and width,
8272   // Allowing one side to be a scalar of element type.
8273   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8274   if (vType.isNull())
8275     return vType;
8276 
8277   QualType LHSType = LHS.get()->getType();
8278 
8279   // If AltiVec, the comparison results in a numeric type, i.e.
8280   // bool for C++, int for C
8281   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8282     return Context.getLogicalOperationType();
8283 
8284   // For non-floating point types, check for self-comparisons of the form
8285   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8286   // often indicate logic errors in the program.
8287   if (!LHSType->hasFloatingRepresentation() &&
8288       ActiveTemplateInstantiations.empty()) {
8289     if (DeclRefExpr* DRL
8290           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8291       if (DeclRefExpr* DRR
8292             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8293         if (DRL->getDecl() == DRR->getDecl())
8294           DiagRuntimeBehavior(Loc, nullptr,
8295                               PDiag(diag::warn_comparison_always)
8296                                 << 0 // self-
8297                                 << 2 // "a constant"
8298                               );
8299   }
8300 
8301   // Check for comparisons of floating point operands using != and ==.
8302   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8303     assert (RHS.get()->getType()->hasFloatingRepresentation());
8304     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8305   }
8306 
8307   // Return a signed type for the vector.
8308   return GetSignedVectorType(LHSType);
8309 }
8310 
CheckVectorLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)8311 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8312                                           SourceLocation Loc) {
8313   // Ensure that either both operands are of the same vector type, or
8314   // one operand is of a vector type and the other is of its element type.
8315   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8316   if (vType.isNull())
8317     return InvalidOperands(Loc, LHS, RHS);
8318   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8319       vType->hasFloatingRepresentation())
8320     return InvalidOperands(Loc, LHS, RHS);
8321 
8322   return GetSignedVectorType(LHS.get()->getType());
8323 }
8324 
CheckBitwiseOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)8325 inline QualType Sema::CheckBitwiseOperands(
8326   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8327   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8328 
8329   if (LHS.get()->getType()->isVectorType() ||
8330       RHS.get()->getType()->isVectorType()) {
8331     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8332         RHS.get()->getType()->hasIntegerRepresentation())
8333       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8334 
8335     return InvalidOperands(Loc, LHS, RHS);
8336   }
8337 
8338   ExprResult LHSResult = LHS, RHSResult = RHS;
8339   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8340                                                  IsCompAssign);
8341   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8342     return QualType();
8343   LHS = LHSResult.get();
8344   RHS = RHSResult.get();
8345 
8346   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8347     return compType;
8348   return InvalidOperands(Loc, LHS, RHS);
8349 }
8350 
CheckLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,unsigned Opc)8351 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8352   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8353 
8354   // Check vector operands differently.
8355   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8356     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8357 
8358   // Diagnose cases where the user write a logical and/or but probably meant a
8359   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8360   // is a constant.
8361   if (LHS.get()->getType()->isIntegerType() &&
8362       !LHS.get()->getType()->isBooleanType() &&
8363       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8364       // Don't warn in macros or template instantiations.
8365       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8366     // If the RHS can be constant folded, and if it constant folds to something
8367     // that isn't 0 or 1 (which indicate a potential logical operation that
8368     // happened to fold to true/false) then warn.
8369     // Parens on the RHS are ignored.
8370     llvm::APSInt Result;
8371     if (RHS.get()->EvaluateAsInt(Result, Context))
8372       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
8373            !RHS.get()->getExprLoc().isMacroID()) ||
8374           (Result != 0 && Result != 1)) {
8375         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8376           << RHS.get()->getSourceRange()
8377           << (Opc == BO_LAnd ? "&&" : "||");
8378         // Suggest replacing the logical operator with the bitwise version
8379         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8380             << (Opc == BO_LAnd ? "&" : "|")
8381             << FixItHint::CreateReplacement(SourceRange(
8382                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8383                                                 getLangOpts())),
8384                                             Opc == BO_LAnd ? "&" : "|");
8385         if (Opc == BO_LAnd)
8386           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8387           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8388               << FixItHint::CreateRemoval(
8389                   SourceRange(
8390                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8391                                                  0, getSourceManager(),
8392                                                  getLangOpts()),
8393                       RHS.get()->getLocEnd()));
8394       }
8395   }
8396 
8397   if (!Context.getLangOpts().CPlusPlus) {
8398     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8399     // not operate on the built-in scalar and vector float types.
8400     if (Context.getLangOpts().OpenCL &&
8401         Context.getLangOpts().OpenCLVersion < 120) {
8402       if (LHS.get()->getType()->isFloatingType() ||
8403           RHS.get()->getType()->isFloatingType())
8404         return InvalidOperands(Loc, LHS, RHS);
8405     }
8406 
8407     LHS = UsualUnaryConversions(LHS.get());
8408     if (LHS.isInvalid())
8409       return QualType();
8410 
8411     RHS = UsualUnaryConversions(RHS.get());
8412     if (RHS.isInvalid())
8413       return QualType();
8414 
8415     if (!LHS.get()->getType()->isScalarType() ||
8416         !RHS.get()->getType()->isScalarType())
8417       return InvalidOperands(Loc, LHS, RHS);
8418 
8419     return Context.IntTy;
8420   }
8421 
8422   // The following is safe because we only use this method for
8423   // non-overloadable operands.
8424 
8425   // C++ [expr.log.and]p1
8426   // C++ [expr.log.or]p1
8427   // The operands are both contextually converted to type bool.
8428   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8429   if (LHSRes.isInvalid())
8430     return InvalidOperands(Loc, LHS, RHS);
8431   LHS = LHSRes;
8432 
8433   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8434   if (RHSRes.isInvalid())
8435     return InvalidOperands(Loc, LHS, RHS);
8436   RHS = RHSRes;
8437 
8438   // C++ [expr.log.and]p2
8439   // C++ [expr.log.or]p2
8440   // The result is a bool.
8441   return Context.BoolTy;
8442 }
8443 
IsReadonlyMessage(Expr * E,Sema & S)8444 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8445   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8446   if (!ME) return false;
8447   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8448   ObjCMessageExpr *Base =
8449     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8450   if (!Base) return false;
8451   return Base->getMethodDecl() != nullptr;
8452 }
8453 
8454 /// Is the given expression (which must be 'const') a reference to a
8455 /// variable which was originally non-const, but which has become
8456 /// 'const' due to being captured within a block?
8457 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
isReferenceToNonConstCapture(Sema & S,Expr * E)8458 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8459   assert(E->isLValue() && E->getType().isConstQualified());
8460   E = E->IgnoreParens();
8461 
8462   // Must be a reference to a declaration from an enclosing scope.
8463   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8464   if (!DRE) return NCCK_None;
8465   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8466 
8467   // The declaration must be a variable which is not declared 'const'.
8468   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8469   if (!var) return NCCK_None;
8470   if (var->getType().isConstQualified()) return NCCK_None;
8471   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8472 
8473   // Decide whether the first capture was for a block or a lambda.
8474   DeclContext *DC = S.CurContext, *Prev = nullptr;
8475   while (DC != var->getDeclContext()) {
8476     Prev = DC;
8477     DC = DC->getParent();
8478   }
8479   // Unless we have an init-capture, we've gone one step too far.
8480   if (!var->isInitCapture())
8481     DC = Prev;
8482   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8483 }
8484 
8485 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8486 /// emit an error and return true.  If so, return false.
CheckForModifiableLvalue(Expr * E,SourceLocation Loc,Sema & S)8487 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8488   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8489   SourceLocation OrigLoc = Loc;
8490   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8491                                                               &Loc);
8492   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8493     IsLV = Expr::MLV_InvalidMessageExpression;
8494   if (IsLV == Expr::MLV_Valid)
8495     return false;
8496 
8497   unsigned Diag = 0;
8498   bool NeedType = false;
8499   switch (IsLV) { // C99 6.5.16p2
8500   case Expr::MLV_ConstQualified:
8501     Diag = diag::err_typecheck_assign_const;
8502 
8503     // Use a specialized diagnostic when we're assigning to an object
8504     // from an enclosing function or block.
8505     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8506       if (NCCK == NCCK_Block)
8507         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8508       else
8509         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8510       break;
8511     }
8512 
8513     // In ARC, use some specialized diagnostics for occasions where we
8514     // infer 'const'.  These are always pseudo-strong variables.
8515     if (S.getLangOpts().ObjCAutoRefCount) {
8516       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8517       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8518         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8519 
8520         // Use the normal diagnostic if it's pseudo-__strong but the
8521         // user actually wrote 'const'.
8522         if (var->isARCPseudoStrong() &&
8523             (!var->getTypeSourceInfo() ||
8524              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8525           // There are two pseudo-strong cases:
8526           //  - self
8527           ObjCMethodDecl *method = S.getCurMethodDecl();
8528           if (method && var == method->getSelfDecl())
8529             Diag = method->isClassMethod()
8530               ? diag::err_typecheck_arc_assign_self_class_method
8531               : diag::err_typecheck_arc_assign_self;
8532 
8533           //  - fast enumeration variables
8534           else
8535             Diag = diag::err_typecheck_arr_assign_enumeration;
8536 
8537           SourceRange Assign;
8538           if (Loc != OrigLoc)
8539             Assign = SourceRange(OrigLoc, OrigLoc);
8540           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8541           // We need to preserve the AST regardless, so migration tool
8542           // can do its job.
8543           return false;
8544         }
8545       }
8546     }
8547 
8548     break;
8549   case Expr::MLV_ArrayType:
8550   case Expr::MLV_ArrayTemporary:
8551     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8552     NeedType = true;
8553     break;
8554   case Expr::MLV_NotObjectType:
8555     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8556     NeedType = true;
8557     break;
8558   case Expr::MLV_LValueCast:
8559     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8560     break;
8561   case Expr::MLV_Valid:
8562     llvm_unreachable("did not take early return for MLV_Valid");
8563   case Expr::MLV_InvalidExpression:
8564   case Expr::MLV_MemberFunction:
8565   case Expr::MLV_ClassTemporary:
8566     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8567     break;
8568   case Expr::MLV_IncompleteType:
8569   case Expr::MLV_IncompleteVoidType:
8570     return S.RequireCompleteType(Loc, E->getType(),
8571              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8572   case Expr::MLV_DuplicateVectorComponents:
8573     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8574     break;
8575   case Expr::MLV_NoSetterProperty:
8576     llvm_unreachable("readonly properties should be processed differently");
8577   case Expr::MLV_InvalidMessageExpression:
8578     Diag = diag::error_readonly_message_assignment;
8579     break;
8580   case Expr::MLV_SubObjCPropertySetting:
8581     Diag = diag::error_no_subobject_property_setting;
8582     break;
8583   }
8584 
8585   SourceRange Assign;
8586   if (Loc != OrigLoc)
8587     Assign = SourceRange(OrigLoc, OrigLoc);
8588   if (NeedType)
8589     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8590   else
8591     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8592   return true;
8593 }
8594 
CheckIdentityFieldAssignment(Expr * LHSExpr,Expr * RHSExpr,SourceLocation Loc,Sema & Sema)8595 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8596                                          SourceLocation Loc,
8597                                          Sema &Sema) {
8598   // C / C++ fields
8599   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8600   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8601   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8602     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8603       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8604   }
8605 
8606   // Objective-C instance variables
8607   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8608   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8609   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8610     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8611     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8612     if (RL && RR && RL->getDecl() == RR->getDecl())
8613       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8614   }
8615 }
8616 
8617 // C99 6.5.16.1
CheckAssignmentOperands(Expr * LHSExpr,ExprResult & RHS,SourceLocation Loc,QualType CompoundType)8618 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8619                                        SourceLocation Loc,
8620                                        QualType CompoundType) {
8621   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8622 
8623   // Verify that LHS is a modifiable lvalue, and emit error if not.
8624   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8625     return QualType();
8626 
8627   QualType LHSType = LHSExpr->getType();
8628   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8629                                              CompoundType;
8630   AssignConvertType ConvTy;
8631   if (CompoundType.isNull()) {
8632     Expr *RHSCheck = RHS.get();
8633 
8634     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8635 
8636     QualType LHSTy(LHSType);
8637     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8638     if (RHS.isInvalid())
8639       return QualType();
8640     // Special case of NSObject attributes on c-style pointer types.
8641     if (ConvTy == IncompatiblePointer &&
8642         ((Context.isObjCNSObjectType(LHSType) &&
8643           RHSType->isObjCObjectPointerType()) ||
8644          (Context.isObjCNSObjectType(RHSType) &&
8645           LHSType->isObjCObjectPointerType())))
8646       ConvTy = Compatible;
8647 
8648     if (ConvTy == Compatible &&
8649         LHSType->isObjCObjectType())
8650         Diag(Loc, diag::err_objc_object_assignment)
8651           << LHSType;
8652 
8653     // If the RHS is a unary plus or minus, check to see if they = and + are
8654     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8655     // instead of "x += 4".
8656     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8657       RHSCheck = ICE->getSubExpr();
8658     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8659       if ((UO->getOpcode() == UO_Plus ||
8660            UO->getOpcode() == UO_Minus) &&
8661           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8662           // Only if the two operators are exactly adjacent.
8663           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8664           // And there is a space or other character before the subexpr of the
8665           // unary +/-.  We don't want to warn on "x=-1".
8666           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8667           UO->getSubExpr()->getLocStart().isFileID()) {
8668         Diag(Loc, diag::warn_not_compound_assign)
8669           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8670           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8671       }
8672     }
8673 
8674     if (ConvTy == Compatible) {
8675       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8676         // Warn about retain cycles where a block captures the LHS, but
8677         // not if the LHS is a simple variable into which the block is
8678         // being stored...unless that variable can be captured by reference!
8679         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8680         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8681         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8682           checkRetainCycles(LHSExpr, RHS.get());
8683 
8684         // It is safe to assign a weak reference into a strong variable.
8685         // Although this code can still have problems:
8686         //   id x = self.weakProp;
8687         //   id y = self.weakProp;
8688         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8689         // paths through the function. This should be revisited if
8690         // -Wrepeated-use-of-weak is made flow-sensitive.
8691         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8692                              RHS.get()->getLocStart()))
8693           getCurFunction()->markSafeWeakUse(RHS.get());
8694 
8695       } else if (getLangOpts().ObjCAutoRefCount) {
8696         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8697       }
8698     }
8699   } else {
8700     // Compound assignment "x += y"
8701     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8702   }
8703 
8704   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8705                                RHS.get(), AA_Assigning))
8706     return QualType();
8707 
8708   CheckForNullPointerDereference(*this, LHSExpr);
8709 
8710   // C99 6.5.16p3: The type of an assignment expression is the type of the
8711   // left operand unless the left operand has qualified type, in which case
8712   // it is the unqualified version of the type of the left operand.
8713   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8714   // is converted to the type of the assignment expression (above).
8715   // C++ 5.17p1: the type of the assignment expression is that of its left
8716   // operand.
8717   return (getLangOpts().CPlusPlus
8718           ? LHSType : LHSType.getUnqualifiedType());
8719 }
8720 
8721 // C99 6.5.17
CheckCommaOperands(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)8722 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8723                                    SourceLocation Loc) {
8724   LHS = S.CheckPlaceholderExpr(LHS.get());
8725   RHS = S.CheckPlaceholderExpr(RHS.get());
8726   if (LHS.isInvalid() || RHS.isInvalid())
8727     return QualType();
8728 
8729   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8730   // operands, but not unary promotions.
8731   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8732 
8733   // So we treat the LHS as a ignored value, and in C++ we allow the
8734   // containing site to determine what should be done with the RHS.
8735   LHS = S.IgnoredValueConversions(LHS.get());
8736   if (LHS.isInvalid())
8737     return QualType();
8738 
8739   S.DiagnoseUnusedExprResult(LHS.get());
8740 
8741   if (!S.getLangOpts().CPlusPlus) {
8742     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8743     if (RHS.isInvalid())
8744       return QualType();
8745     if (!RHS.get()->getType()->isVoidType())
8746       S.RequireCompleteType(Loc, RHS.get()->getType(),
8747                             diag::err_incomplete_type);
8748   }
8749 
8750   return RHS.get()->getType();
8751 }
8752 
8753 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8754 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
CheckIncrementDecrementOperand(Sema & S,Expr * Op,ExprValueKind & VK,SourceLocation OpLoc,bool IsInc,bool IsPrefix)8755 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8756                                                ExprValueKind &VK,
8757                                                SourceLocation OpLoc,
8758                                                bool IsInc, bool IsPrefix) {
8759   if (Op->isTypeDependent())
8760     return S.Context.DependentTy;
8761 
8762   QualType ResType = Op->getType();
8763   // Atomic types can be used for increment / decrement where the non-atomic
8764   // versions can, so ignore the _Atomic() specifier for the purpose of
8765   // checking.
8766   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8767     ResType = ResAtomicType->getValueType();
8768 
8769   assert(!ResType.isNull() && "no type for increment/decrement expression");
8770 
8771   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8772     // Decrement of bool is not allowed.
8773     if (!IsInc) {
8774       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8775       return QualType();
8776     }
8777     // Increment of bool sets it to true, but is deprecated.
8778     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8779   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8780     // Error on enum increments and decrements in C++ mode
8781     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8782     return QualType();
8783   } else if (ResType->isRealType()) {
8784     // OK!
8785   } else if (ResType->isPointerType()) {
8786     // C99 6.5.2.4p2, 6.5.6p2
8787     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8788       return QualType();
8789   } else if (ResType->isObjCObjectPointerType()) {
8790     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8791     // Otherwise, we just need a complete type.
8792     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8793         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8794       return QualType();
8795   } else if (ResType->isAnyComplexType()) {
8796     // C99 does not support ++/-- on complex types, we allow as an extension.
8797     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8798       << ResType << Op->getSourceRange();
8799   } else if (ResType->isPlaceholderType()) {
8800     ExprResult PR = S.CheckPlaceholderExpr(Op);
8801     if (PR.isInvalid()) return QualType();
8802     return CheckIncrementDecrementOperand(S, PR.get(), VK, OpLoc,
8803                                           IsInc, IsPrefix);
8804   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8805     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8806   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8807             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8808     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8809   } else {
8810     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8811       << ResType << int(IsInc) << Op->getSourceRange();
8812     return QualType();
8813   }
8814   // At this point, we know we have a real, complex or pointer type.
8815   // Now make sure the operand is a modifiable lvalue.
8816   if (CheckForModifiableLvalue(Op, OpLoc, S))
8817     return QualType();
8818   // In C++, a prefix increment is the same type as the operand. Otherwise
8819   // (in C or with postfix), the increment is the unqualified type of the
8820   // operand.
8821   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8822     VK = VK_LValue;
8823     return ResType;
8824   } else {
8825     VK = VK_RValue;
8826     return ResType.getUnqualifiedType();
8827   }
8828 }
8829 
8830 
8831 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8832 /// This routine allows us to typecheck complex/recursive expressions
8833 /// where the declaration is needed for type checking. We only need to
8834 /// handle cases when the expression references a function designator
8835 /// or is an lvalue. Here are some examples:
8836 ///  - &(x) => x
8837 ///  - &*****f => f for f a function designator.
8838 ///  - &s.xx => s
8839 ///  - &s.zz[1].yy -> s, if zz is an array
8840 ///  - *(x + 1) -> x, if x is an array
8841 ///  - &"123"[2] -> 0
8842 ///  - & __real__ x -> x
getPrimaryDecl(Expr * E)8843 static ValueDecl *getPrimaryDecl(Expr *E) {
8844   switch (E->getStmtClass()) {
8845   case Stmt::DeclRefExprClass:
8846     return cast<DeclRefExpr>(E)->getDecl();
8847   case Stmt::MemberExprClass:
8848     // If this is an arrow operator, the address is an offset from
8849     // the base's value, so the object the base refers to is
8850     // irrelevant.
8851     if (cast<MemberExpr>(E)->isArrow())
8852       return nullptr;
8853     // Otherwise, the expression refers to a part of the base
8854     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8855   case Stmt::ArraySubscriptExprClass: {
8856     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8857     // promotion of register arrays earlier.
8858     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8859     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8860       if (ICE->getSubExpr()->getType()->isArrayType())
8861         return getPrimaryDecl(ICE->getSubExpr());
8862     }
8863     return nullptr;
8864   }
8865   case Stmt::UnaryOperatorClass: {
8866     UnaryOperator *UO = cast<UnaryOperator>(E);
8867 
8868     switch(UO->getOpcode()) {
8869     case UO_Real:
8870     case UO_Imag:
8871     case UO_Extension:
8872       return getPrimaryDecl(UO->getSubExpr());
8873     default:
8874       return nullptr;
8875     }
8876   }
8877   case Stmt::ParenExprClass:
8878     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8879   case Stmt::ImplicitCastExprClass:
8880     // If the result of an implicit cast is an l-value, we care about
8881     // the sub-expression; otherwise, the result here doesn't matter.
8882     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8883   default:
8884     return nullptr;
8885   }
8886 }
8887 
8888 namespace {
8889   enum {
8890     AO_Bit_Field = 0,
8891     AO_Vector_Element = 1,
8892     AO_Property_Expansion = 2,
8893     AO_Register_Variable = 3,
8894     AO_No_Error = 4
8895   };
8896 }
8897 /// \brief Diagnose invalid operand for address of operations.
8898 ///
8899 /// \param Type The type of operand which cannot have its address taken.
diagnoseAddressOfInvalidType(Sema & S,SourceLocation Loc,Expr * E,unsigned Type)8900 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8901                                          Expr *E, unsigned Type) {
8902   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8903 }
8904 
8905 /// CheckAddressOfOperand - The operand of & must be either a function
8906 /// designator or an lvalue designating an object. If it is an lvalue, the
8907 /// object cannot be declared with storage class register or be a bit field.
8908 /// Note: The usual conversions are *not* applied to the operand of the &
8909 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8910 /// In C++, the operand might be an overloaded function name, in which case
8911 /// we allow the '&' but retain the overloaded-function type.
CheckAddressOfOperand(ExprResult & OrigOp,SourceLocation OpLoc)8912 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8913   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8914     if (PTy->getKind() == BuiltinType::Overload) {
8915       Expr *E = OrigOp.get()->IgnoreParens();
8916       if (!isa<OverloadExpr>(E)) {
8917         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8918         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8919           << OrigOp.get()->getSourceRange();
8920         return QualType();
8921       }
8922 
8923       OverloadExpr *Ovl = cast<OverloadExpr>(E);
8924       if (isa<UnresolvedMemberExpr>(Ovl))
8925         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8926           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8927             << OrigOp.get()->getSourceRange();
8928           return QualType();
8929         }
8930 
8931       return Context.OverloadTy;
8932     }
8933 
8934     if (PTy->getKind() == BuiltinType::UnknownAny)
8935       return Context.UnknownAnyTy;
8936 
8937     if (PTy->getKind() == BuiltinType::BoundMember) {
8938       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8939         << OrigOp.get()->getSourceRange();
8940       return QualType();
8941     }
8942 
8943     OrigOp = CheckPlaceholderExpr(OrigOp.get());
8944     if (OrigOp.isInvalid()) return QualType();
8945   }
8946 
8947   if (OrigOp.get()->isTypeDependent())
8948     return Context.DependentTy;
8949 
8950   assert(!OrigOp.get()->getType()->isPlaceholderType());
8951 
8952   // Make sure to ignore parentheses in subsequent checks
8953   Expr *op = OrigOp.get()->IgnoreParens();
8954 
8955   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
8956   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
8957     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
8958     return QualType();
8959   }
8960 
8961   if (getLangOpts().C99) {
8962     // Implement C99-only parts of addressof rules.
8963     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8964       if (uOp->getOpcode() == UO_Deref)
8965         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8966         // (assuming the deref expression is valid).
8967         return uOp->getSubExpr()->getType();
8968     }
8969     // Technically, there should be a check for array subscript
8970     // expressions here, but the result of one is always an lvalue anyway.
8971   }
8972   ValueDecl *dcl = getPrimaryDecl(op);
8973   Expr::LValueClassification lval = op->ClassifyLValue(Context);
8974   unsigned AddressOfError = AO_No_Error;
8975 
8976   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8977     bool sfinae = (bool)isSFINAEContext();
8978     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8979                                   : diag::ext_typecheck_addrof_temporary)
8980       << op->getType() << op->getSourceRange();
8981     if (sfinae)
8982       return QualType();
8983     // Materialize the temporary as an lvalue so that we can take its address.
8984     OrigOp = op = new (Context)
8985         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
8986   } else if (isa<ObjCSelectorExpr>(op)) {
8987     return Context.getPointerType(op->getType());
8988   } else if (lval == Expr::LV_MemberFunction) {
8989     // If it's an instance method, make a member pointer.
8990     // The expression must have exactly the form &A::foo.
8991 
8992     // If the underlying expression isn't a decl ref, give up.
8993     if (!isa<DeclRefExpr>(op)) {
8994       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8995         << OrigOp.get()->getSourceRange();
8996       return QualType();
8997     }
8998     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8999     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
9000 
9001     // The id-expression was parenthesized.
9002     if (OrigOp.get() != DRE) {
9003       Diag(OpLoc, diag::err_parens_pointer_member_function)
9004         << OrigOp.get()->getSourceRange();
9005 
9006     // The method was named without a qualifier.
9007     } else if (!DRE->getQualifier()) {
9008       if (MD->getParent()->getName().empty())
9009         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9010           << op->getSourceRange();
9011       else {
9012         SmallString<32> Str;
9013         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
9014         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9015           << op->getSourceRange()
9016           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9017       }
9018     }
9019 
9020     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9021     if (isa<CXXDestructorDecl>(MD))
9022       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9023 
9024     QualType MPTy = Context.getMemberPointerType(
9025         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9026     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9027       RequireCompleteType(OpLoc, MPTy, 0);
9028     return MPTy;
9029   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
9030     // C99 6.5.3.2p1
9031     // The operand must be either an l-value or a function designator
9032     if (!op->getType()->isFunctionType()) {
9033       // Use a special diagnostic for loads from property references.
9034       if (isa<PseudoObjectExpr>(op)) {
9035         AddressOfError = AO_Property_Expansion;
9036       } else {
9037         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
9038           << op->getType() << op->getSourceRange();
9039         return QualType();
9040       }
9041     }
9042   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
9043     // The operand cannot be a bit-field
9044     AddressOfError = AO_Bit_Field;
9045   } else if (op->getObjectKind() == OK_VectorComponent) {
9046     // The operand cannot be an element of a vector
9047     AddressOfError = AO_Vector_Element;
9048   } else if (dcl) { // C99 6.5.3.2p1
9049     // We have an lvalue with a decl. Make sure the decl is not declared
9050     // with the register storage-class specifier.
9051     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
9052       // in C++ it is not error to take address of a register
9053       // variable (c++03 7.1.1P3)
9054       if (vd->getStorageClass() == SC_Register &&
9055           !getLangOpts().CPlusPlus) {
9056         AddressOfError = AO_Register_Variable;
9057       }
9058     } else if (isa<FunctionTemplateDecl>(dcl)) {
9059       return Context.OverloadTy;
9060     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
9061       // Okay: we can take the address of a field.
9062       // Could be a pointer to member, though, if there is an explicit
9063       // scope qualifier for the class.
9064       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
9065         DeclContext *Ctx = dcl->getDeclContext();
9066         if (Ctx && Ctx->isRecord()) {
9067           if (dcl->getType()->isReferenceType()) {
9068             Diag(OpLoc,
9069                  diag::err_cannot_form_pointer_to_member_of_reference_type)
9070               << dcl->getDeclName() << dcl->getType();
9071             return QualType();
9072           }
9073 
9074           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
9075             Ctx = Ctx->getParent();
9076 
9077           QualType MPTy = Context.getMemberPointerType(
9078               op->getType(),
9079               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
9080           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9081             RequireCompleteType(OpLoc, MPTy, 0);
9082           return MPTy;
9083         }
9084       }
9085     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
9086       llvm_unreachable("Unknown/unexpected decl type");
9087   }
9088 
9089   if (AddressOfError != AO_No_Error) {
9090     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
9091     return QualType();
9092   }
9093 
9094   if (lval == Expr::LV_IncompleteVoidType) {
9095     // Taking the address of a void variable is technically illegal, but we
9096     // allow it in cases which are otherwise valid.
9097     // Example: "extern void x; void* y = &x;".
9098     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
9099   }
9100 
9101   // If the operand has type "type", the result has type "pointer to type".
9102   if (op->getType()->isObjCObjectType())
9103     return Context.getObjCObjectPointerType(op->getType());
9104   return Context.getPointerType(op->getType());
9105 }
9106 
9107 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
CheckIndirectionOperand(Sema & S,Expr * Op,ExprValueKind & VK,SourceLocation OpLoc)9108 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9109                                         SourceLocation OpLoc) {
9110   if (Op->isTypeDependent())
9111     return S.Context.DependentTy;
9112 
9113   ExprResult ConvResult = S.UsualUnaryConversions(Op);
9114   if (ConvResult.isInvalid())
9115     return QualType();
9116   Op = ConvResult.get();
9117   QualType OpTy = Op->getType();
9118   QualType Result;
9119 
9120   if (isa<CXXReinterpretCastExpr>(Op)) {
9121     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9122     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9123                                      Op->getSourceRange());
9124   }
9125 
9126   if (const PointerType *PT = OpTy->getAs<PointerType>())
9127     Result = PT->getPointeeType();
9128   else if (const ObjCObjectPointerType *OPT =
9129              OpTy->getAs<ObjCObjectPointerType>())
9130     Result = OPT->getPointeeType();
9131   else {
9132     ExprResult PR = S.CheckPlaceholderExpr(Op);
9133     if (PR.isInvalid()) return QualType();
9134     if (PR.get() != Op)
9135       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
9136   }
9137 
9138   if (Result.isNull()) {
9139     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
9140       << OpTy << Op->getSourceRange();
9141     return QualType();
9142   }
9143 
9144   // Note that per both C89 and C99, indirection is always legal, even if Result
9145   // is an incomplete type or void.  It would be possible to warn about
9146   // dereferencing a void pointer, but it's completely well-defined, and such a
9147   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
9148   // for pointers to 'void' but is fine for any other pointer type:
9149   //
9150   // C++ [expr.unary.op]p1:
9151   //   [...] the expression to which [the unary * operator] is applied shall
9152   //   be a pointer to an object type, or a pointer to a function type
9153   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
9154     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
9155       << OpTy << Op->getSourceRange();
9156 
9157   // Dereferences are usually l-values...
9158   VK = VK_LValue;
9159 
9160   // ...except that certain expressions are never l-values in C.
9161   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
9162     VK = VK_RValue;
9163 
9164   return Result;
9165 }
9166 
ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind)9167 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
9168   tok::TokenKind Kind) {
9169   BinaryOperatorKind Opc;
9170   switch (Kind) {
9171   default: llvm_unreachable("Unknown binop!");
9172   case tok::periodstar:           Opc = BO_PtrMemD; break;
9173   case tok::arrowstar:            Opc = BO_PtrMemI; break;
9174   case tok::star:                 Opc = BO_Mul; break;
9175   case tok::slash:                Opc = BO_Div; break;
9176   case tok::percent:              Opc = BO_Rem; break;
9177   case tok::plus:                 Opc = BO_Add; break;
9178   case tok::minus:                Opc = BO_Sub; break;
9179   case tok::lessless:             Opc = BO_Shl; break;
9180   case tok::greatergreater:       Opc = BO_Shr; break;
9181   case tok::lessequal:            Opc = BO_LE; break;
9182   case tok::less:                 Opc = BO_LT; break;
9183   case tok::greaterequal:         Opc = BO_GE; break;
9184   case tok::greater:              Opc = BO_GT; break;
9185   case tok::exclaimequal:         Opc = BO_NE; break;
9186   case tok::equalequal:           Opc = BO_EQ; break;
9187   case tok::amp:                  Opc = BO_And; break;
9188   case tok::caret:                Opc = BO_Xor; break;
9189   case tok::pipe:                 Opc = BO_Or; break;
9190   case tok::ampamp:               Opc = BO_LAnd; break;
9191   case tok::pipepipe:             Opc = BO_LOr; break;
9192   case tok::equal:                Opc = BO_Assign; break;
9193   case tok::starequal:            Opc = BO_MulAssign; break;
9194   case tok::slashequal:           Opc = BO_DivAssign; break;
9195   case tok::percentequal:         Opc = BO_RemAssign; break;
9196   case tok::plusequal:            Opc = BO_AddAssign; break;
9197   case tok::minusequal:           Opc = BO_SubAssign; break;
9198   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
9199   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
9200   case tok::ampequal:             Opc = BO_AndAssign; break;
9201   case tok::caretequal:           Opc = BO_XorAssign; break;
9202   case tok::pipeequal:            Opc = BO_OrAssign; break;
9203   case tok::comma:                Opc = BO_Comma; break;
9204   }
9205   return Opc;
9206 }
9207 
ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)9208 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9209   tok::TokenKind Kind) {
9210   UnaryOperatorKind Opc;
9211   switch (Kind) {
9212   default: llvm_unreachable("Unknown unary op!");
9213   case tok::plusplus:     Opc = UO_PreInc; break;
9214   case tok::minusminus:   Opc = UO_PreDec; break;
9215   case tok::amp:          Opc = UO_AddrOf; break;
9216   case tok::star:         Opc = UO_Deref; break;
9217   case tok::plus:         Opc = UO_Plus; break;
9218   case tok::minus:        Opc = UO_Minus; break;
9219   case tok::tilde:        Opc = UO_Not; break;
9220   case tok::exclaim:      Opc = UO_LNot; break;
9221   case tok::kw___real:    Opc = UO_Real; break;
9222   case tok::kw___imag:    Opc = UO_Imag; break;
9223   case tok::kw___extension__: Opc = UO_Extension; break;
9224   }
9225   return Opc;
9226 }
9227 
9228 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9229 /// This warning is only emitted for builtin assignment operations. It is also
9230 /// suppressed in the event of macro expansions.
DiagnoseSelfAssignment(Sema & S,Expr * LHSExpr,Expr * RHSExpr,SourceLocation OpLoc)9231 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9232                                    SourceLocation OpLoc) {
9233   if (!S.ActiveTemplateInstantiations.empty())
9234     return;
9235   if (OpLoc.isInvalid() || OpLoc.isMacroID())
9236     return;
9237   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9238   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9239   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9240   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9241   if (!LHSDeclRef || !RHSDeclRef ||
9242       LHSDeclRef->getLocation().isMacroID() ||
9243       RHSDeclRef->getLocation().isMacroID())
9244     return;
9245   const ValueDecl *LHSDecl =
9246     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9247   const ValueDecl *RHSDecl =
9248     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9249   if (LHSDecl != RHSDecl)
9250     return;
9251   if (LHSDecl->getType().isVolatileQualified())
9252     return;
9253   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9254     if (RefTy->getPointeeType().isVolatileQualified())
9255       return;
9256 
9257   S.Diag(OpLoc, diag::warn_self_assignment)
9258       << LHSDeclRef->getType()
9259       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9260 }
9261 
9262 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9263 /// is usually indicative of introspection within the Objective-C pointer.
checkObjCPointerIntrospection(Sema & S,ExprResult & L,ExprResult & R,SourceLocation OpLoc)9264 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9265                                           SourceLocation OpLoc) {
9266   if (!S.getLangOpts().ObjC1)
9267     return;
9268 
9269   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
9270   const Expr *LHS = L.get();
9271   const Expr *RHS = R.get();
9272 
9273   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9274     ObjCPointerExpr = LHS;
9275     OtherExpr = RHS;
9276   }
9277   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9278     ObjCPointerExpr = RHS;
9279     OtherExpr = LHS;
9280   }
9281 
9282   // This warning is deliberately made very specific to reduce false
9283   // positives with logic that uses '&' for hashing.  This logic mainly
9284   // looks for code trying to introspect into tagged pointers, which
9285   // code should generally never do.
9286   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9287     unsigned Diag = diag::warn_objc_pointer_masking;
9288     // Determine if we are introspecting the result of performSelectorXXX.
9289     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9290     // Special case messages to -performSelector and friends, which
9291     // can return non-pointer values boxed in a pointer value.
9292     // Some clients may wish to silence warnings in this subcase.
9293     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9294       Selector S = ME->getSelector();
9295       StringRef SelArg0 = S.getNameForSlot(0);
9296       if (SelArg0.startswith("performSelector"))
9297         Diag = diag::warn_objc_pointer_masking_performSelector;
9298     }
9299 
9300     S.Diag(OpLoc, Diag)
9301       << ObjCPointerExpr->getSourceRange();
9302   }
9303 }
9304 
9305 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9306 /// operator @p Opc at location @c TokLoc. This routine only supports
9307 /// built-in operations; ActOnBinOp handles overloaded operators.
CreateBuiltinBinOp(SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)9308 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9309                                     BinaryOperatorKind Opc,
9310                                     Expr *LHSExpr, Expr *RHSExpr) {
9311   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9312     // The syntax only allows initializer lists on the RHS of assignment,
9313     // so we don't need to worry about accepting invalid code for
9314     // non-assignment operators.
9315     // C++11 5.17p9:
9316     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9317     //   of x = {} is x = T().
9318     InitializationKind Kind =
9319         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9320     InitializedEntity Entity =
9321         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9322     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9323     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9324     if (Init.isInvalid())
9325       return Init;
9326     RHSExpr = Init.get();
9327   }
9328 
9329   ExprResult LHS = LHSExpr, RHS = RHSExpr;
9330   QualType ResultTy;     // Result type of the binary operator.
9331   // The following two variables are used for compound assignment operators
9332   QualType CompLHSTy;    // Type of LHS after promotions for computation
9333   QualType CompResultTy; // Type of computation result
9334   ExprValueKind VK = VK_RValue;
9335   ExprObjectKind OK = OK_Ordinary;
9336 
9337   switch (Opc) {
9338   case BO_Assign:
9339     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9340     if (getLangOpts().CPlusPlus &&
9341         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9342       VK = LHS.get()->getValueKind();
9343       OK = LHS.get()->getObjectKind();
9344     }
9345     if (!ResultTy.isNull())
9346       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9347     break;
9348   case BO_PtrMemD:
9349   case BO_PtrMemI:
9350     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9351                                             Opc == BO_PtrMemI);
9352     break;
9353   case BO_Mul:
9354   case BO_Div:
9355     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9356                                            Opc == BO_Div);
9357     break;
9358   case BO_Rem:
9359     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9360     break;
9361   case BO_Add:
9362     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9363     break;
9364   case BO_Sub:
9365     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9366     break;
9367   case BO_Shl:
9368   case BO_Shr:
9369     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9370     break;
9371   case BO_LE:
9372   case BO_LT:
9373   case BO_GE:
9374   case BO_GT:
9375     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9376     break;
9377   case BO_EQ:
9378   case BO_NE:
9379     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9380     break;
9381   case BO_And:
9382     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9383   case BO_Xor:
9384   case BO_Or:
9385     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9386     break;
9387   case BO_LAnd:
9388   case BO_LOr:
9389     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9390     break;
9391   case BO_MulAssign:
9392   case BO_DivAssign:
9393     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9394                                                Opc == BO_DivAssign);
9395     CompLHSTy = CompResultTy;
9396     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9397       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9398     break;
9399   case BO_RemAssign:
9400     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9401     CompLHSTy = CompResultTy;
9402     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9403       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9404     break;
9405   case BO_AddAssign:
9406     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9407     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9408       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9409     break;
9410   case BO_SubAssign:
9411     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9412     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9413       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9414     break;
9415   case BO_ShlAssign:
9416   case BO_ShrAssign:
9417     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9418     CompLHSTy = CompResultTy;
9419     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9420       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9421     break;
9422   case BO_AndAssign:
9423   case BO_OrAssign: // fallthrough
9424 	  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9425   case BO_XorAssign:
9426     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9427     CompLHSTy = CompResultTy;
9428     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9429       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9430     break;
9431   case BO_Comma:
9432     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9433     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9434       VK = RHS.get()->getValueKind();
9435       OK = RHS.get()->getObjectKind();
9436     }
9437     break;
9438   }
9439   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9440     return ExprError();
9441 
9442   // Check for array bounds violations for both sides of the BinaryOperator
9443   CheckArrayAccess(LHS.get());
9444   CheckArrayAccess(RHS.get());
9445 
9446   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9447     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9448                                                  &Context.Idents.get("object_setClass"),
9449                                                  SourceLocation(), LookupOrdinaryName);
9450     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9451       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9452       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9453       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9454       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9455       FixItHint::CreateInsertion(RHSLocEnd, ")");
9456     }
9457     else
9458       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9459   }
9460   else if (const ObjCIvarRefExpr *OIRE =
9461            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9462     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9463 
9464   if (CompResultTy.isNull())
9465     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
9466                                         OK, OpLoc, FPFeatures.fp_contract);
9467   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9468       OK_ObjCProperty) {
9469     VK = VK_LValue;
9470     OK = LHS.get()->getObjectKind();
9471   }
9472   return new (Context) CompoundAssignOperator(
9473       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
9474       OpLoc, FPFeatures.fp_contract);
9475 }
9476 
9477 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9478 /// operators are mixed in a way that suggests that the programmer forgot that
9479 /// comparison operators have higher precedence. The most typical example of
9480 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
DiagnoseBitwisePrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)9481 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9482                                       SourceLocation OpLoc, Expr *LHSExpr,
9483                                       Expr *RHSExpr) {
9484   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9485   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9486 
9487   // Check that one of the sides is a comparison operator.
9488   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9489   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9490   if (!isLeftComp && !isRightComp)
9491     return;
9492 
9493   // Bitwise operations are sometimes used as eager logical ops.
9494   // Don't diagnose this.
9495   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9496   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9497   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9498     return;
9499 
9500   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9501                                                    OpLoc)
9502                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9503   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9504   SourceRange ParensRange = isLeftComp ?
9505       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9506     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9507 
9508   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9509     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9510   SuggestParentheses(Self, OpLoc,
9511     Self.PDiag(diag::note_precedence_silence) << OpStr,
9512     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9513   SuggestParentheses(Self, OpLoc,
9514     Self.PDiag(diag::note_precedence_bitwise_first)
9515       << BinaryOperator::getOpcodeStr(Opc),
9516     ParensRange);
9517 }
9518 
9519 /// \brief It accepts a '&' expr that is inside a '|' one.
9520 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9521 /// in parentheses.
9522 static void
EmitDiagnosticForBitwiseAndInBitwiseOr(Sema & Self,SourceLocation OpLoc,BinaryOperator * Bop)9523 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9524                                        BinaryOperator *Bop) {
9525   assert(Bop->getOpcode() == BO_And);
9526   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9527       << Bop->getSourceRange() << OpLoc;
9528   SuggestParentheses(Self, Bop->getOperatorLoc(),
9529     Self.PDiag(diag::note_precedence_silence)
9530       << Bop->getOpcodeStr(),
9531     Bop->getSourceRange());
9532 }
9533 
9534 /// \brief It accepts a '&&' expr that is inside a '||' one.
9535 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9536 /// in parentheses.
9537 static void
EmitDiagnosticForLogicalAndInLogicalOr(Sema & Self,SourceLocation OpLoc,BinaryOperator * Bop)9538 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9539                                        BinaryOperator *Bop) {
9540   assert(Bop->getOpcode() == BO_LAnd);
9541   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9542       << Bop->getSourceRange() << OpLoc;
9543   SuggestParentheses(Self, Bop->getOperatorLoc(),
9544     Self.PDiag(diag::note_precedence_silence)
9545       << Bop->getOpcodeStr(),
9546     Bop->getSourceRange());
9547 }
9548 
9549 /// \brief Returns true if the given expression can be evaluated as a constant
9550 /// 'true'.
EvaluatesAsTrue(Sema & S,Expr * E)9551 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9552   bool Res;
9553   return !E->isValueDependent() &&
9554          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9555 }
9556 
9557 /// \brief Returns true if the given expression can be evaluated as a constant
9558 /// 'false'.
EvaluatesAsFalse(Sema & S,Expr * E)9559 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9560   bool Res;
9561   return !E->isValueDependent() &&
9562          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9563 }
9564 
9565 /// \brief Look for '&&' in the left hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrLHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)9566 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9567                                              Expr *LHSExpr, Expr *RHSExpr) {
9568   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9569     if (Bop->getOpcode() == BO_LAnd) {
9570       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9571       if (EvaluatesAsFalse(S, RHSExpr))
9572         return;
9573       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9574       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9575         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9576     } else if (Bop->getOpcode() == BO_LOr) {
9577       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9578         // If it's "a || b && 1 || c" we didn't warn earlier for
9579         // "a || b && 1", but warn now.
9580         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9581           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9582       }
9583     }
9584   }
9585 }
9586 
9587 /// \brief Look for '&&' in the right hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrRHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)9588 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9589                                              Expr *LHSExpr, Expr *RHSExpr) {
9590   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9591     if (Bop->getOpcode() == BO_LAnd) {
9592       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9593       if (EvaluatesAsFalse(S, LHSExpr))
9594         return;
9595       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9596       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9597         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9598     }
9599   }
9600 }
9601 
9602 /// \brief Look for '&' in the left or right hand of a '|' expr.
DiagnoseBitwiseAndInBitwiseOr(Sema & S,SourceLocation OpLoc,Expr * OrArg)9603 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9604                                              Expr *OrArg) {
9605   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9606     if (Bop->getOpcode() == BO_And)
9607       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9608   }
9609 }
9610 
DiagnoseAdditionInShift(Sema & S,SourceLocation OpLoc,Expr * SubExpr,StringRef Shift)9611 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9612                                     Expr *SubExpr, StringRef Shift) {
9613   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9614     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9615       StringRef Op = Bop->getOpcodeStr();
9616       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9617           << Bop->getSourceRange() << OpLoc << Shift << Op;
9618       SuggestParentheses(S, Bop->getOperatorLoc(),
9619           S.PDiag(diag::note_precedence_silence) << Op,
9620           Bop->getSourceRange());
9621     }
9622   }
9623 }
9624 
DiagnoseShiftCompare(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)9625 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9626                                  Expr *LHSExpr, Expr *RHSExpr) {
9627   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9628   if (!OCE)
9629     return;
9630 
9631   FunctionDecl *FD = OCE->getDirectCallee();
9632   if (!FD || !FD->isOverloadedOperator())
9633     return;
9634 
9635   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9636   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9637     return;
9638 
9639   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9640       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9641       << (Kind == OO_LessLess);
9642   SuggestParentheses(S, OCE->getOperatorLoc(),
9643                      S.PDiag(diag::note_precedence_silence)
9644                          << (Kind == OO_LessLess ? "<<" : ">>"),
9645                      OCE->getSourceRange());
9646   SuggestParentheses(S, OpLoc,
9647                      S.PDiag(diag::note_evaluate_comparison_first),
9648                      SourceRange(OCE->getArg(1)->getLocStart(),
9649                                  RHSExpr->getLocEnd()));
9650 }
9651 
9652 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9653 /// precedence.
DiagnoseBinOpPrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)9654 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9655                                     SourceLocation OpLoc, Expr *LHSExpr,
9656                                     Expr *RHSExpr){
9657   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9658   if (BinaryOperator::isBitwiseOp(Opc))
9659     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9660 
9661   // Diagnose "arg1 & arg2 | arg3"
9662   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9663     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9664     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9665   }
9666 
9667   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9668   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9669   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9670     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9671     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9672   }
9673 
9674   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9675       || Opc == BO_Shr) {
9676     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9677     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9678     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9679   }
9680 
9681   // Warn on overloaded shift operators and comparisons, such as:
9682   // cout << 5 == 4;
9683   if (BinaryOperator::isComparisonOp(Opc))
9684     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9685 }
9686 
9687 // Binary Operators.  'Tok' is the token for the operator.
ActOnBinOp(Scope * S,SourceLocation TokLoc,tok::TokenKind Kind,Expr * LHSExpr,Expr * RHSExpr)9688 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9689                             tok::TokenKind Kind,
9690                             Expr *LHSExpr, Expr *RHSExpr) {
9691   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9692   assert(LHSExpr && "ActOnBinOp(): missing left expression");
9693   assert(RHSExpr && "ActOnBinOp(): missing right expression");
9694 
9695   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9696   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9697 
9698   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9699 }
9700 
9701 /// Build an overloaded binary operator expression in the given scope.
BuildOverloadedBinOp(Sema & S,Scope * Sc,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHS,Expr * RHS)9702 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9703                                        BinaryOperatorKind Opc,
9704                                        Expr *LHS, Expr *RHS) {
9705   // Find all of the overloaded operators visible from this
9706   // point. We perform both an operator-name lookup from the local
9707   // scope and an argument-dependent lookup based on the types of
9708   // the arguments.
9709   UnresolvedSet<16> Functions;
9710   OverloadedOperatorKind OverOp
9711     = BinaryOperator::getOverloadedOperator(Opc);
9712   if (Sc && OverOp != OO_None)
9713     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9714                                    RHS->getType(), Functions);
9715 
9716   // Build the (potentially-overloaded, potentially-dependent)
9717   // binary operation.
9718   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9719 }
9720 
BuildBinOp(Scope * S,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)9721 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9722                             BinaryOperatorKind Opc,
9723                             Expr *LHSExpr, Expr *RHSExpr) {
9724   // We want to end up calling one of checkPseudoObjectAssignment
9725   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9726   // both expressions are overloadable or either is type-dependent),
9727   // or CreateBuiltinBinOp (in any other case).  We also want to get
9728   // any placeholder types out of the way.
9729 
9730   // Handle pseudo-objects in the LHS.
9731   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9732     // Assignments with a pseudo-object l-value need special analysis.
9733     if (pty->getKind() == BuiltinType::PseudoObject &&
9734         BinaryOperator::isAssignmentOp(Opc))
9735       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9736 
9737     // Don't resolve overloads if the other type is overloadable.
9738     if (pty->getKind() == BuiltinType::Overload) {
9739       // We can't actually test that if we still have a placeholder,
9740       // though.  Fortunately, none of the exceptions we see in that
9741       // code below are valid when the LHS is an overload set.  Note
9742       // that an overload set can be dependently-typed, but it never
9743       // instantiates to having an overloadable type.
9744       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9745       if (resolvedRHS.isInvalid()) return ExprError();
9746       RHSExpr = resolvedRHS.get();
9747 
9748       if (RHSExpr->isTypeDependent() ||
9749           RHSExpr->getType()->isOverloadableType())
9750         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9751     }
9752 
9753     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9754     if (LHS.isInvalid()) return ExprError();
9755     LHSExpr = LHS.get();
9756   }
9757 
9758   // Handle pseudo-objects in the RHS.
9759   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9760     // An overload in the RHS can potentially be resolved by the type
9761     // being assigned to.
9762     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9763       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9764         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9765 
9766       if (LHSExpr->getType()->isOverloadableType())
9767         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9768 
9769       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9770     }
9771 
9772     // Don't resolve overloads if the other type is overloadable.
9773     if (pty->getKind() == BuiltinType::Overload &&
9774         LHSExpr->getType()->isOverloadableType())
9775       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9776 
9777     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9778     if (!resolvedRHS.isUsable()) return ExprError();
9779     RHSExpr = resolvedRHS.get();
9780   }
9781 
9782   if (getLangOpts().CPlusPlus) {
9783     // If either expression is type-dependent, always build an
9784     // overloaded op.
9785     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9786       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9787 
9788     // Otherwise, build an overloaded op if either expression has an
9789     // overloadable type.
9790     if (LHSExpr->getType()->isOverloadableType() ||
9791         RHSExpr->getType()->isOverloadableType())
9792       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9793   }
9794 
9795   // Build a built-in binary operation.
9796   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9797 }
9798 
CreateBuiltinUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * InputExpr)9799 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9800                                       UnaryOperatorKind Opc,
9801                                       Expr *InputExpr) {
9802   ExprResult Input = InputExpr;
9803   ExprValueKind VK = VK_RValue;
9804   ExprObjectKind OK = OK_Ordinary;
9805   QualType resultType;
9806   switch (Opc) {
9807   case UO_PreInc:
9808   case UO_PreDec:
9809   case UO_PostInc:
9810   case UO_PostDec:
9811     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9812                                                 Opc == UO_PreInc ||
9813                                                 Opc == UO_PostInc,
9814                                                 Opc == UO_PreInc ||
9815                                                 Opc == UO_PreDec);
9816     break;
9817   case UO_AddrOf:
9818     resultType = CheckAddressOfOperand(Input, OpLoc);
9819     break;
9820   case UO_Deref: {
9821     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9822     if (Input.isInvalid()) return ExprError();
9823     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9824     break;
9825   }
9826   case UO_Plus:
9827   case UO_Minus:
9828     Input = UsualUnaryConversions(Input.get());
9829     if (Input.isInvalid()) return ExprError();
9830     resultType = Input.get()->getType();
9831     if (resultType->isDependentType())
9832       break;
9833     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9834         resultType->isVectorType())
9835       break;
9836     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9837              Opc == UO_Plus &&
9838              resultType->isPointerType())
9839       break;
9840 
9841     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9842       << resultType << Input.get()->getSourceRange());
9843 
9844   case UO_Not: // bitwise complement
9845     Input = UsualUnaryConversions(Input.get());
9846     if (Input.isInvalid())
9847       return ExprError();
9848     resultType = Input.get()->getType();
9849     if (resultType->isDependentType())
9850       break;
9851     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9852     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9853       // C99 does not support '~' for complex conjugation.
9854       Diag(OpLoc, diag::ext_integer_complement_complex)
9855           << resultType << Input.get()->getSourceRange();
9856     else if (resultType->hasIntegerRepresentation())
9857       break;
9858     else if (resultType->isExtVectorType()) {
9859       if (Context.getLangOpts().OpenCL) {
9860         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9861         // on vector float types.
9862         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9863         if (!T->isIntegerType())
9864           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9865                            << resultType << Input.get()->getSourceRange());
9866       }
9867       break;
9868     } else {
9869       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9870                        << resultType << Input.get()->getSourceRange());
9871     }
9872     break;
9873 
9874   case UO_LNot: // logical negation
9875     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9876     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9877     if (Input.isInvalid()) return ExprError();
9878     resultType = Input.get()->getType();
9879 
9880     // Though we still have to promote half FP to float...
9881     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9882       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
9883       resultType = Context.FloatTy;
9884     }
9885 
9886     if (resultType->isDependentType())
9887       break;
9888     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
9889       // C99 6.5.3.3p1: ok, fallthrough;
9890       if (Context.getLangOpts().CPlusPlus) {
9891         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9892         // operand contextually converted to bool.
9893         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
9894                                   ScalarTypeToBooleanCastKind(resultType));
9895       } else if (Context.getLangOpts().OpenCL &&
9896                  Context.getLangOpts().OpenCLVersion < 120) {
9897         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9898         // operate on scalar float types.
9899         if (!resultType->isIntegerType())
9900           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9901                            << resultType << Input.get()->getSourceRange());
9902       }
9903     } else if (resultType->isExtVectorType()) {
9904       if (Context.getLangOpts().OpenCL &&
9905           Context.getLangOpts().OpenCLVersion < 120) {
9906         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9907         // operate on vector float types.
9908         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9909         if (!T->isIntegerType())
9910           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9911                            << resultType << Input.get()->getSourceRange());
9912       }
9913       // Vector logical not returns the signed variant of the operand type.
9914       resultType = GetSignedVectorType(resultType);
9915       break;
9916     } else {
9917       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9918         << resultType << Input.get()->getSourceRange());
9919     }
9920 
9921     // LNot always has type int. C99 6.5.3.3p5.
9922     // In C++, it's bool. C++ 5.3.1p8
9923     resultType = Context.getLogicalOperationType();
9924     break;
9925   case UO_Real:
9926   case UO_Imag:
9927     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9928     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9929     // complex l-values to ordinary l-values and all other values to r-values.
9930     if (Input.isInvalid()) return ExprError();
9931     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9932       if (Input.get()->getValueKind() != VK_RValue &&
9933           Input.get()->getObjectKind() == OK_Ordinary)
9934         VK = Input.get()->getValueKind();
9935     } else if (!getLangOpts().CPlusPlus) {
9936       // In C, a volatile scalar is read by __imag. In C++, it is not.
9937       Input = DefaultLvalueConversion(Input.get());
9938     }
9939     break;
9940   case UO_Extension:
9941     resultType = Input.get()->getType();
9942     VK = Input.get()->getValueKind();
9943     OK = Input.get()->getObjectKind();
9944     break;
9945   }
9946   if (resultType.isNull() || Input.isInvalid())
9947     return ExprError();
9948 
9949   // Check for array bounds violations in the operand of the UnaryOperator,
9950   // except for the '*' and '&' operators that have to be handled specially
9951   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9952   // that are explicitly defined as valid by the standard).
9953   if (Opc != UO_AddrOf && Opc != UO_Deref)
9954     CheckArrayAccess(Input.get());
9955 
9956   return new (Context)
9957       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
9958 }
9959 
9960 /// \brief Determine whether the given expression is a qualified member
9961 /// access expression, of a form that could be turned into a pointer to member
9962 /// with the address-of operator.
isQualifiedMemberAccess(Expr * E)9963 static bool isQualifiedMemberAccess(Expr *E) {
9964   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9965     if (!DRE->getQualifier())
9966       return false;
9967 
9968     ValueDecl *VD = DRE->getDecl();
9969     if (!VD->isCXXClassMember())
9970       return false;
9971 
9972     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9973       return true;
9974     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9975       return Method->isInstance();
9976 
9977     return false;
9978   }
9979 
9980   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9981     if (!ULE->getQualifier())
9982       return false;
9983 
9984     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9985                                            DEnd = ULE->decls_end();
9986          D != DEnd; ++D) {
9987       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9988         if (Method->isInstance())
9989           return true;
9990       } else {
9991         // Overload set does not contain methods.
9992         break;
9993       }
9994     }
9995 
9996     return false;
9997   }
9998 
9999   return false;
10000 }
10001 
BuildUnaryOp(Scope * S,SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * Input)10002 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
10003                               UnaryOperatorKind Opc, Expr *Input) {
10004   // First things first: handle placeholders so that the
10005   // overloaded-operator check considers the right type.
10006   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
10007     // Increment and decrement of pseudo-object references.
10008     if (pty->getKind() == BuiltinType::PseudoObject &&
10009         UnaryOperator::isIncrementDecrementOp(Opc))
10010       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
10011 
10012     // extension is always a builtin operator.
10013     if (Opc == UO_Extension)
10014       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10015 
10016     // & gets special logic for several kinds of placeholder.
10017     // The builtin code knows what to do.
10018     if (Opc == UO_AddrOf &&
10019         (pty->getKind() == BuiltinType::Overload ||
10020          pty->getKind() == BuiltinType::UnknownAny ||
10021          pty->getKind() == BuiltinType::BoundMember))
10022       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10023 
10024     // Anything else needs to be handled now.
10025     ExprResult Result = CheckPlaceholderExpr(Input);
10026     if (Result.isInvalid()) return ExprError();
10027     Input = Result.get();
10028   }
10029 
10030   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
10031       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
10032       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
10033     // Find all of the overloaded operators visible from this
10034     // point. We perform both an operator-name lookup from the local
10035     // scope and an argument-dependent lookup based on the types of
10036     // the arguments.
10037     UnresolvedSet<16> Functions;
10038     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
10039     if (S && OverOp != OO_None)
10040       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
10041                                    Functions);
10042 
10043     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
10044   }
10045 
10046   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10047 }
10048 
10049 // Unary Operators.  'Tok' is the token for the operator.
ActOnUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Op,Expr * Input)10050 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
10051                               tok::TokenKind Op, Expr *Input) {
10052   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
10053 }
10054 
10055 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ActOnAddrLabel(SourceLocation OpLoc,SourceLocation LabLoc,LabelDecl * TheDecl)10056 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
10057                                 LabelDecl *TheDecl) {
10058   TheDecl->markUsed(Context);
10059   // Create the AST node.  The address of a label always has type 'void*'.
10060   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
10061                                      Context.getPointerType(Context.VoidTy));
10062 }
10063 
10064 /// Given the last statement in a statement-expression, check whether
10065 /// the result is a producing expression (like a call to an
10066 /// ns_returns_retained function) and, if so, rebuild it to hoist the
10067 /// release out of the full-expression.  Otherwise, return null.
10068 /// Cannot fail.
maybeRebuildARCConsumingStmt(Stmt * Statement)10069 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
10070   // Should always be wrapped with one of these.
10071   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
10072   if (!cleanups) return nullptr;
10073 
10074   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
10075   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
10076     return nullptr;
10077 
10078   // Splice out the cast.  This shouldn't modify any interesting
10079   // features of the statement.
10080   Expr *producer = cast->getSubExpr();
10081   assert(producer->getType() == cast->getType());
10082   assert(producer->getValueKind() == cast->getValueKind());
10083   cleanups->setSubExpr(producer);
10084   return cleanups;
10085 }
10086 
ActOnStartStmtExpr()10087 void Sema::ActOnStartStmtExpr() {
10088   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
10089 }
10090 
ActOnStmtExprError()10091 void Sema::ActOnStmtExprError() {
10092   // Note that function is also called by TreeTransform when leaving a
10093   // StmtExpr scope without rebuilding anything.
10094 
10095   DiscardCleanupsInEvaluationContext();
10096   PopExpressionEvaluationContext();
10097 }
10098 
10099 ExprResult
ActOnStmtExpr(SourceLocation LPLoc,Stmt * SubStmt,SourceLocation RPLoc)10100 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
10101                     SourceLocation RPLoc) { // "({..})"
10102   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
10103   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
10104 
10105   if (hasAnyUnrecoverableErrorsInThisFunction())
10106     DiscardCleanupsInEvaluationContext();
10107   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10108   PopExpressionEvaluationContext();
10109 
10110   bool isFileScope
10111     = (getCurFunctionOrMethodDecl() == nullptr) && (getCurBlock() == nullptr);
10112   if (isFileScope)
10113     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
10114 
10115   // FIXME: there are a variety of strange constraints to enforce here, for
10116   // example, it is not possible to goto into a stmt expression apparently.
10117   // More semantic analysis is needed.
10118 
10119   // If there are sub-stmts in the compound stmt, take the type of the last one
10120   // as the type of the stmtexpr.
10121   QualType Ty = Context.VoidTy;
10122   bool StmtExprMayBindToTemp = false;
10123   if (!Compound->body_empty()) {
10124     Stmt *LastStmt = Compound->body_back();
10125     LabelStmt *LastLabelStmt = nullptr;
10126     // If LastStmt is a label, skip down through into the body.
10127     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10128       LastLabelStmt = Label;
10129       LastStmt = Label->getSubStmt();
10130     }
10131 
10132     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10133       // Do function/array conversion on the last expression, but not
10134       // lvalue-to-rvalue.  However, initialize an unqualified type.
10135       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10136       if (LastExpr.isInvalid())
10137         return ExprError();
10138       Ty = LastExpr.get()->getType().getUnqualifiedType();
10139 
10140       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10141         // In ARC, if the final expression ends in a consume, splice
10142         // the consume out and bind it later.  In the alternate case
10143         // (when dealing with a retainable type), the result
10144         // initialization will create a produce.  In both cases the
10145         // result will be +1, and we'll need to balance that out with
10146         // a bind.
10147         if (Expr *rebuiltLastStmt
10148               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10149           LastExpr = rebuiltLastStmt;
10150         } else {
10151           LastExpr = PerformCopyInitialization(
10152                             InitializedEntity::InitializeResult(LPLoc,
10153                                                                 Ty,
10154                                                                 false),
10155                                                    SourceLocation(),
10156                                                LastExpr);
10157         }
10158 
10159         if (LastExpr.isInvalid())
10160           return ExprError();
10161         if (LastExpr.get() != nullptr) {
10162           if (!LastLabelStmt)
10163             Compound->setLastStmt(LastExpr.get());
10164           else
10165             LastLabelStmt->setSubStmt(LastExpr.get());
10166           StmtExprMayBindToTemp = true;
10167         }
10168       }
10169     }
10170   }
10171 
10172   // FIXME: Check that expression type is complete/non-abstract; statement
10173   // expressions are not lvalues.
10174   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10175   if (StmtExprMayBindToTemp)
10176     return MaybeBindToTemporary(ResStmtExpr);
10177   return ResStmtExpr;
10178 }
10179 
BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,TypeSourceInfo * TInfo,OffsetOfComponent * CompPtr,unsigned NumComponents,SourceLocation RParenLoc)10180 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10181                                       TypeSourceInfo *TInfo,
10182                                       OffsetOfComponent *CompPtr,
10183                                       unsigned NumComponents,
10184                                       SourceLocation RParenLoc) {
10185   QualType ArgTy = TInfo->getType();
10186   bool Dependent = ArgTy->isDependentType();
10187   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10188 
10189   // We must have at least one component that refers to the type, and the first
10190   // one is known to be a field designator.  Verify that the ArgTy represents
10191   // a struct/union/class.
10192   if (!Dependent && !ArgTy->isRecordType())
10193     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10194                        << ArgTy << TypeRange);
10195 
10196   // Type must be complete per C99 7.17p3 because a declaring a variable
10197   // with an incomplete type would be ill-formed.
10198   if (!Dependent
10199       && RequireCompleteType(BuiltinLoc, ArgTy,
10200                              diag::err_offsetof_incomplete_type, TypeRange))
10201     return ExprError();
10202 
10203   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10204   // GCC extension, diagnose them.
10205   // FIXME: This diagnostic isn't actually visible because the location is in
10206   // a system header!
10207   if (NumComponents != 1)
10208     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10209       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10210 
10211   bool DidWarnAboutNonPOD = false;
10212   QualType CurrentType = ArgTy;
10213   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10214   SmallVector<OffsetOfNode, 4> Comps;
10215   SmallVector<Expr*, 4> Exprs;
10216   for (unsigned i = 0; i != NumComponents; ++i) {
10217     const OffsetOfComponent &OC = CompPtr[i];
10218     if (OC.isBrackets) {
10219       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10220       if (!CurrentType->isDependentType()) {
10221         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10222         if(!AT)
10223           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10224                            << CurrentType);
10225         CurrentType = AT->getElementType();
10226       } else
10227         CurrentType = Context.DependentTy;
10228 
10229       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10230       if (IdxRval.isInvalid())
10231         return ExprError();
10232       Expr *Idx = IdxRval.get();
10233 
10234       // The expression must be an integral expression.
10235       // FIXME: An integral constant expression?
10236       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10237           !Idx->getType()->isIntegerType())
10238         return ExprError(Diag(Idx->getLocStart(),
10239                               diag::err_typecheck_subscript_not_integer)
10240                          << Idx->getSourceRange());
10241 
10242       // Record this array index.
10243       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10244       Exprs.push_back(Idx);
10245       continue;
10246     }
10247 
10248     // Offset of a field.
10249     if (CurrentType->isDependentType()) {
10250       // We have the offset of a field, but we can't look into the dependent
10251       // type. Just record the identifier of the field.
10252       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10253       CurrentType = Context.DependentTy;
10254       continue;
10255     }
10256 
10257     // We need to have a complete type to look into.
10258     if (RequireCompleteType(OC.LocStart, CurrentType,
10259                             diag::err_offsetof_incomplete_type))
10260       return ExprError();
10261 
10262     // Look for the designated field.
10263     const RecordType *RC = CurrentType->getAs<RecordType>();
10264     if (!RC)
10265       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10266                        << CurrentType);
10267     RecordDecl *RD = RC->getDecl();
10268 
10269     // C++ [lib.support.types]p5:
10270     //   The macro offsetof accepts a restricted set of type arguments in this
10271     //   International Standard. type shall be a POD structure or a POD union
10272     //   (clause 9).
10273     // C++11 [support.types]p4:
10274     //   If type is not a standard-layout class (Clause 9), the results are
10275     //   undefined.
10276     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10277       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10278       unsigned DiagID =
10279         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
10280                             : diag::warn_offsetof_non_pod_type;
10281 
10282       if (!IsSafe && !DidWarnAboutNonPOD &&
10283           DiagRuntimeBehavior(BuiltinLoc, nullptr,
10284                               PDiag(DiagID)
10285                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10286                               << CurrentType))
10287         DidWarnAboutNonPOD = true;
10288     }
10289 
10290     // Look for the field.
10291     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10292     LookupQualifiedName(R, RD);
10293     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10294     IndirectFieldDecl *IndirectMemberDecl = nullptr;
10295     if (!MemberDecl) {
10296       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10297         MemberDecl = IndirectMemberDecl->getAnonField();
10298     }
10299 
10300     if (!MemberDecl)
10301       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10302                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10303                                                               OC.LocEnd));
10304 
10305     // C99 7.17p3:
10306     //   (If the specified member is a bit-field, the behavior is undefined.)
10307     //
10308     // We diagnose this as an error.
10309     if (MemberDecl->isBitField()) {
10310       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10311         << MemberDecl->getDeclName()
10312         << SourceRange(BuiltinLoc, RParenLoc);
10313       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10314       return ExprError();
10315     }
10316 
10317     RecordDecl *Parent = MemberDecl->getParent();
10318     if (IndirectMemberDecl)
10319       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10320 
10321     // If the member was found in a base class, introduce OffsetOfNodes for
10322     // the base class indirections.
10323     CXXBasePaths Paths;
10324     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10325       if (Paths.getDetectedVirtual()) {
10326         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10327           << MemberDecl->getDeclName()
10328           << SourceRange(BuiltinLoc, RParenLoc);
10329         return ExprError();
10330       }
10331 
10332       CXXBasePath &Path = Paths.front();
10333       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10334            B != BEnd; ++B)
10335         Comps.push_back(OffsetOfNode(B->Base));
10336     }
10337 
10338     if (IndirectMemberDecl) {
10339       for (auto *FI : IndirectMemberDecl->chain()) {
10340         assert(isa<FieldDecl>(FI));
10341         Comps.push_back(OffsetOfNode(OC.LocStart,
10342                                      cast<FieldDecl>(FI), OC.LocEnd));
10343       }
10344     } else
10345       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10346 
10347     CurrentType = MemberDecl->getType().getNonReferenceType();
10348   }
10349 
10350   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
10351                               Comps, Exprs, RParenLoc);
10352 }
10353 
ActOnBuiltinOffsetOf(Scope * S,SourceLocation BuiltinLoc,SourceLocation TypeLoc,ParsedType ParsedArgTy,OffsetOfComponent * CompPtr,unsigned NumComponents,SourceLocation RParenLoc)10354 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10355                                       SourceLocation BuiltinLoc,
10356                                       SourceLocation TypeLoc,
10357                                       ParsedType ParsedArgTy,
10358                                       OffsetOfComponent *CompPtr,
10359                                       unsigned NumComponents,
10360                                       SourceLocation RParenLoc) {
10361 
10362   TypeSourceInfo *ArgTInfo;
10363   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10364   if (ArgTy.isNull())
10365     return ExprError();
10366 
10367   if (!ArgTInfo)
10368     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10369 
10370   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10371                               RParenLoc);
10372 }
10373 
10374 
ActOnChooseExpr(SourceLocation BuiltinLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr,SourceLocation RPLoc)10375 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10376                                  Expr *CondExpr,
10377                                  Expr *LHSExpr, Expr *RHSExpr,
10378                                  SourceLocation RPLoc) {
10379   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10380 
10381   ExprValueKind VK = VK_RValue;
10382   ExprObjectKind OK = OK_Ordinary;
10383   QualType resType;
10384   bool ValueDependent = false;
10385   bool CondIsTrue = false;
10386   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10387     resType = Context.DependentTy;
10388     ValueDependent = true;
10389   } else {
10390     // The conditional expression is required to be a constant expression.
10391     llvm::APSInt condEval(32);
10392     ExprResult CondICE
10393       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10394           diag::err_typecheck_choose_expr_requires_constant, false);
10395     if (CondICE.isInvalid())
10396       return ExprError();
10397     CondExpr = CondICE.get();
10398     CondIsTrue = condEval.getZExtValue();
10399 
10400     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10401     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10402 
10403     resType = ActiveExpr->getType();
10404     ValueDependent = ActiveExpr->isValueDependent();
10405     VK = ActiveExpr->getValueKind();
10406     OK = ActiveExpr->getObjectKind();
10407   }
10408 
10409   return new (Context)
10410       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
10411                  CondIsTrue, resType->isDependentType(), ValueDependent);
10412 }
10413 
10414 //===----------------------------------------------------------------------===//
10415 // Clang Extensions.
10416 //===----------------------------------------------------------------------===//
10417 
10418 /// ActOnBlockStart - This callback is invoked when a block literal is started.
ActOnBlockStart(SourceLocation CaretLoc,Scope * CurScope)10419 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10420   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10421 
10422   if (LangOpts.CPlusPlus) {
10423     Decl *ManglingContextDecl;
10424     if (MangleNumberingContext *MCtx =
10425             getCurrentMangleNumberContext(Block->getDeclContext(),
10426                                           ManglingContextDecl)) {
10427       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10428       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10429     }
10430   }
10431 
10432   PushBlockScope(CurScope, Block);
10433   CurContext->addDecl(Block);
10434   if (CurScope)
10435     PushDeclContext(CurScope, Block);
10436   else
10437     CurContext = Block;
10438 
10439   getCurBlock()->HasImplicitReturnType = true;
10440 
10441   // Enter a new evaluation context to insulate the block from any
10442   // cleanups from the enclosing full-expression.
10443   PushExpressionEvaluationContext(PotentiallyEvaluated);
10444 }
10445 
ActOnBlockArguments(SourceLocation CaretLoc,Declarator & ParamInfo,Scope * CurScope)10446 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10447                                Scope *CurScope) {
10448   assert(ParamInfo.getIdentifier() == nullptr &&
10449          "block-id should have no identifier!");
10450   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10451   BlockScopeInfo *CurBlock = getCurBlock();
10452 
10453   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10454   QualType T = Sig->getType();
10455 
10456   // FIXME: We should allow unexpanded parameter packs here, but that would,
10457   // in turn, make the block expression contain unexpanded parameter packs.
10458   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10459     // Drop the parameters.
10460     FunctionProtoType::ExtProtoInfo EPI;
10461     EPI.HasTrailingReturn = false;
10462     EPI.TypeQuals |= DeclSpec::TQ_const;
10463     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10464     Sig = Context.getTrivialTypeSourceInfo(T);
10465   }
10466 
10467   // GetTypeForDeclarator always produces a function type for a block
10468   // literal signature.  Furthermore, it is always a FunctionProtoType
10469   // unless the function was written with a typedef.
10470   assert(T->isFunctionType() &&
10471          "GetTypeForDeclarator made a non-function block signature");
10472 
10473   // Look for an explicit signature in that function type.
10474   FunctionProtoTypeLoc ExplicitSignature;
10475 
10476   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10477   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10478 
10479     // Check whether that explicit signature was synthesized by
10480     // GetTypeForDeclarator.  If so, don't save that as part of the
10481     // written signature.
10482     if (ExplicitSignature.getLocalRangeBegin() ==
10483         ExplicitSignature.getLocalRangeEnd()) {
10484       // This would be much cheaper if we stored TypeLocs instead of
10485       // TypeSourceInfos.
10486       TypeLoc Result = ExplicitSignature.getReturnLoc();
10487       unsigned Size = Result.getFullDataSize();
10488       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10489       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10490 
10491       ExplicitSignature = FunctionProtoTypeLoc();
10492     }
10493   }
10494 
10495   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10496   CurBlock->FunctionType = T;
10497 
10498   const FunctionType *Fn = T->getAs<FunctionType>();
10499   QualType RetTy = Fn->getReturnType();
10500   bool isVariadic =
10501     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10502 
10503   CurBlock->TheDecl->setIsVariadic(isVariadic);
10504 
10505   // Context.DependentTy is used as a placeholder for a missing block
10506   // return type.  TODO:  what should we do with declarators like:
10507   //   ^ * { ... }
10508   // If the answer is "apply template argument deduction"....
10509   if (RetTy != Context.DependentTy) {
10510     CurBlock->ReturnType = RetTy;
10511     CurBlock->TheDecl->setBlockMissingReturnType(false);
10512     CurBlock->HasImplicitReturnType = false;
10513   }
10514 
10515   // Push block parameters from the declarator if we had them.
10516   SmallVector<ParmVarDecl*, 8> Params;
10517   if (ExplicitSignature) {
10518     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
10519       ParmVarDecl *Param = ExplicitSignature.getParam(I);
10520       if (Param->getIdentifier() == nullptr &&
10521           !Param->isImplicit() &&
10522           !Param->isInvalidDecl() &&
10523           !getLangOpts().CPlusPlus)
10524         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10525       Params.push_back(Param);
10526     }
10527 
10528   // Fake up parameter variables if we have a typedef, like
10529   //   ^ fntype { ... }
10530   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10531     for (const auto &I : Fn->param_types()) {
10532       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
10533           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
10534       Params.push_back(Param);
10535     }
10536   }
10537 
10538   // Set the parameters on the block decl.
10539   if (!Params.empty()) {
10540     CurBlock->TheDecl->setParams(Params);
10541     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10542                              CurBlock->TheDecl->param_end(),
10543                              /*CheckParameterNames=*/false);
10544   }
10545 
10546   // Finally we can process decl attributes.
10547   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10548 
10549   // Put the parameter variables in scope.
10550   for (auto AI : CurBlock->TheDecl->params()) {
10551     AI->setOwningFunction(CurBlock->TheDecl);
10552 
10553     // If this has an identifier, add it to the scope stack.
10554     if (AI->getIdentifier()) {
10555       CheckShadow(CurBlock->TheScope, AI);
10556 
10557       PushOnScopeChains(AI, CurBlock->TheScope);
10558     }
10559   }
10560 }
10561 
10562 /// ActOnBlockError - If there is an error parsing a block, this callback
10563 /// is invoked to pop the information about the block from the action impl.
ActOnBlockError(SourceLocation CaretLoc,Scope * CurScope)10564 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10565   // Leave the expression-evaluation context.
10566   DiscardCleanupsInEvaluationContext();
10567   PopExpressionEvaluationContext();
10568 
10569   // Pop off CurBlock, handle nested blocks.
10570   PopDeclContext();
10571   PopFunctionScopeInfo();
10572 }
10573 
10574 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10575 /// literal was successfully completed.  ^(int x){...}
ActOnBlockStmtExpr(SourceLocation CaretLoc,Stmt * Body,Scope * CurScope)10576 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10577                                     Stmt *Body, Scope *CurScope) {
10578   // If blocks are disabled, emit an error.
10579   if (!LangOpts.Blocks)
10580     Diag(CaretLoc, diag::err_blocks_disable);
10581 
10582   // Leave the expression-evaluation context.
10583   if (hasAnyUnrecoverableErrorsInThisFunction())
10584     DiscardCleanupsInEvaluationContext();
10585   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10586   PopExpressionEvaluationContext();
10587 
10588   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10589 
10590   if (BSI->HasImplicitReturnType)
10591     deduceClosureReturnType(*BSI);
10592 
10593   PopDeclContext();
10594 
10595   QualType RetTy = Context.VoidTy;
10596   if (!BSI->ReturnType.isNull())
10597     RetTy = BSI->ReturnType;
10598 
10599   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
10600   QualType BlockTy;
10601 
10602   // Set the captured variables on the block.
10603   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10604   SmallVector<BlockDecl::Capture, 4> Captures;
10605   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10606     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10607     if (Cap.isThisCapture())
10608       continue;
10609     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10610                               Cap.isNested(), Cap.getInitExpr());
10611     Captures.push_back(NewCap);
10612   }
10613   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10614                             BSI->CXXThisCaptureIndex != 0);
10615 
10616   // If the user wrote a function type in some form, try to use that.
10617   if (!BSI->FunctionType.isNull()) {
10618     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10619 
10620     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10621     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10622 
10623     // Turn protoless block types into nullary block types.
10624     if (isa<FunctionNoProtoType>(FTy)) {
10625       FunctionProtoType::ExtProtoInfo EPI;
10626       EPI.ExtInfo = Ext;
10627       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10628 
10629     // Otherwise, if we don't need to change anything about the function type,
10630     // preserve its sugar structure.
10631     } else if (FTy->getReturnType() == RetTy &&
10632                (!NoReturn || FTy->getNoReturnAttr())) {
10633       BlockTy = BSI->FunctionType;
10634 
10635     // Otherwise, make the minimal modifications to the function type.
10636     } else {
10637       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10638       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10639       EPI.TypeQuals = 0; // FIXME: silently?
10640       EPI.ExtInfo = Ext;
10641       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
10642     }
10643 
10644   // If we don't have a function type, just build one from nothing.
10645   } else {
10646     FunctionProtoType::ExtProtoInfo EPI;
10647     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10648     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10649   }
10650 
10651   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10652                            BSI->TheDecl->param_end());
10653   BlockTy = Context.getBlockPointerType(BlockTy);
10654 
10655   // If needed, diagnose invalid gotos and switches in the block.
10656   if (getCurFunction()->NeedsScopeChecking() &&
10657       !PP.isCodeCompletionEnabled())
10658     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10659 
10660   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10661 
10662   // Try to apply the named return value optimization. We have to check again
10663   // if we can do this, though, because blocks keep return statements around
10664   // to deduce an implicit return type.
10665   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10666       !BSI->TheDecl->isDependentContext())
10667     computeNRVO(Body, BSI);
10668 
10669   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10670   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10671   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10672 
10673   // If the block isn't obviously global, i.e. it captures anything at
10674   // all, then we need to do a few things in the surrounding context:
10675   if (Result->getBlockDecl()->hasCaptures()) {
10676     // First, this expression has a new cleanup object.
10677     ExprCleanupObjects.push_back(Result->getBlockDecl());
10678     ExprNeedsCleanups = true;
10679 
10680     // It also gets a branch-protected scope if any of the captured
10681     // variables needs destruction.
10682     for (const auto &CI : Result->getBlockDecl()->captures()) {
10683       const VarDecl *var = CI.getVariable();
10684       if (var->getType().isDestructedType() != QualType::DK_none) {
10685         getCurFunction()->setHasBranchProtectedScope();
10686         break;
10687       }
10688     }
10689   }
10690 
10691   return Result;
10692 }
10693 
ActOnVAArg(SourceLocation BuiltinLoc,Expr * E,ParsedType Ty,SourceLocation RPLoc)10694 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10695                                         Expr *E, ParsedType Ty,
10696                                         SourceLocation RPLoc) {
10697   TypeSourceInfo *TInfo;
10698   GetTypeFromParser(Ty, &TInfo);
10699   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10700 }
10701 
BuildVAArgExpr(SourceLocation BuiltinLoc,Expr * E,TypeSourceInfo * TInfo,SourceLocation RPLoc)10702 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10703                                 Expr *E, TypeSourceInfo *TInfo,
10704                                 SourceLocation RPLoc) {
10705   Expr *OrigExpr = E;
10706 
10707   // Get the va_list type
10708   QualType VaListType = Context.getBuiltinVaListType();
10709   if (VaListType->isArrayType()) {
10710     // Deal with implicit array decay; for example, on x86-64,
10711     // va_list is an array, but it's supposed to decay to
10712     // a pointer for va_arg.
10713     VaListType = Context.getArrayDecayedType(VaListType);
10714     // Make sure the input expression also decays appropriately.
10715     ExprResult Result = UsualUnaryConversions(E);
10716     if (Result.isInvalid())
10717       return ExprError();
10718     E = Result.get();
10719   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10720     // If va_list is a record type and we are compiling in C++ mode,
10721     // check the argument using reference binding.
10722     InitializedEntity Entity
10723       = InitializedEntity::InitializeParameter(Context,
10724           Context.getLValueReferenceType(VaListType), false);
10725     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10726     if (Init.isInvalid())
10727       return ExprError();
10728     E = Init.getAs<Expr>();
10729   } else {
10730     // Otherwise, the va_list argument must be an l-value because
10731     // it is modified by va_arg.
10732     if (!E->isTypeDependent() &&
10733         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10734       return ExprError();
10735   }
10736 
10737   if (!E->isTypeDependent() &&
10738       !Context.hasSameType(VaListType, E->getType())) {
10739     return ExprError(Diag(E->getLocStart(),
10740                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10741       << OrigExpr->getType() << E->getSourceRange());
10742   }
10743 
10744   if (!TInfo->getType()->isDependentType()) {
10745     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10746                             diag::err_second_parameter_to_va_arg_incomplete,
10747                             TInfo->getTypeLoc()))
10748       return ExprError();
10749 
10750     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10751                                TInfo->getType(),
10752                                diag::err_second_parameter_to_va_arg_abstract,
10753                                TInfo->getTypeLoc()))
10754       return ExprError();
10755 
10756     if (!TInfo->getType().isPODType(Context)) {
10757       Diag(TInfo->getTypeLoc().getBeginLoc(),
10758            TInfo->getType()->isObjCLifetimeType()
10759              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10760              : diag::warn_second_parameter_to_va_arg_not_pod)
10761         << TInfo->getType()
10762         << TInfo->getTypeLoc().getSourceRange();
10763     }
10764 
10765     // Check for va_arg where arguments of the given type will be promoted
10766     // (i.e. this va_arg is guaranteed to have undefined behavior).
10767     QualType PromoteType;
10768     if (TInfo->getType()->isPromotableIntegerType()) {
10769       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10770       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10771         PromoteType = QualType();
10772     }
10773     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10774       PromoteType = Context.DoubleTy;
10775     if (!PromoteType.isNull())
10776       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10777                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10778                           << TInfo->getType()
10779                           << PromoteType
10780                           << TInfo->getTypeLoc().getSourceRange());
10781   }
10782 
10783   QualType T = TInfo->getType().getNonLValueExprType(Context);
10784   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
10785 }
10786 
ActOnGNUNullExpr(SourceLocation TokenLoc)10787 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10788   // The type of __null will be int or long, depending on the size of
10789   // pointers on the target.
10790   QualType Ty;
10791   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10792   if (pw == Context.getTargetInfo().getIntWidth())
10793     Ty = Context.IntTy;
10794   else if (pw == Context.getTargetInfo().getLongWidth())
10795     Ty = Context.LongTy;
10796   else if (pw == Context.getTargetInfo().getLongLongWidth())
10797     Ty = Context.LongLongTy;
10798   else {
10799     llvm_unreachable("I don't know size of pointer!");
10800   }
10801 
10802   return new (Context) GNUNullExpr(Ty, TokenLoc);
10803 }
10804 
10805 bool
ConversionToObjCStringLiteralCheck(QualType DstType,Expr * & Exp)10806 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
10807   if (!getLangOpts().ObjC1)
10808     return false;
10809 
10810   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10811   if (!PT)
10812     return false;
10813 
10814   if (!PT->isObjCIdType()) {
10815     // Check if the destination is the 'NSString' interface.
10816     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10817     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10818       return false;
10819   }
10820 
10821   // Ignore any parens, implicit casts (should only be
10822   // array-to-pointer decays), and not-so-opaque values.  The last is
10823   // important for making this trigger for property assignments.
10824   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
10825   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10826     if (OV->getSourceExpr())
10827       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10828 
10829   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10830   if (!SL || !SL->isAscii())
10831     return false;
10832   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
10833     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
10834   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
10835   return true;
10836 }
10837 
DiagnoseAssignmentResult(AssignConvertType ConvTy,SourceLocation Loc,QualType DstType,QualType SrcType,Expr * SrcExpr,AssignmentAction Action,bool * Complained)10838 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10839                                     SourceLocation Loc,
10840                                     QualType DstType, QualType SrcType,
10841                                     Expr *SrcExpr, AssignmentAction Action,
10842                                     bool *Complained) {
10843   if (Complained)
10844     *Complained = false;
10845 
10846   // Decode the result (notice that AST's are still created for extensions).
10847   bool CheckInferredResultType = false;
10848   bool isInvalid = false;
10849   unsigned DiagKind = 0;
10850   FixItHint Hint;
10851   ConversionFixItGenerator ConvHints;
10852   bool MayHaveConvFixit = false;
10853   bool MayHaveFunctionDiff = false;
10854   const ObjCInterfaceDecl *IFace = nullptr;
10855   const ObjCProtocolDecl *PDecl = nullptr;
10856 
10857   switch (ConvTy) {
10858   case Compatible:
10859       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10860       return false;
10861 
10862   case PointerToInt:
10863     DiagKind = diag::ext_typecheck_convert_pointer_int;
10864     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10865     MayHaveConvFixit = true;
10866     break;
10867   case IntToPointer:
10868     DiagKind = diag::ext_typecheck_convert_int_pointer;
10869     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10870     MayHaveConvFixit = true;
10871     break;
10872   case IncompatiblePointer:
10873       DiagKind =
10874         (Action == AA_Passing_CFAudited ?
10875           diag::err_arc_typecheck_convert_incompatible_pointer :
10876           diag::ext_typecheck_convert_incompatible_pointer);
10877     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10878       SrcType->isObjCObjectPointerType();
10879     if (Hint.isNull() && !CheckInferredResultType) {
10880       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10881     }
10882     else if (CheckInferredResultType) {
10883       SrcType = SrcType.getUnqualifiedType();
10884       DstType = DstType.getUnqualifiedType();
10885     }
10886     MayHaveConvFixit = true;
10887     break;
10888   case IncompatiblePointerSign:
10889     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10890     break;
10891   case FunctionVoidPointer:
10892     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10893     break;
10894   case IncompatiblePointerDiscardsQualifiers: {
10895     // Perform array-to-pointer decay if necessary.
10896     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10897 
10898     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10899     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10900     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10901       DiagKind = diag::err_typecheck_incompatible_address_space;
10902       break;
10903 
10904 
10905     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10906       DiagKind = diag::err_typecheck_incompatible_ownership;
10907       break;
10908     }
10909 
10910     llvm_unreachable("unknown error case for discarding qualifiers!");
10911     // fallthrough
10912   }
10913   case CompatiblePointerDiscardsQualifiers:
10914     // If the qualifiers lost were because we were applying the
10915     // (deprecated) C++ conversion from a string literal to a char*
10916     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10917     // Ideally, this check would be performed in
10918     // checkPointerTypesForAssignment. However, that would require a
10919     // bit of refactoring (so that the second argument is an
10920     // expression, rather than a type), which should be done as part
10921     // of a larger effort to fix checkPointerTypesForAssignment for
10922     // C++ semantics.
10923     if (getLangOpts().CPlusPlus &&
10924         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10925       return false;
10926     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10927     break;
10928   case IncompatibleNestedPointerQualifiers:
10929     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10930     break;
10931   case IntToBlockPointer:
10932     DiagKind = diag::err_int_to_block_pointer;
10933     break;
10934   case IncompatibleBlockPointer:
10935     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10936     break;
10937   case IncompatibleObjCQualifiedId: {
10938     if (SrcType->isObjCQualifiedIdType()) {
10939       const ObjCObjectPointerType *srcOPT =
10940                 SrcType->getAs<ObjCObjectPointerType>();
10941       for (auto *srcProto : srcOPT->quals()) {
10942         PDecl = srcProto;
10943         break;
10944       }
10945       if (const ObjCInterfaceType *IFaceT =
10946             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10947         IFace = IFaceT->getDecl();
10948     }
10949     else if (DstType->isObjCQualifiedIdType()) {
10950       const ObjCObjectPointerType *dstOPT =
10951         DstType->getAs<ObjCObjectPointerType>();
10952       for (auto *dstProto : dstOPT->quals()) {
10953         PDecl = dstProto;
10954         break;
10955       }
10956       if (const ObjCInterfaceType *IFaceT =
10957             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10958         IFace = IFaceT->getDecl();
10959     }
10960     DiagKind = diag::warn_incompatible_qualified_id;
10961     break;
10962   }
10963   case IncompatibleVectors:
10964     DiagKind = diag::warn_incompatible_vectors;
10965     break;
10966   case IncompatibleObjCWeakRef:
10967     DiagKind = diag::err_arc_weak_unavailable_assign;
10968     break;
10969   case Incompatible:
10970     DiagKind = diag::err_typecheck_convert_incompatible;
10971     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10972     MayHaveConvFixit = true;
10973     isInvalid = true;
10974     MayHaveFunctionDiff = true;
10975     break;
10976   }
10977 
10978   QualType FirstType, SecondType;
10979   switch (Action) {
10980   case AA_Assigning:
10981   case AA_Initializing:
10982     // The destination type comes first.
10983     FirstType = DstType;
10984     SecondType = SrcType;
10985     break;
10986 
10987   case AA_Returning:
10988   case AA_Passing:
10989   case AA_Passing_CFAudited:
10990   case AA_Converting:
10991   case AA_Sending:
10992   case AA_Casting:
10993     // The source type comes first.
10994     FirstType = SrcType;
10995     SecondType = DstType;
10996     break;
10997   }
10998 
10999   PartialDiagnostic FDiag = PDiag(DiagKind);
11000   if (Action == AA_Passing_CFAudited)
11001     FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
11002   else
11003     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
11004 
11005   // If we can fix the conversion, suggest the FixIts.
11006   assert(ConvHints.isNull() || Hint.isNull());
11007   if (!ConvHints.isNull()) {
11008     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
11009          HE = ConvHints.Hints.end(); HI != HE; ++HI)
11010       FDiag << *HI;
11011   } else {
11012     FDiag << Hint;
11013   }
11014   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
11015 
11016   if (MayHaveFunctionDiff)
11017     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
11018 
11019   Diag(Loc, FDiag);
11020   if (DiagKind == diag::warn_incompatible_qualified_id &&
11021       PDecl && IFace && !IFace->hasDefinition())
11022       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
11023         << IFace->getName() << PDecl->getName();
11024 
11025   if (SecondType == Context.OverloadTy)
11026     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
11027                               FirstType);
11028 
11029   if (CheckInferredResultType)
11030     EmitRelatedResultTypeNote(SrcExpr);
11031 
11032   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
11033     EmitRelatedResultTypeNoteForReturn(DstType);
11034 
11035   if (Complained)
11036     *Complained = true;
11037   return isInvalid;
11038 }
11039 
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result)11040 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11041                                                  llvm::APSInt *Result) {
11042   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
11043   public:
11044     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11045       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
11046     }
11047   } Diagnoser;
11048 
11049   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
11050 }
11051 
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,unsigned DiagID,bool AllowFold)11052 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11053                                                  llvm::APSInt *Result,
11054                                                  unsigned DiagID,
11055                                                  bool AllowFold) {
11056   class IDDiagnoser : public VerifyICEDiagnoser {
11057     unsigned DiagID;
11058 
11059   public:
11060     IDDiagnoser(unsigned DiagID)
11061       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
11062 
11063     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11064       S.Diag(Loc, DiagID) << SR;
11065     }
11066   } Diagnoser(DiagID);
11067 
11068   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
11069 }
11070 
diagnoseFold(Sema & S,SourceLocation Loc,SourceRange SR)11071 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
11072                                             SourceRange SR) {
11073   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
11074 }
11075 
11076 ExprResult
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,VerifyICEDiagnoser & Diagnoser,bool AllowFold)11077 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11078                                       VerifyICEDiagnoser &Diagnoser,
11079                                       bool AllowFold) {
11080   SourceLocation DiagLoc = E->getLocStart();
11081 
11082   if (getLangOpts().CPlusPlus11) {
11083     // C++11 [expr.const]p5:
11084     //   If an expression of literal class type is used in a context where an
11085     //   integral constant expression is required, then that class type shall
11086     //   have a single non-explicit conversion function to an integral or
11087     //   unscoped enumeration type
11088     ExprResult Converted;
11089     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
11090     public:
11091       CXX11ConvertDiagnoser(bool Silent)
11092           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
11093                                 Silent, true) {}
11094 
11095       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11096                                            QualType T) override {
11097         return S.Diag(Loc, diag::err_ice_not_integral) << T;
11098       }
11099 
11100       SemaDiagnosticBuilder diagnoseIncomplete(
11101           Sema &S, SourceLocation Loc, QualType T) override {
11102         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
11103       }
11104 
11105       SemaDiagnosticBuilder diagnoseExplicitConv(
11106           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11107         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
11108       }
11109 
11110       SemaDiagnosticBuilder noteExplicitConv(
11111           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11112         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11113                  << ConvTy->isEnumeralType() << ConvTy;
11114       }
11115 
11116       SemaDiagnosticBuilder diagnoseAmbiguous(
11117           Sema &S, SourceLocation Loc, QualType T) override {
11118         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
11119       }
11120 
11121       SemaDiagnosticBuilder noteAmbiguous(
11122           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11123         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11124                  << ConvTy->isEnumeralType() << ConvTy;
11125       }
11126 
11127       SemaDiagnosticBuilder diagnoseConversion(
11128           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11129         llvm_unreachable("conversion functions are permitted");
11130       }
11131     } ConvertDiagnoser(Diagnoser.Suppress);
11132 
11133     Converted = PerformContextualImplicitConversion(DiagLoc, E,
11134                                                     ConvertDiagnoser);
11135     if (Converted.isInvalid())
11136       return Converted;
11137     E = Converted.get();
11138     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11139       return ExprError();
11140   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11141     // An ICE must be of integral or unscoped enumeration type.
11142     if (!Diagnoser.Suppress)
11143       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11144     return ExprError();
11145   }
11146 
11147   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11148   // in the non-ICE case.
11149   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11150     if (Result)
11151       *Result = E->EvaluateKnownConstInt(Context);
11152     return E;
11153   }
11154 
11155   Expr::EvalResult EvalResult;
11156   SmallVector<PartialDiagnosticAt, 8> Notes;
11157   EvalResult.Diag = &Notes;
11158 
11159   // Try to evaluate the expression, and produce diagnostics explaining why it's
11160   // not a constant expression as a side-effect.
11161   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11162                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11163 
11164   // In C++11, we can rely on diagnostics being produced for any expression
11165   // which is not a constant expression. If no diagnostics were produced, then
11166   // this is a constant expression.
11167   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11168     if (Result)
11169       *Result = EvalResult.Val.getInt();
11170     return E;
11171   }
11172 
11173   // If our only note is the usual "invalid subexpression" note, just point
11174   // the caret at its location rather than producing an essentially
11175   // redundant note.
11176   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11177         diag::note_invalid_subexpr_in_const_expr) {
11178     DiagLoc = Notes[0].first;
11179     Notes.clear();
11180   }
11181 
11182   if (!Folded || !AllowFold) {
11183     if (!Diagnoser.Suppress) {
11184       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11185       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11186         Diag(Notes[I].first, Notes[I].second);
11187     }
11188 
11189     return ExprError();
11190   }
11191 
11192   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11193   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11194     Diag(Notes[I].first, Notes[I].second);
11195 
11196   if (Result)
11197     *Result = EvalResult.Val.getInt();
11198   return E;
11199 }
11200 
11201 namespace {
11202   // Handle the case where we conclude a expression which we speculatively
11203   // considered to be unevaluated is actually evaluated.
11204   class TransformToPE : public TreeTransform<TransformToPE> {
11205     typedef TreeTransform<TransformToPE> BaseTransform;
11206 
11207   public:
TransformToPE(Sema & SemaRef)11208     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11209 
11210     // Make sure we redo semantic analysis
AlwaysRebuild()11211     bool AlwaysRebuild() { return true; }
11212 
11213     // Make sure we handle LabelStmts correctly.
11214     // FIXME: This does the right thing, but maybe we need a more general
11215     // fix to TreeTransform?
TransformLabelStmt(LabelStmt * S)11216     StmtResult TransformLabelStmt(LabelStmt *S) {
11217       S->getDecl()->setStmt(nullptr);
11218       return BaseTransform::TransformLabelStmt(S);
11219     }
11220 
11221     // We need to special-case DeclRefExprs referring to FieldDecls which
11222     // are not part of a member pointer formation; normal TreeTransforming
11223     // doesn't catch this case because of the way we represent them in the AST.
11224     // FIXME: This is a bit ugly; is it really the best way to handle this
11225     // case?
11226     //
11227     // Error on DeclRefExprs referring to FieldDecls.
TransformDeclRefExpr(DeclRefExpr * E)11228     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11229       if (isa<FieldDecl>(E->getDecl()) &&
11230           !SemaRef.isUnevaluatedContext())
11231         return SemaRef.Diag(E->getLocation(),
11232                             diag::err_invalid_non_static_member_use)
11233             << E->getDecl() << E->getSourceRange();
11234 
11235       return BaseTransform::TransformDeclRefExpr(E);
11236     }
11237 
11238     // Exception: filter out member pointer formation
TransformUnaryOperator(UnaryOperator * E)11239     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11240       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11241         return E;
11242 
11243       return BaseTransform::TransformUnaryOperator(E);
11244     }
11245 
TransformLambdaExpr(LambdaExpr * E)11246     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11247       // Lambdas never need to be transformed.
11248       return E;
11249     }
11250   };
11251 }
11252 
TransformToPotentiallyEvaluated(Expr * E)11253 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11254   assert(isUnevaluatedContext() &&
11255          "Should only transform unevaluated expressions");
11256   ExprEvalContexts.back().Context =
11257       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11258   if (isUnevaluatedContext())
11259     return E;
11260   return TransformToPE(*this).TransformExpr(E);
11261 }
11262 
11263 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,Decl * LambdaContextDecl,bool IsDecltype)11264 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11265                                       Decl *LambdaContextDecl,
11266                                       bool IsDecltype) {
11267   ExprEvalContexts.push_back(
11268              ExpressionEvaluationContextRecord(NewContext,
11269                                                ExprCleanupObjects.size(),
11270                                                ExprNeedsCleanups,
11271                                                LambdaContextDecl,
11272                                                IsDecltype));
11273   ExprNeedsCleanups = false;
11274   if (!MaybeODRUseExprs.empty())
11275     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11276 }
11277 
11278 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,ReuseLambdaContextDecl_t,bool IsDecltype)11279 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11280                                       ReuseLambdaContextDecl_t,
11281                                       bool IsDecltype) {
11282   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11283   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11284 }
11285 
PopExpressionEvaluationContext()11286 void Sema::PopExpressionEvaluationContext() {
11287   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11288 
11289   if (!Rec.Lambdas.empty()) {
11290     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11291       unsigned D;
11292       if (Rec.isUnevaluated()) {
11293         // C++11 [expr.prim.lambda]p2:
11294         //   A lambda-expression shall not appear in an unevaluated operand
11295         //   (Clause 5).
11296         D = diag::err_lambda_unevaluated_operand;
11297       } else {
11298         // C++1y [expr.const]p2:
11299         //   A conditional-expression e is a core constant expression unless the
11300         //   evaluation of e, following the rules of the abstract machine, would
11301         //   evaluate [...] a lambda-expression.
11302         D = diag::err_lambda_in_constant_expression;
11303       }
11304       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
11305         Diag(Rec.Lambdas[I]->getLocStart(), D);
11306     } else {
11307       // Mark the capture expressions odr-used. This was deferred
11308       // during lambda expression creation.
11309       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
11310         LambdaExpr *Lambda = Rec.Lambdas[I];
11311         for (LambdaExpr::capture_init_iterator
11312                   C = Lambda->capture_init_begin(),
11313                CEnd = Lambda->capture_init_end();
11314              C != CEnd; ++C) {
11315           MarkDeclarationsReferencedInExpr(*C);
11316         }
11317       }
11318     }
11319   }
11320 
11321   // When are coming out of an unevaluated context, clear out any
11322   // temporaries that we may have created as part of the evaluation of
11323   // the expression in that context: they aren't relevant because they
11324   // will never be constructed.
11325   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11326     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11327                              ExprCleanupObjects.end());
11328     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11329     CleanupVarDeclMarking();
11330     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11331   // Otherwise, merge the contexts together.
11332   } else {
11333     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11334     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11335                             Rec.SavedMaybeODRUseExprs.end());
11336   }
11337 
11338   // Pop the current expression evaluation context off the stack.
11339   ExprEvalContexts.pop_back();
11340 }
11341 
DiscardCleanupsInEvaluationContext()11342 void Sema::DiscardCleanupsInEvaluationContext() {
11343   ExprCleanupObjects.erase(
11344          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11345          ExprCleanupObjects.end());
11346   ExprNeedsCleanups = false;
11347   MaybeODRUseExprs.clear();
11348 }
11349 
HandleExprEvaluationContextForTypeof(Expr * E)11350 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11351   if (!E->getType()->isVariablyModifiedType())
11352     return E;
11353   return TransformToPotentiallyEvaluated(E);
11354 }
11355 
IsPotentiallyEvaluatedContext(Sema & SemaRef)11356 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11357   // Do not mark anything as "used" within a dependent context; wait for
11358   // an instantiation.
11359   if (SemaRef.CurContext->isDependentContext())
11360     return false;
11361 
11362   switch (SemaRef.ExprEvalContexts.back().Context) {
11363     case Sema::Unevaluated:
11364     case Sema::UnevaluatedAbstract:
11365       // We are in an expression that is not potentially evaluated; do nothing.
11366       // (Depending on how you read the standard, we actually do need to do
11367       // something here for null pointer constants, but the standard's
11368       // definition of a null pointer constant is completely crazy.)
11369       return false;
11370 
11371     case Sema::ConstantEvaluated:
11372     case Sema::PotentiallyEvaluated:
11373       // We are in a potentially evaluated expression (or a constant-expression
11374       // in C++03); we need to do implicit template instantiation, implicitly
11375       // define class members, and mark most declarations as used.
11376       return true;
11377 
11378     case Sema::PotentiallyEvaluatedIfUsed:
11379       // Referenced declarations will only be used if the construct in the
11380       // containing expression is used.
11381       return false;
11382   }
11383   llvm_unreachable("Invalid context");
11384 }
11385 
11386 /// \brief Mark a function referenced, and check whether it is odr-used
11387 /// (C++ [basic.def.odr]p2, C99 6.9p3)
MarkFunctionReferenced(SourceLocation Loc,FunctionDecl * Func)11388 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
11389   assert(Func && "No function?");
11390 
11391   Func->setReferenced();
11392 
11393   // C++11 [basic.def.odr]p3:
11394   //   A function whose name appears as a potentially-evaluated expression is
11395   //   odr-used if it is the unique lookup result or the selected member of a
11396   //   set of overloaded functions [...].
11397   //
11398   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11399   // can just check that here. Skip the rest of this function if we've already
11400   // marked the function as used.
11401   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11402     // C++11 [temp.inst]p3:
11403     //   Unless a function template specialization has been explicitly
11404     //   instantiated or explicitly specialized, the function template
11405     //   specialization is implicitly instantiated when the specialization is
11406     //   referenced in a context that requires a function definition to exist.
11407     //
11408     // We consider constexpr function templates to be referenced in a context
11409     // that requires a definition to exist whenever they are referenced.
11410     //
11411     // FIXME: This instantiates constexpr functions too frequently. If this is
11412     // really an unevaluated context (and we're not just in the definition of a
11413     // function template or overload resolution or other cases which we
11414     // incorrectly consider to be unevaluated contexts), and we're not in a
11415     // subexpression which we actually need to evaluate (for instance, a
11416     // template argument, array bound or an expression in a braced-init-list),
11417     // we are not permitted to instantiate this constexpr function definition.
11418     //
11419     // FIXME: This also implicitly defines special members too frequently. They
11420     // are only supposed to be implicitly defined if they are odr-used, but they
11421     // are not odr-used from constant expressions in unevaluated contexts.
11422     // However, they cannot be referenced if they are deleted, and they are
11423     // deleted whenever the implicit definition of the special member would
11424     // fail.
11425     if (!Func->isConstexpr() || Func->getBody())
11426       return;
11427     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11428     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11429       return;
11430   }
11431 
11432   // Note that this declaration has been used.
11433   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11434     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
11435     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11436       if (Constructor->isDefaultConstructor()) {
11437         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
11438           return;
11439         DefineImplicitDefaultConstructor(Loc, Constructor);
11440       } else if (Constructor->isCopyConstructor()) {
11441         DefineImplicitCopyConstructor(Loc, Constructor);
11442       } else if (Constructor->isMoveConstructor()) {
11443         DefineImplicitMoveConstructor(Loc, Constructor);
11444       }
11445     } else if (Constructor->getInheritedConstructor()) {
11446       DefineInheritingConstructor(Loc, Constructor);
11447     }
11448 
11449     MarkVTableUsed(Loc, Constructor->getParent());
11450   } else if (CXXDestructorDecl *Destructor =
11451                  dyn_cast<CXXDestructorDecl>(Func)) {
11452     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
11453     if (Destructor->isDefaulted() && !Destructor->isDeleted())
11454       DefineImplicitDestructor(Loc, Destructor);
11455     if (Destructor->isVirtual())
11456       MarkVTableUsed(Loc, Destructor->getParent());
11457   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11458     if (MethodDecl->isOverloadedOperator() &&
11459         MethodDecl->getOverloadedOperator() == OO_Equal) {
11460       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
11461       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
11462         if (MethodDecl->isCopyAssignmentOperator())
11463           DefineImplicitCopyAssignment(Loc, MethodDecl);
11464         else
11465           DefineImplicitMoveAssignment(Loc, MethodDecl);
11466       }
11467     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11468                MethodDecl->getParent()->isLambda()) {
11469       CXXConversionDecl *Conversion =
11470           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
11471       if (Conversion->isLambdaToBlockPointerConversion())
11472         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11473       else
11474         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11475     } else if (MethodDecl->isVirtual())
11476       MarkVTableUsed(Loc, MethodDecl->getParent());
11477   }
11478 
11479   // Recursive functions should be marked when used from another function.
11480   // FIXME: Is this really right?
11481   if (CurContext == Func) return;
11482 
11483   // Resolve the exception specification for any function which is
11484   // used: CodeGen will need it.
11485   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11486   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11487     ResolveExceptionSpec(Loc, FPT);
11488 
11489   // Implicit instantiation of function templates and member functions of
11490   // class templates.
11491   if (Func->isImplicitlyInstantiable()) {
11492     bool AlreadyInstantiated = false;
11493     SourceLocation PointOfInstantiation = Loc;
11494     if (FunctionTemplateSpecializationInfo *SpecInfo
11495                               = Func->getTemplateSpecializationInfo()) {
11496       if (SpecInfo->getPointOfInstantiation().isInvalid())
11497         SpecInfo->setPointOfInstantiation(Loc);
11498       else if (SpecInfo->getTemplateSpecializationKind()
11499                  == TSK_ImplicitInstantiation) {
11500         AlreadyInstantiated = true;
11501         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11502       }
11503     } else if (MemberSpecializationInfo *MSInfo
11504                                 = Func->getMemberSpecializationInfo()) {
11505       if (MSInfo->getPointOfInstantiation().isInvalid())
11506         MSInfo->setPointOfInstantiation(Loc);
11507       else if (MSInfo->getTemplateSpecializationKind()
11508                  == TSK_ImplicitInstantiation) {
11509         AlreadyInstantiated = true;
11510         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11511       }
11512     }
11513 
11514     if (!AlreadyInstantiated || Func->isConstexpr()) {
11515       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11516           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11517           ActiveTemplateInstantiations.size())
11518         PendingLocalImplicitInstantiations.push_back(
11519             std::make_pair(Func, PointOfInstantiation));
11520       else if (Func->isConstexpr())
11521         // Do not defer instantiations of constexpr functions, to avoid the
11522         // expression evaluator needing to call back into Sema if it sees a
11523         // call to such a function.
11524         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11525       else {
11526         PendingInstantiations.push_back(std::make_pair(Func,
11527                                                        PointOfInstantiation));
11528         // Notify the consumer that a function was implicitly instantiated.
11529         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11530       }
11531     }
11532   } else {
11533     // Walk redefinitions, as some of them may be instantiable.
11534     for (auto i : Func->redecls()) {
11535       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11536         MarkFunctionReferenced(Loc, i);
11537     }
11538   }
11539 
11540   // Keep track of used but undefined functions.
11541   if (!Func->isDefined()) {
11542     if (mightHaveNonExternalLinkage(Func))
11543       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11544     else if (Func->getMostRecentDecl()->isInlined() &&
11545              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11546              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11547       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11548   }
11549 
11550   // Normally the most current decl is marked used while processing the use and
11551   // any subsequent decls are marked used by decl merging. This fails with
11552   // template instantiation since marking can happen at the end of the file
11553   // and, because of the two phase lookup, this function is called with at
11554   // decl in the middle of a decl chain. We loop to maintain the invariant
11555   // that once a decl is used, all decls after it are also used.
11556   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11557     F->markUsed(Context);
11558     if (F == Func)
11559       break;
11560   }
11561 }
11562 
11563 static void
diagnoseUncapturableValueReference(Sema & S,SourceLocation loc,VarDecl * var,DeclContext * DC)11564 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11565                                    VarDecl *var, DeclContext *DC) {
11566   DeclContext *VarDC = var->getDeclContext();
11567 
11568   //  If the parameter still belongs to the translation unit, then
11569   //  we're actually just using one parameter in the declaration of
11570   //  the next.
11571   if (isa<ParmVarDecl>(var) &&
11572       isa<TranslationUnitDecl>(VarDC))
11573     return;
11574 
11575   // For C code, don't diagnose about capture if we're not actually in code
11576   // right now; it's impossible to write a non-constant expression outside of
11577   // function context, so we'll get other (more useful) diagnostics later.
11578   //
11579   // For C++, things get a bit more nasty... it would be nice to suppress this
11580   // diagnostic for certain cases like using a local variable in an array bound
11581   // for a member of a local class, but the correct predicate is not obvious.
11582   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11583     return;
11584 
11585   if (isa<CXXMethodDecl>(VarDC) &&
11586       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11587     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11588       << var->getIdentifier();
11589   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11590     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11591       << var->getIdentifier() << fn->getDeclName();
11592   } else if (isa<BlockDecl>(VarDC)) {
11593     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11594       << var->getIdentifier();
11595   } else {
11596     // FIXME: Is there any other context where a local variable can be
11597     // declared?
11598     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11599       << var->getIdentifier();
11600   }
11601 
11602   S.Diag(var->getLocation(), diag::note_entity_declared_at)
11603       << var->getIdentifier();
11604 
11605   // FIXME: Add additional diagnostic info about class etc. which prevents
11606   // capture.
11607 }
11608 
11609 
isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo * CSI,VarDecl * Var,bool & SubCapturesAreNested,QualType & CaptureType,QualType & DeclRefType)11610 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11611                                       bool &SubCapturesAreNested,
11612                                       QualType &CaptureType,
11613                                       QualType &DeclRefType) {
11614    // Check whether we've already captured it.
11615   if (CSI->CaptureMap.count(Var)) {
11616     // If we found a capture, any subcaptures are nested.
11617     SubCapturesAreNested = true;
11618 
11619     // Retrieve the capture type for this variable.
11620     CaptureType = CSI->getCapture(Var).getCaptureType();
11621 
11622     // Compute the type of an expression that refers to this variable.
11623     DeclRefType = CaptureType.getNonReferenceType();
11624 
11625     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11626     if (Cap.isCopyCapture() &&
11627         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11628       DeclRefType.addConst();
11629     return true;
11630   }
11631   return false;
11632 }
11633 
11634 // Only block literals, captured statements, and lambda expressions can
11635 // capture; other scopes don't work.
getParentOfCapturingContextOrNull(DeclContext * DC,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)11636 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11637                                  SourceLocation Loc,
11638                                  const bool Diagnose, Sema &S) {
11639   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11640     return getLambdaAwareParentOfDeclContext(DC);
11641   else {
11642     if (Diagnose)
11643        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11644   }
11645   return nullptr;
11646 }
11647 
11648 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11649 // certain types of variables (unnamed, variably modified types etc.)
11650 // so check for eligibility.
isVariableCapturable(CapturingScopeInfo * CSI,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)11651 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11652                                  SourceLocation Loc,
11653                                  const bool Diagnose, Sema &S) {
11654 
11655   bool IsBlock = isa<BlockScopeInfo>(CSI);
11656   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11657 
11658   // Lambdas are not allowed to capture unnamed variables
11659   // (e.g. anonymous unions).
11660   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11661   // assuming that's the intent.
11662   if (IsLambda && !Var->getDeclName()) {
11663     if (Diagnose) {
11664       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11665       S.Diag(Var->getLocation(), diag::note_declared_at);
11666     }
11667     return false;
11668   }
11669 
11670   // Prohibit variably-modified types; they're difficult to deal with.
11671   if (Var->getType()->isVariablyModifiedType() && (IsBlock || IsLambda)) {
11672     if (Diagnose) {
11673       if (IsBlock)
11674         S.Diag(Loc, diag::err_ref_vm_type);
11675       else
11676         S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11677       S.Diag(Var->getLocation(), diag::note_previous_decl)
11678         << Var->getDeclName();
11679     }
11680     return false;
11681   }
11682   // Prohibit structs with flexible array members too.
11683   // We cannot capture what is in the tail end of the struct.
11684   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11685     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11686       if (Diagnose) {
11687         if (IsBlock)
11688           S.Diag(Loc, diag::err_ref_flexarray_type);
11689         else
11690           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11691             << Var->getDeclName();
11692         S.Diag(Var->getLocation(), diag::note_previous_decl)
11693           << Var->getDeclName();
11694       }
11695       return false;
11696     }
11697   }
11698   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11699   // Lambdas and captured statements are not allowed to capture __block
11700   // variables; they don't support the expected semantics.
11701   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11702     if (Diagnose) {
11703       S.Diag(Loc, diag::err_capture_block_variable)
11704         << Var->getDeclName() << !IsLambda;
11705       S.Diag(Var->getLocation(), diag::note_previous_decl)
11706         << Var->getDeclName();
11707     }
11708     return false;
11709   }
11710 
11711   return true;
11712 }
11713 
11714 // 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)11715 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11716                                  SourceLocation Loc,
11717                                  const bool BuildAndDiagnose,
11718                                  QualType &CaptureType,
11719                                  QualType &DeclRefType,
11720                                  const bool Nested,
11721                                  Sema &S) {
11722   Expr *CopyExpr = nullptr;
11723   bool ByRef = false;
11724 
11725   // Blocks are not allowed to capture arrays.
11726   if (CaptureType->isArrayType()) {
11727     if (BuildAndDiagnose) {
11728       S.Diag(Loc, diag::err_ref_array_type);
11729       S.Diag(Var->getLocation(), diag::note_previous_decl)
11730       << Var->getDeclName();
11731     }
11732     return false;
11733   }
11734 
11735   // Forbid the block-capture of autoreleasing variables.
11736   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11737     if (BuildAndDiagnose) {
11738       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11739         << /*block*/ 0;
11740       S.Diag(Var->getLocation(), diag::note_previous_decl)
11741         << Var->getDeclName();
11742     }
11743     return false;
11744   }
11745   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11746   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11747     // Block capture by reference does not change the capture or
11748     // declaration reference types.
11749     ByRef = true;
11750   } else {
11751     // Block capture by copy introduces 'const'.
11752     CaptureType = CaptureType.getNonReferenceType().withConst();
11753     DeclRefType = CaptureType;
11754 
11755     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11756       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11757         // The capture logic needs the destructor, so make sure we mark it.
11758         // Usually this is unnecessary because most local variables have
11759         // their destructors marked at declaration time, but parameters are
11760         // an exception because it's technically only the call site that
11761         // actually requires the destructor.
11762         if (isa<ParmVarDecl>(Var))
11763           S.FinalizeVarWithDestructor(Var, Record);
11764 
11765         // Enter a new evaluation context to insulate the copy
11766         // full-expression.
11767         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11768 
11769         // According to the blocks spec, the capture of a variable from
11770         // the stack requires a const copy constructor.  This is not true
11771         // of the copy/move done to move a __block variable to the heap.
11772         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11773                                                   DeclRefType.withConst(),
11774                                                   VK_LValue, Loc);
11775 
11776         ExprResult Result
11777           = S.PerformCopyInitialization(
11778               InitializedEntity::InitializeBlock(Var->getLocation(),
11779                                                   CaptureType, false),
11780               Loc, DeclRef);
11781 
11782         // Build a full-expression copy expression if initialization
11783         // succeeded and used a non-trivial constructor.  Recover from
11784         // errors by pretending that the copy isn't necessary.
11785         if (!Result.isInvalid() &&
11786             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11787                 ->isTrivial()) {
11788           Result = S.MaybeCreateExprWithCleanups(Result);
11789           CopyExpr = Result.get();
11790         }
11791       }
11792     }
11793   }
11794 
11795   // Actually capture the variable.
11796   if (BuildAndDiagnose)
11797     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11798                     SourceLocation(), CaptureType, CopyExpr);
11799 
11800   return true;
11801 
11802 }
11803 
11804 
11805 /// \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 RefersToEnclosingLocal,Sema & S)11806 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11807                                     VarDecl *Var,
11808                                     SourceLocation Loc,
11809                                     const bool BuildAndDiagnose,
11810                                     QualType &CaptureType,
11811                                     QualType &DeclRefType,
11812                                     const bool RefersToEnclosingLocal,
11813                                     Sema &S) {
11814 
11815   // By default, capture variables by reference.
11816   bool ByRef = true;
11817   // Using an LValue reference type is consistent with Lambdas (see below).
11818   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11819   Expr *CopyExpr = nullptr;
11820   if (BuildAndDiagnose) {
11821     // The current implementation assumes that all variables are captured
11822     // by references. Since there is no capture by copy, no expression
11823     // evaluation will be needed.
11824     RecordDecl *RD = RSI->TheRecordDecl;
11825 
11826     FieldDecl *Field
11827       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
11828                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11829                           nullptr, false, ICIS_NoInit);
11830     Field->setImplicit(true);
11831     Field->setAccess(AS_private);
11832     RD->addDecl(Field);
11833 
11834     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11835                                             DeclRefType, VK_LValue, Loc);
11836     Var->setReferenced(true);
11837     Var->markUsed(S.Context);
11838   }
11839 
11840   // Actually capture the variable.
11841   if (BuildAndDiagnose)
11842     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11843                     SourceLocation(), CaptureType, CopyExpr);
11844 
11845 
11846   return true;
11847 }
11848 
11849 /// \brief Create a field within the lambda class for the variable
11850 ///  being captured.  Handle Array captures.
addAsFieldToClosureType(Sema & S,LambdaScopeInfo * LSI,VarDecl * Var,QualType FieldType,QualType DeclRefType,SourceLocation Loc,bool RefersToEnclosingLocal)11851 static ExprResult addAsFieldToClosureType(Sema &S,
11852                                  LambdaScopeInfo *LSI,
11853                                   VarDecl *Var, QualType FieldType,
11854                                   QualType DeclRefType,
11855                                   SourceLocation Loc,
11856                                   bool RefersToEnclosingLocal) {
11857   CXXRecordDecl *Lambda = LSI->Lambda;
11858 
11859   // Build the non-static data member.
11860   FieldDecl *Field
11861     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
11862                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11863                         nullptr, false, ICIS_NoInit);
11864   Field->setImplicit(true);
11865   Field->setAccess(AS_private);
11866   Lambda->addDecl(Field);
11867 
11868   // C++11 [expr.prim.lambda]p21:
11869   //   When the lambda-expression is evaluated, the entities that
11870   //   are captured by copy are used to direct-initialize each
11871   //   corresponding non-static data member of the resulting closure
11872   //   object. (For array members, the array elements are
11873   //   direct-initialized in increasing subscript order.) These
11874   //   initializations are performed in the (unspecified) order in
11875   //   which the non-static data members are declared.
11876 
11877   // Introduce a new evaluation context for the initialization, so
11878   // that temporaries introduced as part of the capture are retained
11879   // to be re-"exported" from the lambda expression itself.
11880   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11881 
11882   // C++ [expr.prim.labda]p12:
11883   //   An entity captured by a lambda-expression is odr-used (3.2) in
11884   //   the scope containing the lambda-expression.
11885   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11886                                           DeclRefType, VK_LValue, Loc);
11887   Var->setReferenced(true);
11888   Var->markUsed(S.Context);
11889 
11890   // When the field has array type, create index variables for each
11891   // dimension of the array. We use these index variables to subscript
11892   // the source array, and other clients (e.g., CodeGen) will perform
11893   // the necessary iteration with these index variables.
11894   SmallVector<VarDecl *, 4> IndexVariables;
11895   QualType BaseType = FieldType;
11896   QualType SizeType = S.Context.getSizeType();
11897   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11898   while (const ConstantArrayType *Array
11899                         = S.Context.getAsConstantArrayType(BaseType)) {
11900     // Create the iteration variable for this array index.
11901     IdentifierInfo *IterationVarName = nullptr;
11902     {
11903       SmallString<8> Str;
11904       llvm::raw_svector_ostream OS(Str);
11905       OS << "__i" << IndexVariables.size();
11906       IterationVarName = &S.Context.Idents.get(OS.str());
11907     }
11908     VarDecl *IterationVar
11909       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11910                         IterationVarName, SizeType,
11911                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11912                         SC_None);
11913     IndexVariables.push_back(IterationVar);
11914     LSI->ArrayIndexVars.push_back(IterationVar);
11915 
11916     // Create a reference to the iteration variable.
11917     ExprResult IterationVarRef
11918       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11919     assert(!IterationVarRef.isInvalid() &&
11920            "Reference to invented variable cannot fail!");
11921     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
11922     assert(!IterationVarRef.isInvalid() &&
11923            "Conversion of invented variable cannot fail!");
11924 
11925     // Subscript the array with this iteration variable.
11926     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11927                              Ref, Loc, IterationVarRef.get(), Loc);
11928     if (Subscript.isInvalid()) {
11929       S.CleanupVarDeclMarking();
11930       S.DiscardCleanupsInEvaluationContext();
11931       return ExprError();
11932     }
11933 
11934     Ref = Subscript.get();
11935     BaseType = Array->getElementType();
11936   }
11937 
11938   // Construct the entity that we will be initializing. For an array, this
11939   // will be first element in the array, which may require several levels
11940   // of array-subscript entities.
11941   SmallVector<InitializedEntity, 4> Entities;
11942   Entities.reserve(1 + IndexVariables.size());
11943   Entities.push_back(
11944     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
11945         Field->getType(), Loc));
11946   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11947     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11948                                                             0,
11949                                                             Entities.back()));
11950 
11951   InitializationKind InitKind
11952     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11953   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11954   ExprResult Result(true);
11955   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11956     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11957 
11958   // If this initialization requires any cleanups (e.g., due to a
11959   // default argument to a copy constructor), note that for the
11960   // lambda.
11961   if (S.ExprNeedsCleanups)
11962     LSI->ExprNeedsCleanups = true;
11963 
11964   // Exit the expression evaluation context used for the capture.
11965   S.CleanupVarDeclMarking();
11966   S.DiscardCleanupsInEvaluationContext();
11967   return Result;
11968 }
11969 
11970 
11971 
11972 /// \brief Capture the given variable in the lambda.
captureInLambda(LambdaScopeInfo * LSI,VarDecl * Var,SourceLocation Loc,const bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const bool RefersToEnclosingLocal,const Sema::TryCaptureKind Kind,SourceLocation EllipsisLoc,const bool IsTopScope,Sema & S)11973 static bool captureInLambda(LambdaScopeInfo *LSI,
11974                             VarDecl *Var,
11975                             SourceLocation Loc,
11976                             const bool BuildAndDiagnose,
11977                             QualType &CaptureType,
11978                             QualType &DeclRefType,
11979                             const bool RefersToEnclosingLocal,
11980                             const Sema::TryCaptureKind Kind,
11981                             SourceLocation EllipsisLoc,
11982                             const bool IsTopScope,
11983                             Sema &S) {
11984 
11985   // Determine whether we are capturing by reference or by value.
11986   bool ByRef = false;
11987   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11988     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11989   } else {
11990     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11991   }
11992 
11993   // Compute the type of the field that will capture this variable.
11994   if (ByRef) {
11995     // C++11 [expr.prim.lambda]p15:
11996     //   An entity is captured by reference if it is implicitly or
11997     //   explicitly captured but not captured by copy. It is
11998     //   unspecified whether additional unnamed non-static data
11999     //   members are declared in the closure type for entities
12000     //   captured by reference.
12001     //
12002     // FIXME: It is not clear whether we want to build an lvalue reference
12003     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12004     // to do the former, while EDG does the latter. Core issue 1249 will
12005     // clarify, but for now we follow GCC because it's a more permissive and
12006     // easily defensible position.
12007     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12008   } else {
12009     // C++11 [expr.prim.lambda]p14:
12010     //   For each entity captured by copy, an unnamed non-static
12011     //   data member is declared in the closure type. The
12012     //   declaration order of these members is unspecified. The type
12013     //   of such a data member is the type of the corresponding
12014     //   captured entity if the entity is not a reference to an
12015     //   object, or the referenced type otherwise. [Note: If the
12016     //   captured entity is a reference to a function, the
12017     //   corresponding data member is also a reference to a
12018     //   function. - end note ]
12019     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12020       if (!RefType->getPointeeType()->isFunctionType())
12021         CaptureType = RefType->getPointeeType();
12022     }
12023 
12024     // Forbid the lambda copy-capture of autoreleasing variables.
12025     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12026       if (BuildAndDiagnose) {
12027         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12028         S.Diag(Var->getLocation(), diag::note_previous_decl)
12029           << Var->getDeclName();
12030       }
12031       return false;
12032     }
12033 
12034     // Make sure that by-copy captures are of a complete and non-abstract type.
12035     if (BuildAndDiagnose) {
12036       if (!CaptureType->isDependentType() &&
12037           S.RequireCompleteType(Loc, CaptureType,
12038                                 diag::err_capture_of_incomplete_type,
12039                                 Var->getDeclName()))
12040         return false;
12041 
12042       if (S.RequireNonAbstractType(Loc, CaptureType,
12043                                    diag::err_capture_of_abstract_type))
12044         return false;
12045     }
12046   }
12047 
12048   // Capture this variable in the lambda.
12049   Expr *CopyExpr = nullptr;
12050   if (BuildAndDiagnose) {
12051     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
12052                                         CaptureType, DeclRefType, Loc,
12053                                         RefersToEnclosingLocal);
12054     if (!Result.isInvalid())
12055       CopyExpr = Result.get();
12056   }
12057 
12058   // Compute the type of a reference to this captured variable.
12059   if (ByRef)
12060     DeclRefType = CaptureType.getNonReferenceType();
12061   else {
12062     // C++ [expr.prim.lambda]p5:
12063     //   The closure type for a lambda-expression has a public inline
12064     //   function call operator [...]. This function call operator is
12065     //   declared const (9.3.1) if and only if the lambda-expression’s
12066     //   parameter-declaration-clause is not followed by mutable.
12067     DeclRefType = CaptureType.getNonReferenceType();
12068     if (!LSI->Mutable && !CaptureType->isReferenceType())
12069       DeclRefType.addConst();
12070   }
12071 
12072   // Add the capture.
12073   if (BuildAndDiagnose)
12074     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
12075                     Loc, EllipsisLoc, CaptureType, CopyExpr);
12076 
12077   return true;
12078 }
12079 
12080 
tryCaptureVariable(VarDecl * Var,SourceLocation ExprLoc,TryCaptureKind Kind,SourceLocation EllipsisLoc,bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const unsigned * const FunctionScopeIndexToStopAt)12081 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
12082                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
12083                               bool BuildAndDiagnose,
12084                               QualType &CaptureType,
12085                               QualType &DeclRefType,
12086 						                const unsigned *const FunctionScopeIndexToStopAt) {
12087   bool Nested = false;
12088 
12089   DeclContext *DC = CurContext;
12090   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
12091       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
12092   // We need to sync up the Declaration Context with the
12093   // FunctionScopeIndexToStopAt
12094   if (FunctionScopeIndexToStopAt) {
12095     unsigned FSIndex = FunctionScopes.size() - 1;
12096     while (FSIndex != MaxFunctionScopesIndex) {
12097       DC = getLambdaAwareParentOfDeclContext(DC);
12098       --FSIndex;
12099     }
12100   }
12101 
12102 
12103   // If the variable is declared in the current context (and is not an
12104   // init-capture), there is no need to capture it.
12105   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
12106   if (!Var->hasLocalStorage()) return true;
12107 
12108   // Walk up the stack to determine whether we can capture the variable,
12109   // performing the "simple" checks that don't depend on type. We stop when
12110   // we've either hit the declared scope of the variable or find an existing
12111   // capture of that variable.  We start from the innermost capturing-entity
12112   // (the DC) and ensure that all intervening capturing-entities
12113   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
12114   // declcontext can either capture the variable or have already captured
12115   // the variable.
12116   CaptureType = Var->getType();
12117   DeclRefType = CaptureType.getNonReferenceType();
12118   bool Explicit = (Kind != TryCapture_Implicit);
12119   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
12120   do {
12121     // Only block literals, captured statements, and lambda expressions can
12122     // capture; other scopes don't work.
12123     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
12124                                                               ExprLoc,
12125                                                               BuildAndDiagnose,
12126                                                               *this);
12127     if (!ParentDC) return true;
12128 
12129     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
12130     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
12131 
12132 
12133     // Check whether we've already captured it.
12134     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12135                                              DeclRefType))
12136       break;
12137     // If we are instantiating a generic lambda call operator body,
12138     // we do not want to capture new variables.  What was captured
12139     // during either a lambdas transformation or initial parsing
12140     // should be used.
12141     if (isGenericLambdaCallOperatorSpecialization(DC)) {
12142       if (BuildAndDiagnose) {
12143         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12144         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12145           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12146           Diag(Var->getLocation(), diag::note_previous_decl)
12147              << Var->getDeclName();
12148           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12149         } else
12150           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12151       }
12152       return true;
12153     }
12154     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12155     // certain types of variables (unnamed, variably modified types etc.)
12156     // so check for eligibility.
12157     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12158        return true;
12159 
12160     // Try to capture variable-length arrays types.
12161     if (Var->getType()->isVariablyModifiedType()) {
12162       // We're going to walk down into the type and look for VLA
12163       // expressions.
12164       QualType QTy = Var->getType();
12165       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
12166         QTy = PVD->getOriginalType();
12167       do {
12168         const Type *Ty = QTy.getTypePtr();
12169         switch (Ty->getTypeClass()) {
12170 #define TYPE(Class, Base)
12171 #define ABSTRACT_TYPE(Class, Base)
12172 #define NON_CANONICAL_TYPE(Class, Base)
12173 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
12174 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
12175 #include "clang/AST/TypeNodes.def"
12176           QTy = QualType();
12177           break;
12178         // These types are never variably-modified.
12179         case Type::Builtin:
12180         case Type::Complex:
12181         case Type::Vector:
12182         case Type::ExtVector:
12183         case Type::Record:
12184         case Type::Enum:
12185         case Type::Elaborated:
12186         case Type::TemplateSpecialization:
12187         case Type::ObjCObject:
12188         case Type::ObjCInterface:
12189         case Type::ObjCObjectPointer:
12190           llvm_unreachable("type class is never variably-modified!");
12191         case Type::Adjusted:
12192           QTy = cast<AdjustedType>(Ty)->getOriginalType();
12193           break;
12194         case Type::Decayed:
12195           QTy = cast<DecayedType>(Ty)->getPointeeType();
12196           break;
12197         case Type::Pointer:
12198           QTy = cast<PointerType>(Ty)->getPointeeType();
12199           break;
12200         case Type::BlockPointer:
12201           QTy = cast<BlockPointerType>(Ty)->getPointeeType();
12202           break;
12203         case Type::LValueReference:
12204         case Type::RValueReference:
12205           QTy = cast<ReferenceType>(Ty)->getPointeeType();
12206           break;
12207         case Type::MemberPointer:
12208           QTy = cast<MemberPointerType>(Ty)->getPointeeType();
12209           break;
12210         case Type::ConstantArray:
12211         case Type::IncompleteArray:
12212           // Losing element qualification here is fine.
12213           QTy = cast<ArrayType>(Ty)->getElementType();
12214           break;
12215         case Type::VariableArray: {
12216           // Losing element qualification here is fine.
12217           const VariableArrayType *Vat = cast<VariableArrayType>(Ty);
12218 
12219           // Unknown size indication requires no size computation.
12220           // Otherwise, evaluate and record it.
12221           if (Expr *Size = Vat->getSizeExpr()) {
12222             MarkDeclarationsReferencedInExpr(Size);
12223           }
12224           QTy = Vat->getElementType();
12225           break;
12226         }
12227         case Type::FunctionProto:
12228         case Type::FunctionNoProto:
12229           QTy = cast<FunctionType>(Ty)->getReturnType();
12230           break;
12231         case Type::Paren:
12232         case Type::TypeOf:
12233         case Type::UnaryTransform:
12234         case Type::Attributed:
12235         case Type::SubstTemplateTypeParm:
12236         case Type::PackExpansion:
12237           // Keep walking after single level desugaring.
12238           QTy = QTy.getSingleStepDesugaredType(getASTContext());
12239           break;
12240         case Type::Typedef:
12241           QTy = cast<TypedefType>(Ty)->desugar();
12242           break;
12243         case Type::Decltype:
12244           QTy = cast<DecltypeType>(Ty)->desugar();
12245           break;
12246         case Type::Auto:
12247           QTy = cast<AutoType>(Ty)->getDeducedType();
12248           break;
12249         case Type::TypeOfExpr:
12250           QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
12251           break;
12252         case Type::Atomic:
12253           QTy = cast<AtomicType>(Ty)->getValueType();
12254           break;
12255         }
12256       } while (!QTy.isNull() && QTy->isVariablyModifiedType());
12257     }
12258 
12259     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12260       // No capture-default, and this is not an explicit capture
12261       // so cannot capture this variable.
12262       if (BuildAndDiagnose) {
12263         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12264         Diag(Var->getLocation(), diag::note_previous_decl)
12265           << Var->getDeclName();
12266         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12267              diag::note_lambda_decl);
12268         // FIXME: If we error out because an outer lambda can not implicitly
12269         // capture a variable that an inner lambda explicitly captures, we
12270         // should have the inner lambda do the explicit capture - because
12271         // it makes for cleaner diagnostics later.  This would purely be done
12272         // so that the diagnostic does not misleadingly claim that a variable
12273         // can not be captured by a lambda implicitly even though it is captured
12274         // explicitly.  Suggestion:
12275         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12276         //    at the function head
12277         //  - cache the StartingDeclContext - this must be a lambda
12278         //  - captureInLambda in the innermost lambda the variable.
12279       }
12280       return true;
12281     }
12282 
12283     FunctionScopesIndex--;
12284     DC = ParentDC;
12285     Explicit = false;
12286   } while (!Var->getDeclContext()->Equals(DC));
12287 
12288   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12289   // computing the type of the capture at each step, checking type-specific
12290   // requirements, and adding captures if requested.
12291   // If the variable had already been captured previously, we start capturing
12292   // at the lambda nested within that one.
12293   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
12294        ++I) {
12295     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12296 
12297     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12298       if (!captureInBlock(BSI, Var, ExprLoc,
12299                           BuildAndDiagnose, CaptureType,
12300                           DeclRefType, Nested, *this))
12301         return true;
12302       Nested = true;
12303     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12304       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
12305                                    BuildAndDiagnose, CaptureType,
12306                                    DeclRefType, Nested, *this))
12307         return true;
12308       Nested = true;
12309     } else {
12310       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12311       if (!captureInLambda(LSI, Var, ExprLoc,
12312                            BuildAndDiagnose, CaptureType,
12313                            DeclRefType, Nested, Kind, EllipsisLoc,
12314                             /*IsTopScope*/I == N - 1, *this))
12315         return true;
12316       Nested = true;
12317     }
12318   }
12319   return false;
12320 }
12321 
tryCaptureVariable(VarDecl * Var,SourceLocation Loc,TryCaptureKind Kind,SourceLocation EllipsisLoc)12322 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12323                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
12324   QualType CaptureType;
12325   QualType DeclRefType;
12326   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12327                             /*BuildAndDiagnose=*/true, CaptureType,
12328                             DeclRefType, nullptr);
12329 }
12330 
getCapturedDeclRefType(VarDecl * Var,SourceLocation Loc)12331 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12332   QualType CaptureType;
12333   QualType DeclRefType;
12334 
12335   // Determine whether we can capture this variable.
12336   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12337                          /*BuildAndDiagnose=*/false, CaptureType,
12338                          DeclRefType, nullptr))
12339     return QualType();
12340 
12341   return DeclRefType;
12342 }
12343 
12344 
12345 
12346 // If either the type of the variable or the initializer is dependent,
12347 // return false. Otherwise, determine whether the variable is a constant
12348 // expression. Use this if you need to know if a variable that might or
12349 // might not be dependent is truly a constant expression.
IsVariableNonDependentAndAConstantExpression(VarDecl * Var,ASTContext & Context)12350 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
12351     ASTContext &Context) {
12352 
12353   if (Var->getType()->isDependentType())
12354     return false;
12355   const VarDecl *DefVD = nullptr;
12356   Var->getAnyInitializer(DefVD);
12357   if (!DefVD)
12358     return false;
12359   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12360   Expr *Init = cast<Expr>(Eval->Value);
12361   if (Init->isValueDependent())
12362     return false;
12363   return IsVariableAConstantExpression(Var, Context);
12364 }
12365 
12366 
UpdateMarkingForLValueToRValue(Expr * E)12367 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12368   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12369   // an object that satisfies the requirements for appearing in a
12370   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12371   // is immediately applied."  This function handles the lvalue-to-rvalue
12372   // conversion part.
12373   MaybeODRUseExprs.erase(E->IgnoreParens());
12374 
12375   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12376   // to a variable that is a constant expression, and if so, identify it as
12377   // a reference to a variable that does not involve an odr-use of that
12378   // variable.
12379   if (LambdaScopeInfo *LSI = getCurLambda()) {
12380     Expr *SansParensExpr = E->IgnoreParens();
12381     VarDecl *Var = nullptr;
12382     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12383       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12384     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12385       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12386 
12387     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12388       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12389   }
12390 }
12391 
ActOnConstantExpression(ExprResult Res)12392 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12393   if (!Res.isUsable())
12394     return Res;
12395 
12396   // If a constant-expression is a reference to a variable where we delay
12397   // deciding whether it is an odr-use, just assume we will apply the
12398   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12399   // (a non-type template argument), we have special handling anyway.
12400   UpdateMarkingForLValueToRValue(Res.get());
12401   return Res;
12402 }
12403 
CleanupVarDeclMarking()12404 void Sema::CleanupVarDeclMarking() {
12405   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12406                                         e = MaybeODRUseExprs.end();
12407        i != e; ++i) {
12408     VarDecl *Var;
12409     SourceLocation Loc;
12410     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12411       Var = cast<VarDecl>(DRE->getDecl());
12412       Loc = DRE->getLocation();
12413     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12414       Var = cast<VarDecl>(ME->getMemberDecl());
12415       Loc = ME->getMemberLoc();
12416     } else {
12417       llvm_unreachable("Unexpcted expression");
12418     }
12419 
12420     MarkVarDeclODRUsed(Var, Loc, *this,
12421                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
12422   }
12423 
12424   MaybeODRUseExprs.clear();
12425 }
12426 
12427 
DoMarkVarDeclReferenced(Sema & SemaRef,SourceLocation Loc,VarDecl * Var,Expr * E)12428 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12429                                     VarDecl *Var, Expr *E) {
12430   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12431          "Invalid Expr argument to DoMarkVarDeclReferenced");
12432   Var->setReferenced();
12433 
12434   // If the context is not potentially evaluated, this is not an odr-use and
12435   // does not trigger instantiation.
12436   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12437     if (SemaRef.isUnevaluatedContext())
12438       return;
12439 
12440     // If we don't yet know whether this context is going to end up being an
12441     // evaluated context, and we're referencing a variable from an enclosing
12442     // scope, add a potential capture.
12443     //
12444     // FIXME: Is this necessary? These contexts are only used for default
12445     // arguments, where local variables can't be used.
12446     const bool RefersToEnclosingScope =
12447         (SemaRef.CurContext != Var->getDeclContext() &&
12448          Var->getDeclContext()->isFunctionOrMethod() &&
12449          Var->hasLocalStorage());
12450     if (!RefersToEnclosingScope)
12451       return;
12452 
12453     if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12454       // If a variable could potentially be odr-used, defer marking it so
12455       // until we finish analyzing the full expression for any lvalue-to-rvalue
12456       // or discarded value conversions that would obviate odr-use.
12457       // Add it to the list of potential captures that will be analyzed
12458       // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12459       // unless the variable is a reference that was initialized by a constant
12460       // expression (this will never need to be captured or odr-used).
12461       assert(E && "Capture variable should be used in an expression.");
12462       if (!Var->getType()->isReferenceType() ||
12463           !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
12464         LSI->addPotentialCapture(E->IgnoreParens());
12465     }
12466     return;
12467   }
12468 
12469   VarTemplateSpecializationDecl *VarSpec =
12470       dyn_cast<VarTemplateSpecializationDecl>(Var);
12471   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12472          "Can't instantiate a partial template specialization.");
12473 
12474   // Perform implicit instantiation of static data members, static data member
12475   // templates of class templates, and variable template specializations. Delay
12476   // instantiations of variable templates, except for those that could be used
12477   // in a constant expression.
12478   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12479   if (isTemplateInstantiation(TSK)) {
12480     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12481 
12482     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12483       if (Var->getPointOfInstantiation().isInvalid()) {
12484         // This is a modification of an existing AST node. Notify listeners.
12485         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12486           L->StaticDataMemberInstantiated(Var);
12487       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12488         // Don't bother trying to instantiate it again, unless we might need
12489         // its initializer before we get to the end of the TU.
12490         TryInstantiating = false;
12491     }
12492 
12493     if (Var->getPointOfInstantiation().isInvalid())
12494       Var->setTemplateSpecializationKind(TSK, Loc);
12495 
12496     if (TryInstantiating) {
12497       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12498       bool InstantiationDependent = false;
12499       bool IsNonDependent =
12500           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12501                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12502                   : true;
12503 
12504       // Do not instantiate specializations that are still type-dependent.
12505       if (IsNonDependent) {
12506         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12507           // Do not defer instantiations of variables which could be used in a
12508           // constant expression.
12509           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12510         } else {
12511           SemaRef.PendingInstantiations
12512               .push_back(std::make_pair(Var, PointOfInstantiation));
12513         }
12514       }
12515     }
12516   }
12517 
12518   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12519   // the requirements for appearing in a constant expression (5.19) and, if
12520   // it is an object, the lvalue-to-rvalue conversion (4.1)
12521   // is immediately applied."  We check the first part here, and
12522   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12523   // Note that we use the C++11 definition everywhere because nothing in
12524   // C++03 depends on whether we get the C++03 version correct. The second
12525   // part does not apply to references, since they are not objects.
12526   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12527     // A reference initialized by a constant expression can never be
12528     // odr-used, so simply ignore it.
12529     if (!Var->getType()->isReferenceType())
12530       SemaRef.MaybeODRUseExprs.insert(E);
12531   } else
12532     MarkVarDeclODRUsed(Var, Loc, SemaRef,
12533                        /*MaxFunctionScopeIndex ptr*/ nullptr);
12534 }
12535 
12536 /// \brief Mark a variable referenced, and check whether it is odr-used
12537 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12538 /// used directly for normal expressions referring to VarDecl.
MarkVariableReferenced(SourceLocation Loc,VarDecl * Var)12539 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12540   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
12541 }
12542 
MarkExprReferenced(Sema & SemaRef,SourceLocation Loc,Decl * D,Expr * E,bool OdrUse)12543 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12544                                Decl *D, Expr *E, bool OdrUse) {
12545   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12546     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12547     return;
12548   }
12549 
12550   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12551 
12552   // If this is a call to a method via a cast, also mark the method in the
12553   // derived class used in case codegen can devirtualize the call.
12554   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12555   if (!ME)
12556     return;
12557   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12558   if (!MD)
12559     return;
12560   const Expr *Base = ME->getBase();
12561   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12562   if (!MostDerivedClassDecl)
12563     return;
12564   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12565   if (!DM || DM->isPure())
12566     return;
12567   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12568 }
12569 
12570 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
MarkDeclRefReferenced(DeclRefExpr * E)12571 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12572   // TODO: update this with DR# once a defect report is filed.
12573   // C++11 defect. The address of a pure member should not be an ODR use, even
12574   // if it's a qualified reference.
12575   bool OdrUse = true;
12576   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12577     if (Method->isVirtual())
12578       OdrUse = false;
12579   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12580 }
12581 
12582 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
MarkMemberReferenced(MemberExpr * E)12583 void Sema::MarkMemberReferenced(MemberExpr *E) {
12584   // C++11 [basic.def.odr]p2:
12585   //   A non-overloaded function whose name appears as a potentially-evaluated
12586   //   expression or a member of a set of candidate functions, if selected by
12587   //   overload resolution when referred to from a potentially-evaluated
12588   //   expression, is odr-used, unless it is a pure virtual function and its
12589   //   name is not explicitly qualified.
12590   bool OdrUse = true;
12591   if (!E->hasQualifier()) {
12592     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12593       if (Method->isPure())
12594         OdrUse = false;
12595   }
12596   SourceLocation Loc = E->getMemberLoc().isValid() ?
12597                             E->getMemberLoc() : E->getLocStart();
12598   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12599 }
12600 
12601 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12602 /// marks the declaration referenced, and performs odr-use checking for
12603 /// functions and variables. This method should not be used when building a
12604 /// normal expression which refers to a variable.
MarkAnyDeclReferenced(SourceLocation Loc,Decl * D,bool OdrUse)12605 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12606   if (OdrUse) {
12607     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12608       MarkVariableReferenced(Loc, VD);
12609       return;
12610     }
12611     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12612       MarkFunctionReferenced(Loc, FD);
12613       return;
12614     }
12615   }
12616   D->setReferenced();
12617 }
12618 
12619 namespace {
12620   // Mark all of the declarations referenced
12621   // FIXME: Not fully implemented yet! We need to have a better understanding
12622   // of when we're entering
12623   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12624     Sema &S;
12625     SourceLocation Loc;
12626 
12627   public:
12628     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12629 
MarkReferencedDecls(Sema & S,SourceLocation Loc)12630     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12631 
12632     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12633     bool TraverseRecordType(RecordType *T);
12634   };
12635 }
12636 
TraverseTemplateArgument(const TemplateArgument & Arg)12637 bool MarkReferencedDecls::TraverseTemplateArgument(
12638     const TemplateArgument &Arg) {
12639   if (Arg.getKind() == TemplateArgument::Declaration) {
12640     if (Decl *D = Arg.getAsDecl())
12641       S.MarkAnyDeclReferenced(Loc, D, true);
12642   }
12643 
12644   return Inherited::TraverseTemplateArgument(Arg);
12645 }
12646 
TraverseRecordType(RecordType * T)12647 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12648   if (ClassTemplateSpecializationDecl *Spec
12649                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12650     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12651     return TraverseTemplateArguments(Args.data(), Args.size());
12652   }
12653 
12654   return true;
12655 }
12656 
MarkDeclarationsReferencedInType(SourceLocation Loc,QualType T)12657 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12658   MarkReferencedDecls Marker(*this, Loc);
12659   Marker.TraverseType(Context.getCanonicalType(T));
12660 }
12661 
12662 namespace {
12663   /// \brief Helper class that marks all of the declarations referenced by
12664   /// potentially-evaluated subexpressions as "referenced".
12665   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12666     Sema &S;
12667     bool SkipLocalVariables;
12668 
12669   public:
12670     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12671 
EvaluatedExprMarker(Sema & S,bool SkipLocalVariables)12672     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12673       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12674 
VisitDeclRefExpr(DeclRefExpr * E)12675     void VisitDeclRefExpr(DeclRefExpr *E) {
12676       // If we were asked not to visit local variables, don't.
12677       if (SkipLocalVariables) {
12678         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12679           if (VD->hasLocalStorage())
12680             return;
12681       }
12682 
12683       S.MarkDeclRefReferenced(E);
12684     }
12685 
VisitMemberExpr(MemberExpr * E)12686     void VisitMemberExpr(MemberExpr *E) {
12687       S.MarkMemberReferenced(E);
12688       Inherited::VisitMemberExpr(E);
12689     }
12690 
VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr * E)12691     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12692       S.MarkFunctionReferenced(E->getLocStart(),
12693             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12694       Visit(E->getSubExpr());
12695     }
12696 
VisitCXXNewExpr(CXXNewExpr * E)12697     void VisitCXXNewExpr(CXXNewExpr *E) {
12698       if (E->getOperatorNew())
12699         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12700       if (E->getOperatorDelete())
12701         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12702       Inherited::VisitCXXNewExpr(E);
12703     }
12704 
VisitCXXDeleteExpr(CXXDeleteExpr * E)12705     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12706       if (E->getOperatorDelete())
12707         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12708       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12709       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12710         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12711         S.MarkFunctionReferenced(E->getLocStart(),
12712                                     S.LookupDestructor(Record));
12713       }
12714 
12715       Inherited::VisitCXXDeleteExpr(E);
12716     }
12717 
VisitCXXConstructExpr(CXXConstructExpr * E)12718     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12719       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12720       Inherited::VisitCXXConstructExpr(E);
12721     }
12722 
VisitCXXDefaultArgExpr(CXXDefaultArgExpr * E)12723     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12724       Visit(E->getExpr());
12725     }
12726 
VisitImplicitCastExpr(ImplicitCastExpr * E)12727     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12728       Inherited::VisitImplicitCastExpr(E);
12729 
12730       if (E->getCastKind() == CK_LValueToRValue)
12731         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12732     }
12733   };
12734 }
12735 
12736 /// \brief Mark any declarations that appear within this expression or any
12737 /// potentially-evaluated subexpressions as "referenced".
12738 ///
12739 /// \param SkipLocalVariables If true, don't mark local variables as
12740 /// 'referenced'.
MarkDeclarationsReferencedInExpr(Expr * E,bool SkipLocalVariables)12741 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12742                                             bool SkipLocalVariables) {
12743   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12744 }
12745 
12746 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12747 /// of the program being compiled.
12748 ///
12749 /// This routine emits the given diagnostic when the code currently being
12750 /// type-checked is "potentially evaluated", meaning that there is a
12751 /// possibility that the code will actually be executable. Code in sizeof()
12752 /// expressions, code used only during overload resolution, etc., are not
12753 /// potentially evaluated. This routine will suppress such diagnostics or,
12754 /// in the absolutely nutty case of potentially potentially evaluated
12755 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12756 /// later.
12757 ///
12758 /// This routine should be used for all diagnostics that describe the run-time
12759 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12760 /// Failure to do so will likely result in spurious diagnostics or failures
12761 /// during overload resolution or within sizeof/alignof/typeof/typeid.
DiagRuntimeBehavior(SourceLocation Loc,const Stmt * Statement,const PartialDiagnostic & PD)12762 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12763                                const PartialDiagnostic &PD) {
12764   switch (ExprEvalContexts.back().Context) {
12765   case Unevaluated:
12766   case UnevaluatedAbstract:
12767     // The argument will never be evaluated, so don't complain.
12768     break;
12769 
12770   case ConstantEvaluated:
12771     // Relevant diagnostics should be produced by constant evaluation.
12772     break;
12773 
12774   case PotentiallyEvaluated:
12775   case PotentiallyEvaluatedIfUsed:
12776     if (Statement && getCurFunctionOrMethodDecl()) {
12777       FunctionScopes.back()->PossiblyUnreachableDiags.
12778         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12779     }
12780     else
12781       Diag(Loc, PD);
12782 
12783     return true;
12784   }
12785 
12786   return false;
12787 }
12788 
CheckCallReturnType(QualType ReturnType,SourceLocation Loc,CallExpr * CE,FunctionDecl * FD)12789 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12790                                CallExpr *CE, FunctionDecl *FD) {
12791   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12792     return false;
12793 
12794   // If we're inside a decltype's expression, don't check for a valid return
12795   // type or construct temporaries until we know whether this is the last call.
12796   if (ExprEvalContexts.back().IsDecltype) {
12797     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12798     return false;
12799   }
12800 
12801   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12802     FunctionDecl *FD;
12803     CallExpr *CE;
12804 
12805   public:
12806     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12807       : FD(FD), CE(CE) { }
12808 
12809     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
12810       if (!FD) {
12811         S.Diag(Loc, diag::err_call_incomplete_return)
12812           << T << CE->getSourceRange();
12813         return;
12814       }
12815 
12816       S.Diag(Loc, diag::err_call_function_incomplete_return)
12817         << CE->getSourceRange() << FD->getDeclName() << T;
12818       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
12819           << FD->getDeclName();
12820     }
12821   } Diagnoser(FD, CE);
12822 
12823   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12824     return true;
12825 
12826   return false;
12827 }
12828 
12829 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12830 // will prevent this condition from triggering, which is what we want.
DiagnoseAssignmentAsCondition(Expr * E)12831 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12832   SourceLocation Loc;
12833 
12834   unsigned diagnostic = diag::warn_condition_is_assignment;
12835   bool IsOrAssign = false;
12836 
12837   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12838     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12839       return;
12840 
12841     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12842 
12843     // Greylist some idioms by putting them into a warning subcategory.
12844     if (ObjCMessageExpr *ME
12845           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12846       Selector Sel = ME->getSelector();
12847 
12848       // self = [<foo> init...]
12849       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12850         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12851 
12852       // <foo> = [<bar> nextObject]
12853       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12854         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12855     }
12856 
12857     Loc = Op->getOperatorLoc();
12858   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12859     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12860       return;
12861 
12862     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12863     Loc = Op->getOperatorLoc();
12864   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12865     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12866   else {
12867     // Not an assignment.
12868     return;
12869   }
12870 
12871   Diag(Loc, diagnostic) << E->getSourceRange();
12872 
12873   SourceLocation Open = E->getLocStart();
12874   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12875   Diag(Loc, diag::note_condition_assign_silence)
12876         << FixItHint::CreateInsertion(Open, "(")
12877         << FixItHint::CreateInsertion(Close, ")");
12878 
12879   if (IsOrAssign)
12880     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12881       << FixItHint::CreateReplacement(Loc, "!=");
12882   else
12883     Diag(Loc, diag::note_condition_assign_to_comparison)
12884       << FixItHint::CreateReplacement(Loc, "==");
12885 }
12886 
12887 /// \brief Redundant parentheses over an equality comparison can indicate
12888 /// that the user intended an assignment used as condition.
DiagnoseEqualityWithExtraParens(ParenExpr * ParenE)12889 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12890   // Don't warn if the parens came from a macro.
12891   SourceLocation parenLoc = ParenE->getLocStart();
12892   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12893     return;
12894   // Don't warn for dependent expressions.
12895   if (ParenE->isTypeDependent())
12896     return;
12897 
12898   Expr *E = ParenE->IgnoreParens();
12899 
12900   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12901     if (opE->getOpcode() == BO_EQ &&
12902         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12903                                                            == Expr::MLV_Valid) {
12904       SourceLocation Loc = opE->getOperatorLoc();
12905 
12906       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12907       SourceRange ParenERange = ParenE->getSourceRange();
12908       Diag(Loc, diag::note_equality_comparison_silence)
12909         << FixItHint::CreateRemoval(ParenERange.getBegin())
12910         << FixItHint::CreateRemoval(ParenERange.getEnd());
12911       Diag(Loc, diag::note_equality_comparison_to_assign)
12912         << FixItHint::CreateReplacement(Loc, "=");
12913     }
12914 }
12915 
CheckBooleanCondition(Expr * E,SourceLocation Loc)12916 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12917   DiagnoseAssignmentAsCondition(E);
12918   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12919     DiagnoseEqualityWithExtraParens(parenE);
12920 
12921   ExprResult result = CheckPlaceholderExpr(E);
12922   if (result.isInvalid()) return ExprError();
12923   E = result.get();
12924 
12925   if (!E->isTypeDependent()) {
12926     if (getLangOpts().CPlusPlus)
12927       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12928 
12929     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12930     if (ERes.isInvalid())
12931       return ExprError();
12932     E = ERes.get();
12933 
12934     QualType T = E->getType();
12935     if (!T->isScalarType()) { // C99 6.8.4.1p1
12936       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12937         << T << E->getSourceRange();
12938       return ExprError();
12939     }
12940   }
12941 
12942   return E;
12943 }
12944 
ActOnBooleanCondition(Scope * S,SourceLocation Loc,Expr * SubExpr)12945 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12946                                        Expr *SubExpr) {
12947   if (!SubExpr)
12948     return ExprError();
12949 
12950   return CheckBooleanCondition(SubExpr, Loc);
12951 }
12952 
12953 namespace {
12954   /// A visitor for rebuilding a call to an __unknown_any expression
12955   /// to have an appropriate type.
12956   struct RebuildUnknownAnyFunction
12957     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12958 
12959     Sema &S;
12960 
RebuildUnknownAnyFunction__anon68c4f85a0811::RebuildUnknownAnyFunction12961     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12962 
VisitStmt__anon68c4f85a0811::RebuildUnknownAnyFunction12963     ExprResult VisitStmt(Stmt *S) {
12964       llvm_unreachable("unexpected statement!");
12965     }
12966 
VisitExpr__anon68c4f85a0811::RebuildUnknownAnyFunction12967     ExprResult VisitExpr(Expr *E) {
12968       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12969         << E->getSourceRange();
12970       return ExprError();
12971     }
12972 
12973     /// Rebuild an expression which simply semantically wraps another
12974     /// expression which it shares the type and value kind of.
rebuildSugarExpr__anon68c4f85a0811::RebuildUnknownAnyFunction12975     template <class T> ExprResult rebuildSugarExpr(T *E) {
12976       ExprResult SubResult = Visit(E->getSubExpr());
12977       if (SubResult.isInvalid()) return ExprError();
12978 
12979       Expr *SubExpr = SubResult.get();
12980       E->setSubExpr(SubExpr);
12981       E->setType(SubExpr->getType());
12982       E->setValueKind(SubExpr->getValueKind());
12983       assert(E->getObjectKind() == OK_Ordinary);
12984       return E;
12985     }
12986 
VisitParenExpr__anon68c4f85a0811::RebuildUnknownAnyFunction12987     ExprResult VisitParenExpr(ParenExpr *E) {
12988       return rebuildSugarExpr(E);
12989     }
12990 
VisitUnaryExtension__anon68c4f85a0811::RebuildUnknownAnyFunction12991     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12992       return rebuildSugarExpr(E);
12993     }
12994 
VisitUnaryAddrOf__anon68c4f85a0811::RebuildUnknownAnyFunction12995     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12996       ExprResult SubResult = Visit(E->getSubExpr());
12997       if (SubResult.isInvalid()) return ExprError();
12998 
12999       Expr *SubExpr = SubResult.get();
13000       E->setSubExpr(SubExpr);
13001       E->setType(S.Context.getPointerType(SubExpr->getType()));
13002       assert(E->getValueKind() == VK_RValue);
13003       assert(E->getObjectKind() == OK_Ordinary);
13004       return E;
13005     }
13006 
resolveDecl__anon68c4f85a0811::RebuildUnknownAnyFunction13007     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
13008       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
13009 
13010       E->setType(VD->getType());
13011 
13012       assert(E->getValueKind() == VK_RValue);
13013       if (S.getLangOpts().CPlusPlus &&
13014           !(isa<CXXMethodDecl>(VD) &&
13015             cast<CXXMethodDecl>(VD)->isInstance()))
13016         E->setValueKind(VK_LValue);
13017 
13018       return E;
13019     }
13020 
VisitMemberExpr__anon68c4f85a0811::RebuildUnknownAnyFunction13021     ExprResult VisitMemberExpr(MemberExpr *E) {
13022       return resolveDecl(E, E->getMemberDecl());
13023     }
13024 
VisitDeclRefExpr__anon68c4f85a0811::RebuildUnknownAnyFunction13025     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13026       return resolveDecl(E, E->getDecl());
13027     }
13028   };
13029 }
13030 
13031 /// Given a function expression of unknown-any type, try to rebuild it
13032 /// to have a function type.
rebuildUnknownAnyFunction(Sema & S,Expr * FunctionExpr)13033 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
13034   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
13035   if (Result.isInvalid()) return ExprError();
13036   return S.DefaultFunctionArrayConversion(Result.get());
13037 }
13038 
13039 namespace {
13040   /// A visitor for rebuilding an expression of type __unknown_anytype
13041   /// into one which resolves the type directly on the referring
13042   /// expression.  Strict preservation of the original source
13043   /// structure is not a goal.
13044   struct RebuildUnknownAnyExpr
13045     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
13046 
13047     Sema &S;
13048 
13049     /// The current destination type.
13050     QualType DestType;
13051 
RebuildUnknownAnyExpr__anon68c4f85a0911::RebuildUnknownAnyExpr13052     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
13053       : S(S), DestType(CastType) {}
13054 
VisitStmt__anon68c4f85a0911::RebuildUnknownAnyExpr13055     ExprResult VisitStmt(Stmt *S) {
13056       llvm_unreachable("unexpected statement!");
13057     }
13058 
VisitExpr__anon68c4f85a0911::RebuildUnknownAnyExpr13059     ExprResult VisitExpr(Expr *E) {
13060       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13061         << E->getSourceRange();
13062       return ExprError();
13063     }
13064 
13065     ExprResult VisitCallExpr(CallExpr *E);
13066     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
13067 
13068     /// Rebuild an expression which simply semantically wraps another
13069     /// expression which it shares the type and value kind of.
rebuildSugarExpr__anon68c4f85a0911::RebuildUnknownAnyExpr13070     template <class T> ExprResult rebuildSugarExpr(T *E) {
13071       ExprResult SubResult = Visit(E->getSubExpr());
13072       if (SubResult.isInvalid()) return ExprError();
13073       Expr *SubExpr = SubResult.get();
13074       E->setSubExpr(SubExpr);
13075       E->setType(SubExpr->getType());
13076       E->setValueKind(SubExpr->getValueKind());
13077       assert(E->getObjectKind() == OK_Ordinary);
13078       return E;
13079     }
13080 
VisitParenExpr__anon68c4f85a0911::RebuildUnknownAnyExpr13081     ExprResult VisitParenExpr(ParenExpr *E) {
13082       return rebuildSugarExpr(E);
13083     }
13084 
VisitUnaryExtension__anon68c4f85a0911::RebuildUnknownAnyExpr13085     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13086       return rebuildSugarExpr(E);
13087     }
13088 
VisitUnaryAddrOf__anon68c4f85a0911::RebuildUnknownAnyExpr13089     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13090       const PointerType *Ptr = DestType->getAs<PointerType>();
13091       if (!Ptr) {
13092         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
13093           << E->getSourceRange();
13094         return ExprError();
13095       }
13096       assert(E->getValueKind() == VK_RValue);
13097       assert(E->getObjectKind() == OK_Ordinary);
13098       E->setType(DestType);
13099 
13100       // Build the sub-expression as if it were an object of the pointee type.
13101       DestType = Ptr->getPointeeType();
13102       ExprResult SubResult = Visit(E->getSubExpr());
13103       if (SubResult.isInvalid()) return ExprError();
13104       E->setSubExpr(SubResult.get());
13105       return E;
13106     }
13107 
13108     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
13109 
13110     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
13111 
VisitMemberExpr__anon68c4f85a0911::RebuildUnknownAnyExpr13112     ExprResult VisitMemberExpr(MemberExpr *E) {
13113       return resolveDecl(E, E->getMemberDecl());
13114     }
13115 
VisitDeclRefExpr__anon68c4f85a0911::RebuildUnknownAnyExpr13116     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13117       return resolveDecl(E, E->getDecl());
13118     }
13119   };
13120 }
13121 
13122 /// Rebuilds a call expression which yielded __unknown_anytype.
VisitCallExpr(CallExpr * E)13123 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
13124   Expr *CalleeExpr = E->getCallee();
13125 
13126   enum FnKind {
13127     FK_MemberFunction,
13128     FK_FunctionPointer,
13129     FK_BlockPointer
13130   };
13131 
13132   FnKind Kind;
13133   QualType CalleeType = CalleeExpr->getType();
13134   if (CalleeType == S.Context.BoundMemberTy) {
13135     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
13136     Kind = FK_MemberFunction;
13137     CalleeType = Expr::findBoundMemberType(CalleeExpr);
13138   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
13139     CalleeType = Ptr->getPointeeType();
13140     Kind = FK_FunctionPointer;
13141   } else {
13142     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
13143     Kind = FK_BlockPointer;
13144   }
13145   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
13146 
13147   // Verify that this is a legal result type of a function.
13148   if (DestType->isArrayType() || DestType->isFunctionType()) {
13149     unsigned diagID = diag::err_func_returning_array_function;
13150     if (Kind == FK_BlockPointer)
13151       diagID = diag::err_block_returning_array_function;
13152 
13153     S.Diag(E->getExprLoc(), diagID)
13154       << DestType->isFunctionType() << DestType;
13155     return ExprError();
13156   }
13157 
13158   // Otherwise, go ahead and set DestType as the call's result.
13159   E->setType(DestType.getNonLValueExprType(S.Context));
13160   E->setValueKind(Expr::getValueKindForType(DestType));
13161   assert(E->getObjectKind() == OK_Ordinary);
13162 
13163   // Rebuild the function type, replacing the result type with DestType.
13164   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
13165   if (Proto) {
13166     // __unknown_anytype(...) is a special case used by the debugger when
13167     // it has no idea what a function's signature is.
13168     //
13169     // We want to build this call essentially under the K&R
13170     // unprototyped rules, but making a FunctionNoProtoType in C++
13171     // would foul up all sorts of assumptions.  However, we cannot
13172     // simply pass all arguments as variadic arguments, nor can we
13173     // portably just call the function under a non-variadic type; see
13174     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
13175     // However, it turns out that in practice it is generally safe to
13176     // call a function declared as "A foo(B,C,D);" under the prototype
13177     // "A foo(B,C,D,...);".  The only known exception is with the
13178     // Windows ABI, where any variadic function is implicitly cdecl
13179     // regardless of its normal CC.  Therefore we change the parameter
13180     // types to match the types of the arguments.
13181     //
13182     // This is a hack, but it is far superior to moving the
13183     // corresponding target-specific code from IR-gen to Sema/AST.
13184 
13185     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
13186     SmallVector<QualType, 8> ArgTypes;
13187     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
13188       ArgTypes.reserve(E->getNumArgs());
13189       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
13190         Expr *Arg = E->getArg(i);
13191         QualType ArgType = Arg->getType();
13192         if (E->isLValue()) {
13193           ArgType = S.Context.getLValueReferenceType(ArgType);
13194         } else if (E->isXValue()) {
13195           ArgType = S.Context.getRValueReferenceType(ArgType);
13196         }
13197         ArgTypes.push_back(ArgType);
13198       }
13199       ParamTypes = ArgTypes;
13200     }
13201     DestType = S.Context.getFunctionType(DestType, ParamTypes,
13202                                          Proto->getExtProtoInfo());
13203   } else {
13204     DestType = S.Context.getFunctionNoProtoType(DestType,
13205                                                 FnType->getExtInfo());
13206   }
13207 
13208   // Rebuild the appropriate pointer-to-function type.
13209   switch (Kind) {
13210   case FK_MemberFunction:
13211     // Nothing to do.
13212     break;
13213 
13214   case FK_FunctionPointer:
13215     DestType = S.Context.getPointerType(DestType);
13216     break;
13217 
13218   case FK_BlockPointer:
13219     DestType = S.Context.getBlockPointerType(DestType);
13220     break;
13221   }
13222 
13223   // Finally, we can recurse.
13224   ExprResult CalleeResult = Visit(CalleeExpr);
13225   if (!CalleeResult.isUsable()) return ExprError();
13226   E->setCallee(CalleeResult.get());
13227 
13228   // Bind a temporary if necessary.
13229   return S.MaybeBindToTemporary(E);
13230 }
13231 
VisitObjCMessageExpr(ObjCMessageExpr * E)13232 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
13233   // Verify that this is a legal result type of a call.
13234   if (DestType->isArrayType() || DestType->isFunctionType()) {
13235     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13236       << DestType->isFunctionType() << DestType;
13237     return ExprError();
13238   }
13239 
13240   // Rewrite the method result type if available.
13241   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13242     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13243     Method->setReturnType(DestType);
13244   }
13245 
13246   // Change the type of the message.
13247   E->setType(DestType.getNonReferenceType());
13248   E->setValueKind(Expr::getValueKindForType(DestType));
13249 
13250   return S.MaybeBindToTemporary(E);
13251 }
13252 
VisitImplicitCastExpr(ImplicitCastExpr * E)13253 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
13254   // The only case we should ever see here is a function-to-pointer decay.
13255   if (E->getCastKind() == CK_FunctionToPointerDecay) {
13256     assert(E->getValueKind() == VK_RValue);
13257     assert(E->getObjectKind() == OK_Ordinary);
13258 
13259     E->setType(DestType);
13260 
13261     // Rebuild the sub-expression as the pointee (function) type.
13262     DestType = DestType->castAs<PointerType>()->getPointeeType();
13263 
13264     ExprResult Result = Visit(E->getSubExpr());
13265     if (!Result.isUsable()) return ExprError();
13266 
13267     E->setSubExpr(Result.get());
13268     return E;
13269   } else if (E->getCastKind() == CK_LValueToRValue) {
13270     assert(E->getValueKind() == VK_RValue);
13271     assert(E->getObjectKind() == OK_Ordinary);
13272 
13273     assert(isa<BlockPointerType>(E->getType()));
13274 
13275     E->setType(DestType);
13276 
13277     // The sub-expression has to be a lvalue reference, so rebuild it as such.
13278     DestType = S.Context.getLValueReferenceType(DestType);
13279 
13280     ExprResult Result = Visit(E->getSubExpr());
13281     if (!Result.isUsable()) return ExprError();
13282 
13283     E->setSubExpr(Result.get());
13284     return E;
13285   } else {
13286     llvm_unreachable("Unhandled cast type!");
13287   }
13288 }
13289 
resolveDecl(Expr * E,ValueDecl * VD)13290 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13291   ExprValueKind ValueKind = VK_LValue;
13292   QualType Type = DestType;
13293 
13294   // We know how to make this work for certain kinds of decls:
13295 
13296   //  - functions
13297   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13298     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13299       DestType = Ptr->getPointeeType();
13300       ExprResult Result = resolveDecl(E, VD);
13301       if (Result.isInvalid()) return ExprError();
13302       return S.ImpCastExprToType(Result.get(), Type,
13303                                  CK_FunctionToPointerDecay, VK_RValue);
13304     }
13305 
13306     if (!Type->isFunctionType()) {
13307       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13308         << VD << E->getSourceRange();
13309       return ExprError();
13310     }
13311 
13312     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
13313       if (MD->isInstance()) {
13314         ValueKind = VK_RValue;
13315         Type = S.Context.BoundMemberTy;
13316       }
13317 
13318     // Function references aren't l-values in C.
13319     if (!S.getLangOpts().CPlusPlus)
13320       ValueKind = VK_RValue;
13321 
13322   //  - variables
13323   } else if (isa<VarDecl>(VD)) {
13324     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
13325       Type = RefTy->getPointeeType();
13326     } else if (Type->isFunctionType()) {
13327       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
13328         << VD << E->getSourceRange();
13329       return ExprError();
13330     }
13331 
13332   //  - nothing else
13333   } else {
13334     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
13335       << VD << E->getSourceRange();
13336     return ExprError();
13337   }
13338 
13339   // Modifying the declaration like this is friendly to IR-gen but
13340   // also really dangerous.
13341   VD->setType(DestType);
13342   E->setType(Type);
13343   E->setValueKind(ValueKind);
13344   return E;
13345 }
13346 
13347 /// Check a cast of an unknown-any type.  We intentionally only
13348 /// trigger this for C-style casts.
checkUnknownAnyCast(SourceRange TypeRange,QualType CastType,Expr * CastExpr,CastKind & CastKind,ExprValueKind & VK,CXXCastPath & Path)13349 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
13350                                      Expr *CastExpr, CastKind &CastKind,
13351                                      ExprValueKind &VK, CXXCastPath &Path) {
13352   // Rewrite the casted expression from scratch.
13353   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13354   if (!result.isUsable()) return ExprError();
13355 
13356   CastExpr = result.get();
13357   VK = CastExpr->getValueKind();
13358   CastKind = CK_NoOp;
13359 
13360   return CastExpr;
13361 }
13362 
forceUnknownAnyToType(Expr * E,QualType ToType)13363 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13364   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13365 }
13366 
checkUnknownAnyArg(SourceLocation callLoc,Expr * arg,QualType & paramType)13367 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13368                                     Expr *arg, QualType &paramType) {
13369   // If the syntactic form of the argument is not an explicit cast of
13370   // any sort, just do default argument promotion.
13371   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13372   if (!castArg) {
13373     ExprResult result = DefaultArgumentPromotion(arg);
13374     if (result.isInvalid()) return ExprError();
13375     paramType = result.get()->getType();
13376     return result;
13377   }
13378 
13379   // Otherwise, use the type that was written in the explicit cast.
13380   assert(!arg->hasPlaceholderType());
13381   paramType = castArg->getTypeAsWritten();
13382 
13383   // Copy-initialize a parameter of that type.
13384   InitializedEntity entity =
13385     InitializedEntity::InitializeParameter(Context, paramType,
13386                                            /*consumed*/ false);
13387   return PerformCopyInitialization(entity, callLoc, arg);
13388 }
13389 
diagnoseUnknownAnyExpr(Sema & S,Expr * E)13390 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13391   Expr *orig = E;
13392   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13393   while (true) {
13394     E = E->IgnoreParenImpCasts();
13395     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13396       E = call->getCallee();
13397       diagID = diag::err_uncasted_call_of_unknown_any;
13398     } else {
13399       break;
13400     }
13401   }
13402 
13403   SourceLocation loc;
13404   NamedDecl *d;
13405   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13406     loc = ref->getLocation();
13407     d = ref->getDecl();
13408   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13409     loc = mem->getMemberLoc();
13410     d = mem->getMemberDecl();
13411   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13412     diagID = diag::err_uncasted_call_of_unknown_any;
13413     loc = msg->getSelectorStartLoc();
13414     d = msg->getMethodDecl();
13415     if (!d) {
13416       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13417         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13418         << orig->getSourceRange();
13419       return ExprError();
13420     }
13421   } else {
13422     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13423       << E->getSourceRange();
13424     return ExprError();
13425   }
13426 
13427   S.Diag(loc, diagID) << d << orig->getSourceRange();
13428 
13429   // Never recoverable.
13430   return ExprError();
13431 }
13432 
13433 /// Check for operands with placeholder types and complain if found.
13434 /// Returns true if there was an error and no recovery was possible.
CheckPlaceholderExpr(Expr * E)13435 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13436   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13437   if (!placeholderType) return E;
13438 
13439   switch (placeholderType->getKind()) {
13440 
13441   // Overloaded expressions.
13442   case BuiltinType::Overload: {
13443     // Try to resolve a single function template specialization.
13444     // This is obligatory.
13445     ExprResult result = E;
13446     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13447       return result;
13448 
13449     // If that failed, try to recover with a call.
13450     } else {
13451       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13452                            /*complain*/ true);
13453       return result;
13454     }
13455   }
13456 
13457   // Bound member functions.
13458   case BuiltinType::BoundMember: {
13459     ExprResult result = E;
13460     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13461                          /*complain*/ true);
13462     return result;
13463   }
13464 
13465   // ARC unbridged casts.
13466   case BuiltinType::ARCUnbridgedCast: {
13467     Expr *realCast = stripARCUnbridgedCast(E);
13468     diagnoseARCUnbridgedCast(realCast);
13469     return realCast;
13470   }
13471 
13472   // Expressions of unknown type.
13473   case BuiltinType::UnknownAny:
13474     return diagnoseUnknownAnyExpr(*this, E);
13475 
13476   // Pseudo-objects.
13477   case BuiltinType::PseudoObject:
13478     return checkPseudoObjectRValue(E);
13479 
13480   case BuiltinType::BuiltinFn:
13481     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13482     return ExprError();
13483 
13484   // Everything else should be impossible.
13485 #define BUILTIN_TYPE(Id, SingletonId) \
13486   case BuiltinType::Id:
13487 #define PLACEHOLDER_TYPE(Id, SingletonId)
13488 #include "clang/AST/BuiltinTypes.def"
13489     break;
13490   }
13491 
13492   llvm_unreachable("invalid placeholder type!");
13493 }
13494 
CheckCaseExpression(Expr * E)13495 bool Sema::CheckCaseExpression(Expr *E) {
13496   if (E->isTypeDependent())
13497     return true;
13498   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13499     return E->getType()->isIntegralOrEnumerationType();
13500   return false;
13501 }
13502 
13503 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13504 ExprResult
ActOnObjCBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)13505 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13506   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13507          "Unknown Objective-C Boolean value!");
13508   QualType BoolT = Context.ObjCBuiltinBoolTy;
13509   if (!Context.getBOOLDecl()) {
13510     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13511                         Sema::LookupOrdinaryName);
13512     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13513       NamedDecl *ND = Result.getFoundDecl();
13514       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13515         Context.setBOOLDecl(TD);
13516     }
13517   }
13518   if (Context.getBOOLDecl())
13519     BoolT = Context.getBOOLType();
13520   return new (Context)
13521       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
13522 }
13523