1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Overload.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/Support/ConvertUTF.h"
48 using namespace clang;
49 using namespace sema;
50 
51 /// Determine whether the use of this declaration is valid, without
52 /// emitting diagnostics.
53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
54   // See if this is an auto-typed variable whose initializer we are parsing.
55   if (ParsingInitForAutoVars.count(D))
56     return false;
57 
58   // See if this is a deleted function.
59   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60     if (FD->isDeleted())
61       return false;
62 
63     // If the function has a deduced return type, and we can't deduce it,
64     // then we can't use it either.
65     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
66         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
67       return false;
68   }
69 
70   // See if this function is unavailable.
71   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
72       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
73     return false;
74 
75   return true;
76 }
77 
78 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
79   // Warn if this is used but marked unused.
80   if (const auto *A = D->getAttr<UnusedAttr>()) {
81     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
82     // should diagnose them.
83     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
84         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
85       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
86       if (DC && !DC->hasAttr<UnusedAttr>())
87         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
88     }
89   }
90 }
91 
92 /// Emit a note explaining that this function is deleted.
93 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
94   assert(Decl->isDeleted());
95 
96   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
97 
98   if (Method && Method->isDeleted() && Method->isDefaulted()) {
99     // If the method was explicitly defaulted, point at that declaration.
100     if (!Method->isImplicit())
101       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
102 
103     // Try to diagnose why this special member function was implicitly
104     // deleted. This might fail, if that reason no longer applies.
105     CXXSpecialMember CSM = getSpecialMember(Method);
106     if (CSM != CXXInvalid)
107       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
108 
109     return;
110   }
111 
112   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
113   if (Ctor && Ctor->isInheritingConstructor())
114     return NoteDeletedInheritingConstructor(Ctor);
115 
116   Diag(Decl->getLocation(), diag::note_availability_specified_here)
117     << Decl << true;
118 }
119 
120 /// Determine whether a FunctionDecl was ever declared with an
121 /// explicit storage class.
122 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
123   for (auto I : D->redecls()) {
124     if (I->getStorageClass() != SC_None)
125       return true;
126   }
127   return false;
128 }
129 
130 /// Check whether we're in an extern inline function and referring to a
131 /// variable or function with internal linkage (C11 6.7.4p3).
132 ///
133 /// This is only a warning because we used to silently accept this code, but
134 /// in many cases it will not behave correctly. This is not enabled in C++ mode
135 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
136 /// and so while there may still be user mistakes, most of the time we can't
137 /// prove that there are errors.
138 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
139                                                       const NamedDecl *D,
140                                                       SourceLocation Loc) {
141   // This is disabled under C++; there are too many ways for this to fire in
142   // contexts where the warning is a false positive, or where it is technically
143   // correct but benign.
144   if (S.getLangOpts().CPlusPlus)
145     return;
146 
147   // Check if this is an inlined function or method.
148   FunctionDecl *Current = S.getCurFunctionDecl();
149   if (!Current)
150     return;
151   if (!Current->isInlined())
152     return;
153   if (!Current->isExternallyVisible())
154     return;
155 
156   // Check if the decl has internal linkage.
157   if (D->getFormalLinkage() != InternalLinkage)
158     return;
159 
160   // Downgrade from ExtWarn to Extension if
161   //  (1) the supposedly external inline function is in the main file,
162   //      and probably won't be included anywhere else.
163   //  (2) the thing we're referencing is a pure function.
164   //  (3) the thing we're referencing is another inline function.
165   // This last can give us false negatives, but it's better than warning on
166   // wrappers for simple C library functions.
167   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
168   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
169   if (!DowngradeWarning && UsedFn)
170     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
171 
172   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
173                                : diag::ext_internal_in_extern_inline)
174     << /*IsVar=*/!UsedFn << D;
175 
176   S.MaybeSuggestAddingStaticToDecl(Current);
177 
178   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
179       << D;
180 }
181 
182 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
183   const FunctionDecl *First = Cur->getFirstDecl();
184 
185   // Suggest "static" on the function, if possible.
186   if (!hasAnyExplicitStorageClass(First)) {
187     SourceLocation DeclBegin = First->getSourceRange().getBegin();
188     Diag(DeclBegin, diag::note_convert_inline_to_static)
189       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
190   }
191 }
192 
193 /// Determine whether the use of this declaration is valid, and
194 /// emit any corresponding diagnostics.
195 ///
196 /// This routine diagnoses various problems with referencing
197 /// declarations that can occur when using a declaration. For example,
198 /// it might warn if a deprecated or unavailable declaration is being
199 /// used, or produce an error (and return true) if a C++0x deleted
200 /// function is being used.
201 ///
202 /// \returns true if there was an error (this declaration cannot be
203 /// referenced), false otherwise.
204 ///
205 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
206                              const ObjCInterfaceDecl *UnknownObjCClass,
207                              bool ObjCPropertyAccess,
208                              bool AvoidPartialAvailabilityChecks) {
209   SourceLocation Loc = Locs.front();
210   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
211     // If there were any diagnostics suppressed by template argument deduction,
212     // emit them now.
213     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
214     if (Pos != SuppressedDiagnostics.end()) {
215       for (const PartialDiagnosticAt &Suppressed : Pos->second)
216         Diag(Suppressed.first, Suppressed.second);
217 
218       // Clear out the list of suppressed diagnostics, so that we don't emit
219       // them again for this specialization. However, we don't obsolete this
220       // entry from the table, because we want to avoid ever emitting these
221       // diagnostics again.
222       Pos->second.clear();
223     }
224 
225     // C++ [basic.start.main]p3:
226     //   The function 'main' shall not be used within a program.
227     if (cast<FunctionDecl>(D)->isMain())
228       Diag(Loc, diag::ext_main_used);
229   }
230 
231   // See if this is an auto-typed variable whose initializer we are parsing.
232   if (ParsingInitForAutoVars.count(D)) {
233     if (isa<BindingDecl>(D)) {
234       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
235         << D->getDeclName();
236     } else {
237       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
238         << D->getDeclName() << cast<VarDecl>(D)->getType();
239     }
240     return true;
241   }
242 
243   // See if this is a deleted function.
244   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245     if (FD->isDeleted()) {
246       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
247       if (Ctor && Ctor->isInheritingConstructor())
248         Diag(Loc, diag::err_deleted_inherited_ctor_use)
249             << Ctor->getParent()
250             << Ctor->getInheritedConstructor().getConstructor()->getParent();
251       else
252         Diag(Loc, diag::err_deleted_function_use);
253       NoteDeletedFunction(FD);
254       return true;
255     }
256 
257     // If the function has a deduced return type, and we can't deduce it,
258     // then we can't use it either.
259     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
260         DeduceReturnType(FD, Loc))
261       return true;
262 
263     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
264       return true;
265   }
266 
267   auto getReferencedObjCProp = [](const NamedDecl *D) ->
268                                       const ObjCPropertyDecl * {
269     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
270       return MD->findPropertyDecl();
271     return nullptr;
272   };
273   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
274     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
275       return true;
276   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
277       return true;
278   }
279 
280   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
281   // Only the variables omp_in and omp_out are allowed in the combiner.
282   // Only the variables omp_priv and omp_orig are allowed in the
283   // initializer-clause.
284   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
285   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
286       isa<VarDecl>(D)) {
287     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
288         << getCurFunction()->HasOMPDeclareReductionCombiner;
289     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
290     return true;
291   }
292 
293   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
294                              AvoidPartialAvailabilityChecks);
295 
296   DiagnoseUnusedOfDecl(*this, D, Loc);
297 
298   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
299 
300   return false;
301 }
302 
303 /// Retrieve the message suffix that should be added to a
304 /// diagnostic complaining about the given function being deleted or
305 /// unavailable.
306 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
307   std::string Message;
308   if (FD->getAvailability(&Message))
309     return ": " + Message;
310 
311   return std::string();
312 }
313 
314 /// DiagnoseSentinelCalls - This routine checks whether a call or
315 /// message-send is to a declaration with the sentinel attribute, and
316 /// if so, it checks that the requirements of the sentinel are
317 /// satisfied.
318 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
319                                  ArrayRef<Expr *> Args) {
320   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
321   if (!attr)
322     return;
323 
324   // The number of formal parameters of the declaration.
325   unsigned numFormalParams;
326 
327   // The kind of declaration.  This is also an index into a %select in
328   // the diagnostic.
329   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
330 
331   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
332     numFormalParams = MD->param_size();
333     calleeType = CT_Method;
334   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
335     numFormalParams = FD->param_size();
336     calleeType = CT_Function;
337   } else if (isa<VarDecl>(D)) {
338     QualType type = cast<ValueDecl>(D)->getType();
339     const FunctionType *fn = nullptr;
340     if (const PointerType *ptr = type->getAs<PointerType>()) {
341       fn = ptr->getPointeeType()->getAs<FunctionType>();
342       if (!fn) return;
343       calleeType = CT_Function;
344     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
345       fn = ptr->getPointeeType()->castAs<FunctionType>();
346       calleeType = CT_Block;
347     } else {
348       return;
349     }
350 
351     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
352       numFormalParams = proto->getNumParams();
353     } else {
354       numFormalParams = 0;
355     }
356   } else {
357     return;
358   }
359 
360   // "nullPos" is the number of formal parameters at the end which
361   // effectively count as part of the variadic arguments.  This is
362   // useful if you would prefer to not have *any* formal parameters,
363   // but the language forces you to have at least one.
364   unsigned nullPos = attr->getNullPos();
365   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
366   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
367 
368   // The number of arguments which should follow the sentinel.
369   unsigned numArgsAfterSentinel = attr->getSentinel();
370 
371   // If there aren't enough arguments for all the formal parameters,
372   // the sentinel, and the args after the sentinel, complain.
373   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
374     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
375     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
376     return;
377   }
378 
379   // Otherwise, find the sentinel expression.
380   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
381   if (!sentinelExpr) return;
382   if (sentinelExpr->isValueDependent()) return;
383   if (Context.isSentinelNullExpr(sentinelExpr)) return;
384 
385   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
386   // or 'NULL' if those are actually defined in the context.  Only use
387   // 'nil' for ObjC methods, where it's much more likely that the
388   // variadic arguments form a list of object pointers.
389   SourceLocation MissingNilLoc
390     = getLocForEndOfToken(sentinelExpr->getLocEnd());
391   std::string NullValue;
392   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
393     NullValue = "nil";
394   else if (getLangOpts().CPlusPlus11)
395     NullValue = "nullptr";
396   else if (PP.isMacroDefined("NULL"))
397     NullValue = "NULL";
398   else
399     NullValue = "(void*) 0";
400 
401   if (MissingNilLoc.isInvalid())
402     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
403   else
404     Diag(MissingNilLoc, diag::warn_missing_sentinel)
405       << int(calleeType)
406       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
407   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
408 }
409 
410 SourceRange Sema::getExprRange(Expr *E) const {
411   return E ? E->getSourceRange() : SourceRange();
412 }
413 
414 //===----------------------------------------------------------------------===//
415 //  Standard Promotions and Conversions
416 //===----------------------------------------------------------------------===//
417 
418 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
419 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
420   // Handle any placeholder expressions which made it here.
421   if (E->getType()->isPlaceholderType()) {
422     ExprResult result = CheckPlaceholderExpr(E);
423     if (result.isInvalid()) return ExprError();
424     E = result.get();
425   }
426 
427   QualType Ty = E->getType();
428   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
429 
430   if (Ty->isFunctionType()) {
431     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
432       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
433         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
434           return ExprError();
435 
436     E = ImpCastExprToType(E, Context.getPointerType(Ty),
437                           CK_FunctionToPointerDecay).get();
438   } else if (Ty->isArrayType()) {
439     // In C90 mode, arrays only promote to pointers if the array expression is
440     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
441     // type 'array of type' is converted to an expression that has type 'pointer
442     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
443     // that has type 'array of type' ...".  The relevant change is "an lvalue"
444     // (C90) to "an expression" (C99).
445     //
446     // C++ 4.2p1:
447     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
448     // T" can be converted to an rvalue of type "pointer to T".
449     //
450     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
451       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
452                             CK_ArrayToPointerDecay).get();
453   }
454   return E;
455 }
456 
457 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
458   // Check to see if we are dereferencing a null pointer.  If so,
459   // and if not volatile-qualified, this is undefined behavior that the
460   // optimizer will delete, so warn about it.  People sometimes try to use this
461   // to get a deterministic trap and are surprised by clang's behavior.  This
462   // only handles the pattern "*null", which is a very syntactic check.
463   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
464     if (UO->getOpcode() == UO_Deref &&
465         UO->getSubExpr()->IgnoreParenCasts()->
466           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
467         !UO->getType().isVolatileQualified()) {
468     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
469                           S.PDiag(diag::warn_indirection_through_null)
470                             << UO->getSubExpr()->getSourceRange());
471     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
472                         S.PDiag(diag::note_indirection_through_null));
473   }
474 }
475 
476 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
477                                     SourceLocation AssignLoc,
478                                     const Expr* RHS) {
479   const ObjCIvarDecl *IV = OIRE->getDecl();
480   if (!IV)
481     return;
482 
483   DeclarationName MemberName = IV->getDeclName();
484   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
485   if (!Member || !Member->isStr("isa"))
486     return;
487 
488   const Expr *Base = OIRE->getBase();
489   QualType BaseType = Base->getType();
490   if (OIRE->isArrow())
491     BaseType = BaseType->getPointeeType();
492   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
493     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
494       ObjCInterfaceDecl *ClassDeclared = nullptr;
495       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
496       if (!ClassDeclared->getSuperClass()
497           && (*ClassDeclared->ivar_begin()) == IV) {
498         if (RHS) {
499           NamedDecl *ObjectSetClass =
500             S.LookupSingleName(S.TUScope,
501                                &S.Context.Idents.get("object_setClass"),
502                                SourceLocation(), S.LookupOrdinaryName);
503           if (ObjectSetClass) {
504             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
505             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
506             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
507             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
508                                                      AssignLoc), ",") <<
509             FixItHint::CreateInsertion(RHSLocEnd, ")");
510           }
511           else
512             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
513         } else {
514           NamedDecl *ObjectGetClass =
515             S.LookupSingleName(S.TUScope,
516                                &S.Context.Idents.get("object_getClass"),
517                                SourceLocation(), S.LookupOrdinaryName);
518           if (ObjectGetClass)
519             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
520             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
521             FixItHint::CreateReplacement(
522                                          SourceRange(OIRE->getOpLoc(),
523                                                      OIRE->getLocEnd()), ")");
524           else
525             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
526         }
527         S.Diag(IV->getLocation(), diag::note_ivar_decl);
528       }
529     }
530 }
531 
532 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
533   // Handle any placeholder expressions which made it here.
534   if (E->getType()->isPlaceholderType()) {
535     ExprResult result = CheckPlaceholderExpr(E);
536     if (result.isInvalid()) return ExprError();
537     E = result.get();
538   }
539 
540   // C++ [conv.lval]p1:
541   //   A glvalue of a non-function, non-array type T can be
542   //   converted to a prvalue.
543   if (!E->isGLValue()) return E;
544 
545   QualType T = E->getType();
546   assert(!T.isNull() && "r-value conversion on typeless expression?");
547 
548   // We don't want to throw lvalue-to-rvalue casts on top of
549   // expressions of certain types in C++.
550   if (getLangOpts().CPlusPlus &&
551       (E->getType() == Context.OverloadTy ||
552        T->isDependentType() ||
553        T->isRecordType()))
554     return E;
555 
556   // The C standard is actually really unclear on this point, and
557   // DR106 tells us what the result should be but not why.  It's
558   // generally best to say that void types just doesn't undergo
559   // lvalue-to-rvalue at all.  Note that expressions of unqualified
560   // 'void' type are never l-values, but qualified void can be.
561   if (T->isVoidType())
562     return E;
563 
564   // OpenCL usually rejects direct accesses to values of 'half' type.
565   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
566       T->isHalfType()) {
567     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
568       << 0 << T;
569     return ExprError();
570   }
571 
572   CheckForNullPointerDereference(*this, E);
573   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
574     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
575                                      &Context.Idents.get("object_getClass"),
576                                      SourceLocation(), LookupOrdinaryName);
577     if (ObjectGetClass)
578       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
579         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
580         FixItHint::CreateReplacement(
581                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
582     else
583       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
584   }
585   else if (const ObjCIvarRefExpr *OIRE =
586             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
587     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
588 
589   // C++ [conv.lval]p1:
590   //   [...] If T is a non-class type, the type of the prvalue is the
591   //   cv-unqualified version of T. Otherwise, the type of the
592   //   rvalue is T.
593   //
594   // C99 6.3.2.1p2:
595   //   If the lvalue has qualified type, the value has the unqualified
596   //   version of the type of the lvalue; otherwise, the value has the
597   //   type of the lvalue.
598   if (T.hasQualifiers())
599     T = T.getUnqualifiedType();
600 
601   // Under the MS ABI, lock down the inheritance model now.
602   if (T->isMemberPointerType() &&
603       Context.getTargetInfo().getCXXABI().isMicrosoft())
604     (void)isCompleteType(E->getExprLoc(), T);
605 
606   UpdateMarkingForLValueToRValue(E);
607 
608   // Loading a __weak object implicitly retains the value, so we need a cleanup to
609   // balance that.
610   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
611     Cleanup.setExprNeedsCleanups(true);
612 
613   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
614                                             nullptr, VK_RValue);
615 
616   // C11 6.3.2.1p2:
617   //   ... if the lvalue has atomic type, the value has the non-atomic version
618   //   of the type of the lvalue ...
619   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
620     T = Atomic->getValueType().getUnqualifiedType();
621     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
622                                    nullptr, VK_RValue);
623   }
624 
625   return Res;
626 }
627 
628 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
629   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
630   if (Res.isInvalid())
631     return ExprError();
632   Res = DefaultLvalueConversion(Res.get());
633   if (Res.isInvalid())
634     return ExprError();
635   return Res;
636 }
637 
638 /// CallExprUnaryConversions - a special case of an unary conversion
639 /// performed on a function designator of a call expression.
640 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
641   QualType Ty = E->getType();
642   ExprResult Res = E;
643   // Only do implicit cast for a function type, but not for a pointer
644   // to function type.
645   if (Ty->isFunctionType()) {
646     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
647                             CK_FunctionToPointerDecay).get();
648     if (Res.isInvalid())
649       return ExprError();
650   }
651   Res = DefaultLvalueConversion(Res.get());
652   if (Res.isInvalid())
653     return ExprError();
654   return Res.get();
655 }
656 
657 /// UsualUnaryConversions - Performs various conversions that are common to most
658 /// operators (C99 6.3). The conversions of array and function types are
659 /// sometimes suppressed. For example, the array->pointer conversion doesn't
660 /// apply if the array is an argument to the sizeof or address (&) operators.
661 /// In these instances, this routine should *not* be called.
662 ExprResult Sema::UsualUnaryConversions(Expr *E) {
663   // First, convert to an r-value.
664   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
665   if (Res.isInvalid())
666     return ExprError();
667   E = Res.get();
668 
669   QualType Ty = E->getType();
670   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
671 
672   // Half FP have to be promoted to float unless it is natively supported
673   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
674     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
675 
676   // Try to perform integral promotions if the object has a theoretically
677   // promotable type.
678   if (Ty->isIntegralOrUnscopedEnumerationType()) {
679     // C99 6.3.1.1p2:
680     //
681     //   The following may be used in an expression wherever an int or
682     //   unsigned int may be used:
683     //     - an object or expression with an integer type whose integer
684     //       conversion rank is less than or equal to the rank of int
685     //       and unsigned int.
686     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
687     //
688     //   If an int can represent all values of the original type, the
689     //   value is converted to an int; otherwise, it is converted to an
690     //   unsigned int. These are called the integer promotions. All
691     //   other types are unchanged by the integer promotions.
692 
693     QualType PTy = Context.isPromotableBitField(E);
694     if (!PTy.isNull()) {
695       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
696       return E;
697     }
698     if (Ty->isPromotableIntegerType()) {
699       QualType PT = Context.getPromotedIntegerType(Ty);
700       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
701       return E;
702     }
703   }
704   return E;
705 }
706 
707 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
708 /// do not have a prototype. Arguments that have type float or __fp16
709 /// are promoted to double. All other argument types are converted by
710 /// UsualUnaryConversions().
711 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
712   QualType Ty = E->getType();
713   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
714 
715   ExprResult Res = UsualUnaryConversions(E);
716   if (Res.isInvalid())
717     return ExprError();
718   E = Res.get();
719 
720   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
721   // promote to double.
722   // Note that default argument promotion applies only to float (and
723   // half/fp16); it does not apply to _Float16.
724   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
725   if (BTy && (BTy->getKind() == BuiltinType::Half ||
726               BTy->getKind() == BuiltinType::Float)) {
727     if (getLangOpts().OpenCL &&
728         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
729         if (BTy->getKind() == BuiltinType::Half) {
730             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
731         }
732     } else {
733       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
734     }
735   }
736 
737   // C++ performs lvalue-to-rvalue conversion as a default argument
738   // promotion, even on class types, but note:
739   //   C++11 [conv.lval]p2:
740   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
741   //     operand or a subexpression thereof the value contained in the
742   //     referenced object is not accessed. Otherwise, if the glvalue
743   //     has a class type, the conversion copy-initializes a temporary
744   //     of type T from the glvalue and the result of the conversion
745   //     is a prvalue for the temporary.
746   // FIXME: add some way to gate this entire thing for correctness in
747   // potentially potentially evaluated contexts.
748   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
749     ExprResult Temp = PerformCopyInitialization(
750                        InitializedEntity::InitializeTemporary(E->getType()),
751                                                 E->getExprLoc(), E);
752     if (Temp.isInvalid())
753       return ExprError();
754     E = Temp.get();
755   }
756 
757   return E;
758 }
759 
760 /// Determine the degree of POD-ness for an expression.
761 /// Incomplete types are considered POD, since this check can be performed
762 /// when we're in an unevaluated context.
763 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
764   if (Ty->isIncompleteType()) {
765     // C++11 [expr.call]p7:
766     //   After these conversions, if the argument does not have arithmetic,
767     //   enumeration, pointer, pointer to member, or class type, the program
768     //   is ill-formed.
769     //
770     // Since we've already performed array-to-pointer and function-to-pointer
771     // decay, the only such type in C++ is cv void. This also handles
772     // initializer lists as variadic arguments.
773     if (Ty->isVoidType())
774       return VAK_Invalid;
775 
776     if (Ty->isObjCObjectType())
777       return VAK_Invalid;
778     return VAK_Valid;
779   }
780 
781   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
782     return VAK_Invalid;
783 
784   if (Ty.isCXX98PODType(Context))
785     return VAK_Valid;
786 
787   // C++11 [expr.call]p7:
788   //   Passing a potentially-evaluated argument of class type (Clause 9)
789   //   having a non-trivial copy constructor, a non-trivial move constructor,
790   //   or a non-trivial destructor, with no corresponding parameter,
791   //   is conditionally-supported with implementation-defined semantics.
792   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
793     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
794       if (!Record->hasNonTrivialCopyConstructor() &&
795           !Record->hasNonTrivialMoveConstructor() &&
796           !Record->hasNonTrivialDestructor())
797         return VAK_ValidInCXX11;
798 
799   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
800     return VAK_Valid;
801 
802   if (Ty->isObjCObjectType())
803     return VAK_Invalid;
804 
805   if (getLangOpts().MSVCCompat)
806     return VAK_MSVCUndefined;
807 
808   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
809   // permitted to reject them. We should consider doing so.
810   return VAK_Undefined;
811 }
812 
813 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
814   // Don't allow one to pass an Objective-C interface to a vararg.
815   const QualType &Ty = E->getType();
816   VarArgKind VAK = isValidVarArgType(Ty);
817 
818   // Complain about passing non-POD types through varargs.
819   switch (VAK) {
820   case VAK_ValidInCXX11:
821     DiagRuntimeBehavior(
822         E->getLocStart(), nullptr,
823         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
824           << Ty << CT);
825     LLVM_FALLTHROUGH;
826   case VAK_Valid:
827     if (Ty->isRecordType()) {
828       // This is unlikely to be what the user intended. If the class has a
829       // 'c_str' member function, the user probably meant to call that.
830       DiagRuntimeBehavior(E->getLocStart(), nullptr,
831                           PDiag(diag::warn_pass_class_arg_to_vararg)
832                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
833     }
834     break;
835 
836   case VAK_Undefined:
837   case VAK_MSVCUndefined:
838     DiagRuntimeBehavior(
839         E->getLocStart(), nullptr,
840         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
841           << getLangOpts().CPlusPlus11 << Ty << CT);
842     break;
843 
844   case VAK_Invalid:
845     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
846       Diag(E->getLocStart(),
847            diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT;
848     else if (Ty->isObjCObjectType())
849       DiagRuntimeBehavior(
850           E->getLocStart(), nullptr,
851           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
852             << Ty << CT);
853     else
854       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
855         << isa<InitListExpr>(E) << Ty << CT;
856     break;
857   }
858 }
859 
860 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
861 /// will create a trap if the resulting type is not a POD type.
862 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
863                                                   FunctionDecl *FDecl) {
864   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
865     // Strip the unbridged-cast placeholder expression off, if applicable.
866     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
867         (CT == VariadicMethod ||
868          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
869       E = stripARCUnbridgedCast(E);
870 
871     // Otherwise, do normal placeholder checking.
872     } else {
873       ExprResult ExprRes = CheckPlaceholderExpr(E);
874       if (ExprRes.isInvalid())
875         return ExprError();
876       E = ExprRes.get();
877     }
878   }
879 
880   ExprResult ExprRes = DefaultArgumentPromotion(E);
881   if (ExprRes.isInvalid())
882     return ExprError();
883   E = ExprRes.get();
884 
885   // Diagnostics regarding non-POD argument types are
886   // emitted along with format string checking in Sema::CheckFunctionCall().
887   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
888     // Turn this into a trap.
889     CXXScopeSpec SS;
890     SourceLocation TemplateKWLoc;
891     UnqualifiedId Name;
892     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
893                        E->getLocStart());
894     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
895                                           Name, true, false);
896     if (TrapFn.isInvalid())
897       return ExprError();
898 
899     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
900                                     E->getLocStart(), None,
901                                     E->getLocEnd());
902     if (Call.isInvalid())
903       return ExprError();
904 
905     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
906                                   Call.get(), E);
907     if (Comma.isInvalid())
908       return ExprError();
909     return Comma.get();
910   }
911 
912   if (!getLangOpts().CPlusPlus &&
913       RequireCompleteType(E->getExprLoc(), E->getType(),
914                           diag::err_call_incomplete_argument))
915     return ExprError();
916 
917   return E;
918 }
919 
920 /// Converts an integer to complex float type.  Helper function of
921 /// UsualArithmeticConversions()
922 ///
923 /// \return false if the integer expression is an integer type and is
924 /// successfully converted to the complex type.
925 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
926                                                   ExprResult &ComplexExpr,
927                                                   QualType IntTy,
928                                                   QualType ComplexTy,
929                                                   bool SkipCast) {
930   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
931   if (SkipCast) return false;
932   if (IntTy->isIntegerType()) {
933     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
934     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
935     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
936                                   CK_FloatingRealToComplex);
937   } else {
938     assert(IntTy->isComplexIntegerType());
939     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
940                                   CK_IntegralComplexToFloatingComplex);
941   }
942   return false;
943 }
944 
945 /// Handle arithmetic conversion with complex types.  Helper function of
946 /// UsualArithmeticConversions()
947 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
948                                              ExprResult &RHS, QualType LHSType,
949                                              QualType RHSType,
950                                              bool IsCompAssign) {
951   // if we have an integer operand, the result is the complex type.
952   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
953                                              /*skipCast*/false))
954     return LHSType;
955   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
956                                              /*skipCast*/IsCompAssign))
957     return RHSType;
958 
959   // This handles complex/complex, complex/float, or float/complex.
960   // When both operands are complex, the shorter operand is converted to the
961   // type of the longer, and that is the type of the result. This corresponds
962   // to what is done when combining two real floating-point operands.
963   // The fun begins when size promotion occur across type domains.
964   // From H&S 6.3.4: When one operand is complex and the other is a real
965   // floating-point type, the less precise type is converted, within it's
966   // real or complex domain, to the precision of the other type. For example,
967   // when combining a "long double" with a "double _Complex", the
968   // "double _Complex" is promoted to "long double _Complex".
969 
970   // Compute the rank of the two types, regardless of whether they are complex.
971   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
972 
973   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
974   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
975   QualType LHSElementType =
976       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
977   QualType RHSElementType =
978       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
979 
980   QualType ResultType = S.Context.getComplexType(LHSElementType);
981   if (Order < 0) {
982     // Promote the precision of the LHS if not an assignment.
983     ResultType = S.Context.getComplexType(RHSElementType);
984     if (!IsCompAssign) {
985       if (LHSComplexType)
986         LHS =
987             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
988       else
989         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
990     }
991   } else if (Order > 0) {
992     // Promote the precision of the RHS.
993     if (RHSComplexType)
994       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
995     else
996       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
997   }
998   return ResultType;
999 }
1000 
1001 /// Handle arithmetic conversion from integer to float.  Helper function
1002 /// of UsualArithmeticConversions()
1003 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1004                                            ExprResult &IntExpr,
1005                                            QualType FloatTy, QualType IntTy,
1006                                            bool ConvertFloat, bool ConvertInt) {
1007   if (IntTy->isIntegerType()) {
1008     if (ConvertInt)
1009       // Convert intExpr to the lhs floating point type.
1010       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1011                                     CK_IntegralToFloating);
1012     return FloatTy;
1013   }
1014 
1015   // Convert both sides to the appropriate complex float.
1016   assert(IntTy->isComplexIntegerType());
1017   QualType result = S.Context.getComplexType(FloatTy);
1018 
1019   // _Complex int -> _Complex float
1020   if (ConvertInt)
1021     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1022                                   CK_IntegralComplexToFloatingComplex);
1023 
1024   // float -> _Complex float
1025   if (ConvertFloat)
1026     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1027                                     CK_FloatingRealToComplex);
1028 
1029   return result;
1030 }
1031 
1032 /// Handle arithmethic conversion with floating point types.  Helper
1033 /// function of UsualArithmeticConversions()
1034 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1035                                       ExprResult &RHS, QualType LHSType,
1036                                       QualType RHSType, bool IsCompAssign) {
1037   bool LHSFloat = LHSType->isRealFloatingType();
1038   bool RHSFloat = RHSType->isRealFloatingType();
1039 
1040   // If we have two real floating types, convert the smaller operand
1041   // to the bigger result.
1042   if (LHSFloat && RHSFloat) {
1043     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1044     if (order > 0) {
1045       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1046       return LHSType;
1047     }
1048 
1049     assert(order < 0 && "illegal float comparison");
1050     if (!IsCompAssign)
1051       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1052     return RHSType;
1053   }
1054 
1055   if (LHSFloat) {
1056     // Half FP has to be promoted to float unless it is natively supported
1057     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1058       LHSType = S.Context.FloatTy;
1059 
1060     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1061                                       /*convertFloat=*/!IsCompAssign,
1062                                       /*convertInt=*/ true);
1063   }
1064   assert(RHSFloat);
1065   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1066                                     /*convertInt=*/ true,
1067                                     /*convertFloat=*/!IsCompAssign);
1068 }
1069 
1070 /// Diagnose attempts to convert between __float128 and long double if
1071 /// there is no support for such conversion. Helper function of
1072 /// UsualArithmeticConversions().
1073 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1074                                       QualType RHSType) {
1075   /*  No issue converting if at least one of the types is not a floating point
1076       type or the two types have the same rank.
1077   */
1078   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1079       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1080     return false;
1081 
1082   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1083          "The remaining types must be floating point types.");
1084 
1085   auto *LHSComplex = LHSType->getAs<ComplexType>();
1086   auto *RHSComplex = RHSType->getAs<ComplexType>();
1087 
1088   QualType LHSElemType = LHSComplex ?
1089     LHSComplex->getElementType() : LHSType;
1090   QualType RHSElemType = RHSComplex ?
1091     RHSComplex->getElementType() : RHSType;
1092 
1093   // No issue if the two types have the same representation
1094   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1095       &S.Context.getFloatTypeSemantics(RHSElemType))
1096     return false;
1097 
1098   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1099                                 RHSElemType == S.Context.LongDoubleTy);
1100   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1101                             RHSElemType == S.Context.Float128Ty);
1102 
1103   // We've handled the situation where __float128 and long double have the same
1104   // representation. We allow all conversions for all possible long double types
1105   // except PPC's double double.
1106   return Float128AndLongDouble &&
1107     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1108      &llvm::APFloat::PPCDoubleDouble());
1109 }
1110 
1111 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1112 
1113 namespace {
1114 /// These helper callbacks are placed in an anonymous namespace to
1115 /// permit their use as function template parameters.
1116 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1117   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1118 }
1119 
1120 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1121   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1122                              CK_IntegralComplexCast);
1123 }
1124 }
1125 
1126 /// Handle integer arithmetic conversions.  Helper function of
1127 /// UsualArithmeticConversions()
1128 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1129 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1130                                         ExprResult &RHS, QualType LHSType,
1131                                         QualType RHSType, bool IsCompAssign) {
1132   // The rules for this case are in C99 6.3.1.8
1133   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1134   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1135   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1136   if (LHSSigned == RHSSigned) {
1137     // Same signedness; use the higher-ranked type
1138     if (order >= 0) {
1139       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1140       return LHSType;
1141     } else if (!IsCompAssign)
1142       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1143     return RHSType;
1144   } else if (order != (LHSSigned ? 1 : -1)) {
1145     // The unsigned type has greater than or equal rank to the
1146     // signed type, so use the unsigned type
1147     if (RHSSigned) {
1148       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1149       return LHSType;
1150     } else if (!IsCompAssign)
1151       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1152     return RHSType;
1153   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1154     // The two types are different widths; if we are here, that
1155     // means the signed type is larger than the unsigned type, so
1156     // use the signed type.
1157     if (LHSSigned) {
1158       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1159       return LHSType;
1160     } else if (!IsCompAssign)
1161       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1162     return RHSType;
1163   } else {
1164     // The signed type is higher-ranked than the unsigned type,
1165     // but isn't actually any bigger (like unsigned int and long
1166     // on most 32-bit systems).  Use the unsigned type corresponding
1167     // to the signed type.
1168     QualType result =
1169       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1170     RHS = (*doRHSCast)(S, RHS.get(), result);
1171     if (!IsCompAssign)
1172       LHS = (*doLHSCast)(S, LHS.get(), result);
1173     return result;
1174   }
1175 }
1176 
1177 /// Handle conversions with GCC complex int extension.  Helper function
1178 /// of UsualArithmeticConversions()
1179 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1180                                            ExprResult &RHS, QualType LHSType,
1181                                            QualType RHSType,
1182                                            bool IsCompAssign) {
1183   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1184   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1185 
1186   if (LHSComplexInt && RHSComplexInt) {
1187     QualType LHSEltType = LHSComplexInt->getElementType();
1188     QualType RHSEltType = RHSComplexInt->getElementType();
1189     QualType ScalarType =
1190       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1191         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1192 
1193     return S.Context.getComplexType(ScalarType);
1194   }
1195 
1196   if (LHSComplexInt) {
1197     QualType LHSEltType = LHSComplexInt->getElementType();
1198     QualType ScalarType =
1199       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1200         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1201     QualType ComplexType = S.Context.getComplexType(ScalarType);
1202     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1203                               CK_IntegralRealToComplex);
1204 
1205     return ComplexType;
1206   }
1207 
1208   assert(RHSComplexInt);
1209 
1210   QualType RHSEltType = RHSComplexInt->getElementType();
1211   QualType ScalarType =
1212     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1213       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1214   QualType ComplexType = S.Context.getComplexType(ScalarType);
1215 
1216   if (!IsCompAssign)
1217     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1218                               CK_IntegralRealToComplex);
1219   return ComplexType;
1220 }
1221 
1222 /// UsualArithmeticConversions - Performs various conversions that are common to
1223 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1224 /// routine returns the first non-arithmetic type found. The client is
1225 /// responsible for emitting appropriate error diagnostics.
1226 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1227                                           bool IsCompAssign) {
1228   if (!IsCompAssign) {
1229     LHS = UsualUnaryConversions(LHS.get());
1230     if (LHS.isInvalid())
1231       return QualType();
1232   }
1233 
1234   RHS = UsualUnaryConversions(RHS.get());
1235   if (RHS.isInvalid())
1236     return QualType();
1237 
1238   // For conversion purposes, we ignore any qualifiers.
1239   // For example, "const float" and "float" are equivalent.
1240   QualType LHSType =
1241     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1242   QualType RHSType =
1243     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1244 
1245   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1246   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1247     LHSType = AtomicLHS->getValueType();
1248 
1249   // If both types are identical, no conversion is needed.
1250   if (LHSType == RHSType)
1251     return LHSType;
1252 
1253   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1254   // The caller can deal with this (e.g. pointer + int).
1255   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1256     return QualType();
1257 
1258   // Apply unary and bitfield promotions to the LHS's type.
1259   QualType LHSUnpromotedType = LHSType;
1260   if (LHSType->isPromotableIntegerType())
1261     LHSType = Context.getPromotedIntegerType(LHSType);
1262   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1263   if (!LHSBitfieldPromoteTy.isNull())
1264     LHSType = LHSBitfieldPromoteTy;
1265   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1266     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1267 
1268   // If both types are identical, no conversion is needed.
1269   if (LHSType == RHSType)
1270     return LHSType;
1271 
1272   // At this point, we have two different arithmetic types.
1273 
1274   // Diagnose attempts to convert between __float128 and long double where
1275   // such conversions currently can't be handled.
1276   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1277     return QualType();
1278 
1279   // Handle complex types first (C99 6.3.1.8p1).
1280   if (LHSType->isComplexType() || RHSType->isComplexType())
1281     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1282                                         IsCompAssign);
1283 
1284   // Now handle "real" floating types (i.e. float, double, long double).
1285   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1286     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1287                                  IsCompAssign);
1288 
1289   // Handle GCC complex int extension.
1290   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1291     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1292                                       IsCompAssign);
1293 
1294   // Finally, we have two differing integer types.
1295   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1296            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1297 }
1298 
1299 
1300 //===----------------------------------------------------------------------===//
1301 //  Semantic Analysis for various Expression Types
1302 //===----------------------------------------------------------------------===//
1303 
1304 
1305 ExprResult
1306 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1307                                 SourceLocation DefaultLoc,
1308                                 SourceLocation RParenLoc,
1309                                 Expr *ControllingExpr,
1310                                 ArrayRef<ParsedType> ArgTypes,
1311                                 ArrayRef<Expr *> ArgExprs) {
1312   unsigned NumAssocs = ArgTypes.size();
1313   assert(NumAssocs == ArgExprs.size());
1314 
1315   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1316   for (unsigned i = 0; i < NumAssocs; ++i) {
1317     if (ArgTypes[i])
1318       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1319     else
1320       Types[i] = nullptr;
1321   }
1322 
1323   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1324                                              ControllingExpr,
1325                                              llvm::makeArrayRef(Types, NumAssocs),
1326                                              ArgExprs);
1327   delete [] Types;
1328   return ER;
1329 }
1330 
1331 ExprResult
1332 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1333                                  SourceLocation DefaultLoc,
1334                                  SourceLocation RParenLoc,
1335                                  Expr *ControllingExpr,
1336                                  ArrayRef<TypeSourceInfo *> Types,
1337                                  ArrayRef<Expr *> Exprs) {
1338   unsigned NumAssocs = Types.size();
1339   assert(NumAssocs == Exprs.size());
1340 
1341   // Decay and strip qualifiers for the controlling expression type, and handle
1342   // placeholder type replacement. See committee discussion from WG14 DR423.
1343   {
1344     EnterExpressionEvaluationContext Unevaluated(
1345         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1346     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1347     if (R.isInvalid())
1348       return ExprError();
1349     ControllingExpr = R.get();
1350   }
1351 
1352   // The controlling expression is an unevaluated operand, so side effects are
1353   // likely unintended.
1354   if (!inTemplateInstantiation() &&
1355       ControllingExpr->HasSideEffects(Context, false))
1356     Diag(ControllingExpr->getExprLoc(),
1357          diag::warn_side_effects_unevaluated_context);
1358 
1359   bool TypeErrorFound = false,
1360        IsResultDependent = ControllingExpr->isTypeDependent(),
1361        ContainsUnexpandedParameterPack
1362          = ControllingExpr->containsUnexpandedParameterPack();
1363 
1364   for (unsigned i = 0; i < NumAssocs; ++i) {
1365     if (Exprs[i]->containsUnexpandedParameterPack())
1366       ContainsUnexpandedParameterPack = true;
1367 
1368     if (Types[i]) {
1369       if (Types[i]->getType()->containsUnexpandedParameterPack())
1370         ContainsUnexpandedParameterPack = true;
1371 
1372       if (Types[i]->getType()->isDependentType()) {
1373         IsResultDependent = true;
1374       } else {
1375         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1376         // complete object type other than a variably modified type."
1377         unsigned D = 0;
1378         if (Types[i]->getType()->isIncompleteType())
1379           D = diag::err_assoc_type_incomplete;
1380         else if (!Types[i]->getType()->isObjectType())
1381           D = diag::err_assoc_type_nonobject;
1382         else if (Types[i]->getType()->isVariablyModifiedType())
1383           D = diag::err_assoc_type_variably_modified;
1384 
1385         if (D != 0) {
1386           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1387             << Types[i]->getTypeLoc().getSourceRange()
1388             << Types[i]->getType();
1389           TypeErrorFound = true;
1390         }
1391 
1392         // C11 6.5.1.1p2 "No two generic associations in the same generic
1393         // selection shall specify compatible types."
1394         for (unsigned j = i+1; j < NumAssocs; ++j)
1395           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1396               Context.typesAreCompatible(Types[i]->getType(),
1397                                          Types[j]->getType())) {
1398             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1399                  diag::err_assoc_compatible_types)
1400               << Types[j]->getTypeLoc().getSourceRange()
1401               << Types[j]->getType()
1402               << Types[i]->getType();
1403             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1404                  diag::note_compat_assoc)
1405               << Types[i]->getTypeLoc().getSourceRange()
1406               << Types[i]->getType();
1407             TypeErrorFound = true;
1408           }
1409       }
1410     }
1411   }
1412   if (TypeErrorFound)
1413     return ExprError();
1414 
1415   // If we determined that the generic selection is result-dependent, don't
1416   // try to compute the result expression.
1417   if (IsResultDependent)
1418     return new (Context) GenericSelectionExpr(
1419         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1420         ContainsUnexpandedParameterPack);
1421 
1422   SmallVector<unsigned, 1> CompatIndices;
1423   unsigned DefaultIndex = -1U;
1424   for (unsigned i = 0; i < NumAssocs; ++i) {
1425     if (!Types[i])
1426       DefaultIndex = i;
1427     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1428                                         Types[i]->getType()))
1429       CompatIndices.push_back(i);
1430   }
1431 
1432   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1433   // type compatible with at most one of the types named in its generic
1434   // association list."
1435   if (CompatIndices.size() > 1) {
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_multi_match)
1440       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1441       << (unsigned) CompatIndices.size();
1442     for (unsigned I : CompatIndices) {
1443       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1444            diag::note_compat_assoc)
1445         << Types[I]->getTypeLoc().getSourceRange()
1446         << Types[I]->getType();
1447     }
1448     return ExprError();
1449   }
1450 
1451   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1452   // its controlling expression shall have type compatible with exactly one of
1453   // the types named in its generic association list."
1454   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1455     // We strip parens here because the controlling expression is typically
1456     // parenthesized in macro definitions.
1457     ControllingExpr = ControllingExpr->IgnoreParens();
1458     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1459       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1460     return ExprError();
1461   }
1462 
1463   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1464   // type name that is compatible with the type of the controlling expression,
1465   // then the result expression of the generic selection is the expression
1466   // in that generic association. Otherwise, the result expression of the
1467   // generic selection is the expression in the default generic association."
1468   unsigned ResultIndex =
1469     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1470 
1471   return new (Context) GenericSelectionExpr(
1472       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1473       ContainsUnexpandedParameterPack, ResultIndex);
1474 }
1475 
1476 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1477 /// location of the token and the offset of the ud-suffix within it.
1478 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1479                                      unsigned Offset) {
1480   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1481                                         S.getLangOpts());
1482 }
1483 
1484 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1485 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1486 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1487                                                  IdentifierInfo *UDSuffix,
1488                                                  SourceLocation UDSuffixLoc,
1489                                                  ArrayRef<Expr*> Args,
1490                                                  SourceLocation LitEndLoc) {
1491   assert(Args.size() <= 2 && "too many arguments for literal operator");
1492 
1493   QualType ArgTy[2];
1494   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1495     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1496     if (ArgTy[ArgIdx]->isArrayType())
1497       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1498   }
1499 
1500   DeclarationName OpName =
1501     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1502   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1503   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1504 
1505   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1506   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1507                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1508                               /*AllowStringTemplate*/ false,
1509                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1510     return ExprError();
1511 
1512   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1513 }
1514 
1515 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1516 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1517 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1518 /// multiple tokens.  However, the common case is that StringToks points to one
1519 /// string.
1520 ///
1521 ExprResult
1522 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1523   assert(!StringToks.empty() && "Must have at least one string!");
1524 
1525   StringLiteralParser Literal(StringToks, PP);
1526   if (Literal.hadError)
1527     return ExprError();
1528 
1529   SmallVector<SourceLocation, 4> StringTokLocs;
1530   for (const Token &Tok : StringToks)
1531     StringTokLocs.push_back(Tok.getLocation());
1532 
1533   QualType CharTy = Context.CharTy;
1534   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1535   if (Literal.isWide()) {
1536     CharTy = Context.getWideCharType();
1537     Kind = StringLiteral::Wide;
1538   } else if (Literal.isUTF8()) {
1539     if (getLangOpts().Char8)
1540       CharTy = Context.Char8Ty;
1541     Kind = StringLiteral::UTF8;
1542   } else if (Literal.isUTF16()) {
1543     CharTy = Context.Char16Ty;
1544     Kind = StringLiteral::UTF16;
1545   } else if (Literal.isUTF32()) {
1546     CharTy = Context.Char32Ty;
1547     Kind = StringLiteral::UTF32;
1548   } else if (Literal.isPascal()) {
1549     CharTy = Context.UnsignedCharTy;
1550   }
1551 
1552   QualType CharTyConst = CharTy;
1553   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1554   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1555     CharTyConst.addConst();
1556 
1557   CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1558 
1559   // Get an array type for the string, according to C99 6.4.5.  This includes
1560   // the nul terminator character as well as the string length for pascal
1561   // strings.
1562   QualType StrTy = Context.getConstantArrayType(
1563       CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1564       ArrayType::Normal, 0);
1565 
1566   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1567   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1568                                              Kind, Literal.Pascal, StrTy,
1569                                              &StringTokLocs[0],
1570                                              StringTokLocs.size());
1571   if (Literal.getUDSuffix().empty())
1572     return Lit;
1573 
1574   // We're building a user-defined literal.
1575   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1576   SourceLocation UDSuffixLoc =
1577     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1578                    Literal.getUDSuffixOffset());
1579 
1580   // Make sure we're allowed user-defined literals here.
1581   if (!UDLScope)
1582     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1583 
1584   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1585   //   operator "" X (str, len)
1586   QualType SizeType = Context.getSizeType();
1587 
1588   DeclarationName OpName =
1589     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1590   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1591   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1592 
1593   QualType ArgTy[] = {
1594     Context.getArrayDecayedType(StrTy), SizeType
1595   };
1596 
1597   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1598   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1599                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1600                                 /*AllowStringTemplate*/ true,
1601                                 /*DiagnoseMissing*/ true)) {
1602 
1603   case LOLR_Cooked: {
1604     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1605     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1606                                                     StringTokLocs[0]);
1607     Expr *Args[] = { Lit, LenArg };
1608 
1609     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1610   }
1611 
1612   case LOLR_StringTemplate: {
1613     TemplateArgumentListInfo ExplicitArgs;
1614 
1615     unsigned CharBits = Context.getIntWidth(CharTy);
1616     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1617     llvm::APSInt Value(CharBits, CharIsUnsigned);
1618 
1619     TemplateArgument TypeArg(CharTy);
1620     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1621     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1622 
1623     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1624       Value = Lit->getCodeUnit(I);
1625       TemplateArgument Arg(Context, Value, CharTy);
1626       TemplateArgumentLocInfo ArgInfo;
1627       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1628     }
1629     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1630                                     &ExplicitArgs);
1631   }
1632   case LOLR_Raw:
1633   case LOLR_Template:
1634   case LOLR_ErrorNoDiagnostic:
1635     llvm_unreachable("unexpected literal operator lookup result");
1636   case LOLR_Error:
1637     return ExprError();
1638   }
1639   llvm_unreachable("unexpected literal operator lookup result");
1640 }
1641 
1642 ExprResult
1643 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1644                        SourceLocation Loc,
1645                        const CXXScopeSpec *SS) {
1646   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1647   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1648 }
1649 
1650 /// BuildDeclRefExpr - Build an expression that references a
1651 /// declaration that does not require a closure capture.
1652 ExprResult
1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1654                        const DeclarationNameInfo &NameInfo,
1655                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1656                        const TemplateArgumentListInfo *TemplateArgs) {
1657   bool RefersToCapturedVariable =
1658       isa<VarDecl>(D) &&
1659       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1660 
1661   DeclRefExpr *E;
1662   if (isa<VarTemplateSpecializationDecl>(D)) {
1663     VarTemplateSpecializationDecl *VarSpec =
1664         cast<VarTemplateSpecializationDecl>(D);
1665 
1666     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1667                                         : NestedNameSpecifierLoc(),
1668                             VarSpec->getTemplateKeywordLoc(), D,
1669                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1670                             FoundD, TemplateArgs);
1671   } else {
1672     assert(!TemplateArgs && "No template arguments for non-variable"
1673                             " template specialization references");
1674     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1675                                         : NestedNameSpecifierLoc(),
1676                             SourceLocation(), D, RefersToCapturedVariable,
1677                             NameInfo, Ty, VK, FoundD);
1678   }
1679 
1680   MarkDeclRefReferenced(E);
1681 
1682   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1683       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1684       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1685     getCurFunction()->recordUseOfWeak(E);
1686 
1687   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1688   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1689     FD = IFD->getAnonField();
1690   if (FD) {
1691     UnusedPrivateFields.remove(FD);
1692     // Just in case we're building an illegal pointer-to-member.
1693     if (FD->isBitField())
1694       E->setObjectKind(OK_BitField);
1695   }
1696 
1697   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1698   // designates a bit-field.
1699   if (auto *BD = dyn_cast<BindingDecl>(D))
1700     if (auto *BE = BD->getBinding())
1701       E->setObjectKind(BE->getObjectKind());
1702 
1703   return E;
1704 }
1705 
1706 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1707 /// possibly a list of template arguments.
1708 ///
1709 /// If this produces template arguments, it is permitted to call
1710 /// DecomposeTemplateName.
1711 ///
1712 /// This actually loses a lot of source location information for
1713 /// non-standard name kinds; we should consider preserving that in
1714 /// some way.
1715 void
1716 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1717                              TemplateArgumentListInfo &Buffer,
1718                              DeclarationNameInfo &NameInfo,
1719                              const TemplateArgumentListInfo *&TemplateArgs) {
1720   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1721     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1722     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1723 
1724     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1725                                        Id.TemplateId->NumArgs);
1726     translateTemplateArguments(TemplateArgsPtr, Buffer);
1727 
1728     TemplateName TName = Id.TemplateId->Template.get();
1729     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1730     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1731     TemplateArgs = &Buffer;
1732   } else {
1733     NameInfo = GetNameFromUnqualifiedId(Id);
1734     TemplateArgs = nullptr;
1735   }
1736 }
1737 
1738 static void emitEmptyLookupTypoDiagnostic(
1739     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1740     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1741     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1742   DeclContext *Ctx =
1743       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1744   if (!TC) {
1745     // Emit a special diagnostic for failed member lookups.
1746     // FIXME: computing the declaration context might fail here (?)
1747     if (Ctx)
1748       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1749                                                  << SS.getRange();
1750     else
1751       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1752     return;
1753   }
1754 
1755   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1756   bool DroppedSpecifier =
1757       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1758   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1759                         ? diag::note_implicit_param_decl
1760                         : diag::note_previous_decl;
1761   if (!Ctx)
1762     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1763                          SemaRef.PDiag(NoteID));
1764   else
1765     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1766                                  << Typo << Ctx << DroppedSpecifier
1767                                  << SS.getRange(),
1768                          SemaRef.PDiag(NoteID));
1769 }
1770 
1771 /// Diagnose an empty lookup.
1772 ///
1773 /// \return false if new lookup candidates were found
1774 bool
1775 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1776                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1777                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1778                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1779   DeclarationName Name = R.getLookupName();
1780 
1781   unsigned diagnostic = diag::err_undeclared_var_use;
1782   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1783   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1784       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1785       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1786     diagnostic = diag::err_undeclared_use;
1787     diagnostic_suggest = diag::err_undeclared_use_suggest;
1788   }
1789 
1790   // If the original lookup was an unqualified lookup, fake an
1791   // unqualified lookup.  This is useful when (for example) the
1792   // original lookup would not have found something because it was a
1793   // dependent name.
1794   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1795   while (DC) {
1796     if (isa<CXXRecordDecl>(DC)) {
1797       LookupQualifiedName(R, DC);
1798 
1799       if (!R.empty()) {
1800         // Don't give errors about ambiguities in this lookup.
1801         R.suppressDiagnostics();
1802 
1803         // During a default argument instantiation the CurContext points
1804         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1805         // function parameter list, hence add an explicit check.
1806         bool isDefaultArgument =
1807             !CodeSynthesisContexts.empty() &&
1808             CodeSynthesisContexts.back().Kind ==
1809                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1810         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1811         bool isInstance = CurMethod &&
1812                           CurMethod->isInstance() &&
1813                           DC == CurMethod->getParent() && !isDefaultArgument;
1814 
1815         // Give a code modification hint to insert 'this->'.
1816         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1817         // Actually quite difficult!
1818         if (getLangOpts().MSVCCompat)
1819           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1820         if (isInstance) {
1821           Diag(R.getNameLoc(), diagnostic) << Name
1822             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1823           CheckCXXThisCapture(R.getNameLoc());
1824         } else {
1825           Diag(R.getNameLoc(), diagnostic) << Name;
1826         }
1827 
1828         // Do we really want to note all of these?
1829         for (NamedDecl *D : R)
1830           Diag(D->getLocation(), diag::note_dependent_var_use);
1831 
1832         // Return true if we are inside a default argument instantiation
1833         // and the found name refers to an instance member function, otherwise
1834         // the function calling DiagnoseEmptyLookup will try to create an
1835         // implicit member call and this is wrong for default argument.
1836         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1837           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1838           return true;
1839         }
1840 
1841         // Tell the callee to try to recover.
1842         return false;
1843       }
1844 
1845       R.clear();
1846     }
1847 
1848     // In Microsoft mode, if we are performing lookup from within a friend
1849     // function definition declared at class scope then we must set
1850     // DC to the lexical parent to be able to search into the parent
1851     // class.
1852     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1853         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1854         DC->getLexicalParent()->isRecord())
1855       DC = DC->getLexicalParent();
1856     else
1857       DC = DC->getParent();
1858   }
1859 
1860   // We didn't find anything, so try to correct for a typo.
1861   TypoCorrection Corrected;
1862   if (S && Out) {
1863     SourceLocation TypoLoc = R.getNameLoc();
1864     assert(!ExplicitTemplateArgs &&
1865            "Diagnosing an empty lookup with explicit template args!");
1866     *Out = CorrectTypoDelayed(
1867         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1868         [=](const TypoCorrection &TC) {
1869           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1870                                         diagnostic, diagnostic_suggest);
1871         },
1872         nullptr, CTK_ErrorRecovery);
1873     if (*Out)
1874       return true;
1875   } else if (S && (Corrected =
1876                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1877                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1878     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1879     bool DroppedSpecifier =
1880         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1881     R.setLookupName(Corrected.getCorrection());
1882 
1883     bool AcceptableWithRecovery = false;
1884     bool AcceptableWithoutRecovery = false;
1885     NamedDecl *ND = Corrected.getFoundDecl();
1886     if (ND) {
1887       if (Corrected.isOverloaded()) {
1888         OverloadCandidateSet OCS(R.getNameLoc(),
1889                                  OverloadCandidateSet::CSK_Normal);
1890         OverloadCandidateSet::iterator Best;
1891         for (NamedDecl *CD : Corrected) {
1892           if (FunctionTemplateDecl *FTD =
1893                    dyn_cast<FunctionTemplateDecl>(CD))
1894             AddTemplateOverloadCandidate(
1895                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1896                 Args, OCS);
1897           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1898             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1899               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1900                                    Args, OCS);
1901         }
1902         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1903         case OR_Success:
1904           ND = Best->FoundDecl;
1905           Corrected.setCorrectionDecl(ND);
1906           break;
1907         default:
1908           // FIXME: Arbitrarily pick the first declaration for the note.
1909           Corrected.setCorrectionDecl(ND);
1910           break;
1911         }
1912       }
1913       R.addDecl(ND);
1914       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1915         CXXRecordDecl *Record = nullptr;
1916         if (Corrected.getCorrectionSpecifier()) {
1917           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1918           Record = Ty->getAsCXXRecordDecl();
1919         }
1920         if (!Record)
1921           Record = cast<CXXRecordDecl>(
1922               ND->getDeclContext()->getRedeclContext());
1923         R.setNamingClass(Record);
1924       }
1925 
1926       auto *UnderlyingND = ND->getUnderlyingDecl();
1927       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1928                                isa<FunctionTemplateDecl>(UnderlyingND);
1929       // FIXME: If we ended up with a typo for a type name or
1930       // Objective-C class name, we're in trouble because the parser
1931       // is in the wrong place to recover. Suggest the typo
1932       // correction, but don't make it a fix-it since we're not going
1933       // to recover well anyway.
1934       AcceptableWithoutRecovery =
1935           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1936     } else {
1937       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1938       // because we aren't able to recover.
1939       AcceptableWithoutRecovery = true;
1940     }
1941 
1942     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1943       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1944                             ? diag::note_implicit_param_decl
1945                             : diag::note_previous_decl;
1946       if (SS.isEmpty())
1947         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1948                      PDiag(NoteID), AcceptableWithRecovery);
1949       else
1950         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1951                                   << Name << computeDeclContext(SS, false)
1952                                   << DroppedSpecifier << SS.getRange(),
1953                      PDiag(NoteID), AcceptableWithRecovery);
1954 
1955       // Tell the callee whether to try to recover.
1956       return !AcceptableWithRecovery;
1957     }
1958   }
1959   R.clear();
1960 
1961   // Emit a special diagnostic for failed member lookups.
1962   // FIXME: computing the declaration context might fail here (?)
1963   if (!SS.isEmpty()) {
1964     Diag(R.getNameLoc(), diag::err_no_member)
1965       << Name << computeDeclContext(SS, false)
1966       << SS.getRange();
1967     return true;
1968   }
1969 
1970   // Give up, we can't recover.
1971   Diag(R.getNameLoc(), diagnostic) << Name;
1972   return true;
1973 }
1974 
1975 /// In Microsoft mode, if we are inside a template class whose parent class has
1976 /// dependent base classes, and we can't resolve an unqualified identifier, then
1977 /// assume the identifier is a member of a dependent base class.  We can only
1978 /// recover successfully in static methods, instance methods, and other contexts
1979 /// where 'this' is available.  This doesn't precisely match MSVC's
1980 /// instantiation model, but it's close enough.
1981 static Expr *
1982 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1983                                DeclarationNameInfo &NameInfo,
1984                                SourceLocation TemplateKWLoc,
1985                                const TemplateArgumentListInfo *TemplateArgs) {
1986   // Only try to recover from lookup into dependent bases in static methods or
1987   // contexts where 'this' is available.
1988   QualType ThisType = S.getCurrentThisType();
1989   const CXXRecordDecl *RD = nullptr;
1990   if (!ThisType.isNull())
1991     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1992   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1993     RD = MD->getParent();
1994   if (!RD || !RD->hasAnyDependentBases())
1995     return nullptr;
1996 
1997   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1998   // is available, suggest inserting 'this->' as a fixit.
1999   SourceLocation Loc = NameInfo.getLoc();
2000   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2001   DB << NameInfo.getName() << RD;
2002 
2003   if (!ThisType.isNull()) {
2004     DB << FixItHint::CreateInsertion(Loc, "this->");
2005     return CXXDependentScopeMemberExpr::Create(
2006         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2007         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2008         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2009   }
2010 
2011   // Synthesize a fake NNS that points to the derived class.  This will
2012   // perform name lookup during template instantiation.
2013   CXXScopeSpec SS;
2014   auto *NNS =
2015       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2016   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2017   return DependentScopeDeclRefExpr::Create(
2018       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2019       TemplateArgs);
2020 }
2021 
2022 ExprResult
2023 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2024                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2025                         bool HasTrailingLParen, bool IsAddressOfOperand,
2026                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2027                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2028   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2029          "cannot be direct & operand and have a trailing lparen");
2030   if (SS.isInvalid())
2031     return ExprError();
2032 
2033   TemplateArgumentListInfo TemplateArgsBuffer;
2034 
2035   // Decompose the UnqualifiedId into the following data.
2036   DeclarationNameInfo NameInfo;
2037   const TemplateArgumentListInfo *TemplateArgs;
2038   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2039 
2040   DeclarationName Name = NameInfo.getName();
2041   IdentifierInfo *II = Name.getAsIdentifierInfo();
2042   SourceLocation NameLoc = NameInfo.getLoc();
2043 
2044   if (II && II->isEditorPlaceholder()) {
2045     // FIXME: When typed placeholders are supported we can create a typed
2046     // placeholder expression node.
2047     return ExprError();
2048   }
2049 
2050   // C++ [temp.dep.expr]p3:
2051   //   An id-expression is type-dependent if it contains:
2052   //     -- an identifier that was declared with a dependent type,
2053   //        (note: handled after lookup)
2054   //     -- a template-id that is dependent,
2055   //        (note: handled in BuildTemplateIdExpr)
2056   //     -- a conversion-function-id that specifies a dependent type,
2057   //     -- a nested-name-specifier that contains a class-name that
2058   //        names a dependent type.
2059   // Determine whether this is a member of an unknown specialization;
2060   // we need to handle these differently.
2061   bool DependentID = false;
2062   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2063       Name.getCXXNameType()->isDependentType()) {
2064     DependentID = true;
2065   } else if (SS.isSet()) {
2066     if (DeclContext *DC = computeDeclContext(SS, false)) {
2067       if (RequireCompleteDeclContext(SS, DC))
2068         return ExprError();
2069     } else {
2070       DependentID = true;
2071     }
2072   }
2073 
2074   if (DependentID)
2075     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2076                                       IsAddressOfOperand, TemplateArgs);
2077 
2078   // Perform the required lookup.
2079   LookupResult R(*this, NameInfo,
2080                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2081                      ? LookupObjCImplicitSelfParam
2082                      : LookupOrdinaryName);
2083   if (TemplateKWLoc.isValid() || TemplateArgs) {
2084     // Lookup the template name again to correctly establish the context in
2085     // which it was found. This is really unfortunate as we already did the
2086     // lookup to determine that it was a template name in the first place. If
2087     // this becomes a performance hit, we can work harder to preserve those
2088     // results until we get here but it's likely not worth it.
2089     bool MemberOfUnknownSpecialization;
2090     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2091                        MemberOfUnknownSpecialization);
2092 
2093     if (MemberOfUnknownSpecialization ||
2094         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2095       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2096                                         IsAddressOfOperand, TemplateArgs);
2097   } else {
2098     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2099     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2100 
2101     // If the result might be in a dependent base class, this is a dependent
2102     // id-expression.
2103     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2104       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2105                                         IsAddressOfOperand, TemplateArgs);
2106 
2107     // If this reference is in an Objective-C method, then we need to do
2108     // some special Objective-C lookup, too.
2109     if (IvarLookupFollowUp) {
2110       ExprResult E(LookupInObjCMethod(R, S, II, true));
2111       if (E.isInvalid())
2112         return ExprError();
2113 
2114       if (Expr *Ex = E.getAs<Expr>())
2115         return Ex;
2116     }
2117   }
2118 
2119   if (R.isAmbiguous())
2120     return ExprError();
2121 
2122   // This could be an implicitly declared function reference (legal in C90,
2123   // extension in C99, forbidden in C++).
2124   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2125     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2126     if (D) R.addDecl(D);
2127   }
2128 
2129   // Determine whether this name might be a candidate for
2130   // argument-dependent lookup.
2131   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2132 
2133   if (R.empty() && !ADL) {
2134     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2135       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2136                                                    TemplateKWLoc, TemplateArgs))
2137         return E;
2138     }
2139 
2140     // Don't diagnose an empty lookup for inline assembly.
2141     if (IsInlineAsmIdentifier)
2142       return ExprError();
2143 
2144     // If this name wasn't predeclared and if this is not a function
2145     // call, diagnose the problem.
2146     TypoExpr *TE = nullptr;
2147     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2148         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2149     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2150     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2151            "Typo correction callback misconfigured");
2152     if (CCC) {
2153       // Make sure the callback knows what the typo being diagnosed is.
2154       CCC->setTypoName(II);
2155       if (SS.isValid())
2156         CCC->setTypoNNS(SS.getScopeRep());
2157     }
2158     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2159     // a template name, but we happen to have always already looked up the name
2160     // before we get here if it must be a template name.
2161     if (DiagnoseEmptyLookup(S, SS, R,
2162                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2163                             nullptr, None, &TE)) {
2164       if (TE && KeywordReplacement) {
2165         auto &State = getTypoExprState(TE);
2166         auto BestTC = State.Consumer->getNextCorrection();
2167         if (BestTC.isKeyword()) {
2168           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2169           if (State.DiagHandler)
2170             State.DiagHandler(BestTC);
2171           KeywordReplacement->startToken();
2172           KeywordReplacement->setKind(II->getTokenID());
2173           KeywordReplacement->setIdentifierInfo(II);
2174           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2175           // Clean up the state associated with the TypoExpr, since it has
2176           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2177           clearDelayedTypo(TE);
2178           // Signal that a correction to a keyword was performed by returning a
2179           // valid-but-null ExprResult.
2180           return (Expr*)nullptr;
2181         }
2182         State.Consumer->resetCorrectionStream();
2183       }
2184       return TE ? TE : ExprError();
2185     }
2186 
2187     assert(!R.empty() &&
2188            "DiagnoseEmptyLookup returned false but added no results");
2189 
2190     // If we found an Objective-C instance variable, let
2191     // LookupInObjCMethod build the appropriate expression to
2192     // reference the ivar.
2193     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2194       R.clear();
2195       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2196       // In a hopelessly buggy code, Objective-C instance variable
2197       // lookup fails and no expression will be built to reference it.
2198       if (!E.isInvalid() && !E.get())
2199         return ExprError();
2200       return E;
2201     }
2202   }
2203 
2204   // This is guaranteed from this point on.
2205   assert(!R.empty() || ADL);
2206 
2207   // Check whether this might be a C++ implicit instance member access.
2208   // C++ [class.mfct.non-static]p3:
2209   //   When an id-expression that is not part of a class member access
2210   //   syntax and not used to form a pointer to member is used in the
2211   //   body of a non-static member function of class X, if name lookup
2212   //   resolves the name in the id-expression to a non-static non-type
2213   //   member of some class C, the id-expression is transformed into a
2214   //   class member access expression using (*this) as the
2215   //   postfix-expression to the left of the . operator.
2216   //
2217   // But we don't actually need to do this for '&' operands if R
2218   // resolved to a function or overloaded function set, because the
2219   // expression is ill-formed if it actually works out to be a
2220   // non-static member function:
2221   //
2222   // C++ [expr.ref]p4:
2223   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2224   //   [t]he expression can be used only as the left-hand operand of a
2225   //   member function call.
2226   //
2227   // There are other safeguards against such uses, but it's important
2228   // to get this right here so that we don't end up making a
2229   // spuriously dependent expression if we're inside a dependent
2230   // instance method.
2231   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2232     bool MightBeImplicitMember;
2233     if (!IsAddressOfOperand)
2234       MightBeImplicitMember = true;
2235     else if (!SS.isEmpty())
2236       MightBeImplicitMember = false;
2237     else if (R.isOverloadedResult())
2238       MightBeImplicitMember = false;
2239     else if (R.isUnresolvableResult())
2240       MightBeImplicitMember = true;
2241     else
2242       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2243                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2244                               isa<MSPropertyDecl>(R.getFoundDecl());
2245 
2246     if (MightBeImplicitMember)
2247       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2248                                              R, TemplateArgs, S);
2249   }
2250 
2251   if (TemplateArgs || TemplateKWLoc.isValid()) {
2252 
2253     // In C++1y, if this is a variable template id, then check it
2254     // in BuildTemplateIdExpr().
2255     // The single lookup result must be a variable template declaration.
2256     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2257         Id.TemplateId->Kind == TNK_Var_template) {
2258       assert(R.getAsSingle<VarTemplateDecl>() &&
2259              "There should only be one declaration found.");
2260     }
2261 
2262     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2263   }
2264 
2265   return BuildDeclarationNameExpr(SS, R, ADL);
2266 }
2267 
2268 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2269 /// declaration name, generally during template instantiation.
2270 /// There's a large number of things which don't need to be done along
2271 /// this path.
2272 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2273     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2274     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2275   DeclContext *DC = computeDeclContext(SS, false);
2276   if (!DC)
2277     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2278                                      NameInfo, /*TemplateArgs=*/nullptr);
2279 
2280   if (RequireCompleteDeclContext(SS, DC))
2281     return ExprError();
2282 
2283   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2284   LookupQualifiedName(R, DC);
2285 
2286   if (R.isAmbiguous())
2287     return ExprError();
2288 
2289   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2290     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2291                                      NameInfo, /*TemplateArgs=*/nullptr);
2292 
2293   if (R.empty()) {
2294     Diag(NameInfo.getLoc(), diag::err_no_member)
2295       << NameInfo.getName() << DC << SS.getRange();
2296     return ExprError();
2297   }
2298 
2299   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2300     // Diagnose a missing typename if this resolved unambiguously to a type in
2301     // a dependent context.  If we can recover with a type, downgrade this to
2302     // a warning in Microsoft compatibility mode.
2303     unsigned DiagID = diag::err_typename_missing;
2304     if (RecoveryTSI && getLangOpts().MSVCCompat)
2305       DiagID = diag::ext_typename_missing;
2306     SourceLocation Loc = SS.getBeginLoc();
2307     auto D = Diag(Loc, DiagID);
2308     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2309       << SourceRange(Loc, NameInfo.getEndLoc());
2310 
2311     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2312     // context.
2313     if (!RecoveryTSI)
2314       return ExprError();
2315 
2316     // Only issue the fixit if we're prepared to recover.
2317     D << FixItHint::CreateInsertion(Loc, "typename ");
2318 
2319     // Recover by pretending this was an elaborated type.
2320     QualType Ty = Context.getTypeDeclType(TD);
2321     TypeLocBuilder TLB;
2322     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2323 
2324     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2325     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2326     QTL.setElaboratedKeywordLoc(SourceLocation());
2327     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2328 
2329     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2330 
2331     return ExprEmpty();
2332   }
2333 
2334   // Defend against this resolving to an implicit member access. We usually
2335   // won't get here if this might be a legitimate a class member (we end up in
2336   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2337   // a pointer-to-member or in an unevaluated context in C++11.
2338   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2339     return BuildPossibleImplicitMemberExpr(SS,
2340                                            /*TemplateKWLoc=*/SourceLocation(),
2341                                            R, /*TemplateArgs=*/nullptr, S);
2342 
2343   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2344 }
2345 
2346 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2347 /// detected that we're currently inside an ObjC method.  Perform some
2348 /// additional lookup.
2349 ///
2350 /// Ideally, most of this would be done by lookup, but there's
2351 /// actually quite a lot of extra work involved.
2352 ///
2353 /// Returns a null sentinel to indicate trivial success.
2354 ExprResult
2355 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2356                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2357   SourceLocation Loc = Lookup.getNameLoc();
2358   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2359 
2360   // Check for error condition which is already reported.
2361   if (!CurMethod)
2362     return ExprError();
2363 
2364   // There are two cases to handle here.  1) scoped lookup could have failed,
2365   // in which case we should look for an ivar.  2) scoped lookup could have
2366   // found a decl, but that decl is outside the current instance method (i.e.
2367   // a global variable).  In these two cases, we do a lookup for an ivar with
2368   // this name, if the lookup sucedes, we replace it our current decl.
2369 
2370   // If we're in a class method, we don't normally want to look for
2371   // ivars.  But if we don't find anything else, and there's an
2372   // ivar, that's an error.
2373   bool IsClassMethod = CurMethod->isClassMethod();
2374 
2375   bool LookForIvars;
2376   if (Lookup.empty())
2377     LookForIvars = true;
2378   else if (IsClassMethod)
2379     LookForIvars = false;
2380   else
2381     LookForIvars = (Lookup.isSingleResult() &&
2382                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2383   ObjCInterfaceDecl *IFace = nullptr;
2384   if (LookForIvars) {
2385     IFace = CurMethod->getClassInterface();
2386     ObjCInterfaceDecl *ClassDeclared;
2387     ObjCIvarDecl *IV = nullptr;
2388     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2389       // Diagnose using an ivar in a class method.
2390       if (IsClassMethod)
2391         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2392                          << IV->getDeclName());
2393 
2394       // If we're referencing an invalid decl, just return this as a silent
2395       // error node.  The error diagnostic was already emitted on the decl.
2396       if (IV->isInvalidDecl())
2397         return ExprError();
2398 
2399       // Check if referencing a field with __attribute__((deprecated)).
2400       if (DiagnoseUseOfDecl(IV, Loc))
2401         return ExprError();
2402 
2403       // Diagnose the use of an ivar outside of the declaring class.
2404       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2405           !declaresSameEntity(ClassDeclared, IFace) &&
2406           !getLangOpts().DebuggerSupport)
2407         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2408 
2409       // FIXME: This should use a new expr for a direct reference, don't
2410       // turn this into Self->ivar, just return a BareIVarExpr or something.
2411       IdentifierInfo &II = Context.Idents.get("self");
2412       UnqualifiedId SelfName;
2413       SelfName.setIdentifier(&II, SourceLocation());
2414       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2415       CXXScopeSpec SelfScopeSpec;
2416       SourceLocation TemplateKWLoc;
2417       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2418                                               SelfName, false, false);
2419       if (SelfExpr.isInvalid())
2420         return ExprError();
2421 
2422       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2423       if (SelfExpr.isInvalid())
2424         return ExprError();
2425 
2426       MarkAnyDeclReferenced(Loc, IV, true);
2427 
2428       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2429       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2430           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2431         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2432 
2433       ObjCIvarRefExpr *Result = new (Context)
2434           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2435                           IV->getLocation(), SelfExpr.get(), true, true);
2436 
2437       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2438         if (!isUnevaluatedContext() &&
2439             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2440           getCurFunction()->recordUseOfWeak(Result);
2441       }
2442       if (getLangOpts().ObjCAutoRefCount) {
2443         if (CurContext->isClosure())
2444           Diag(Loc, diag::warn_implicitly_retains_self)
2445             << FixItHint::CreateInsertion(Loc, "self->");
2446       }
2447 
2448       return Result;
2449     }
2450   } else if (CurMethod->isInstanceMethod()) {
2451     // We should warn if a local variable hides an ivar.
2452     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2453       ObjCInterfaceDecl *ClassDeclared;
2454       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2455         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2456             declaresSameEntity(IFace, ClassDeclared))
2457           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2458       }
2459     }
2460   } else if (Lookup.isSingleResult() &&
2461              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2462     // If accessing a stand-alone ivar in a class method, this is an error.
2463     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2464       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2465                        << IV->getDeclName());
2466   }
2467 
2468   if (Lookup.empty() && II && AllowBuiltinCreation) {
2469     // FIXME. Consolidate this with similar code in LookupName.
2470     if (unsigned BuiltinID = II->getBuiltinID()) {
2471       if (!(getLangOpts().CPlusPlus &&
2472             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2473         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2474                                            S, Lookup.isForRedeclaration(),
2475                                            Lookup.getNameLoc());
2476         if (D) Lookup.addDecl(D);
2477       }
2478     }
2479   }
2480   // Sentinel value saying that we didn't do anything special.
2481   return ExprResult((Expr *)nullptr);
2482 }
2483 
2484 /// Cast a base object to a member's actual type.
2485 ///
2486 /// Logically this happens in three phases:
2487 ///
2488 /// * First we cast from the base type to the naming class.
2489 ///   The naming class is the class into which we were looking
2490 ///   when we found the member;  it's the qualifier type if a
2491 ///   qualifier was provided, and otherwise it's the base type.
2492 ///
2493 /// * Next we cast from the naming class to the declaring class.
2494 ///   If the member we found was brought into a class's scope by
2495 ///   a using declaration, this is that class;  otherwise it's
2496 ///   the class declaring the member.
2497 ///
2498 /// * Finally we cast from the declaring class to the "true"
2499 ///   declaring class of the member.  This conversion does not
2500 ///   obey access control.
2501 ExprResult
2502 Sema::PerformObjectMemberConversion(Expr *From,
2503                                     NestedNameSpecifier *Qualifier,
2504                                     NamedDecl *FoundDecl,
2505                                     NamedDecl *Member) {
2506   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2507   if (!RD)
2508     return From;
2509 
2510   QualType DestRecordType;
2511   QualType DestType;
2512   QualType FromRecordType;
2513   QualType FromType = From->getType();
2514   bool PointerConversions = false;
2515   if (isa<FieldDecl>(Member)) {
2516     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2517 
2518     if (FromType->getAs<PointerType>()) {
2519       DestType = Context.getPointerType(DestRecordType);
2520       FromRecordType = FromType->getPointeeType();
2521       PointerConversions = true;
2522     } else {
2523       DestType = DestRecordType;
2524       FromRecordType = FromType;
2525     }
2526   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2527     if (Method->isStatic())
2528       return From;
2529 
2530     DestType = Method->getThisType(Context);
2531     DestRecordType = DestType->getPointeeType();
2532 
2533     if (FromType->getAs<PointerType>()) {
2534       FromRecordType = FromType->getPointeeType();
2535       PointerConversions = true;
2536     } else {
2537       FromRecordType = FromType;
2538       DestType = DestRecordType;
2539     }
2540   } else {
2541     // No conversion necessary.
2542     return From;
2543   }
2544 
2545   if (DestType->isDependentType() || FromType->isDependentType())
2546     return From;
2547 
2548   // If the unqualified types are the same, no conversion is necessary.
2549   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2550     return From;
2551 
2552   SourceRange FromRange = From->getSourceRange();
2553   SourceLocation FromLoc = FromRange.getBegin();
2554 
2555   ExprValueKind VK = From->getValueKind();
2556 
2557   // C++ [class.member.lookup]p8:
2558   //   [...] Ambiguities can often be resolved by qualifying a name with its
2559   //   class name.
2560   //
2561   // If the member was a qualified name and the qualified referred to a
2562   // specific base subobject type, we'll cast to that intermediate type
2563   // first and then to the object in which the member is declared. That allows
2564   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2565   //
2566   //   class Base { public: int x; };
2567   //   class Derived1 : public Base { };
2568   //   class Derived2 : public Base { };
2569   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2570   //
2571   //   void VeryDerived::f() {
2572   //     x = 17; // error: ambiguous base subobjects
2573   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2574   //   }
2575   if (Qualifier && Qualifier->getAsType()) {
2576     QualType QType = QualType(Qualifier->getAsType(), 0);
2577     assert(QType->isRecordType() && "lookup done with non-record type");
2578 
2579     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2580 
2581     // In C++98, the qualifier type doesn't actually have to be a base
2582     // type of the object type, in which case we just ignore it.
2583     // Otherwise build the appropriate casts.
2584     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2585       CXXCastPath BasePath;
2586       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2587                                        FromLoc, FromRange, &BasePath))
2588         return ExprError();
2589 
2590       if (PointerConversions)
2591         QType = Context.getPointerType(QType);
2592       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2593                                VK, &BasePath).get();
2594 
2595       FromType = QType;
2596       FromRecordType = QRecordType;
2597 
2598       // If the qualifier type was the same as the destination type,
2599       // we're done.
2600       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2601         return From;
2602     }
2603   }
2604 
2605   bool IgnoreAccess = false;
2606 
2607   // If we actually found the member through a using declaration, cast
2608   // down to the using declaration's type.
2609   //
2610   // Pointer equality is fine here because only one declaration of a
2611   // class ever has member declarations.
2612   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2613     assert(isa<UsingShadowDecl>(FoundDecl));
2614     QualType URecordType = Context.getTypeDeclType(
2615                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2616 
2617     // We only need to do this if the naming-class to declaring-class
2618     // conversion is non-trivial.
2619     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2620       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2621       CXXCastPath BasePath;
2622       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2623                                        FromLoc, FromRange, &BasePath))
2624         return ExprError();
2625 
2626       QualType UType = URecordType;
2627       if (PointerConversions)
2628         UType = Context.getPointerType(UType);
2629       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2630                                VK, &BasePath).get();
2631       FromType = UType;
2632       FromRecordType = URecordType;
2633     }
2634 
2635     // We don't do access control for the conversion from the
2636     // declaring class to the true declaring class.
2637     IgnoreAccess = true;
2638   }
2639 
2640   CXXCastPath BasePath;
2641   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2642                                    FromLoc, FromRange, &BasePath,
2643                                    IgnoreAccess))
2644     return ExprError();
2645 
2646   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2647                            VK, &BasePath);
2648 }
2649 
2650 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2651                                       const LookupResult &R,
2652                                       bool HasTrailingLParen) {
2653   // Only when used directly as the postfix-expression of a call.
2654   if (!HasTrailingLParen)
2655     return false;
2656 
2657   // Never if a scope specifier was provided.
2658   if (SS.isSet())
2659     return false;
2660 
2661   // Only in C++ or ObjC++.
2662   if (!getLangOpts().CPlusPlus)
2663     return false;
2664 
2665   // Turn off ADL when we find certain kinds of declarations during
2666   // normal lookup:
2667   for (NamedDecl *D : R) {
2668     // C++0x [basic.lookup.argdep]p3:
2669     //     -- a declaration of a class member
2670     // Since using decls preserve this property, we check this on the
2671     // original decl.
2672     if (D->isCXXClassMember())
2673       return false;
2674 
2675     // C++0x [basic.lookup.argdep]p3:
2676     //     -- a block-scope function declaration that is not a
2677     //        using-declaration
2678     // NOTE: we also trigger this for function templates (in fact, we
2679     // don't check the decl type at all, since all other decl types
2680     // turn off ADL anyway).
2681     if (isa<UsingShadowDecl>(D))
2682       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2683     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2684       return false;
2685 
2686     // C++0x [basic.lookup.argdep]p3:
2687     //     -- a declaration that is neither a function or a function
2688     //        template
2689     // And also for builtin functions.
2690     if (isa<FunctionDecl>(D)) {
2691       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2692 
2693       // But also builtin functions.
2694       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2695         return false;
2696     } else if (!isa<FunctionTemplateDecl>(D))
2697       return false;
2698   }
2699 
2700   return true;
2701 }
2702 
2703 
2704 /// Diagnoses obvious problems with the use of the given declaration
2705 /// as an expression.  This is only actually called for lookups that
2706 /// were not overloaded, and it doesn't promise that the declaration
2707 /// will in fact be used.
2708 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2709   if (D->isInvalidDecl())
2710     return true;
2711 
2712   if (isa<TypedefNameDecl>(D)) {
2713     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2714     return true;
2715   }
2716 
2717   if (isa<ObjCInterfaceDecl>(D)) {
2718     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2719     return true;
2720   }
2721 
2722   if (isa<NamespaceDecl>(D)) {
2723     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2724     return true;
2725   }
2726 
2727   return false;
2728 }
2729 
2730 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2731                                           LookupResult &R, bool NeedsADL,
2732                                           bool AcceptInvalidDecl) {
2733   // If this is a single, fully-resolved result and we don't need ADL,
2734   // just build an ordinary singleton decl ref.
2735   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2736     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2737                                     R.getRepresentativeDecl(), nullptr,
2738                                     AcceptInvalidDecl);
2739 
2740   // We only need to check the declaration if there's exactly one
2741   // result, because in the overloaded case the results can only be
2742   // functions and function templates.
2743   if (R.isSingleResult() &&
2744       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2745     return ExprError();
2746 
2747   // Otherwise, just build an unresolved lookup expression.  Suppress
2748   // any lookup-related diagnostics; we'll hash these out later, when
2749   // we've picked a target.
2750   R.suppressDiagnostics();
2751 
2752   UnresolvedLookupExpr *ULE
2753     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2754                                    SS.getWithLocInContext(Context),
2755                                    R.getLookupNameInfo(),
2756                                    NeedsADL, R.isOverloadedResult(),
2757                                    R.begin(), R.end());
2758 
2759   return ULE;
2760 }
2761 
2762 static void
2763 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2764                                    ValueDecl *var, DeclContext *DC);
2765 
2766 /// Complete semantic analysis for a reference to the given declaration.
2767 ExprResult Sema::BuildDeclarationNameExpr(
2768     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2769     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2770     bool AcceptInvalidDecl) {
2771   assert(D && "Cannot refer to a NULL declaration");
2772   assert(!isa<FunctionTemplateDecl>(D) &&
2773          "Cannot refer unambiguously to a function template");
2774 
2775   SourceLocation Loc = NameInfo.getLoc();
2776   if (CheckDeclInExpr(*this, Loc, D))
2777     return ExprError();
2778 
2779   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2780     // Specifically diagnose references to class templates that are missing
2781     // a template argument list.
2782     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2783     return ExprError();
2784   }
2785 
2786   // Make sure that we're referring to a value.
2787   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2788   if (!VD) {
2789     Diag(Loc, diag::err_ref_non_value)
2790       << D << SS.getRange();
2791     Diag(D->getLocation(), diag::note_declared_at);
2792     return ExprError();
2793   }
2794 
2795   // Check whether this declaration can be used. Note that we suppress
2796   // this check when we're going to perform argument-dependent lookup
2797   // on this function name, because this might not be the function
2798   // that overload resolution actually selects.
2799   if (DiagnoseUseOfDecl(VD, Loc))
2800     return ExprError();
2801 
2802   // Only create DeclRefExpr's for valid Decl's.
2803   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2804     return ExprError();
2805 
2806   // Handle members of anonymous structs and unions.  If we got here,
2807   // and the reference is to a class member indirect field, then this
2808   // must be the subject of a pointer-to-member expression.
2809   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2810     if (!indirectField->isCXXClassMember())
2811       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2812                                                       indirectField);
2813 
2814   {
2815     QualType type = VD->getType();
2816     if (type.isNull())
2817       return ExprError();
2818     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2819       // C++ [except.spec]p17:
2820       //   An exception-specification is considered to be needed when:
2821       //   - in an expression, the function is the unique lookup result or
2822       //     the selected member of a set of overloaded functions.
2823       ResolveExceptionSpec(Loc, FPT);
2824       type = VD->getType();
2825     }
2826     ExprValueKind valueKind = VK_RValue;
2827 
2828     switch (D->getKind()) {
2829     // Ignore all the non-ValueDecl kinds.
2830 #define ABSTRACT_DECL(kind)
2831 #define VALUE(type, base)
2832 #define DECL(type, base) \
2833     case Decl::type:
2834 #include "clang/AST/DeclNodes.inc"
2835       llvm_unreachable("invalid value decl kind");
2836 
2837     // These shouldn't make it here.
2838     case Decl::ObjCAtDefsField:
2839     case Decl::ObjCIvar:
2840       llvm_unreachable("forming non-member reference to ivar?");
2841 
2842     // Enum constants are always r-values and never references.
2843     // Unresolved using declarations are dependent.
2844     case Decl::EnumConstant:
2845     case Decl::UnresolvedUsingValue:
2846     case Decl::OMPDeclareReduction:
2847       valueKind = VK_RValue;
2848       break;
2849 
2850     // Fields and indirect fields that got here must be for
2851     // pointer-to-member expressions; we just call them l-values for
2852     // internal consistency, because this subexpression doesn't really
2853     // exist in the high-level semantics.
2854     case Decl::Field:
2855     case Decl::IndirectField:
2856       assert(getLangOpts().CPlusPlus &&
2857              "building reference to field in C?");
2858 
2859       // These can't have reference type in well-formed programs, but
2860       // for internal consistency we do this anyway.
2861       type = type.getNonReferenceType();
2862       valueKind = VK_LValue;
2863       break;
2864 
2865     // Non-type template parameters are either l-values or r-values
2866     // depending on the type.
2867     case Decl::NonTypeTemplateParm: {
2868       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2869         type = reftype->getPointeeType();
2870         valueKind = VK_LValue; // even if the parameter is an r-value reference
2871         break;
2872       }
2873 
2874       // For non-references, we need to strip qualifiers just in case
2875       // the template parameter was declared as 'const int' or whatever.
2876       valueKind = VK_RValue;
2877       type = type.getUnqualifiedType();
2878       break;
2879     }
2880 
2881     case Decl::Var:
2882     case Decl::VarTemplateSpecialization:
2883     case Decl::VarTemplatePartialSpecialization:
2884     case Decl::Decomposition:
2885     case Decl::OMPCapturedExpr:
2886       // In C, "extern void blah;" is valid and is an r-value.
2887       if (!getLangOpts().CPlusPlus &&
2888           !type.hasQualifiers() &&
2889           type->isVoidType()) {
2890         valueKind = VK_RValue;
2891         break;
2892       }
2893       LLVM_FALLTHROUGH;
2894 
2895     case Decl::ImplicitParam:
2896     case Decl::ParmVar: {
2897       // These are always l-values.
2898       valueKind = VK_LValue;
2899       type = type.getNonReferenceType();
2900 
2901       // FIXME: Does the addition of const really only apply in
2902       // potentially-evaluated contexts? Since the variable isn't actually
2903       // captured in an unevaluated context, it seems that the answer is no.
2904       if (!isUnevaluatedContext()) {
2905         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2906         if (!CapturedType.isNull())
2907           type = CapturedType;
2908       }
2909 
2910       break;
2911     }
2912 
2913     case Decl::Binding: {
2914       // These are always lvalues.
2915       valueKind = VK_LValue;
2916       type = type.getNonReferenceType();
2917       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2918       // decides how that's supposed to work.
2919       auto *BD = cast<BindingDecl>(VD);
2920       if (BD->getDeclContext()->isFunctionOrMethod() &&
2921           BD->getDeclContext() != CurContext)
2922         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2923       break;
2924     }
2925 
2926     case Decl::Function: {
2927       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2928         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2929           type = Context.BuiltinFnTy;
2930           valueKind = VK_RValue;
2931           break;
2932         }
2933       }
2934 
2935       const FunctionType *fty = type->castAs<FunctionType>();
2936 
2937       // If we're referring to a function with an __unknown_anytype
2938       // result type, make the entire expression __unknown_anytype.
2939       if (fty->getReturnType() == Context.UnknownAnyTy) {
2940         type = Context.UnknownAnyTy;
2941         valueKind = VK_RValue;
2942         break;
2943       }
2944 
2945       // Functions are l-values in C++.
2946       if (getLangOpts().CPlusPlus) {
2947         valueKind = VK_LValue;
2948         break;
2949       }
2950 
2951       // C99 DR 316 says that, if a function type comes from a
2952       // function definition (without a prototype), that type is only
2953       // used for checking compatibility. Therefore, when referencing
2954       // the function, we pretend that we don't have the full function
2955       // type.
2956       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2957           isa<FunctionProtoType>(fty))
2958         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2959                                               fty->getExtInfo());
2960 
2961       // Functions are r-values in C.
2962       valueKind = VK_RValue;
2963       break;
2964     }
2965 
2966     case Decl::CXXDeductionGuide:
2967       llvm_unreachable("building reference to deduction guide");
2968 
2969     case Decl::MSProperty:
2970       valueKind = VK_LValue;
2971       break;
2972 
2973     case Decl::CXXMethod:
2974       // If we're referring to a method with an __unknown_anytype
2975       // result type, make the entire expression __unknown_anytype.
2976       // This should only be possible with a type written directly.
2977       if (const FunctionProtoType *proto
2978             = dyn_cast<FunctionProtoType>(VD->getType()))
2979         if (proto->getReturnType() == Context.UnknownAnyTy) {
2980           type = Context.UnknownAnyTy;
2981           valueKind = VK_RValue;
2982           break;
2983         }
2984 
2985       // C++ methods are l-values if static, r-values if non-static.
2986       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2987         valueKind = VK_LValue;
2988         break;
2989       }
2990       LLVM_FALLTHROUGH;
2991 
2992     case Decl::CXXConversion:
2993     case Decl::CXXDestructor:
2994     case Decl::CXXConstructor:
2995       valueKind = VK_RValue;
2996       break;
2997     }
2998 
2999     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3000                             TemplateArgs);
3001   }
3002 }
3003 
3004 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3005                                     SmallString<32> &Target) {
3006   Target.resize(CharByteWidth * (Source.size() + 1));
3007   char *ResultPtr = &Target[0];
3008   const llvm::UTF8 *ErrorPtr;
3009   bool success =
3010       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3011   (void)success;
3012   assert(success);
3013   Target.resize(ResultPtr - &Target[0]);
3014 }
3015 
3016 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3017                                      PredefinedExpr::IdentType IT) {
3018   // Pick the current block, lambda, captured statement or function.
3019   Decl *currentDecl = nullptr;
3020   if (const BlockScopeInfo *BSI = getCurBlock())
3021     currentDecl = BSI->TheDecl;
3022   else if (const LambdaScopeInfo *LSI = getCurLambda())
3023     currentDecl = LSI->CallOperator;
3024   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3025     currentDecl = CSI->TheCapturedDecl;
3026   else
3027     currentDecl = getCurFunctionOrMethodDecl();
3028 
3029   if (!currentDecl) {
3030     Diag(Loc, diag::ext_predef_outside_function);
3031     currentDecl = Context.getTranslationUnitDecl();
3032   }
3033 
3034   QualType ResTy;
3035   StringLiteral *SL = nullptr;
3036   if (cast<DeclContext>(currentDecl)->isDependentContext())
3037     ResTy = Context.DependentTy;
3038   else {
3039     // Pre-defined identifiers are of type char[x], where x is the length of
3040     // the string.
3041     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3042     unsigned Length = Str.length();
3043 
3044     llvm::APInt LengthI(32, Length + 1);
3045     if (IT == PredefinedExpr::LFunction) {
3046       ResTy =
3047           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3048       SmallString<32> RawChars;
3049       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3050                               Str, RawChars);
3051       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3052                                            /*IndexTypeQuals*/ 0);
3053       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3054                                  /*Pascal*/ false, ResTy, Loc);
3055     } else {
3056       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3057       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3058                                            /*IndexTypeQuals*/ 0);
3059       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3060                                  /*Pascal*/ false, ResTy, Loc);
3061     }
3062   }
3063 
3064   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3065 }
3066 
3067 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3068   PredefinedExpr::IdentType IT;
3069 
3070   switch (Kind) {
3071   default: llvm_unreachable("Unknown simple primary expr!");
3072   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3073   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3074   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3075   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3076   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3077   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3078   }
3079 
3080   return BuildPredefinedExpr(Loc, IT);
3081 }
3082 
3083 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3084   SmallString<16> CharBuffer;
3085   bool Invalid = false;
3086   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3087   if (Invalid)
3088     return ExprError();
3089 
3090   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3091                             PP, Tok.getKind());
3092   if (Literal.hadError())
3093     return ExprError();
3094 
3095   QualType Ty;
3096   if (Literal.isWide())
3097     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3098   else if (Literal.isUTF8() && getLangOpts().Char8)
3099     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3100   else if (Literal.isUTF16())
3101     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3102   else if (Literal.isUTF32())
3103     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3104   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3105     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3106   else
3107     Ty = Context.CharTy;  // 'x' -> char in C++
3108 
3109   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3110   if (Literal.isWide())
3111     Kind = CharacterLiteral::Wide;
3112   else if (Literal.isUTF16())
3113     Kind = CharacterLiteral::UTF16;
3114   else if (Literal.isUTF32())
3115     Kind = CharacterLiteral::UTF32;
3116   else if (Literal.isUTF8())
3117     Kind = CharacterLiteral::UTF8;
3118 
3119   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3120                                              Tok.getLocation());
3121 
3122   if (Literal.getUDSuffix().empty())
3123     return Lit;
3124 
3125   // We're building a user-defined literal.
3126   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3127   SourceLocation UDSuffixLoc =
3128     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3129 
3130   // Make sure we're allowed user-defined literals here.
3131   if (!UDLScope)
3132     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3133 
3134   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3135   //   operator "" X (ch)
3136   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3137                                         Lit, Tok.getLocation());
3138 }
3139 
3140 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3141   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3142   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3143                                 Context.IntTy, Loc);
3144 }
3145 
3146 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3147                                   QualType Ty, SourceLocation Loc) {
3148   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3149 
3150   using llvm::APFloat;
3151   APFloat Val(Format);
3152 
3153   APFloat::opStatus result = Literal.GetFloatValue(Val);
3154 
3155   // Overflow is always an error, but underflow is only an error if
3156   // we underflowed to zero (APFloat reports denormals as underflow).
3157   if ((result & APFloat::opOverflow) ||
3158       ((result & APFloat::opUnderflow) && Val.isZero())) {
3159     unsigned diagnostic;
3160     SmallString<20> buffer;
3161     if (result & APFloat::opOverflow) {
3162       diagnostic = diag::warn_float_overflow;
3163       APFloat::getLargest(Format).toString(buffer);
3164     } else {
3165       diagnostic = diag::warn_float_underflow;
3166       APFloat::getSmallest(Format).toString(buffer);
3167     }
3168 
3169     S.Diag(Loc, diagnostic)
3170       << Ty
3171       << StringRef(buffer.data(), buffer.size());
3172   }
3173 
3174   bool isExact = (result == APFloat::opOK);
3175   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3176 }
3177 
3178 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3179   assert(E && "Invalid expression");
3180 
3181   if (E->isValueDependent())
3182     return false;
3183 
3184   QualType QT = E->getType();
3185   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3186     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3187     return true;
3188   }
3189 
3190   llvm::APSInt ValueAPS;
3191   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3192 
3193   if (R.isInvalid())
3194     return true;
3195 
3196   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3197   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3198     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3199         << ValueAPS.toString(10) << ValueIsPositive;
3200     return true;
3201   }
3202 
3203   return false;
3204 }
3205 
3206 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3207   // Fast path for a single digit (which is quite common).  A single digit
3208   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3209   if (Tok.getLength() == 1) {
3210     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3211     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3212   }
3213 
3214   SmallString<128> SpellingBuffer;
3215   // NumericLiteralParser wants to overread by one character.  Add padding to
3216   // the buffer in case the token is copied to the buffer.  If getSpelling()
3217   // returns a StringRef to the memory buffer, it should have a null char at
3218   // the EOF, so it is also safe.
3219   SpellingBuffer.resize(Tok.getLength() + 1);
3220 
3221   // Get the spelling of the token, which eliminates trigraphs, etc.
3222   bool Invalid = false;
3223   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3224   if (Invalid)
3225     return ExprError();
3226 
3227   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3228   if (Literal.hadError)
3229     return ExprError();
3230 
3231   if (Literal.hasUDSuffix()) {
3232     // We're building a user-defined literal.
3233     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3234     SourceLocation UDSuffixLoc =
3235       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3236 
3237     // Make sure we're allowed user-defined literals here.
3238     if (!UDLScope)
3239       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3240 
3241     QualType CookedTy;
3242     if (Literal.isFloatingLiteral()) {
3243       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3244       // long double, the literal is treated as a call of the form
3245       //   operator "" X (f L)
3246       CookedTy = Context.LongDoubleTy;
3247     } else {
3248       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3249       // unsigned long long, the literal is treated as a call of the form
3250       //   operator "" X (n ULL)
3251       CookedTy = Context.UnsignedLongLongTy;
3252     }
3253 
3254     DeclarationName OpName =
3255       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3256     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3257     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3258 
3259     SourceLocation TokLoc = Tok.getLocation();
3260 
3261     // Perform literal operator lookup to determine if we're building a raw
3262     // literal or a cooked one.
3263     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3264     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3265                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3266                                   /*AllowStringTemplate*/ false,
3267                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3268     case LOLR_ErrorNoDiagnostic:
3269       // Lookup failure for imaginary constants isn't fatal, there's still the
3270       // GNU extension producing _Complex types.
3271       break;
3272     case LOLR_Error:
3273       return ExprError();
3274     case LOLR_Cooked: {
3275       Expr *Lit;
3276       if (Literal.isFloatingLiteral()) {
3277         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3278       } else {
3279         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3280         if (Literal.GetIntegerValue(ResultVal))
3281           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3282               << /* Unsigned */ 1;
3283         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3284                                      Tok.getLocation());
3285       }
3286       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3287     }
3288 
3289     case LOLR_Raw: {
3290       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3291       // literal is treated as a call of the form
3292       //   operator "" X ("n")
3293       unsigned Length = Literal.getUDSuffixOffset();
3294       QualType StrTy = Context.getConstantArrayType(
3295           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3296           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3297       Expr *Lit = StringLiteral::Create(
3298           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3299           /*Pascal*/false, StrTy, &TokLoc, 1);
3300       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3301     }
3302 
3303     case LOLR_Template: {
3304       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3305       // template), L is treated as a call fo the form
3306       //   operator "" X <'c1', 'c2', ... 'ck'>()
3307       // where n is the source character sequence c1 c2 ... ck.
3308       TemplateArgumentListInfo ExplicitArgs;
3309       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3310       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3311       llvm::APSInt Value(CharBits, CharIsUnsigned);
3312       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3313         Value = TokSpelling[I];
3314         TemplateArgument Arg(Context, Value, Context.CharTy);
3315         TemplateArgumentLocInfo ArgInfo;
3316         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3317       }
3318       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3319                                       &ExplicitArgs);
3320     }
3321     case LOLR_StringTemplate:
3322       llvm_unreachable("unexpected literal operator lookup result");
3323     }
3324   }
3325 
3326   Expr *Res;
3327 
3328   if (Literal.isFloatingLiteral()) {
3329     QualType Ty;
3330     if (Literal.isHalf){
3331       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3332         Ty = Context.HalfTy;
3333       else {
3334         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3335         return ExprError();
3336       }
3337     } else if (Literal.isFloat)
3338       Ty = Context.FloatTy;
3339     else if (Literal.isLong)
3340       Ty = Context.LongDoubleTy;
3341     else if (Literal.isFloat16)
3342       Ty = Context.Float16Ty;
3343     else if (Literal.isFloat128)
3344       Ty = Context.Float128Ty;
3345     else
3346       Ty = Context.DoubleTy;
3347 
3348     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3349 
3350     if (Ty == Context.DoubleTy) {
3351       if (getLangOpts().SinglePrecisionConstants) {
3352         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3353         if (BTy->getKind() != BuiltinType::Float) {
3354           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3355         }
3356       } else if (getLangOpts().OpenCL &&
3357                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3358         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3359         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3360         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3361       }
3362     }
3363   } else if (!Literal.isIntegerLiteral()) {
3364     return ExprError();
3365   } else {
3366     QualType Ty;
3367 
3368     // 'long long' is a C99 or C++11 feature.
3369     if (!getLangOpts().C99 && Literal.isLongLong) {
3370       if (getLangOpts().CPlusPlus)
3371         Diag(Tok.getLocation(),
3372              getLangOpts().CPlusPlus11 ?
3373              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3374       else
3375         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3376     }
3377 
3378     // Get the value in the widest-possible width.
3379     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3380     llvm::APInt ResultVal(MaxWidth, 0);
3381 
3382     if (Literal.GetIntegerValue(ResultVal)) {
3383       // If this value didn't fit into uintmax_t, error and force to ull.
3384       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3385           << /* Unsigned */ 1;
3386       Ty = Context.UnsignedLongLongTy;
3387       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3388              "long long is not intmax_t?");
3389     } else {
3390       // If this value fits into a ULL, try to figure out what else it fits into
3391       // according to the rules of C99 6.4.4.1p5.
3392 
3393       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3394       // be an unsigned int.
3395       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3396 
3397       // Check from smallest to largest, picking the smallest type we can.
3398       unsigned Width = 0;
3399 
3400       // Microsoft specific integer suffixes are explicitly sized.
3401       if (Literal.MicrosoftInteger) {
3402         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3403           Width = 8;
3404           Ty = Context.CharTy;
3405         } else {
3406           Width = Literal.MicrosoftInteger;
3407           Ty = Context.getIntTypeForBitwidth(Width,
3408                                              /*Signed=*/!Literal.isUnsigned);
3409         }
3410       }
3411 
3412       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3413         // Are int/unsigned possibilities?
3414         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3415 
3416         // Does it fit in a unsigned int?
3417         if (ResultVal.isIntN(IntSize)) {
3418           // Does it fit in a signed int?
3419           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3420             Ty = Context.IntTy;
3421           else if (AllowUnsigned)
3422             Ty = Context.UnsignedIntTy;
3423           Width = IntSize;
3424         }
3425       }
3426 
3427       // Are long/unsigned long possibilities?
3428       if (Ty.isNull() && !Literal.isLongLong) {
3429         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3430 
3431         // Does it fit in a unsigned long?
3432         if (ResultVal.isIntN(LongSize)) {
3433           // Does it fit in a signed long?
3434           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3435             Ty = Context.LongTy;
3436           else if (AllowUnsigned)
3437             Ty = Context.UnsignedLongTy;
3438           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3439           // is compatible.
3440           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3441             const unsigned LongLongSize =
3442                 Context.getTargetInfo().getLongLongWidth();
3443             Diag(Tok.getLocation(),
3444                  getLangOpts().CPlusPlus
3445                      ? Literal.isLong
3446                            ? diag::warn_old_implicitly_unsigned_long_cxx
3447                            : /*C++98 UB*/ diag::
3448                                  ext_old_implicitly_unsigned_long_cxx
3449                      : diag::warn_old_implicitly_unsigned_long)
3450                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3451                                             : /*will be ill-formed*/ 1);
3452             Ty = Context.UnsignedLongTy;
3453           }
3454           Width = LongSize;
3455         }
3456       }
3457 
3458       // Check long long if needed.
3459       if (Ty.isNull()) {
3460         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3461 
3462         // Does it fit in a unsigned long long?
3463         if (ResultVal.isIntN(LongLongSize)) {
3464           // Does it fit in a signed long long?
3465           // To be compatible with MSVC, hex integer literals ending with the
3466           // LL or i64 suffix are always signed in Microsoft mode.
3467           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3468               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3469             Ty = Context.LongLongTy;
3470           else if (AllowUnsigned)
3471             Ty = Context.UnsignedLongLongTy;
3472           Width = LongLongSize;
3473         }
3474       }
3475 
3476       // If we still couldn't decide a type, we probably have something that
3477       // does not fit in a signed long long, but has no U suffix.
3478       if (Ty.isNull()) {
3479         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3480         Ty = Context.UnsignedLongLongTy;
3481         Width = Context.getTargetInfo().getLongLongWidth();
3482       }
3483 
3484       if (ResultVal.getBitWidth() != Width)
3485         ResultVal = ResultVal.trunc(Width);
3486     }
3487     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3488   }
3489 
3490   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3491   if (Literal.isImaginary) {
3492     Res = new (Context) ImaginaryLiteral(Res,
3493                                         Context.getComplexType(Res->getType()));
3494 
3495     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3496   }
3497   return Res;
3498 }
3499 
3500 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3501   assert(E && "ActOnParenExpr() missing expr");
3502   return new (Context) ParenExpr(L, R, E);
3503 }
3504 
3505 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3506                                          SourceLocation Loc,
3507                                          SourceRange ArgRange) {
3508   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3509   // scalar or vector data type argument..."
3510   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3511   // type (C99 6.2.5p18) or void.
3512   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3513     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3514       << T << ArgRange;
3515     return true;
3516   }
3517 
3518   assert((T->isVoidType() || !T->isIncompleteType()) &&
3519          "Scalar types should always be complete");
3520   return false;
3521 }
3522 
3523 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3524                                            SourceLocation Loc,
3525                                            SourceRange ArgRange,
3526                                            UnaryExprOrTypeTrait TraitKind) {
3527   // Invalid types must be hard errors for SFINAE in C++.
3528   if (S.LangOpts.CPlusPlus)
3529     return true;
3530 
3531   // C99 6.5.3.4p1:
3532   if (T->isFunctionType() &&
3533       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3534     // sizeof(function)/alignof(function) is allowed as an extension.
3535     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3536       << TraitKind << ArgRange;
3537     return false;
3538   }
3539 
3540   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3541   // this is an error (OpenCL v1.1 s6.3.k)
3542   if (T->isVoidType()) {
3543     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3544                                         : diag::ext_sizeof_alignof_void_type;
3545     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3546     return false;
3547   }
3548 
3549   return true;
3550 }
3551 
3552 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3553                                              SourceLocation Loc,
3554                                              SourceRange ArgRange,
3555                                              UnaryExprOrTypeTrait TraitKind) {
3556   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3557   // runtime doesn't allow it.
3558   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3559     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3560       << T << (TraitKind == UETT_SizeOf)
3561       << ArgRange;
3562     return true;
3563   }
3564 
3565   return false;
3566 }
3567 
3568 /// Check whether E is a pointer from a decayed array type (the decayed
3569 /// pointer type is equal to T) and emit a warning if it is.
3570 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3571                                      Expr *E) {
3572   // Don't warn if the operation changed the type.
3573   if (T != E->getType())
3574     return;
3575 
3576   // Now look for array decays.
3577   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3578   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3579     return;
3580 
3581   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3582                                              << ICE->getType()
3583                                              << ICE->getSubExpr()->getType();
3584 }
3585 
3586 /// Check the constraints on expression operands to unary type expression
3587 /// and type traits.
3588 ///
3589 /// Completes any types necessary and validates the constraints on the operand
3590 /// expression. The logic mostly mirrors the type-based overload, but may modify
3591 /// the expression as it completes the type for that expression through template
3592 /// instantiation, etc.
3593 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3594                                             UnaryExprOrTypeTrait ExprKind) {
3595   QualType ExprTy = E->getType();
3596   assert(!ExprTy->isReferenceType());
3597 
3598   if (ExprKind == UETT_VecStep)
3599     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3600                                         E->getSourceRange());
3601 
3602   // Whitelist some types as extensions
3603   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3604                                       E->getSourceRange(), ExprKind))
3605     return false;
3606 
3607   // 'alignof' applied to an expression only requires the base element type of
3608   // the expression to be complete. 'sizeof' requires the expression's type to
3609   // be complete (and will attempt to complete it if it's an array of unknown
3610   // bound).
3611   if (ExprKind == UETT_AlignOf) {
3612     if (RequireCompleteType(E->getExprLoc(),
3613                             Context.getBaseElementType(E->getType()),
3614                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3615                             E->getSourceRange()))
3616       return true;
3617   } else {
3618     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3619                                 ExprKind, E->getSourceRange()))
3620       return true;
3621   }
3622 
3623   // Completing the expression's type may have changed it.
3624   ExprTy = E->getType();
3625   assert(!ExprTy->isReferenceType());
3626 
3627   if (ExprTy->isFunctionType()) {
3628     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3629       << ExprKind << E->getSourceRange();
3630     return true;
3631   }
3632 
3633   // The operand for sizeof and alignof is in an unevaluated expression context,
3634   // so side effects could result in unintended consequences.
3635   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3636       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3637     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3638 
3639   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3640                                        E->getSourceRange(), ExprKind))
3641     return true;
3642 
3643   if (ExprKind == UETT_SizeOf) {
3644     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3645       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3646         QualType OType = PVD->getOriginalType();
3647         QualType Type = PVD->getType();
3648         if (Type->isPointerType() && OType->isArrayType()) {
3649           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3650             << Type << OType;
3651           Diag(PVD->getLocation(), diag::note_declared_at);
3652         }
3653       }
3654     }
3655 
3656     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3657     // decays into a pointer and returns an unintended result. This is most
3658     // likely a typo for "sizeof(array) op x".
3659     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3660       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3661                                BO->getLHS());
3662       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3663                                BO->getRHS());
3664     }
3665   }
3666 
3667   return false;
3668 }
3669 
3670 /// Check the constraints on operands to unary expression and type
3671 /// traits.
3672 ///
3673 /// This will complete any types necessary, and validate the various constraints
3674 /// on those operands.
3675 ///
3676 /// The UsualUnaryConversions() function is *not* called by this routine.
3677 /// C99 6.3.2.1p[2-4] all state:
3678 ///   Except when it is the operand of the sizeof operator ...
3679 ///
3680 /// C++ [expr.sizeof]p4
3681 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3682 ///   standard conversions are not applied to the operand of sizeof.
3683 ///
3684 /// This policy is followed for all of the unary trait expressions.
3685 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3686                                             SourceLocation OpLoc,
3687                                             SourceRange ExprRange,
3688                                             UnaryExprOrTypeTrait ExprKind) {
3689   if (ExprType->isDependentType())
3690     return false;
3691 
3692   // C++ [expr.sizeof]p2:
3693   //     When applied to a reference or a reference type, the result
3694   //     is the size of the referenced type.
3695   // C++11 [expr.alignof]p3:
3696   //     When alignof is applied to a reference type, the result
3697   //     shall be the alignment of the referenced type.
3698   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3699     ExprType = Ref->getPointeeType();
3700 
3701   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3702   //   When alignof or _Alignof is applied to an array type, the result
3703   //   is the alignment of the element type.
3704   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3705     ExprType = Context.getBaseElementType(ExprType);
3706 
3707   if (ExprKind == UETT_VecStep)
3708     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3709 
3710   // Whitelist some types as extensions
3711   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3712                                       ExprKind))
3713     return false;
3714 
3715   if (RequireCompleteType(OpLoc, ExprType,
3716                           diag::err_sizeof_alignof_incomplete_type,
3717                           ExprKind, ExprRange))
3718     return true;
3719 
3720   if (ExprType->isFunctionType()) {
3721     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3722       << ExprKind << ExprRange;
3723     return true;
3724   }
3725 
3726   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3727                                        ExprKind))
3728     return true;
3729 
3730   return false;
3731 }
3732 
3733 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3734   E = E->IgnoreParens();
3735 
3736   // Cannot know anything else if the expression is dependent.
3737   if (E->isTypeDependent())
3738     return false;
3739 
3740   if (E->getObjectKind() == OK_BitField) {
3741     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3742        << 1 << E->getSourceRange();
3743     return true;
3744   }
3745 
3746   ValueDecl *D = nullptr;
3747   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3748     D = DRE->getDecl();
3749   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3750     D = ME->getMemberDecl();
3751   }
3752 
3753   // If it's a field, require the containing struct to have a
3754   // complete definition so that we can compute the layout.
3755   //
3756   // This can happen in C++11 onwards, either by naming the member
3757   // in a way that is not transformed into a member access expression
3758   // (in an unevaluated operand, for instance), or by naming the member
3759   // in a trailing-return-type.
3760   //
3761   // For the record, since __alignof__ on expressions is a GCC
3762   // extension, GCC seems to permit this but always gives the
3763   // nonsensical answer 0.
3764   //
3765   // We don't really need the layout here --- we could instead just
3766   // directly check for all the appropriate alignment-lowing
3767   // attributes --- but that would require duplicating a lot of
3768   // logic that just isn't worth duplicating for such a marginal
3769   // use-case.
3770   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3771     // Fast path this check, since we at least know the record has a
3772     // definition if we can find a member of it.
3773     if (!FD->getParent()->isCompleteDefinition()) {
3774       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3775         << E->getSourceRange();
3776       return true;
3777     }
3778 
3779     // Otherwise, if it's a field, and the field doesn't have
3780     // reference type, then it must have a complete type (or be a
3781     // flexible array member, which we explicitly want to
3782     // white-list anyway), which makes the following checks trivial.
3783     if (!FD->getType()->isReferenceType())
3784       return false;
3785   }
3786 
3787   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3788 }
3789 
3790 bool Sema::CheckVecStepExpr(Expr *E) {
3791   E = E->IgnoreParens();
3792 
3793   // Cannot know anything else if the expression is dependent.
3794   if (E->isTypeDependent())
3795     return false;
3796 
3797   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3798 }
3799 
3800 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3801                                         CapturingScopeInfo *CSI) {
3802   assert(T->isVariablyModifiedType());
3803   assert(CSI != nullptr);
3804 
3805   // We're going to walk down into the type and look for VLA expressions.
3806   do {
3807     const Type *Ty = T.getTypePtr();
3808     switch (Ty->getTypeClass()) {
3809 #define TYPE(Class, Base)
3810 #define ABSTRACT_TYPE(Class, Base)
3811 #define NON_CANONICAL_TYPE(Class, Base)
3812 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3813 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3814 #include "clang/AST/TypeNodes.def"
3815       T = QualType();
3816       break;
3817     // These types are never variably-modified.
3818     case Type::Builtin:
3819     case Type::Complex:
3820     case Type::Vector:
3821     case Type::ExtVector:
3822     case Type::Record:
3823     case Type::Enum:
3824     case Type::Elaborated:
3825     case Type::TemplateSpecialization:
3826     case Type::ObjCObject:
3827     case Type::ObjCInterface:
3828     case Type::ObjCObjectPointer:
3829     case Type::ObjCTypeParam:
3830     case Type::Pipe:
3831       llvm_unreachable("type class is never variably-modified!");
3832     case Type::Adjusted:
3833       T = cast<AdjustedType>(Ty)->getOriginalType();
3834       break;
3835     case Type::Decayed:
3836       T = cast<DecayedType>(Ty)->getPointeeType();
3837       break;
3838     case Type::Pointer:
3839       T = cast<PointerType>(Ty)->getPointeeType();
3840       break;
3841     case Type::BlockPointer:
3842       T = cast<BlockPointerType>(Ty)->getPointeeType();
3843       break;
3844     case Type::LValueReference:
3845     case Type::RValueReference:
3846       T = cast<ReferenceType>(Ty)->getPointeeType();
3847       break;
3848     case Type::MemberPointer:
3849       T = cast<MemberPointerType>(Ty)->getPointeeType();
3850       break;
3851     case Type::ConstantArray:
3852     case Type::IncompleteArray:
3853       // Losing element qualification here is fine.
3854       T = cast<ArrayType>(Ty)->getElementType();
3855       break;
3856     case Type::VariableArray: {
3857       // Losing element qualification here is fine.
3858       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3859 
3860       // Unknown size indication requires no size computation.
3861       // Otherwise, evaluate and record it.
3862       if (auto Size = VAT->getSizeExpr()) {
3863         if (!CSI->isVLATypeCaptured(VAT)) {
3864           RecordDecl *CapRecord = nullptr;
3865           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3866             CapRecord = LSI->Lambda;
3867           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3868             CapRecord = CRSI->TheRecordDecl;
3869           }
3870           if (CapRecord) {
3871             auto ExprLoc = Size->getExprLoc();
3872             auto SizeType = Context.getSizeType();
3873             // Build the non-static data member.
3874             auto Field =
3875                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3876                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3877                                   /*BW*/ nullptr, /*Mutable*/ false,
3878                                   /*InitStyle*/ ICIS_NoInit);
3879             Field->setImplicit(true);
3880             Field->setAccess(AS_private);
3881             Field->setCapturedVLAType(VAT);
3882             CapRecord->addDecl(Field);
3883 
3884             CSI->addVLATypeCapture(ExprLoc, SizeType);
3885           }
3886         }
3887       }
3888       T = VAT->getElementType();
3889       break;
3890     }
3891     case Type::FunctionProto:
3892     case Type::FunctionNoProto:
3893       T = cast<FunctionType>(Ty)->getReturnType();
3894       break;
3895     case Type::Paren:
3896     case Type::TypeOf:
3897     case Type::UnaryTransform:
3898     case Type::Attributed:
3899     case Type::SubstTemplateTypeParm:
3900     case Type::PackExpansion:
3901       // Keep walking after single level desugaring.
3902       T = T.getSingleStepDesugaredType(Context);
3903       break;
3904     case Type::Typedef:
3905       T = cast<TypedefType>(Ty)->desugar();
3906       break;
3907     case Type::Decltype:
3908       T = cast<DecltypeType>(Ty)->desugar();
3909       break;
3910     case Type::Auto:
3911     case Type::DeducedTemplateSpecialization:
3912       T = cast<DeducedType>(Ty)->getDeducedType();
3913       break;
3914     case Type::TypeOfExpr:
3915       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3916       break;
3917     case Type::Atomic:
3918       T = cast<AtomicType>(Ty)->getValueType();
3919       break;
3920     }
3921   } while (!T.isNull() && T->isVariablyModifiedType());
3922 }
3923 
3924 /// Build a sizeof or alignof expression given a type operand.
3925 ExprResult
3926 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3927                                      SourceLocation OpLoc,
3928                                      UnaryExprOrTypeTrait ExprKind,
3929                                      SourceRange R) {
3930   if (!TInfo)
3931     return ExprError();
3932 
3933   QualType T = TInfo->getType();
3934 
3935   if (!T->isDependentType() &&
3936       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3937     return ExprError();
3938 
3939   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3940     if (auto *TT = T->getAs<TypedefType>()) {
3941       for (auto I = FunctionScopes.rbegin(),
3942                 E = std::prev(FunctionScopes.rend());
3943            I != E; ++I) {
3944         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3945         if (CSI == nullptr)
3946           break;
3947         DeclContext *DC = nullptr;
3948         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3949           DC = LSI->CallOperator;
3950         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3951           DC = CRSI->TheCapturedDecl;
3952         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3953           DC = BSI->TheDecl;
3954         if (DC) {
3955           if (DC->containsDecl(TT->getDecl()))
3956             break;
3957           captureVariablyModifiedType(Context, T, CSI);
3958         }
3959       }
3960     }
3961   }
3962 
3963   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3964   return new (Context) UnaryExprOrTypeTraitExpr(
3965       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3966 }
3967 
3968 /// Build a sizeof or alignof expression given an expression
3969 /// operand.
3970 ExprResult
3971 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3972                                      UnaryExprOrTypeTrait ExprKind) {
3973   ExprResult PE = CheckPlaceholderExpr(E);
3974   if (PE.isInvalid())
3975     return ExprError();
3976 
3977   E = PE.get();
3978 
3979   // Verify that the operand is valid.
3980   bool isInvalid = false;
3981   if (E->isTypeDependent()) {
3982     // Delay type-checking for type-dependent expressions.
3983   } else if (ExprKind == UETT_AlignOf) {
3984     isInvalid = CheckAlignOfExpr(*this, E);
3985   } else if (ExprKind == UETT_VecStep) {
3986     isInvalid = CheckVecStepExpr(E);
3987   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3988       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3989       isInvalid = true;
3990   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3991     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3992     isInvalid = true;
3993   } else {
3994     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3995   }
3996 
3997   if (isInvalid)
3998     return ExprError();
3999 
4000   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4001     PE = TransformToPotentiallyEvaluated(E);
4002     if (PE.isInvalid()) return ExprError();
4003     E = PE.get();
4004   }
4005 
4006   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4007   return new (Context) UnaryExprOrTypeTraitExpr(
4008       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4009 }
4010 
4011 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4012 /// expr and the same for @c alignof and @c __alignof
4013 /// Note that the ArgRange is invalid if isType is false.
4014 ExprResult
4015 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4016                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4017                                     void *TyOrEx, SourceRange ArgRange) {
4018   // If error parsing type, ignore.
4019   if (!TyOrEx) return ExprError();
4020 
4021   if (IsType) {
4022     TypeSourceInfo *TInfo;
4023     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4024     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4025   }
4026 
4027   Expr *ArgEx = (Expr *)TyOrEx;
4028   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4029   return Result;
4030 }
4031 
4032 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4033                                      bool IsReal) {
4034   if (V.get()->isTypeDependent())
4035     return S.Context.DependentTy;
4036 
4037   // _Real and _Imag are only l-values for normal l-values.
4038   if (V.get()->getObjectKind() != OK_Ordinary) {
4039     V = S.DefaultLvalueConversion(V.get());
4040     if (V.isInvalid())
4041       return QualType();
4042   }
4043 
4044   // These operators return the element type of a complex type.
4045   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4046     return CT->getElementType();
4047 
4048   // Otherwise they pass through real integer and floating point types here.
4049   if (V.get()->getType()->isArithmeticType())
4050     return V.get()->getType();
4051 
4052   // Test for placeholders.
4053   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4054   if (PR.isInvalid()) return QualType();
4055   if (PR.get() != V.get()) {
4056     V = PR;
4057     return CheckRealImagOperand(S, V, Loc, IsReal);
4058   }
4059 
4060   // Reject anything else.
4061   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4062     << (IsReal ? "__real" : "__imag");
4063   return QualType();
4064 }
4065 
4066 
4067 
4068 ExprResult
4069 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4070                           tok::TokenKind Kind, Expr *Input) {
4071   UnaryOperatorKind Opc;
4072   switch (Kind) {
4073   default: llvm_unreachable("Unknown unary op!");
4074   case tok::plusplus:   Opc = UO_PostInc; break;
4075   case tok::minusminus: Opc = UO_PostDec; break;
4076   }
4077 
4078   // Since this might is a postfix expression, get rid of ParenListExprs.
4079   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4080   if (Result.isInvalid()) return ExprError();
4081   Input = Result.get();
4082 
4083   return BuildUnaryOp(S, OpLoc, Opc, Input);
4084 }
4085 
4086 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4087 ///
4088 /// \return true on error
4089 static bool checkArithmeticOnObjCPointer(Sema &S,
4090                                          SourceLocation opLoc,
4091                                          Expr *op) {
4092   assert(op->getType()->isObjCObjectPointerType());
4093   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4094       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4095     return false;
4096 
4097   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4098     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4099     << op->getSourceRange();
4100   return true;
4101 }
4102 
4103 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4104   auto *BaseNoParens = Base->IgnoreParens();
4105   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4106     return MSProp->getPropertyDecl()->getType()->isArrayType();
4107   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4108 }
4109 
4110 ExprResult
4111 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4112                               Expr *idx, SourceLocation rbLoc) {
4113   if (base && !base->getType().isNull() &&
4114       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4115     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4116                                     /*Length=*/nullptr, rbLoc);
4117 
4118   // Since this might be a postfix expression, get rid of ParenListExprs.
4119   if (isa<ParenListExpr>(base)) {
4120     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4121     if (result.isInvalid()) return ExprError();
4122     base = result.get();
4123   }
4124 
4125   // Handle any non-overload placeholder types in the base and index
4126   // expressions.  We can't handle overloads here because the other
4127   // operand might be an overloadable type, in which case the overload
4128   // resolution for the operator overload should get the first crack
4129   // at the overload.
4130   bool IsMSPropertySubscript = false;
4131   if (base->getType()->isNonOverloadPlaceholderType()) {
4132     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4133     if (!IsMSPropertySubscript) {
4134       ExprResult result = CheckPlaceholderExpr(base);
4135       if (result.isInvalid())
4136         return ExprError();
4137       base = result.get();
4138     }
4139   }
4140   if (idx->getType()->isNonOverloadPlaceholderType()) {
4141     ExprResult result = CheckPlaceholderExpr(idx);
4142     if (result.isInvalid()) return ExprError();
4143     idx = result.get();
4144   }
4145 
4146   // Build an unanalyzed expression if either operand is type-dependent.
4147   if (getLangOpts().CPlusPlus &&
4148       (base->isTypeDependent() || idx->isTypeDependent())) {
4149     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4150                                             VK_LValue, OK_Ordinary, rbLoc);
4151   }
4152 
4153   // MSDN, property (C++)
4154   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4155   // This attribute can also be used in the declaration of an empty array in a
4156   // class or structure definition. For example:
4157   // __declspec(property(get=GetX, put=PutX)) int x[];
4158   // The above statement indicates that x[] can be used with one or more array
4159   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4160   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4161   if (IsMSPropertySubscript) {
4162     // Build MS property subscript expression if base is MS property reference
4163     // or MS property subscript.
4164     return new (Context) MSPropertySubscriptExpr(
4165         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4166   }
4167 
4168   // Use C++ overloaded-operator rules if either operand has record
4169   // type.  The spec says to do this if either type is *overloadable*,
4170   // but enum types can't declare subscript operators or conversion
4171   // operators, so there's nothing interesting for overload resolution
4172   // to do if there aren't any record types involved.
4173   //
4174   // ObjC pointers have their own subscripting logic that is not tied
4175   // to overload resolution and so should not take this path.
4176   if (getLangOpts().CPlusPlus &&
4177       (base->getType()->isRecordType() ||
4178        (!base->getType()->isObjCObjectPointerType() &&
4179         idx->getType()->isRecordType()))) {
4180     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4181   }
4182 
4183   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4184 }
4185 
4186 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4187                                           Expr *LowerBound,
4188                                           SourceLocation ColonLoc, Expr *Length,
4189                                           SourceLocation RBLoc) {
4190   if (Base->getType()->isPlaceholderType() &&
4191       !Base->getType()->isSpecificPlaceholderType(
4192           BuiltinType::OMPArraySection)) {
4193     ExprResult Result = CheckPlaceholderExpr(Base);
4194     if (Result.isInvalid())
4195       return ExprError();
4196     Base = Result.get();
4197   }
4198   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4199     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4200     if (Result.isInvalid())
4201       return ExprError();
4202     Result = DefaultLvalueConversion(Result.get());
4203     if (Result.isInvalid())
4204       return ExprError();
4205     LowerBound = Result.get();
4206   }
4207   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4208     ExprResult Result = CheckPlaceholderExpr(Length);
4209     if (Result.isInvalid())
4210       return ExprError();
4211     Result = DefaultLvalueConversion(Result.get());
4212     if (Result.isInvalid())
4213       return ExprError();
4214     Length = Result.get();
4215   }
4216 
4217   // Build an unanalyzed expression if either operand is type-dependent.
4218   if (Base->isTypeDependent() ||
4219       (LowerBound &&
4220        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4221       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4222     return new (Context)
4223         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4224                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4225   }
4226 
4227   // Perform default conversions.
4228   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4229   QualType ResultTy;
4230   if (OriginalTy->isAnyPointerType()) {
4231     ResultTy = OriginalTy->getPointeeType();
4232   } else if (OriginalTy->isArrayType()) {
4233     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4234   } else {
4235     return ExprError(
4236         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4237         << Base->getSourceRange());
4238   }
4239   // C99 6.5.2.1p1
4240   if (LowerBound) {
4241     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4242                                                       LowerBound);
4243     if (Res.isInvalid())
4244       return ExprError(Diag(LowerBound->getExprLoc(),
4245                             diag::err_omp_typecheck_section_not_integer)
4246                        << 0 << LowerBound->getSourceRange());
4247     LowerBound = Res.get();
4248 
4249     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4250         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4251       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4252           << 0 << LowerBound->getSourceRange();
4253   }
4254   if (Length) {
4255     auto Res =
4256         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4257     if (Res.isInvalid())
4258       return ExprError(Diag(Length->getExprLoc(),
4259                             diag::err_omp_typecheck_section_not_integer)
4260                        << 1 << Length->getSourceRange());
4261     Length = Res.get();
4262 
4263     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4264         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4265       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4266           << 1 << Length->getSourceRange();
4267   }
4268 
4269   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4270   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4271   // type. Note that functions are not objects, and that (in C99 parlance)
4272   // incomplete types are not object types.
4273   if (ResultTy->isFunctionType()) {
4274     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4275         << ResultTy << Base->getSourceRange();
4276     return ExprError();
4277   }
4278 
4279   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4280                           diag::err_omp_section_incomplete_type, Base))
4281     return ExprError();
4282 
4283   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4284     llvm::APSInt LowerBoundValue;
4285     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4286       // OpenMP 4.5, [2.4 Array Sections]
4287       // The array section must be a subset of the original array.
4288       if (LowerBoundValue.isNegative()) {
4289         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4290             << LowerBound->getSourceRange();
4291         return ExprError();
4292       }
4293     }
4294   }
4295 
4296   if (Length) {
4297     llvm::APSInt LengthValue;
4298     if (Length->EvaluateAsInt(LengthValue, Context)) {
4299       // OpenMP 4.5, [2.4 Array Sections]
4300       // The length must evaluate to non-negative integers.
4301       if (LengthValue.isNegative()) {
4302         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4303             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4304             << Length->getSourceRange();
4305         return ExprError();
4306       }
4307     }
4308   } else if (ColonLoc.isValid() &&
4309              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4310                                       !OriginalTy->isVariableArrayType()))) {
4311     // OpenMP 4.5, [2.4 Array Sections]
4312     // When the size of the array dimension is not known, the length must be
4313     // specified explicitly.
4314     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4315         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4316     return ExprError();
4317   }
4318 
4319   if (!Base->getType()->isSpecificPlaceholderType(
4320           BuiltinType::OMPArraySection)) {
4321     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4322     if (Result.isInvalid())
4323       return ExprError();
4324     Base = Result.get();
4325   }
4326   return new (Context)
4327       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4328                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4329 }
4330 
4331 ExprResult
4332 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4333                                       Expr *Idx, SourceLocation RLoc) {
4334   Expr *LHSExp = Base;
4335   Expr *RHSExp = Idx;
4336 
4337   ExprValueKind VK = VK_LValue;
4338   ExprObjectKind OK = OK_Ordinary;
4339 
4340   // Per C++ core issue 1213, the result is an xvalue if either operand is
4341   // a non-lvalue array, and an lvalue otherwise.
4342   if (getLangOpts().CPlusPlus11 &&
4343       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4344        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4345     VK = VK_XValue;
4346 
4347   // Perform default conversions.
4348   if (!LHSExp->getType()->getAs<VectorType>()) {
4349     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4350     if (Result.isInvalid())
4351       return ExprError();
4352     LHSExp = Result.get();
4353   }
4354   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4355   if (Result.isInvalid())
4356     return ExprError();
4357   RHSExp = Result.get();
4358 
4359   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4360 
4361   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4362   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4363   // in the subscript position. As a result, we need to derive the array base
4364   // and index from the expression types.
4365   Expr *BaseExpr, *IndexExpr;
4366   QualType ResultType;
4367   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4368     BaseExpr = LHSExp;
4369     IndexExpr = RHSExp;
4370     ResultType = Context.DependentTy;
4371   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4372     BaseExpr = LHSExp;
4373     IndexExpr = RHSExp;
4374     ResultType = PTy->getPointeeType();
4375   } else if (const ObjCObjectPointerType *PTy =
4376                LHSTy->getAs<ObjCObjectPointerType>()) {
4377     BaseExpr = LHSExp;
4378     IndexExpr = RHSExp;
4379 
4380     // Use custom logic if this should be the pseudo-object subscript
4381     // expression.
4382     if (!LangOpts.isSubscriptPointerArithmetic())
4383       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4384                                           nullptr);
4385 
4386     ResultType = PTy->getPointeeType();
4387   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4388      // Handle the uncommon case of "123[Ptr]".
4389     BaseExpr = RHSExp;
4390     IndexExpr = LHSExp;
4391     ResultType = PTy->getPointeeType();
4392   } else if (const ObjCObjectPointerType *PTy =
4393                RHSTy->getAs<ObjCObjectPointerType>()) {
4394      // Handle the uncommon case of "123[Ptr]".
4395     BaseExpr = RHSExp;
4396     IndexExpr = LHSExp;
4397     ResultType = PTy->getPointeeType();
4398     if (!LangOpts.isSubscriptPointerArithmetic()) {
4399       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4400         << ResultType << BaseExpr->getSourceRange();
4401       return ExprError();
4402     }
4403   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4404     BaseExpr = LHSExp;    // vectors: V[123]
4405     IndexExpr = RHSExp;
4406     VK = LHSExp->getValueKind();
4407     if (VK != VK_RValue)
4408       OK = OK_VectorComponent;
4409 
4410     ResultType = VTy->getElementType();
4411     QualType BaseType = BaseExpr->getType();
4412     Qualifiers BaseQuals = BaseType.getQualifiers();
4413     Qualifiers MemberQuals = ResultType.getQualifiers();
4414     Qualifiers Combined = BaseQuals + MemberQuals;
4415     if (Combined != MemberQuals)
4416       ResultType = Context.getQualifiedType(ResultType, Combined);
4417   } else if (LHSTy->isArrayType()) {
4418     // If we see an array that wasn't promoted by
4419     // DefaultFunctionArrayLvalueConversion, it must be an array that
4420     // wasn't promoted because of the C90 rule that doesn't
4421     // allow promoting non-lvalue arrays.  Warn, then
4422     // force the promotion here.
4423     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4424         LHSExp->getSourceRange();
4425     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4426                                CK_ArrayToPointerDecay).get();
4427     LHSTy = LHSExp->getType();
4428 
4429     BaseExpr = LHSExp;
4430     IndexExpr = RHSExp;
4431     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4432   } else if (RHSTy->isArrayType()) {
4433     // Same as previous, except for 123[f().a] case
4434     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4435         RHSExp->getSourceRange();
4436     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4437                                CK_ArrayToPointerDecay).get();
4438     RHSTy = RHSExp->getType();
4439 
4440     BaseExpr = RHSExp;
4441     IndexExpr = LHSExp;
4442     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4443   } else {
4444     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4445        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4446   }
4447   // C99 6.5.2.1p1
4448   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4449     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4450                      << IndexExpr->getSourceRange());
4451 
4452   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4453        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4454          && !IndexExpr->isTypeDependent())
4455     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4456 
4457   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4458   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4459   // type. Note that Functions are not objects, and that (in C99 parlance)
4460   // incomplete types are not object types.
4461   if (ResultType->isFunctionType()) {
4462     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4463       << ResultType << BaseExpr->getSourceRange();
4464     return ExprError();
4465   }
4466 
4467   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4468     // GNU extension: subscripting on pointer to void
4469     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4470       << BaseExpr->getSourceRange();
4471 
4472     // C forbids expressions of unqualified void type from being l-values.
4473     // See IsCForbiddenLValueType.
4474     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4475   } else if (!ResultType->isDependentType() &&
4476       RequireCompleteType(LLoc, ResultType,
4477                           diag::err_subscript_incomplete_type, BaseExpr))
4478     return ExprError();
4479 
4480   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4481          !ResultType.isCForbiddenLValueType());
4482 
4483   return new (Context)
4484       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4485 }
4486 
4487 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4488                                   ParmVarDecl *Param) {
4489   if (Param->hasUnparsedDefaultArg()) {
4490     Diag(CallLoc,
4491          diag::err_use_of_default_argument_to_function_declared_later) <<
4492       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4493     Diag(UnparsedDefaultArgLocs[Param],
4494          diag::note_default_argument_declared_here);
4495     return true;
4496   }
4497 
4498   if (Param->hasUninstantiatedDefaultArg()) {
4499     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4500 
4501     EnterExpressionEvaluationContext EvalContext(
4502         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4503 
4504     // Instantiate the expression.
4505     //
4506     // FIXME: Pass in a correct Pattern argument, otherwise
4507     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4508     //
4509     // template<typename T>
4510     // struct A {
4511     //   static int FooImpl();
4512     //
4513     //   template<typename Tp>
4514     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4515     //   // template argument list [[T], [Tp]], should be [[Tp]].
4516     //   friend A<Tp> Foo(int a);
4517     // };
4518     //
4519     // template<typename T>
4520     // A<T> Foo(int a = A<T>::FooImpl());
4521     MultiLevelTemplateArgumentList MutiLevelArgList
4522       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4523 
4524     InstantiatingTemplate Inst(*this, CallLoc, Param,
4525                                MutiLevelArgList.getInnermost());
4526     if (Inst.isInvalid())
4527       return true;
4528     if (Inst.isAlreadyInstantiating()) {
4529       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4530       Param->setInvalidDecl();
4531       return true;
4532     }
4533 
4534     ExprResult Result;
4535     {
4536       // C++ [dcl.fct.default]p5:
4537       //   The names in the [default argument] expression are bound, and
4538       //   the semantic constraints are checked, at the point where the
4539       //   default argument expression appears.
4540       ContextRAII SavedContext(*this, FD);
4541       LocalInstantiationScope Local(*this);
4542       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4543                                 /*DirectInit*/false);
4544     }
4545     if (Result.isInvalid())
4546       return true;
4547 
4548     // Check the expression as an initializer for the parameter.
4549     InitializedEntity Entity
4550       = InitializedEntity::InitializeParameter(Context, Param);
4551     InitializationKind Kind
4552       = InitializationKind::CreateCopy(Param->getLocation(),
4553              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4554     Expr *ResultE = Result.getAs<Expr>();
4555 
4556     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4557     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4558     if (Result.isInvalid())
4559       return true;
4560 
4561     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4562                                  Param->getOuterLocStart());
4563     if (Result.isInvalid())
4564       return true;
4565 
4566     // Remember the instantiated default argument.
4567     Param->setDefaultArg(Result.getAs<Expr>());
4568     if (ASTMutationListener *L = getASTMutationListener()) {
4569       L->DefaultArgumentInstantiated(Param);
4570     }
4571   }
4572 
4573   // If the default argument expression is not set yet, we are building it now.
4574   if (!Param->hasInit()) {
4575     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4576     Param->setInvalidDecl();
4577     return true;
4578   }
4579 
4580   // If the default expression creates temporaries, we need to
4581   // push them to the current stack of expression temporaries so they'll
4582   // be properly destroyed.
4583   // FIXME: We should really be rebuilding the default argument with new
4584   // bound temporaries; see the comment in PR5810.
4585   // We don't need to do that with block decls, though, because
4586   // blocks in default argument expression can never capture anything.
4587   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4588     // Set the "needs cleanups" bit regardless of whether there are
4589     // any explicit objects.
4590     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4591 
4592     // Append all the objects to the cleanup list.  Right now, this
4593     // should always be a no-op, because blocks in default argument
4594     // expressions should never be able to capture anything.
4595     assert(!Init->getNumObjects() &&
4596            "default argument expression has capturing blocks?");
4597   }
4598 
4599   // We already type-checked the argument, so we know it works.
4600   // Just mark all of the declarations in this potentially-evaluated expression
4601   // as being "referenced".
4602   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4603                                    /*SkipLocalVariables=*/true);
4604   return false;
4605 }
4606 
4607 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4608                                         FunctionDecl *FD, ParmVarDecl *Param) {
4609   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4610     return ExprError();
4611   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4612 }
4613 
4614 Sema::VariadicCallType
4615 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4616                           Expr *Fn) {
4617   if (Proto && Proto->isVariadic()) {
4618     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4619       return VariadicConstructor;
4620     else if (Fn && Fn->getType()->isBlockPointerType())
4621       return VariadicBlock;
4622     else if (FDecl) {
4623       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4624         if (Method->isInstance())
4625           return VariadicMethod;
4626     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4627       return VariadicMethod;
4628     return VariadicFunction;
4629   }
4630   return VariadicDoesNotApply;
4631 }
4632 
4633 namespace {
4634 class FunctionCallCCC : public FunctionCallFilterCCC {
4635 public:
4636   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4637                   unsigned NumArgs, MemberExpr *ME)
4638       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4639         FunctionName(FuncName) {}
4640 
4641   bool ValidateCandidate(const TypoCorrection &candidate) override {
4642     if (!candidate.getCorrectionSpecifier() ||
4643         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4644       return false;
4645     }
4646 
4647     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4648   }
4649 
4650 private:
4651   const IdentifierInfo *const FunctionName;
4652 };
4653 }
4654 
4655 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4656                                                FunctionDecl *FDecl,
4657                                                ArrayRef<Expr *> Args) {
4658   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4659   DeclarationName FuncName = FDecl->getDeclName();
4660   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4661 
4662   if (TypoCorrection Corrected = S.CorrectTypo(
4663           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4664           S.getScopeForContext(S.CurContext), nullptr,
4665           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4666                                              Args.size(), ME),
4667           Sema::CTK_ErrorRecovery)) {
4668     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4669       if (Corrected.isOverloaded()) {
4670         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4671         OverloadCandidateSet::iterator Best;
4672         for (NamedDecl *CD : Corrected) {
4673           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4674             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4675                                    OCS);
4676         }
4677         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4678         case OR_Success:
4679           ND = Best->FoundDecl;
4680           Corrected.setCorrectionDecl(ND);
4681           break;
4682         default:
4683           break;
4684         }
4685       }
4686       ND = ND->getUnderlyingDecl();
4687       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4688         return Corrected;
4689     }
4690   }
4691   return TypoCorrection();
4692 }
4693 
4694 /// ConvertArgumentsForCall - Converts the arguments specified in
4695 /// Args/NumArgs to the parameter types of the function FDecl with
4696 /// function prototype Proto. Call is the call expression itself, and
4697 /// Fn is the function expression. For a C++ member function, this
4698 /// routine does not attempt to convert the object argument. Returns
4699 /// true if the call is ill-formed.
4700 bool
4701 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4702                               FunctionDecl *FDecl,
4703                               const FunctionProtoType *Proto,
4704                               ArrayRef<Expr *> Args,
4705                               SourceLocation RParenLoc,
4706                               bool IsExecConfig) {
4707   // Bail out early if calling a builtin with custom typechecking.
4708   if (FDecl)
4709     if (unsigned ID = FDecl->getBuiltinID())
4710       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4711         return false;
4712 
4713   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4714   // assignment, to the types of the corresponding parameter, ...
4715   unsigned NumParams = Proto->getNumParams();
4716   bool Invalid = false;
4717   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4718   unsigned FnKind = Fn->getType()->isBlockPointerType()
4719                        ? 1 /* block */
4720                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4721                                        : 0 /* function */);
4722 
4723   // If too few arguments are available (and we don't have default
4724   // arguments for the remaining parameters), don't make the call.
4725   if (Args.size() < NumParams) {
4726     if (Args.size() < MinArgs) {
4727       TypoCorrection TC;
4728       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4729         unsigned diag_id =
4730             MinArgs == NumParams && !Proto->isVariadic()
4731                 ? diag::err_typecheck_call_too_few_args_suggest
4732                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4733         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4734                                         << static_cast<unsigned>(Args.size())
4735                                         << TC.getCorrectionRange());
4736       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4737         Diag(RParenLoc,
4738              MinArgs == NumParams && !Proto->isVariadic()
4739                  ? diag::err_typecheck_call_too_few_args_one
4740                  : diag::err_typecheck_call_too_few_args_at_least_one)
4741             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4742       else
4743         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4744                             ? diag::err_typecheck_call_too_few_args
4745                             : diag::err_typecheck_call_too_few_args_at_least)
4746             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4747             << Fn->getSourceRange();
4748 
4749       // Emit the location of the prototype.
4750       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4751         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4752           << FDecl;
4753 
4754       return true;
4755     }
4756     Call->setNumArgs(Context, NumParams);
4757   }
4758 
4759   // If too many are passed and not variadic, error on the extras and drop
4760   // them.
4761   if (Args.size() > NumParams) {
4762     if (!Proto->isVariadic()) {
4763       TypoCorrection TC;
4764       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4765         unsigned diag_id =
4766             MinArgs == NumParams && !Proto->isVariadic()
4767                 ? diag::err_typecheck_call_too_many_args_suggest
4768                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4769         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4770                                         << static_cast<unsigned>(Args.size())
4771                                         << TC.getCorrectionRange());
4772       } else if (NumParams == 1 && FDecl &&
4773                  FDecl->getParamDecl(0)->getDeclName())
4774         Diag(Args[NumParams]->getLocStart(),
4775              MinArgs == NumParams
4776                  ? diag::err_typecheck_call_too_many_args_one
4777                  : diag::err_typecheck_call_too_many_args_at_most_one)
4778             << FnKind << FDecl->getParamDecl(0)
4779             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4780             << SourceRange(Args[NumParams]->getLocStart(),
4781                            Args.back()->getLocEnd());
4782       else
4783         Diag(Args[NumParams]->getLocStart(),
4784              MinArgs == NumParams
4785                  ? diag::err_typecheck_call_too_many_args
4786                  : diag::err_typecheck_call_too_many_args_at_most)
4787             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4788             << Fn->getSourceRange()
4789             << SourceRange(Args[NumParams]->getLocStart(),
4790                            Args.back()->getLocEnd());
4791 
4792       // Emit the location of the prototype.
4793       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4794         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4795           << FDecl;
4796 
4797       // This deletes the extra arguments.
4798       Call->setNumArgs(Context, NumParams);
4799       return true;
4800     }
4801   }
4802   SmallVector<Expr *, 8> AllArgs;
4803   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4804 
4805   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4806                                    Proto, 0, Args, AllArgs, CallType);
4807   if (Invalid)
4808     return true;
4809   unsigned TotalNumArgs = AllArgs.size();
4810   for (unsigned i = 0; i < TotalNumArgs; ++i)
4811     Call->setArg(i, AllArgs[i]);
4812 
4813   return false;
4814 }
4815 
4816 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4817                                   const FunctionProtoType *Proto,
4818                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4819                                   SmallVectorImpl<Expr *> &AllArgs,
4820                                   VariadicCallType CallType, bool AllowExplicit,
4821                                   bool IsListInitialization) {
4822   unsigned NumParams = Proto->getNumParams();
4823   bool Invalid = false;
4824   size_t ArgIx = 0;
4825   // Continue to check argument types (even if we have too few/many args).
4826   for (unsigned i = FirstParam; i < NumParams; i++) {
4827     QualType ProtoArgType = Proto->getParamType(i);
4828 
4829     Expr *Arg;
4830     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4831     if (ArgIx < Args.size()) {
4832       Arg = Args[ArgIx++];
4833 
4834       if (RequireCompleteType(Arg->getLocStart(),
4835                               ProtoArgType,
4836                               diag::err_call_incomplete_argument, Arg))
4837         return true;
4838 
4839       // Strip the unbridged-cast placeholder expression off, if applicable.
4840       bool CFAudited = false;
4841       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4842           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4843           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4844         Arg = stripARCUnbridgedCast(Arg);
4845       else if (getLangOpts().ObjCAutoRefCount &&
4846                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4847                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4848         CFAudited = true;
4849 
4850       if (Proto->getExtParameterInfo(i).isNoEscape())
4851         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
4852           BE->getBlockDecl()->setDoesNotEscape();
4853 
4854       InitializedEntity Entity =
4855           Param ? InitializedEntity::InitializeParameter(Context, Param,
4856                                                          ProtoArgType)
4857                 : InitializedEntity::InitializeParameter(
4858                       Context, ProtoArgType, Proto->isParamConsumed(i));
4859 
4860       // Remember that parameter belongs to a CF audited API.
4861       if (CFAudited)
4862         Entity.setParameterCFAudited();
4863 
4864       ExprResult ArgE = PerformCopyInitialization(
4865           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4866       if (ArgE.isInvalid())
4867         return true;
4868 
4869       Arg = ArgE.getAs<Expr>();
4870     } else {
4871       assert(Param && "can't use default arguments without a known callee");
4872 
4873       ExprResult ArgExpr =
4874         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4875       if (ArgExpr.isInvalid())
4876         return true;
4877 
4878       Arg = ArgExpr.getAs<Expr>();
4879     }
4880 
4881     // Check for array bounds violations for each argument to the call. This
4882     // check only triggers warnings when the argument isn't a more complex Expr
4883     // with its own checking, such as a BinaryOperator.
4884     CheckArrayAccess(Arg);
4885 
4886     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4887     CheckStaticArrayArgument(CallLoc, Param, Arg);
4888 
4889     AllArgs.push_back(Arg);
4890   }
4891 
4892   // If this is a variadic call, handle args passed through "...".
4893   if (CallType != VariadicDoesNotApply) {
4894     // Assume that extern "C" functions with variadic arguments that
4895     // return __unknown_anytype aren't *really* variadic.
4896     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4897         FDecl->isExternC()) {
4898       for (Expr *A : Args.slice(ArgIx)) {
4899         QualType paramType; // ignored
4900         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4901         Invalid |= arg.isInvalid();
4902         AllArgs.push_back(arg.get());
4903       }
4904 
4905     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4906     } else {
4907       for (Expr *A : Args.slice(ArgIx)) {
4908         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4909         Invalid |= Arg.isInvalid();
4910         AllArgs.push_back(Arg.get());
4911       }
4912     }
4913 
4914     // Check for array bounds violations.
4915     for (Expr *A : Args.slice(ArgIx))
4916       CheckArrayAccess(A);
4917   }
4918   return Invalid;
4919 }
4920 
4921 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4922   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4923   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4924     TL = DTL.getOriginalLoc();
4925   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4926     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4927       << ATL.getLocalSourceRange();
4928 }
4929 
4930 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4931 /// array parameter, check that it is non-null, and that if it is formed by
4932 /// array-to-pointer decay, the underlying array is sufficiently large.
4933 ///
4934 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4935 /// array type derivation, then for each call to the function, the value of the
4936 /// corresponding actual argument shall provide access to the first element of
4937 /// an array with at least as many elements as specified by the size expression.
4938 void
4939 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4940                                ParmVarDecl *Param,
4941                                const Expr *ArgExpr) {
4942   // Static array parameters are not supported in C++.
4943   if (!Param || getLangOpts().CPlusPlus)
4944     return;
4945 
4946   QualType OrigTy = Param->getOriginalType();
4947 
4948   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4949   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4950     return;
4951 
4952   if (ArgExpr->isNullPointerConstant(Context,
4953                                      Expr::NPC_NeverValueDependent)) {
4954     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4955     DiagnoseCalleeStaticArrayParam(*this, Param);
4956     return;
4957   }
4958 
4959   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4960   if (!CAT)
4961     return;
4962 
4963   const ConstantArrayType *ArgCAT =
4964     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4965   if (!ArgCAT)
4966     return;
4967 
4968   if (ArgCAT->getSize().ult(CAT->getSize())) {
4969     Diag(CallLoc, diag::warn_static_array_too_small)
4970       << ArgExpr->getSourceRange()
4971       << (unsigned) ArgCAT->getSize().getZExtValue()
4972       << (unsigned) CAT->getSize().getZExtValue();
4973     DiagnoseCalleeStaticArrayParam(*this, Param);
4974   }
4975 }
4976 
4977 /// Given a function expression of unknown-any type, try to rebuild it
4978 /// to have a function type.
4979 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4980 
4981 /// Is the given type a placeholder that we need to lower out
4982 /// immediately during argument processing?
4983 static bool isPlaceholderToRemoveAsArg(QualType type) {
4984   // Placeholders are never sugared.
4985   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4986   if (!placeholder) return false;
4987 
4988   switch (placeholder->getKind()) {
4989   // Ignore all the non-placeholder types.
4990 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4991   case BuiltinType::Id:
4992 #include "clang/Basic/OpenCLImageTypes.def"
4993 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4994 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4995 #include "clang/AST/BuiltinTypes.def"
4996     return false;
4997 
4998   // We cannot lower out overload sets; they might validly be resolved
4999   // by the call machinery.
5000   case BuiltinType::Overload:
5001     return false;
5002 
5003   // Unbridged casts in ARC can be handled in some call positions and
5004   // should be left in place.
5005   case BuiltinType::ARCUnbridgedCast:
5006     return false;
5007 
5008   // Pseudo-objects should be converted as soon as possible.
5009   case BuiltinType::PseudoObject:
5010     return true;
5011 
5012   // The debugger mode could theoretically but currently does not try
5013   // to resolve unknown-typed arguments based on known parameter types.
5014   case BuiltinType::UnknownAny:
5015     return true;
5016 
5017   // These are always invalid as call arguments and should be reported.
5018   case BuiltinType::BoundMember:
5019   case BuiltinType::BuiltinFn:
5020   case BuiltinType::OMPArraySection:
5021     return true;
5022 
5023   }
5024   llvm_unreachable("bad builtin type kind");
5025 }
5026 
5027 /// Check an argument list for placeholders that we won't try to
5028 /// handle later.
5029 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5030   // Apply this processing to all the arguments at once instead of
5031   // dying at the first failure.
5032   bool hasInvalid = false;
5033   for (size_t i = 0, e = args.size(); i != e; i++) {
5034     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5035       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5036       if (result.isInvalid()) hasInvalid = true;
5037       else args[i] = result.get();
5038     } else if (hasInvalid) {
5039       (void)S.CorrectDelayedTyposInExpr(args[i]);
5040     }
5041   }
5042   return hasInvalid;
5043 }
5044 
5045 /// If a builtin function has a pointer argument with no explicit address
5046 /// space, then it should be able to accept a pointer to any address
5047 /// space as input.  In order to do this, we need to replace the
5048 /// standard builtin declaration with one that uses the same address space
5049 /// as the call.
5050 ///
5051 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5052 ///                  it does not contain any pointer arguments without
5053 ///                  an address space qualifer.  Otherwise the rewritten
5054 ///                  FunctionDecl is returned.
5055 /// TODO: Handle pointer return types.
5056 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5057                                                 const FunctionDecl *FDecl,
5058                                                 MultiExprArg ArgExprs) {
5059 
5060   QualType DeclType = FDecl->getType();
5061   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5062 
5063   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5064       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5065     return nullptr;
5066 
5067   bool NeedsNewDecl = false;
5068   unsigned i = 0;
5069   SmallVector<QualType, 8> OverloadParams;
5070 
5071   for (QualType ParamType : FT->param_types()) {
5072 
5073     // Convert array arguments to pointer to simplify type lookup.
5074     ExprResult ArgRes =
5075         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5076     if (ArgRes.isInvalid())
5077       return nullptr;
5078     Expr *Arg = ArgRes.get();
5079     QualType ArgType = Arg->getType();
5080     if (!ParamType->isPointerType() ||
5081         ParamType.getQualifiers().hasAddressSpace() ||
5082         !ArgType->isPointerType() ||
5083         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5084       OverloadParams.push_back(ParamType);
5085       continue;
5086     }
5087 
5088     NeedsNewDecl = true;
5089     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5090 
5091     QualType PointeeType = ParamType->getPointeeType();
5092     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5093     OverloadParams.push_back(Context.getPointerType(PointeeType));
5094   }
5095 
5096   if (!NeedsNewDecl)
5097     return nullptr;
5098 
5099   FunctionProtoType::ExtProtoInfo EPI;
5100   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5101                                                 OverloadParams, EPI);
5102   DeclContext *Parent = Context.getTranslationUnitDecl();
5103   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5104                                                     FDecl->getLocation(),
5105                                                     FDecl->getLocation(),
5106                                                     FDecl->getIdentifier(),
5107                                                     OverloadTy,
5108                                                     /*TInfo=*/nullptr,
5109                                                     SC_Extern, false,
5110                                                     /*hasPrototype=*/true);
5111   SmallVector<ParmVarDecl*, 16> Params;
5112   FT = cast<FunctionProtoType>(OverloadTy);
5113   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5114     QualType ParamType = FT->getParamType(i);
5115     ParmVarDecl *Parm =
5116         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5117                                 SourceLocation(), nullptr, ParamType,
5118                                 /*TInfo=*/nullptr, SC_None, nullptr);
5119     Parm->setScopeInfo(0, i);
5120     Params.push_back(Parm);
5121   }
5122   OverloadDecl->setParams(Params);
5123   return OverloadDecl;
5124 }
5125 
5126 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5127                                     FunctionDecl *Callee,
5128                                     MultiExprArg ArgExprs) {
5129   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5130   // similar attributes) really don't like it when functions are called with an
5131   // invalid number of args.
5132   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5133                          /*PartialOverloading=*/false) &&
5134       !Callee->isVariadic())
5135     return;
5136   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5137     return;
5138 
5139   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5140     S.Diag(Fn->getLocStart(),
5141            isa<CXXMethodDecl>(Callee)
5142                ? diag::err_ovl_no_viable_member_function_in_call
5143                : diag::err_ovl_no_viable_function_in_call)
5144         << Callee << Callee->getSourceRange();
5145     S.Diag(Callee->getLocation(),
5146            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5147         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5148     return;
5149   }
5150 }
5151 
5152 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5153     const UnresolvedMemberExpr *const UME, Sema &S) {
5154 
5155   const auto GetFunctionLevelDCIfCXXClass =
5156       [](Sema &S) -> const CXXRecordDecl * {
5157     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5158     if (!DC || !DC->getParent())
5159       return nullptr;
5160 
5161     // If the call to some member function was made from within a member
5162     // function body 'M' return return 'M's parent.
5163     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5164       return MD->getParent()->getCanonicalDecl();
5165     // else the call was made from within a default member initializer of a
5166     // class, so return the class.
5167     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5168       return RD->getCanonicalDecl();
5169     return nullptr;
5170   };
5171   // If our DeclContext is neither a member function nor a class (in the
5172   // case of a lambda in a default member initializer), we can't have an
5173   // enclosing 'this'.
5174 
5175   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5176   if (!CurParentClass)
5177     return false;
5178 
5179   // The naming class for implicit member functions call is the class in which
5180   // name lookup starts.
5181   const CXXRecordDecl *const NamingClass =
5182       UME->getNamingClass()->getCanonicalDecl();
5183   assert(NamingClass && "Must have naming class even for implicit access");
5184 
5185   // If the unresolved member functions were found in a 'naming class' that is
5186   // related (either the same or derived from) to the class that contains the
5187   // member function that itself contained the implicit member access.
5188 
5189   return CurParentClass == NamingClass ||
5190          CurParentClass->isDerivedFrom(NamingClass);
5191 }
5192 
5193 static void
5194 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5195     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5196 
5197   if (!UME)
5198     return;
5199 
5200   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5201   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5202   // already been captured, or if this is an implicit member function call (if
5203   // it isn't, an attempt to capture 'this' should already have been made).
5204   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5205       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5206     return;
5207 
5208   // Check if the naming class in which the unresolved members were found is
5209   // related (same as or is a base of) to the enclosing class.
5210 
5211   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5212     return;
5213 
5214 
5215   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5216   // If the enclosing function is not dependent, then this lambda is
5217   // capture ready, so if we can capture this, do so.
5218   if (!EnclosingFunctionCtx->isDependentContext()) {
5219     // If the current lambda and all enclosing lambdas can capture 'this' -
5220     // then go ahead and capture 'this' (since our unresolved overload set
5221     // contains at least one non-static member function).
5222     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5223       S.CheckCXXThisCapture(CallLoc);
5224   } else if (S.CurContext->isDependentContext()) {
5225     // ... since this is an implicit member reference, that might potentially
5226     // involve a 'this' capture, mark 'this' for potential capture in
5227     // enclosing lambdas.
5228     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5229       CurLSI->addPotentialThisCapture(CallLoc);
5230   }
5231 }
5232 
5233 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5234 /// This provides the location of the left/right parens and a list of comma
5235 /// locations.
5236 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5237                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5238                                Expr *ExecConfig, bool IsExecConfig) {
5239   // Since this might be a postfix expression, get rid of ParenListExprs.
5240   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5241   if (Result.isInvalid()) return ExprError();
5242   Fn = Result.get();
5243 
5244   if (checkArgsForPlaceholders(*this, ArgExprs))
5245     return ExprError();
5246 
5247   if (getLangOpts().CPlusPlus) {
5248     // If this is a pseudo-destructor expression, build the call immediately.
5249     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5250       if (!ArgExprs.empty()) {
5251         // Pseudo-destructor calls should not have any arguments.
5252         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5253             << FixItHint::CreateRemoval(
5254                    SourceRange(ArgExprs.front()->getLocStart(),
5255                                ArgExprs.back()->getLocEnd()));
5256       }
5257 
5258       return new (Context)
5259           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5260     }
5261     if (Fn->getType() == Context.PseudoObjectTy) {
5262       ExprResult result = CheckPlaceholderExpr(Fn);
5263       if (result.isInvalid()) return ExprError();
5264       Fn = result.get();
5265     }
5266 
5267     // Determine whether this is a dependent call inside a C++ template,
5268     // in which case we won't do any semantic analysis now.
5269     bool Dependent = false;
5270     if (Fn->isTypeDependent())
5271       Dependent = true;
5272     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5273       Dependent = true;
5274 
5275     if (Dependent) {
5276       if (ExecConfig) {
5277         return new (Context) CUDAKernelCallExpr(
5278             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5279             Context.DependentTy, VK_RValue, RParenLoc);
5280       } else {
5281 
5282        tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5283             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5284             Fn->getLocStart());
5285 
5286         return new (Context) CallExpr(
5287             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5288       }
5289     }
5290 
5291     // Determine whether this is a call to an object (C++ [over.call.object]).
5292     if (Fn->getType()->isRecordType())
5293       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5294                                           RParenLoc);
5295 
5296     if (Fn->getType() == Context.UnknownAnyTy) {
5297       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5298       if (result.isInvalid()) return ExprError();
5299       Fn = result.get();
5300     }
5301 
5302     if (Fn->getType() == Context.BoundMemberTy) {
5303       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5304                                        RParenLoc);
5305     }
5306   }
5307 
5308   // Check for overloaded calls.  This can happen even in C due to extensions.
5309   if (Fn->getType() == Context.OverloadTy) {
5310     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5311 
5312     // We aren't supposed to apply this logic if there's an '&' involved.
5313     if (!find.HasFormOfMemberPointer) {
5314       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5315         return new (Context) CallExpr(
5316             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5317       OverloadExpr *ovl = find.Expression;
5318       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5319         return BuildOverloadedCallExpr(
5320             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5321             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5322       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5323                                        RParenLoc);
5324     }
5325   }
5326 
5327   // If we're directly calling a function, get the appropriate declaration.
5328   if (Fn->getType() == Context.UnknownAnyTy) {
5329     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5330     if (result.isInvalid()) return ExprError();
5331     Fn = result.get();
5332   }
5333 
5334   Expr *NakedFn = Fn->IgnoreParens();
5335 
5336   bool CallingNDeclIndirectly = false;
5337   NamedDecl *NDecl = nullptr;
5338   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5339     if (UnOp->getOpcode() == UO_AddrOf) {
5340       CallingNDeclIndirectly = true;
5341       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5342     }
5343   }
5344 
5345   if (isa<DeclRefExpr>(NakedFn)) {
5346     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5347 
5348     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5349     if (FDecl && FDecl->getBuiltinID()) {
5350       // Rewrite the function decl for this builtin by replacing parameters
5351       // with no explicit address space with the address space of the arguments
5352       // in ArgExprs.
5353       if ((FDecl =
5354                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5355         NDecl = FDecl;
5356         Fn = DeclRefExpr::Create(
5357             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5358             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5359       }
5360     }
5361   } else if (isa<MemberExpr>(NakedFn))
5362     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5363 
5364   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5365     if (CallingNDeclIndirectly &&
5366         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5367                                            Fn->getLocStart()))
5368       return ExprError();
5369 
5370     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5371       return ExprError();
5372 
5373     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5374   }
5375 
5376   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5377                                ExecConfig, IsExecConfig);
5378 }
5379 
5380 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5381 ///
5382 /// __builtin_astype( value, dst type )
5383 ///
5384 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5385                                  SourceLocation BuiltinLoc,
5386                                  SourceLocation RParenLoc) {
5387   ExprValueKind VK = VK_RValue;
5388   ExprObjectKind OK = OK_Ordinary;
5389   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5390   QualType SrcTy = E->getType();
5391   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5392     return ExprError(Diag(BuiltinLoc,
5393                           diag::err_invalid_astype_of_different_size)
5394                      << DstTy
5395                      << SrcTy
5396                      << E->getSourceRange());
5397   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5398 }
5399 
5400 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5401 /// provided arguments.
5402 ///
5403 /// __builtin_convertvector( value, dst type )
5404 ///
5405 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5406                                         SourceLocation BuiltinLoc,
5407                                         SourceLocation RParenLoc) {
5408   TypeSourceInfo *TInfo;
5409   GetTypeFromParser(ParsedDestTy, &TInfo);
5410   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5411 }
5412 
5413 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5414 /// i.e. an expression not of \p OverloadTy.  The expression should
5415 /// unary-convert to an expression of function-pointer or
5416 /// block-pointer type.
5417 ///
5418 /// \param NDecl the declaration being called, if available
5419 ExprResult
5420 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5421                             SourceLocation LParenLoc,
5422                             ArrayRef<Expr *> Args,
5423                             SourceLocation RParenLoc,
5424                             Expr *Config, bool IsExecConfig) {
5425   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5426   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5427 
5428   // Functions with 'interrupt' attribute cannot be called directly.
5429   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5430     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5431     return ExprError();
5432   }
5433 
5434   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5435   // so there's some risk when calling out to non-interrupt handler functions
5436   // that the callee might not preserve them. This is easy to diagnose here,
5437   // but can be very challenging to debug.
5438   if (auto *Caller = getCurFunctionDecl())
5439     if (Caller->hasAttr<ARMInterruptAttr>()) {
5440       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5441       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5442         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5443     }
5444 
5445   // Promote the function operand.
5446   // We special-case function promotion here because we only allow promoting
5447   // builtin functions to function pointers in the callee of a call.
5448   ExprResult Result;
5449   if (BuiltinID &&
5450       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5451     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5452                                CK_BuiltinFnToFnPtr).get();
5453   } else {
5454     Result = CallExprUnaryConversions(Fn);
5455   }
5456   if (Result.isInvalid())
5457     return ExprError();
5458   Fn = Result.get();
5459 
5460   // Make the call expr early, before semantic checks.  This guarantees cleanup
5461   // of arguments and function on error.
5462   CallExpr *TheCall;
5463   if (Config)
5464     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5465                                                cast<CallExpr>(Config), Args,
5466                                                Context.BoolTy, VK_RValue,
5467                                                RParenLoc);
5468   else
5469     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5470                                      VK_RValue, RParenLoc);
5471 
5472   if (!getLangOpts().CPlusPlus) {
5473     // C cannot always handle TypoExpr nodes in builtin calls and direct
5474     // function calls as their argument checking don't necessarily handle
5475     // dependent types properly, so make sure any TypoExprs have been
5476     // dealt with.
5477     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5478     if (!Result.isUsable()) return ExprError();
5479     TheCall = dyn_cast<CallExpr>(Result.get());
5480     if (!TheCall) return Result;
5481     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5482   }
5483 
5484   // Bail out early if calling a builtin with custom typechecking.
5485   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5486     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5487 
5488  retry:
5489   const FunctionType *FuncT;
5490   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5491     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5492     // have type pointer to function".
5493     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5494     if (!FuncT)
5495       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5496                          << Fn->getType() << Fn->getSourceRange());
5497   } else if (const BlockPointerType *BPT =
5498                Fn->getType()->getAs<BlockPointerType>()) {
5499     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5500   } else {
5501     // Handle calls to expressions of unknown-any type.
5502     if (Fn->getType() == Context.UnknownAnyTy) {
5503       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5504       if (rewrite.isInvalid()) return ExprError();
5505       Fn = rewrite.get();
5506       TheCall->setCallee(Fn);
5507       goto retry;
5508     }
5509 
5510     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5511       << Fn->getType() << Fn->getSourceRange());
5512   }
5513 
5514   if (getLangOpts().CUDA) {
5515     if (Config) {
5516       // CUDA: Kernel calls must be to global functions
5517       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5518         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5519             << FDecl << Fn->getSourceRange());
5520 
5521       // CUDA: Kernel function must have 'void' return type
5522       if (!FuncT->getReturnType()->isVoidType())
5523         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5524             << Fn->getType() << Fn->getSourceRange());
5525     } else {
5526       // CUDA: Calls to global functions must be configured
5527       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5528         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5529             << FDecl << Fn->getSourceRange());
5530     }
5531   }
5532 
5533   // Check for a valid return type
5534   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5535                           FDecl))
5536     return ExprError();
5537 
5538   // We know the result type of the call, set it.
5539   TheCall->setType(FuncT->getCallResultType(Context));
5540   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5541 
5542   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5543   if (Proto) {
5544     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5545                                 IsExecConfig))
5546       return ExprError();
5547   } else {
5548     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5549 
5550     if (FDecl) {
5551       // Check if we have too few/too many template arguments, based
5552       // on our knowledge of the function definition.
5553       const FunctionDecl *Def = nullptr;
5554       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5555         Proto = Def->getType()->getAs<FunctionProtoType>();
5556        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5557           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5558           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5559       }
5560 
5561       // If the function we're calling isn't a function prototype, but we have
5562       // a function prototype from a prior declaratiom, use that prototype.
5563       if (!FDecl->hasPrototype())
5564         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5565     }
5566 
5567     // Promote the arguments (C99 6.5.2.2p6).
5568     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5569       Expr *Arg = Args[i];
5570 
5571       if (Proto && i < Proto->getNumParams()) {
5572         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5573             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5574         ExprResult ArgE =
5575             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5576         if (ArgE.isInvalid())
5577           return true;
5578 
5579         Arg = ArgE.getAs<Expr>();
5580 
5581       } else {
5582         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5583 
5584         if (ArgE.isInvalid())
5585           return true;
5586 
5587         Arg = ArgE.getAs<Expr>();
5588       }
5589 
5590       if (RequireCompleteType(Arg->getLocStart(),
5591                               Arg->getType(),
5592                               diag::err_call_incomplete_argument, Arg))
5593         return ExprError();
5594 
5595       TheCall->setArg(i, Arg);
5596     }
5597   }
5598 
5599   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5600     if (!Method->isStatic())
5601       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5602         << Fn->getSourceRange());
5603 
5604   // Check for sentinels
5605   if (NDecl)
5606     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5607 
5608   // Do special checking on direct calls to functions.
5609   if (FDecl) {
5610     if (CheckFunctionCall(FDecl, TheCall, Proto))
5611       return ExprError();
5612 
5613     if (BuiltinID)
5614       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5615   } else if (NDecl) {
5616     if (CheckPointerCall(NDecl, TheCall, Proto))
5617       return ExprError();
5618   } else {
5619     if (CheckOtherCall(TheCall, Proto))
5620       return ExprError();
5621   }
5622 
5623   return MaybeBindToTemporary(TheCall);
5624 }
5625 
5626 ExprResult
5627 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5628                            SourceLocation RParenLoc, Expr *InitExpr) {
5629   assert(Ty && "ActOnCompoundLiteral(): missing type");
5630   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5631 
5632   TypeSourceInfo *TInfo;
5633   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5634   if (!TInfo)
5635     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5636 
5637   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5638 }
5639 
5640 ExprResult
5641 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5642                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5643   QualType literalType = TInfo->getType();
5644 
5645   if (literalType->isArrayType()) {
5646     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5647           diag::err_illegal_decl_array_incomplete_type,
5648           SourceRange(LParenLoc,
5649                       LiteralExpr->getSourceRange().getEnd())))
5650       return ExprError();
5651     if (literalType->isVariableArrayType())
5652       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5653         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5654   } else if (!literalType->isDependentType() &&
5655              RequireCompleteType(LParenLoc, literalType,
5656                diag::err_typecheck_decl_incomplete_type,
5657                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5658     return ExprError();
5659 
5660   InitializedEntity Entity
5661     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5662   InitializationKind Kind
5663     = InitializationKind::CreateCStyleCast(LParenLoc,
5664                                            SourceRange(LParenLoc, RParenLoc),
5665                                            /*InitList=*/true);
5666   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5667   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5668                                       &literalType);
5669   if (Result.isInvalid())
5670     return ExprError();
5671   LiteralExpr = Result.get();
5672 
5673   bool isFileScope = !CurContext->isFunctionOrMethod();
5674   if (isFileScope &&
5675       !LiteralExpr->isTypeDependent() &&
5676       !LiteralExpr->isValueDependent() &&
5677       !literalType->isDependentType()) { // 6.5.2.5p3
5678     if (CheckForConstantInitializer(LiteralExpr, literalType))
5679       return ExprError();
5680   }
5681 
5682   // In C, compound literals are l-values for some reason.
5683   // For GCC compatibility, in C++, file-scope array compound literals with
5684   // constant initializers are also l-values, and compound literals are
5685   // otherwise prvalues.
5686   //
5687   // (GCC also treats C++ list-initialized file-scope array prvalues with
5688   // constant initializers as l-values, but that's non-conforming, so we don't
5689   // follow it there.)
5690   //
5691   // FIXME: It would be better to handle the lvalue cases as materializing and
5692   // lifetime-extending a temporary object, but our materialized temporaries
5693   // representation only supports lifetime extension from a variable, not "out
5694   // of thin air".
5695   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5696   // is bound to the result of applying array-to-pointer decay to the compound
5697   // literal.
5698   // FIXME: GCC supports compound literals of reference type, which should
5699   // obviously have a value kind derived from the kind of reference involved.
5700   ExprValueKind VK =
5701       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5702           ? VK_RValue
5703           : VK_LValue;
5704 
5705   return MaybeBindToTemporary(
5706       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5707                                         VK, LiteralExpr, isFileScope));
5708 }
5709 
5710 ExprResult
5711 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5712                     SourceLocation RBraceLoc) {
5713   // Immediately handle non-overload placeholders.  Overloads can be
5714   // resolved contextually, but everything else here can't.
5715   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5716     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5717       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5718 
5719       // Ignore failures; dropping the entire initializer list because
5720       // of one failure would be terrible for indexing/etc.
5721       if (result.isInvalid()) continue;
5722 
5723       InitArgList[I] = result.get();
5724     }
5725   }
5726 
5727   // Semantic analysis for initializers is done by ActOnDeclarator() and
5728   // CheckInitializer() - it requires knowledge of the object being initialized.
5729 
5730   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5731                                                RBraceLoc);
5732   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5733   return E;
5734 }
5735 
5736 /// Do an explicit extend of the given block pointer if we're in ARC.
5737 void Sema::maybeExtendBlockObject(ExprResult &E) {
5738   assert(E.get()->getType()->isBlockPointerType());
5739   assert(E.get()->isRValue());
5740 
5741   // Only do this in an r-value context.
5742   if (!getLangOpts().ObjCAutoRefCount) return;
5743 
5744   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5745                                CK_ARCExtendBlockObject, E.get(),
5746                                /*base path*/ nullptr, VK_RValue);
5747   Cleanup.setExprNeedsCleanups(true);
5748 }
5749 
5750 /// Prepare a conversion of the given expression to an ObjC object
5751 /// pointer type.
5752 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5753   QualType type = E.get()->getType();
5754   if (type->isObjCObjectPointerType()) {
5755     return CK_BitCast;
5756   } else if (type->isBlockPointerType()) {
5757     maybeExtendBlockObject(E);
5758     return CK_BlockPointerToObjCPointerCast;
5759   } else {
5760     assert(type->isPointerType());
5761     return CK_CPointerToObjCPointerCast;
5762   }
5763 }
5764 
5765 /// Prepares for a scalar cast, performing all the necessary stages
5766 /// except the final cast and returning the kind required.
5767 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5768   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5769   // Also, callers should have filtered out the invalid cases with
5770   // pointers.  Everything else should be possible.
5771 
5772   QualType SrcTy = Src.get()->getType();
5773   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5774     return CK_NoOp;
5775 
5776   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5777   case Type::STK_MemberPointer:
5778     llvm_unreachable("member pointer type in C");
5779 
5780   case Type::STK_CPointer:
5781   case Type::STK_BlockPointer:
5782   case Type::STK_ObjCObjectPointer:
5783     switch (DestTy->getScalarTypeKind()) {
5784     case Type::STK_CPointer: {
5785       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5786       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5787       if (SrcAS != DestAS)
5788         return CK_AddressSpaceConversion;
5789       return CK_BitCast;
5790     }
5791     case Type::STK_BlockPointer:
5792       return (SrcKind == Type::STK_BlockPointer
5793                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5794     case Type::STK_ObjCObjectPointer:
5795       if (SrcKind == Type::STK_ObjCObjectPointer)
5796         return CK_BitCast;
5797       if (SrcKind == Type::STK_CPointer)
5798         return CK_CPointerToObjCPointerCast;
5799       maybeExtendBlockObject(Src);
5800       return CK_BlockPointerToObjCPointerCast;
5801     case Type::STK_Bool:
5802       return CK_PointerToBoolean;
5803     case Type::STK_Integral:
5804       return CK_PointerToIntegral;
5805     case Type::STK_Floating:
5806     case Type::STK_FloatingComplex:
5807     case Type::STK_IntegralComplex:
5808     case Type::STK_MemberPointer:
5809       llvm_unreachable("illegal cast from pointer");
5810     }
5811     llvm_unreachable("Should have returned before this");
5812 
5813   case Type::STK_Bool: // casting from bool is like casting from an integer
5814   case Type::STK_Integral:
5815     switch (DestTy->getScalarTypeKind()) {
5816     case Type::STK_CPointer:
5817     case Type::STK_ObjCObjectPointer:
5818     case Type::STK_BlockPointer:
5819       if (Src.get()->isNullPointerConstant(Context,
5820                                            Expr::NPC_ValueDependentIsNull))
5821         return CK_NullToPointer;
5822       return CK_IntegralToPointer;
5823     case Type::STK_Bool:
5824       return CK_IntegralToBoolean;
5825     case Type::STK_Integral:
5826       return CK_IntegralCast;
5827     case Type::STK_Floating:
5828       return CK_IntegralToFloating;
5829     case Type::STK_IntegralComplex:
5830       Src = ImpCastExprToType(Src.get(),
5831                       DestTy->castAs<ComplexType>()->getElementType(),
5832                       CK_IntegralCast);
5833       return CK_IntegralRealToComplex;
5834     case Type::STK_FloatingComplex:
5835       Src = ImpCastExprToType(Src.get(),
5836                       DestTy->castAs<ComplexType>()->getElementType(),
5837                       CK_IntegralToFloating);
5838       return CK_FloatingRealToComplex;
5839     case Type::STK_MemberPointer:
5840       llvm_unreachable("member pointer type in C");
5841     }
5842     llvm_unreachable("Should have returned before this");
5843 
5844   case Type::STK_Floating:
5845     switch (DestTy->getScalarTypeKind()) {
5846     case Type::STK_Floating:
5847       return CK_FloatingCast;
5848     case Type::STK_Bool:
5849       return CK_FloatingToBoolean;
5850     case Type::STK_Integral:
5851       return CK_FloatingToIntegral;
5852     case Type::STK_FloatingComplex:
5853       Src = ImpCastExprToType(Src.get(),
5854                               DestTy->castAs<ComplexType>()->getElementType(),
5855                               CK_FloatingCast);
5856       return CK_FloatingRealToComplex;
5857     case Type::STK_IntegralComplex:
5858       Src = ImpCastExprToType(Src.get(),
5859                               DestTy->castAs<ComplexType>()->getElementType(),
5860                               CK_FloatingToIntegral);
5861       return CK_IntegralRealToComplex;
5862     case Type::STK_CPointer:
5863     case Type::STK_ObjCObjectPointer:
5864     case Type::STK_BlockPointer:
5865       llvm_unreachable("valid float->pointer cast?");
5866     case Type::STK_MemberPointer:
5867       llvm_unreachable("member pointer type in C");
5868     }
5869     llvm_unreachable("Should have returned before this");
5870 
5871   case Type::STK_FloatingComplex:
5872     switch (DestTy->getScalarTypeKind()) {
5873     case Type::STK_FloatingComplex:
5874       return CK_FloatingComplexCast;
5875     case Type::STK_IntegralComplex:
5876       return CK_FloatingComplexToIntegralComplex;
5877     case Type::STK_Floating: {
5878       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5879       if (Context.hasSameType(ET, DestTy))
5880         return CK_FloatingComplexToReal;
5881       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5882       return CK_FloatingCast;
5883     }
5884     case Type::STK_Bool:
5885       return CK_FloatingComplexToBoolean;
5886     case Type::STK_Integral:
5887       Src = ImpCastExprToType(Src.get(),
5888                               SrcTy->castAs<ComplexType>()->getElementType(),
5889                               CK_FloatingComplexToReal);
5890       return CK_FloatingToIntegral;
5891     case Type::STK_CPointer:
5892     case Type::STK_ObjCObjectPointer:
5893     case Type::STK_BlockPointer:
5894       llvm_unreachable("valid complex float->pointer cast?");
5895     case Type::STK_MemberPointer:
5896       llvm_unreachable("member pointer type in C");
5897     }
5898     llvm_unreachable("Should have returned before this");
5899 
5900   case Type::STK_IntegralComplex:
5901     switch (DestTy->getScalarTypeKind()) {
5902     case Type::STK_FloatingComplex:
5903       return CK_IntegralComplexToFloatingComplex;
5904     case Type::STK_IntegralComplex:
5905       return CK_IntegralComplexCast;
5906     case Type::STK_Integral: {
5907       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5908       if (Context.hasSameType(ET, DestTy))
5909         return CK_IntegralComplexToReal;
5910       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5911       return CK_IntegralCast;
5912     }
5913     case Type::STK_Bool:
5914       return CK_IntegralComplexToBoolean;
5915     case Type::STK_Floating:
5916       Src = ImpCastExprToType(Src.get(),
5917                               SrcTy->castAs<ComplexType>()->getElementType(),
5918                               CK_IntegralComplexToReal);
5919       return CK_IntegralToFloating;
5920     case Type::STK_CPointer:
5921     case Type::STK_ObjCObjectPointer:
5922     case Type::STK_BlockPointer:
5923       llvm_unreachable("valid complex int->pointer cast?");
5924     case Type::STK_MemberPointer:
5925       llvm_unreachable("member pointer type in C");
5926     }
5927     llvm_unreachable("Should have returned before this");
5928   }
5929 
5930   llvm_unreachable("Unhandled scalar cast");
5931 }
5932 
5933 static bool breakDownVectorType(QualType type, uint64_t &len,
5934                                 QualType &eltType) {
5935   // Vectors are simple.
5936   if (const VectorType *vecType = type->getAs<VectorType>()) {
5937     len = vecType->getNumElements();
5938     eltType = vecType->getElementType();
5939     assert(eltType->isScalarType());
5940     return true;
5941   }
5942 
5943   // We allow lax conversion to and from non-vector types, but only if
5944   // they're real types (i.e. non-complex, non-pointer scalar types).
5945   if (!type->isRealType()) return false;
5946 
5947   len = 1;
5948   eltType = type;
5949   return true;
5950 }
5951 
5952 /// Are the two types lax-compatible vector types?  That is, given
5953 /// that one of them is a vector, do they have equal storage sizes,
5954 /// where the storage size is the number of elements times the element
5955 /// size?
5956 ///
5957 /// This will also return false if either of the types is neither a
5958 /// vector nor a real type.
5959 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5960   assert(destTy->isVectorType() || srcTy->isVectorType());
5961 
5962   // Disallow lax conversions between scalars and ExtVectors (these
5963   // conversions are allowed for other vector types because common headers
5964   // depend on them).  Most scalar OP ExtVector cases are handled by the
5965   // splat path anyway, which does what we want (convert, not bitcast).
5966   // What this rules out for ExtVectors is crazy things like char4*float.
5967   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5968   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5969 
5970   uint64_t srcLen, destLen;
5971   QualType srcEltTy, destEltTy;
5972   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5973   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5974 
5975   // ASTContext::getTypeSize will return the size rounded up to a
5976   // power of 2, so instead of using that, we need to use the raw
5977   // element size multiplied by the element count.
5978   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5979   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5980 
5981   return (srcLen * srcEltSize == destLen * destEltSize);
5982 }
5983 
5984 /// Is this a legal conversion between two types, one of which is
5985 /// known to be a vector type?
5986 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5987   assert(destTy->isVectorType() || srcTy->isVectorType());
5988 
5989   if (!Context.getLangOpts().LaxVectorConversions)
5990     return false;
5991   return areLaxCompatibleVectorTypes(srcTy, destTy);
5992 }
5993 
5994 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5995                            CastKind &Kind) {
5996   assert(VectorTy->isVectorType() && "Not a vector type!");
5997 
5998   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5999     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6000       return Diag(R.getBegin(),
6001                   Ty->isVectorType() ?
6002                   diag::err_invalid_conversion_between_vectors :
6003                   diag::err_invalid_conversion_between_vector_and_integer)
6004         << VectorTy << Ty << R;
6005   } else
6006     return Diag(R.getBegin(),
6007                 diag::err_invalid_conversion_between_vector_and_scalar)
6008       << VectorTy << Ty << R;
6009 
6010   Kind = CK_BitCast;
6011   return false;
6012 }
6013 
6014 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6015   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6016 
6017   if (DestElemTy == SplattedExpr->getType())
6018     return SplattedExpr;
6019 
6020   assert(DestElemTy->isFloatingType() ||
6021          DestElemTy->isIntegralOrEnumerationType());
6022 
6023   CastKind CK;
6024   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6025     // OpenCL requires that we convert `true` boolean expressions to -1, but
6026     // only when splatting vectors.
6027     if (DestElemTy->isFloatingType()) {
6028       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6029       // in two steps: boolean to signed integral, then to floating.
6030       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6031                                                  CK_BooleanToSignedIntegral);
6032       SplattedExpr = CastExprRes.get();
6033       CK = CK_IntegralToFloating;
6034     } else {
6035       CK = CK_BooleanToSignedIntegral;
6036     }
6037   } else {
6038     ExprResult CastExprRes = SplattedExpr;
6039     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6040     if (CastExprRes.isInvalid())
6041       return ExprError();
6042     SplattedExpr = CastExprRes.get();
6043   }
6044   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6045 }
6046 
6047 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6048                                     Expr *CastExpr, CastKind &Kind) {
6049   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6050 
6051   QualType SrcTy = CastExpr->getType();
6052 
6053   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6054   // an ExtVectorType.
6055   // In OpenCL, casts between vectors of different types are not allowed.
6056   // (See OpenCL 6.2).
6057   if (SrcTy->isVectorType()) {
6058     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6059         (getLangOpts().OpenCL &&
6060          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6061       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6062         << DestTy << SrcTy << R;
6063       return ExprError();
6064     }
6065     Kind = CK_BitCast;
6066     return CastExpr;
6067   }
6068 
6069   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6070   // conversion will take place first from scalar to elt type, and then
6071   // splat from elt type to vector.
6072   if (SrcTy->isPointerType())
6073     return Diag(R.getBegin(),
6074                 diag::err_invalid_conversion_between_vector_and_scalar)
6075       << DestTy << SrcTy << R;
6076 
6077   Kind = CK_VectorSplat;
6078   return prepareVectorSplat(DestTy, CastExpr);
6079 }
6080 
6081 ExprResult
6082 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6083                     Declarator &D, ParsedType &Ty,
6084                     SourceLocation RParenLoc, Expr *CastExpr) {
6085   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6086          "ActOnCastExpr(): missing type or expr");
6087 
6088   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6089   if (D.isInvalidType())
6090     return ExprError();
6091 
6092   if (getLangOpts().CPlusPlus) {
6093     // Check that there are no default arguments (C++ only).
6094     CheckExtraCXXDefaultArguments(D);
6095   } else {
6096     // Make sure any TypoExprs have been dealt with.
6097     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6098     if (!Res.isUsable())
6099       return ExprError();
6100     CastExpr = Res.get();
6101   }
6102 
6103   checkUnusedDeclAttributes(D);
6104 
6105   QualType castType = castTInfo->getType();
6106   Ty = CreateParsedType(castType, castTInfo);
6107 
6108   bool isVectorLiteral = false;
6109 
6110   // Check for an altivec or OpenCL literal,
6111   // i.e. all the elements are integer constants.
6112   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6113   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6114   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6115        && castType->isVectorType() && (PE || PLE)) {
6116     if (PLE && PLE->getNumExprs() == 0) {
6117       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6118       return ExprError();
6119     }
6120     if (PE || PLE->getNumExprs() == 1) {
6121       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6122       if (!E->getType()->isVectorType())
6123         isVectorLiteral = true;
6124     }
6125     else
6126       isVectorLiteral = true;
6127   }
6128 
6129   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6130   // then handle it as such.
6131   if (isVectorLiteral)
6132     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6133 
6134   // If the Expr being casted is a ParenListExpr, handle it specially.
6135   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6136   // sequence of BinOp comma operators.
6137   if (isa<ParenListExpr>(CastExpr)) {
6138     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6139     if (Result.isInvalid()) return ExprError();
6140     CastExpr = Result.get();
6141   }
6142 
6143   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6144       !getSourceManager().isInSystemMacro(LParenLoc))
6145     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6146 
6147   CheckTollFreeBridgeCast(castType, CastExpr);
6148 
6149   CheckObjCBridgeRelatedCast(castType, CastExpr);
6150 
6151   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6152 
6153   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6154 }
6155 
6156 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6157                                     SourceLocation RParenLoc, Expr *E,
6158                                     TypeSourceInfo *TInfo) {
6159   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6160          "Expected paren or paren list expression");
6161 
6162   Expr **exprs;
6163   unsigned numExprs;
6164   Expr *subExpr;
6165   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6166   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6167     LiteralLParenLoc = PE->getLParenLoc();
6168     LiteralRParenLoc = PE->getRParenLoc();
6169     exprs = PE->getExprs();
6170     numExprs = PE->getNumExprs();
6171   } else { // isa<ParenExpr> by assertion at function entrance
6172     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6173     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6174     subExpr = cast<ParenExpr>(E)->getSubExpr();
6175     exprs = &subExpr;
6176     numExprs = 1;
6177   }
6178 
6179   QualType Ty = TInfo->getType();
6180   assert(Ty->isVectorType() && "Expected vector type");
6181 
6182   SmallVector<Expr *, 8> initExprs;
6183   const VectorType *VTy = Ty->getAs<VectorType>();
6184   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6185 
6186   // '(...)' form of vector initialization in AltiVec: the number of
6187   // initializers must be one or must match the size of the vector.
6188   // If a single value is specified in the initializer then it will be
6189   // replicated to all the components of the vector
6190   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6191     // The number of initializers must be one or must match the size of the
6192     // vector. If a single value is specified in the initializer then it will
6193     // be replicated to all the components of the vector
6194     if (numExprs == 1) {
6195       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6196       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6197       if (Literal.isInvalid())
6198         return ExprError();
6199       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6200                                   PrepareScalarCast(Literal, ElemTy));
6201       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6202     }
6203     else if (numExprs < numElems) {
6204       Diag(E->getExprLoc(),
6205            diag::err_incorrect_number_of_vector_initializers);
6206       return ExprError();
6207     }
6208     else
6209       initExprs.append(exprs, exprs + numExprs);
6210   }
6211   else {
6212     // For OpenCL, when the number of initializers is a single value,
6213     // it will be replicated to all components of the vector.
6214     if (getLangOpts().OpenCL &&
6215         VTy->getVectorKind() == VectorType::GenericVector &&
6216         numExprs == 1) {
6217         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6218         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6219         if (Literal.isInvalid())
6220           return ExprError();
6221         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6222                                     PrepareScalarCast(Literal, ElemTy));
6223         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6224     }
6225 
6226     initExprs.append(exprs, exprs + numExprs);
6227   }
6228   // FIXME: This means that pretty-printing the final AST will produce curly
6229   // braces instead of the original commas.
6230   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6231                                                    initExprs, LiteralRParenLoc);
6232   initE->setType(Ty);
6233   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6234 }
6235 
6236 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6237 /// the ParenListExpr into a sequence of comma binary operators.
6238 ExprResult
6239 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6240   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6241   if (!E)
6242     return OrigExpr;
6243 
6244   ExprResult Result(E->getExpr(0));
6245 
6246   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6247     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6248                         E->getExpr(i));
6249 
6250   if (Result.isInvalid()) return ExprError();
6251 
6252   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6253 }
6254 
6255 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6256                                     SourceLocation R,
6257                                     MultiExprArg Val) {
6258   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6259   return expr;
6260 }
6261 
6262 /// Emit a specialized diagnostic when one expression is a null pointer
6263 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6264 /// emitted.
6265 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6266                                       SourceLocation QuestionLoc) {
6267   Expr *NullExpr = LHSExpr;
6268   Expr *NonPointerExpr = RHSExpr;
6269   Expr::NullPointerConstantKind NullKind =
6270       NullExpr->isNullPointerConstant(Context,
6271                                       Expr::NPC_ValueDependentIsNotNull);
6272 
6273   if (NullKind == Expr::NPCK_NotNull) {
6274     NullExpr = RHSExpr;
6275     NonPointerExpr = LHSExpr;
6276     NullKind =
6277         NullExpr->isNullPointerConstant(Context,
6278                                         Expr::NPC_ValueDependentIsNotNull);
6279   }
6280 
6281   if (NullKind == Expr::NPCK_NotNull)
6282     return false;
6283 
6284   if (NullKind == Expr::NPCK_ZeroExpression)
6285     return false;
6286 
6287   if (NullKind == Expr::NPCK_ZeroLiteral) {
6288     // In this case, check to make sure that we got here from a "NULL"
6289     // string in the source code.
6290     NullExpr = NullExpr->IgnoreParenImpCasts();
6291     SourceLocation loc = NullExpr->getExprLoc();
6292     if (!findMacroSpelling(loc, "NULL"))
6293       return false;
6294   }
6295 
6296   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6297   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6298       << NonPointerExpr->getType() << DiagType
6299       << NonPointerExpr->getSourceRange();
6300   return true;
6301 }
6302 
6303 /// Return false if the condition expression is valid, true otherwise.
6304 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6305   QualType CondTy = Cond->getType();
6306 
6307   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6308   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6309     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6310       << CondTy << Cond->getSourceRange();
6311     return true;
6312   }
6313 
6314   // C99 6.5.15p2
6315   if (CondTy->isScalarType()) return false;
6316 
6317   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6318     << CondTy << Cond->getSourceRange();
6319   return true;
6320 }
6321 
6322 /// Handle when one or both operands are void type.
6323 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6324                                          ExprResult &RHS) {
6325     Expr *LHSExpr = LHS.get();
6326     Expr *RHSExpr = RHS.get();
6327 
6328     if (!LHSExpr->getType()->isVoidType())
6329       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6330         << RHSExpr->getSourceRange();
6331     if (!RHSExpr->getType()->isVoidType())
6332       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6333         << LHSExpr->getSourceRange();
6334     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6335     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6336     return S.Context.VoidTy;
6337 }
6338 
6339 /// Return false if the NullExpr can be promoted to PointerTy,
6340 /// true otherwise.
6341 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6342                                         QualType PointerTy) {
6343   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6344       !NullExpr.get()->isNullPointerConstant(S.Context,
6345                                             Expr::NPC_ValueDependentIsNull))
6346     return true;
6347 
6348   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6349   return false;
6350 }
6351 
6352 /// Checks compatibility between two pointers and return the resulting
6353 /// type.
6354 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6355                                                      ExprResult &RHS,
6356                                                      SourceLocation Loc) {
6357   QualType LHSTy = LHS.get()->getType();
6358   QualType RHSTy = RHS.get()->getType();
6359 
6360   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6361     // Two identical pointers types are always compatible.
6362     return LHSTy;
6363   }
6364 
6365   QualType lhptee, rhptee;
6366 
6367   // Get the pointee types.
6368   bool IsBlockPointer = false;
6369   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6370     lhptee = LHSBTy->getPointeeType();
6371     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6372     IsBlockPointer = true;
6373   } else {
6374     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6375     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6376   }
6377 
6378   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6379   // differently qualified versions of compatible types, the result type is
6380   // a pointer to an appropriately qualified version of the composite
6381   // type.
6382 
6383   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6384   // clause doesn't make sense for our extensions. E.g. address space 2 should
6385   // be incompatible with address space 3: they may live on different devices or
6386   // anything.
6387   Qualifiers lhQual = lhptee.getQualifiers();
6388   Qualifiers rhQual = rhptee.getQualifiers();
6389 
6390   LangAS ResultAddrSpace = LangAS::Default;
6391   LangAS LAddrSpace = lhQual.getAddressSpace();
6392   LangAS RAddrSpace = rhQual.getAddressSpace();
6393   if (S.getLangOpts().OpenCL) {
6394     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6395     // spaces is disallowed.
6396     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6397       ResultAddrSpace = LAddrSpace;
6398     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6399       ResultAddrSpace = RAddrSpace;
6400     else {
6401       S.Diag(Loc,
6402              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6403           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6404           << RHS.get()->getSourceRange();
6405       return QualType();
6406     }
6407   }
6408 
6409   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6410   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6411   lhQual.removeCVRQualifiers();
6412   rhQual.removeCVRQualifiers();
6413 
6414   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6415   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6416   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6417   // qual types are compatible iff
6418   //  * corresponded types are compatible
6419   //  * CVR qualifiers are equal
6420   //  * address spaces are equal
6421   // Thus for conditional operator we merge CVR and address space unqualified
6422   // pointees and if there is a composite type we return a pointer to it with
6423   // merged qualifiers.
6424   if (S.getLangOpts().OpenCL) {
6425     LHSCastKind = LAddrSpace == ResultAddrSpace
6426                       ? CK_BitCast
6427                       : CK_AddressSpaceConversion;
6428     RHSCastKind = RAddrSpace == ResultAddrSpace
6429                       ? CK_BitCast
6430                       : CK_AddressSpaceConversion;
6431     lhQual.removeAddressSpace();
6432     rhQual.removeAddressSpace();
6433   }
6434 
6435   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6436   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6437 
6438   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6439 
6440   if (CompositeTy.isNull()) {
6441     // In this situation, we assume void* type. No especially good
6442     // reason, but this is what gcc does, and we do have to pick
6443     // to get a consistent AST.
6444     QualType incompatTy;
6445     incompatTy = S.Context.getPointerType(
6446         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6447     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6448     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6449     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6450     // for casts between types with incompatible address space qualifiers.
6451     // For the following code the compiler produces casts between global and
6452     // local address spaces of the corresponded innermost pointees:
6453     // local int *global *a;
6454     // global int *global *b;
6455     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6456     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6457         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6458         << RHS.get()->getSourceRange();
6459     return incompatTy;
6460   }
6461 
6462   // The pointer types are compatible.
6463   // In case of OpenCL ResultTy should have the address space qualifier
6464   // which is a superset of address spaces of both the 2nd and the 3rd
6465   // operands of the conditional operator.
6466   QualType ResultTy = [&, ResultAddrSpace]() {
6467     if (S.getLangOpts().OpenCL) {
6468       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6469       CompositeQuals.setAddressSpace(ResultAddrSpace);
6470       return S.Context
6471           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6472           .withCVRQualifiers(MergedCVRQual);
6473     }
6474     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6475   }();
6476   if (IsBlockPointer)
6477     ResultTy = S.Context.getBlockPointerType(ResultTy);
6478   else
6479     ResultTy = S.Context.getPointerType(ResultTy);
6480 
6481   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6482   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6483   return ResultTy;
6484 }
6485 
6486 /// Return the resulting type when the operands are both block pointers.
6487 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6488                                                           ExprResult &LHS,
6489                                                           ExprResult &RHS,
6490                                                           SourceLocation Loc) {
6491   QualType LHSTy = LHS.get()->getType();
6492   QualType RHSTy = RHS.get()->getType();
6493 
6494   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6495     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6496       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6497       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6498       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6499       return destType;
6500     }
6501     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6502       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6503       << RHS.get()->getSourceRange();
6504     return QualType();
6505   }
6506 
6507   // We have 2 block pointer types.
6508   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6509 }
6510 
6511 /// Return the resulting type when the operands are both pointers.
6512 static QualType
6513 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6514                                             ExprResult &RHS,
6515                                             SourceLocation Loc) {
6516   // get the pointer types
6517   QualType LHSTy = LHS.get()->getType();
6518   QualType RHSTy = RHS.get()->getType();
6519 
6520   // get the "pointed to" types
6521   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6522   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6523 
6524   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6525   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6526     // Figure out necessary qualifiers (C99 6.5.15p6)
6527     QualType destPointee
6528       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6529     QualType destType = S.Context.getPointerType(destPointee);
6530     // Add qualifiers if necessary.
6531     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6532     // Promote to void*.
6533     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6534     return destType;
6535   }
6536   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6537     QualType destPointee
6538       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6539     QualType destType = S.Context.getPointerType(destPointee);
6540     // Add qualifiers if necessary.
6541     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6542     // Promote to void*.
6543     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6544     return destType;
6545   }
6546 
6547   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6548 }
6549 
6550 /// Return false if the first expression is not an integer and the second
6551 /// expression is not a pointer, true otherwise.
6552 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6553                                         Expr* PointerExpr, SourceLocation Loc,
6554                                         bool IsIntFirstExpr) {
6555   if (!PointerExpr->getType()->isPointerType() ||
6556       !Int.get()->getType()->isIntegerType())
6557     return false;
6558 
6559   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6560   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6561 
6562   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6563     << Expr1->getType() << Expr2->getType()
6564     << Expr1->getSourceRange() << Expr2->getSourceRange();
6565   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6566                             CK_IntegralToPointer);
6567   return true;
6568 }
6569 
6570 /// Simple conversion between integer and floating point types.
6571 ///
6572 /// Used when handling the OpenCL conditional operator where the
6573 /// condition is a vector while the other operands are scalar.
6574 ///
6575 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6576 /// types are either integer or floating type. Between the two
6577 /// operands, the type with the higher rank is defined as the "result
6578 /// type". The other operand needs to be promoted to the same type. No
6579 /// other type promotion is allowed. We cannot use
6580 /// UsualArithmeticConversions() for this purpose, since it always
6581 /// promotes promotable types.
6582 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6583                                             ExprResult &RHS,
6584                                             SourceLocation QuestionLoc) {
6585   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6586   if (LHS.isInvalid())
6587     return QualType();
6588   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6589   if (RHS.isInvalid())
6590     return QualType();
6591 
6592   // For conversion purposes, we ignore any qualifiers.
6593   // For example, "const float" and "float" are equivalent.
6594   QualType LHSType =
6595     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6596   QualType RHSType =
6597     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6598 
6599   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6600     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6601       << LHSType << LHS.get()->getSourceRange();
6602     return QualType();
6603   }
6604 
6605   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6606     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6607       << RHSType << RHS.get()->getSourceRange();
6608     return QualType();
6609   }
6610 
6611   // If both types are identical, no conversion is needed.
6612   if (LHSType == RHSType)
6613     return LHSType;
6614 
6615   // Now handle "real" floating types (i.e. float, double, long double).
6616   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6617     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6618                                  /*IsCompAssign = */ false);
6619 
6620   // Finally, we have two differing integer types.
6621   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6622   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6623 }
6624 
6625 /// Convert scalar operands to a vector that matches the
6626 ///        condition in length.
6627 ///
6628 /// Used when handling the OpenCL conditional operator where the
6629 /// condition is a vector while the other operands are scalar.
6630 ///
6631 /// We first compute the "result type" for the scalar operands
6632 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6633 /// into a vector of that type where the length matches the condition
6634 /// vector type. s6.11.6 requires that the element types of the result
6635 /// and the condition must have the same number of bits.
6636 static QualType
6637 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6638                               QualType CondTy, SourceLocation QuestionLoc) {
6639   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6640   if (ResTy.isNull()) return QualType();
6641 
6642   const VectorType *CV = CondTy->getAs<VectorType>();
6643   assert(CV);
6644 
6645   // Determine the vector result type
6646   unsigned NumElements = CV->getNumElements();
6647   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6648 
6649   // Ensure that all types have the same number of bits
6650   if (S.Context.getTypeSize(CV->getElementType())
6651       != S.Context.getTypeSize(ResTy)) {
6652     // Since VectorTy is created internally, it does not pretty print
6653     // with an OpenCL name. Instead, we just print a description.
6654     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6655     SmallString<64> Str;
6656     llvm::raw_svector_ostream OS(Str);
6657     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6658     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6659       << CondTy << OS.str();
6660     return QualType();
6661   }
6662 
6663   // Convert operands to the vector result type
6664   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6665   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6666 
6667   return VectorTy;
6668 }
6669 
6670 /// Return false if this is a valid OpenCL condition vector
6671 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6672                                        SourceLocation QuestionLoc) {
6673   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6674   // integral type.
6675   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6676   assert(CondTy);
6677   QualType EleTy = CondTy->getElementType();
6678   if (EleTy->isIntegerType()) return false;
6679 
6680   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6681     << Cond->getType() << Cond->getSourceRange();
6682   return true;
6683 }
6684 
6685 /// Return false if the vector condition type and the vector
6686 ///        result type are compatible.
6687 ///
6688 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6689 /// number of elements, and their element types have the same number
6690 /// of bits.
6691 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6692                               SourceLocation QuestionLoc) {
6693   const VectorType *CV = CondTy->getAs<VectorType>();
6694   const VectorType *RV = VecResTy->getAs<VectorType>();
6695   assert(CV && RV);
6696 
6697   if (CV->getNumElements() != RV->getNumElements()) {
6698     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6699       << CondTy << VecResTy;
6700     return true;
6701   }
6702 
6703   QualType CVE = CV->getElementType();
6704   QualType RVE = RV->getElementType();
6705 
6706   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6707     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6708       << CondTy << VecResTy;
6709     return true;
6710   }
6711 
6712   return false;
6713 }
6714 
6715 /// Return the resulting type for the conditional operator in
6716 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6717 ///        s6.3.i) when the condition is a vector type.
6718 static QualType
6719 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6720                              ExprResult &LHS, ExprResult &RHS,
6721                              SourceLocation QuestionLoc) {
6722   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6723   if (Cond.isInvalid())
6724     return QualType();
6725   QualType CondTy = Cond.get()->getType();
6726 
6727   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6728     return QualType();
6729 
6730   // If either operand is a vector then find the vector type of the
6731   // result as specified in OpenCL v1.1 s6.3.i.
6732   if (LHS.get()->getType()->isVectorType() ||
6733       RHS.get()->getType()->isVectorType()) {
6734     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6735                                               /*isCompAssign*/false,
6736                                               /*AllowBothBool*/true,
6737                                               /*AllowBoolConversions*/false);
6738     if (VecResTy.isNull()) return QualType();
6739     // The result type must match the condition type as specified in
6740     // OpenCL v1.1 s6.11.6.
6741     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6742       return QualType();
6743     return VecResTy;
6744   }
6745 
6746   // Both operands are scalar.
6747   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6748 }
6749 
6750 /// Return true if the Expr is block type
6751 static bool checkBlockType(Sema &S, const Expr *E) {
6752   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6753     QualType Ty = CE->getCallee()->getType();
6754     if (Ty->isBlockPointerType()) {
6755       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6756       return true;
6757     }
6758   }
6759   return false;
6760 }
6761 
6762 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6763 /// In that case, LHS = cond.
6764 /// C99 6.5.15
6765 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6766                                         ExprResult &RHS, ExprValueKind &VK,
6767                                         ExprObjectKind &OK,
6768                                         SourceLocation QuestionLoc) {
6769 
6770   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6771   if (!LHSResult.isUsable()) return QualType();
6772   LHS = LHSResult;
6773 
6774   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6775   if (!RHSResult.isUsable()) return QualType();
6776   RHS = RHSResult;
6777 
6778   // C++ is sufficiently different to merit its own checker.
6779   if (getLangOpts().CPlusPlus)
6780     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6781 
6782   VK = VK_RValue;
6783   OK = OK_Ordinary;
6784 
6785   // The OpenCL operator with a vector condition is sufficiently
6786   // different to merit its own checker.
6787   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6788     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6789 
6790   // First, check the condition.
6791   Cond = UsualUnaryConversions(Cond.get());
6792   if (Cond.isInvalid())
6793     return QualType();
6794   if (checkCondition(*this, Cond.get(), QuestionLoc))
6795     return QualType();
6796 
6797   // Now check the two expressions.
6798   if (LHS.get()->getType()->isVectorType() ||
6799       RHS.get()->getType()->isVectorType())
6800     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6801                                /*AllowBothBool*/true,
6802                                /*AllowBoolConversions*/false);
6803 
6804   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6805   if (LHS.isInvalid() || RHS.isInvalid())
6806     return QualType();
6807 
6808   QualType LHSTy = LHS.get()->getType();
6809   QualType RHSTy = RHS.get()->getType();
6810 
6811   // Diagnose attempts to convert between __float128 and long double where
6812   // such conversions currently can't be handled.
6813   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6814     Diag(QuestionLoc,
6815          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6816       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6817     return QualType();
6818   }
6819 
6820   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6821   // selection operator (?:).
6822   if (getLangOpts().OpenCL &&
6823       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6824     return QualType();
6825   }
6826 
6827   // If both operands have arithmetic type, do the usual arithmetic conversions
6828   // to find a common type: C99 6.5.15p3,5.
6829   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6830     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6831     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6832 
6833     return ResTy;
6834   }
6835 
6836   // If both operands are the same structure or union type, the result is that
6837   // type.
6838   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6839     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6840       if (LHSRT->getDecl() == RHSRT->getDecl())
6841         // "If both the operands have structure or union type, the result has
6842         // that type."  This implies that CV qualifiers are dropped.
6843         return LHSTy.getUnqualifiedType();
6844     // FIXME: Type of conditional expression must be complete in C mode.
6845   }
6846 
6847   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6848   // The following || allows only one side to be void (a GCC-ism).
6849   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6850     return checkConditionalVoidType(*this, LHS, RHS);
6851   }
6852 
6853   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6854   // the type of the other operand."
6855   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6856   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6857 
6858   // All objective-c pointer type analysis is done here.
6859   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6860                                                         QuestionLoc);
6861   if (LHS.isInvalid() || RHS.isInvalid())
6862     return QualType();
6863   if (!compositeType.isNull())
6864     return compositeType;
6865 
6866 
6867   // Handle block pointer types.
6868   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6869     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6870                                                      QuestionLoc);
6871 
6872   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6873   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6874     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6875                                                        QuestionLoc);
6876 
6877   // GCC compatibility: soften pointer/integer mismatch.  Note that
6878   // null pointers have been filtered out by this point.
6879   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6880       /*isIntFirstExpr=*/true))
6881     return RHSTy;
6882   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6883       /*isIntFirstExpr=*/false))
6884     return LHSTy;
6885 
6886   // Emit a better diagnostic if one of the expressions is a null pointer
6887   // constant and the other is not a pointer type. In this case, the user most
6888   // likely forgot to take the address of the other expression.
6889   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6890     return QualType();
6891 
6892   // Otherwise, the operands are not compatible.
6893   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6894     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6895     << RHS.get()->getSourceRange();
6896   return QualType();
6897 }
6898 
6899 /// FindCompositeObjCPointerType - Helper method to find composite type of
6900 /// two objective-c pointer types of the two input expressions.
6901 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6902                                             SourceLocation QuestionLoc) {
6903   QualType LHSTy = LHS.get()->getType();
6904   QualType RHSTy = RHS.get()->getType();
6905 
6906   // Handle things like Class and struct objc_class*.  Here we case the result
6907   // to the pseudo-builtin, because that will be implicitly cast back to the
6908   // redefinition type if an attempt is made to access its fields.
6909   if (LHSTy->isObjCClassType() &&
6910       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6911     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6912     return LHSTy;
6913   }
6914   if (RHSTy->isObjCClassType() &&
6915       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6916     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6917     return RHSTy;
6918   }
6919   // And the same for struct objc_object* / id
6920   if (LHSTy->isObjCIdType() &&
6921       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6922     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6923     return LHSTy;
6924   }
6925   if (RHSTy->isObjCIdType() &&
6926       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6927     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6928     return RHSTy;
6929   }
6930   // And the same for struct objc_selector* / SEL
6931   if (Context.isObjCSelType(LHSTy) &&
6932       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6933     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6934     return LHSTy;
6935   }
6936   if (Context.isObjCSelType(RHSTy) &&
6937       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6938     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6939     return RHSTy;
6940   }
6941   // Check constraints for Objective-C object pointers types.
6942   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6943 
6944     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6945       // Two identical object pointer types are always compatible.
6946       return LHSTy;
6947     }
6948     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6949     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6950     QualType compositeType = LHSTy;
6951 
6952     // If both operands are interfaces and either operand can be
6953     // assigned to the other, use that type as the composite
6954     // type. This allows
6955     //   xxx ? (A*) a : (B*) b
6956     // where B is a subclass of A.
6957     //
6958     // Additionally, as for assignment, if either type is 'id'
6959     // allow silent coercion. Finally, if the types are
6960     // incompatible then make sure to use 'id' as the composite
6961     // type so the result is acceptable for sending messages to.
6962 
6963     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6964     // It could return the composite type.
6965     if (!(compositeType =
6966           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6967       // Nothing more to do.
6968     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6969       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6970     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6971       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6972     } else if ((LHSTy->isObjCQualifiedIdType() ||
6973                 RHSTy->isObjCQualifiedIdType()) &&
6974                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6975       // Need to handle "id<xx>" explicitly.
6976       // GCC allows qualified id and any Objective-C type to devolve to
6977       // id. Currently localizing to here until clear this should be
6978       // part of ObjCQualifiedIdTypesAreCompatible.
6979       compositeType = Context.getObjCIdType();
6980     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6981       compositeType = Context.getObjCIdType();
6982     } else {
6983       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6984       << LHSTy << RHSTy
6985       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6986       QualType incompatTy = Context.getObjCIdType();
6987       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6988       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6989       return incompatTy;
6990     }
6991     // The object pointer types are compatible.
6992     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6993     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6994     return compositeType;
6995   }
6996   // Check Objective-C object pointer types and 'void *'
6997   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6998     if (getLangOpts().ObjCAutoRefCount) {
6999       // ARC forbids the implicit conversion of object pointers to 'void *',
7000       // so these types are not compatible.
7001       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7002           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7003       LHS = RHS = true;
7004       return QualType();
7005     }
7006     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7007     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7008     QualType destPointee
7009     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7010     QualType destType = Context.getPointerType(destPointee);
7011     // Add qualifiers if necessary.
7012     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7013     // Promote to void*.
7014     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7015     return destType;
7016   }
7017   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7018     if (getLangOpts().ObjCAutoRefCount) {
7019       // ARC forbids the implicit conversion of object pointers to 'void *',
7020       // so these types are not compatible.
7021       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7022           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7023       LHS = RHS = true;
7024       return QualType();
7025     }
7026     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7027     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7028     QualType destPointee
7029     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7030     QualType destType = Context.getPointerType(destPointee);
7031     // Add qualifiers if necessary.
7032     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7033     // Promote to void*.
7034     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7035     return destType;
7036   }
7037   return QualType();
7038 }
7039 
7040 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7041 /// ParenRange in parentheses.
7042 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7043                                const PartialDiagnostic &Note,
7044                                SourceRange ParenRange) {
7045   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7046   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7047       EndLoc.isValid()) {
7048     Self.Diag(Loc, Note)
7049       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7050       << FixItHint::CreateInsertion(EndLoc, ")");
7051   } else {
7052     // We can't display the parentheses, so just show the bare note.
7053     Self.Diag(Loc, Note) << ParenRange;
7054   }
7055 }
7056 
7057 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7058   return BinaryOperator::isAdditiveOp(Opc) ||
7059          BinaryOperator::isMultiplicativeOp(Opc) ||
7060          BinaryOperator::isShiftOp(Opc);
7061 }
7062 
7063 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7064 /// expression, either using a built-in or overloaded operator,
7065 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7066 /// expression.
7067 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7068                                    Expr **RHSExprs) {
7069   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7070   E = E->IgnoreImpCasts();
7071   E = E->IgnoreConversionOperator();
7072   E = E->IgnoreImpCasts();
7073 
7074   // Built-in binary operator.
7075   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7076     if (IsArithmeticOp(OP->getOpcode())) {
7077       *Opcode = OP->getOpcode();
7078       *RHSExprs = OP->getRHS();
7079       return true;
7080     }
7081   }
7082 
7083   // Overloaded operator.
7084   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7085     if (Call->getNumArgs() != 2)
7086       return false;
7087 
7088     // Make sure this is really a binary operator that is safe to pass into
7089     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7090     OverloadedOperatorKind OO = Call->getOperator();
7091     if (OO < OO_Plus || OO > OO_Arrow ||
7092         OO == OO_PlusPlus || OO == OO_MinusMinus)
7093       return false;
7094 
7095     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7096     if (IsArithmeticOp(OpKind)) {
7097       *Opcode = OpKind;
7098       *RHSExprs = Call->getArg(1);
7099       return true;
7100     }
7101   }
7102 
7103   return false;
7104 }
7105 
7106 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7107 /// or is a logical expression such as (x==y) which has int type, but is
7108 /// commonly interpreted as boolean.
7109 static bool ExprLooksBoolean(Expr *E) {
7110   E = E->IgnoreParenImpCasts();
7111 
7112   if (E->getType()->isBooleanType())
7113     return true;
7114   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7115     return OP->isComparisonOp() || OP->isLogicalOp();
7116   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7117     return OP->getOpcode() == UO_LNot;
7118   if (E->getType()->isPointerType())
7119     return true;
7120 
7121   return false;
7122 }
7123 
7124 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7125 /// and binary operator are mixed in a way that suggests the programmer assumed
7126 /// the conditional operator has higher precedence, for example:
7127 /// "int x = a + someBinaryCondition ? 1 : 2".
7128 static void DiagnoseConditionalPrecedence(Sema &Self,
7129                                           SourceLocation OpLoc,
7130                                           Expr *Condition,
7131                                           Expr *LHSExpr,
7132                                           Expr *RHSExpr) {
7133   BinaryOperatorKind CondOpcode;
7134   Expr *CondRHS;
7135 
7136   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7137     return;
7138   if (!ExprLooksBoolean(CondRHS))
7139     return;
7140 
7141   // The condition is an arithmetic binary expression, with a right-
7142   // hand side that looks boolean, so warn.
7143 
7144   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7145       << Condition->getSourceRange()
7146       << BinaryOperator::getOpcodeStr(CondOpcode);
7147 
7148   SuggestParentheses(Self, OpLoc,
7149     Self.PDiag(diag::note_precedence_silence)
7150       << BinaryOperator::getOpcodeStr(CondOpcode),
7151     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7152 
7153   SuggestParentheses(Self, OpLoc,
7154     Self.PDiag(diag::note_precedence_conditional_first),
7155     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7156 }
7157 
7158 /// Compute the nullability of a conditional expression.
7159 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7160                                               QualType LHSTy, QualType RHSTy,
7161                                               ASTContext &Ctx) {
7162   if (!ResTy->isAnyPointerType())
7163     return ResTy;
7164 
7165   auto GetNullability = [&Ctx](QualType Ty) {
7166     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7167     if (Kind)
7168       return *Kind;
7169     return NullabilityKind::Unspecified;
7170   };
7171 
7172   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7173   NullabilityKind MergedKind;
7174 
7175   // Compute nullability of a binary conditional expression.
7176   if (IsBin) {
7177     if (LHSKind == NullabilityKind::NonNull)
7178       MergedKind = NullabilityKind::NonNull;
7179     else
7180       MergedKind = RHSKind;
7181   // Compute nullability of a normal conditional expression.
7182   } else {
7183     if (LHSKind == NullabilityKind::Nullable ||
7184         RHSKind == NullabilityKind::Nullable)
7185       MergedKind = NullabilityKind::Nullable;
7186     else if (LHSKind == NullabilityKind::NonNull)
7187       MergedKind = RHSKind;
7188     else if (RHSKind == NullabilityKind::NonNull)
7189       MergedKind = LHSKind;
7190     else
7191       MergedKind = NullabilityKind::Unspecified;
7192   }
7193 
7194   // Return if ResTy already has the correct nullability.
7195   if (GetNullability(ResTy) == MergedKind)
7196     return ResTy;
7197 
7198   // Strip all nullability from ResTy.
7199   while (ResTy->getNullability(Ctx))
7200     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7201 
7202   // Create a new AttributedType with the new nullability kind.
7203   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7204   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7205 }
7206 
7207 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7208 /// in the case of a the GNU conditional expr extension.
7209 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7210                                     SourceLocation ColonLoc,
7211                                     Expr *CondExpr, Expr *LHSExpr,
7212                                     Expr *RHSExpr) {
7213   if (!getLangOpts().CPlusPlus) {
7214     // C cannot handle TypoExpr nodes in the condition because it
7215     // doesn't handle dependent types properly, so make sure any TypoExprs have
7216     // been dealt with before checking the operands.
7217     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7218     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7219     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7220 
7221     if (!CondResult.isUsable())
7222       return ExprError();
7223 
7224     if (LHSExpr) {
7225       if (!LHSResult.isUsable())
7226         return ExprError();
7227     }
7228 
7229     if (!RHSResult.isUsable())
7230       return ExprError();
7231 
7232     CondExpr = CondResult.get();
7233     LHSExpr = LHSResult.get();
7234     RHSExpr = RHSResult.get();
7235   }
7236 
7237   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7238   // was the condition.
7239   OpaqueValueExpr *opaqueValue = nullptr;
7240   Expr *commonExpr = nullptr;
7241   if (!LHSExpr) {
7242     commonExpr = CondExpr;
7243     // Lower out placeholder types first.  This is important so that we don't
7244     // try to capture a placeholder. This happens in few cases in C++; such
7245     // as Objective-C++'s dictionary subscripting syntax.
7246     if (commonExpr->hasPlaceholderType()) {
7247       ExprResult result = CheckPlaceholderExpr(commonExpr);
7248       if (!result.isUsable()) return ExprError();
7249       commonExpr = result.get();
7250     }
7251     // We usually want to apply unary conversions *before* saving, except
7252     // in the special case of a C++ l-value conditional.
7253     if (!(getLangOpts().CPlusPlus
7254           && !commonExpr->isTypeDependent()
7255           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7256           && commonExpr->isGLValue()
7257           && commonExpr->isOrdinaryOrBitFieldObject()
7258           && RHSExpr->isOrdinaryOrBitFieldObject()
7259           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7260       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7261       if (commonRes.isInvalid())
7262         return ExprError();
7263       commonExpr = commonRes.get();
7264     }
7265 
7266     // If the common expression is a class or array prvalue, materialize it
7267     // so that we can safely refer to it multiple times.
7268     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7269                                    commonExpr->getType()->isArrayType())) {
7270       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7271       if (MatExpr.isInvalid())
7272         return ExprError();
7273       commonExpr = MatExpr.get();
7274     }
7275 
7276     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7277                                                 commonExpr->getType(),
7278                                                 commonExpr->getValueKind(),
7279                                                 commonExpr->getObjectKind(),
7280                                                 commonExpr);
7281     LHSExpr = CondExpr = opaqueValue;
7282   }
7283 
7284   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7285   ExprValueKind VK = VK_RValue;
7286   ExprObjectKind OK = OK_Ordinary;
7287   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7288   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7289                                              VK, OK, QuestionLoc);
7290   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7291       RHS.isInvalid())
7292     return ExprError();
7293 
7294   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7295                                 RHS.get());
7296 
7297   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7298 
7299   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7300                                          Context);
7301 
7302   if (!commonExpr)
7303     return new (Context)
7304         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7305                             RHS.get(), result, VK, OK);
7306 
7307   return new (Context) BinaryConditionalOperator(
7308       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7309       ColonLoc, result, VK, OK);
7310 }
7311 
7312 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7313 // being closely modeled after the C99 spec:-). The odd characteristic of this
7314 // routine is it effectively iqnores the qualifiers on the top level pointee.
7315 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7316 // FIXME: add a couple examples in this comment.
7317 static Sema::AssignConvertType
7318 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7319   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7320   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7321 
7322   // get the "pointed to" type (ignoring qualifiers at the top level)
7323   const Type *lhptee, *rhptee;
7324   Qualifiers lhq, rhq;
7325   std::tie(lhptee, lhq) =
7326       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7327   std::tie(rhptee, rhq) =
7328       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7329 
7330   Sema::AssignConvertType ConvTy = Sema::Compatible;
7331 
7332   // C99 6.5.16.1p1: This following citation is common to constraints
7333   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7334   // qualifiers of the type *pointed to* by the right;
7335 
7336   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7337   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7338       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7339     // Ignore lifetime for further calculation.
7340     lhq.removeObjCLifetime();
7341     rhq.removeObjCLifetime();
7342   }
7343 
7344   if (!lhq.compatiblyIncludes(rhq)) {
7345     // Treat address-space mismatches as fatal.  TODO: address subspaces
7346     if (!lhq.isAddressSpaceSupersetOf(rhq))
7347       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7348 
7349     // It's okay to add or remove GC or lifetime qualifiers when converting to
7350     // and from void*.
7351     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7352                         .compatiblyIncludes(
7353                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7354              && (lhptee->isVoidType() || rhptee->isVoidType()))
7355       ; // keep old
7356 
7357     // Treat lifetime mismatches as fatal.
7358     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7359       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7360 
7361     // For GCC/MS compatibility, other qualifier mismatches are treated
7362     // as still compatible in C.
7363     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7364   }
7365 
7366   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7367   // incomplete type and the other is a pointer to a qualified or unqualified
7368   // version of void...
7369   if (lhptee->isVoidType()) {
7370     if (rhptee->isIncompleteOrObjectType())
7371       return ConvTy;
7372 
7373     // As an extension, we allow cast to/from void* to function pointer.
7374     assert(rhptee->isFunctionType());
7375     return Sema::FunctionVoidPointer;
7376   }
7377 
7378   if (rhptee->isVoidType()) {
7379     if (lhptee->isIncompleteOrObjectType())
7380       return ConvTy;
7381 
7382     // As an extension, we allow cast to/from void* to function pointer.
7383     assert(lhptee->isFunctionType());
7384     return Sema::FunctionVoidPointer;
7385   }
7386 
7387   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7388   // unqualified versions of compatible types, ...
7389   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7390   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7391     // Check if the pointee types are compatible ignoring the sign.
7392     // We explicitly check for char so that we catch "char" vs
7393     // "unsigned char" on systems where "char" is unsigned.
7394     if (lhptee->isCharType())
7395       ltrans = S.Context.UnsignedCharTy;
7396     else if (lhptee->hasSignedIntegerRepresentation())
7397       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7398 
7399     if (rhptee->isCharType())
7400       rtrans = S.Context.UnsignedCharTy;
7401     else if (rhptee->hasSignedIntegerRepresentation())
7402       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7403 
7404     if (ltrans == rtrans) {
7405       // Types are compatible ignoring the sign. Qualifier incompatibility
7406       // takes priority over sign incompatibility because the sign
7407       // warning can be disabled.
7408       if (ConvTy != Sema::Compatible)
7409         return ConvTy;
7410 
7411       return Sema::IncompatiblePointerSign;
7412     }
7413 
7414     // If we are a multi-level pointer, it's possible that our issue is simply
7415     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7416     // the eventual target type is the same and the pointers have the same
7417     // level of indirection, this must be the issue.
7418     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7419       do {
7420         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7421         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7422       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7423 
7424       if (lhptee == rhptee)
7425         return Sema::IncompatibleNestedPointerQualifiers;
7426     }
7427 
7428     // General pointer incompatibility takes priority over qualifiers.
7429     return Sema::IncompatiblePointer;
7430   }
7431   if (!S.getLangOpts().CPlusPlus &&
7432       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7433     return Sema::IncompatiblePointer;
7434   return ConvTy;
7435 }
7436 
7437 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7438 /// block pointer types are compatible or whether a block and normal pointer
7439 /// are compatible. It is more restrict than comparing two function pointer
7440 // types.
7441 static Sema::AssignConvertType
7442 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7443                                     QualType RHSType) {
7444   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7445   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7446 
7447   QualType lhptee, rhptee;
7448 
7449   // get the "pointed to" type (ignoring qualifiers at the top level)
7450   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7451   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7452 
7453   // In C++, the types have to match exactly.
7454   if (S.getLangOpts().CPlusPlus)
7455     return Sema::IncompatibleBlockPointer;
7456 
7457   Sema::AssignConvertType ConvTy = Sema::Compatible;
7458 
7459   // For blocks we enforce that qualifiers are identical.
7460   Qualifiers LQuals = lhptee.getLocalQualifiers();
7461   Qualifiers RQuals = rhptee.getLocalQualifiers();
7462   if (S.getLangOpts().OpenCL) {
7463     LQuals.removeAddressSpace();
7464     RQuals.removeAddressSpace();
7465   }
7466   if (LQuals != RQuals)
7467     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7468 
7469   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7470   // assignment.
7471   // The current behavior is similar to C++ lambdas. A block might be
7472   // assigned to a variable iff its return type and parameters are compatible
7473   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7474   // an assignment. Presumably it should behave in way that a function pointer
7475   // assignment does in C, so for each parameter and return type:
7476   //  * CVR and address space of LHS should be a superset of CVR and address
7477   //  space of RHS.
7478   //  * unqualified types should be compatible.
7479   if (S.getLangOpts().OpenCL) {
7480     if (!S.Context.typesAreBlockPointerCompatible(
7481             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7482             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7483       return Sema::IncompatibleBlockPointer;
7484   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7485     return Sema::IncompatibleBlockPointer;
7486 
7487   return ConvTy;
7488 }
7489 
7490 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7491 /// for assignment compatibility.
7492 static Sema::AssignConvertType
7493 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7494                                    QualType RHSType) {
7495   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7496   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7497 
7498   if (LHSType->isObjCBuiltinType()) {
7499     // Class is not compatible with ObjC object pointers.
7500     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7501         !RHSType->isObjCQualifiedClassType())
7502       return Sema::IncompatiblePointer;
7503     return Sema::Compatible;
7504   }
7505   if (RHSType->isObjCBuiltinType()) {
7506     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7507         !LHSType->isObjCQualifiedClassType())
7508       return Sema::IncompatiblePointer;
7509     return Sema::Compatible;
7510   }
7511   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7512   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7513 
7514   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7515       // make an exception for id<P>
7516       !LHSType->isObjCQualifiedIdType())
7517     return Sema::CompatiblePointerDiscardsQualifiers;
7518 
7519   if (S.Context.typesAreCompatible(LHSType, RHSType))
7520     return Sema::Compatible;
7521   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7522     return Sema::IncompatibleObjCQualifiedId;
7523   return Sema::IncompatiblePointer;
7524 }
7525 
7526 Sema::AssignConvertType
7527 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7528                                  QualType LHSType, QualType RHSType) {
7529   // Fake up an opaque expression.  We don't actually care about what
7530   // cast operations are required, so if CheckAssignmentConstraints
7531   // adds casts to this they'll be wasted, but fortunately that doesn't
7532   // usually happen on valid code.
7533   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7534   ExprResult RHSPtr = &RHSExpr;
7535   CastKind K;
7536 
7537   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7538 }
7539 
7540 /// This helper function returns true if QT is a vector type that has element
7541 /// type ElementType.
7542 static bool isVector(QualType QT, QualType ElementType) {
7543   if (const VectorType *VT = QT->getAs<VectorType>())
7544     return VT->getElementType() == ElementType;
7545   return false;
7546 }
7547 
7548 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7549 /// has code to accommodate several GCC extensions when type checking
7550 /// pointers. Here are some objectionable examples that GCC considers warnings:
7551 ///
7552 ///  int a, *pint;
7553 ///  short *pshort;
7554 ///  struct foo *pfoo;
7555 ///
7556 ///  pint = pshort; // warning: assignment from incompatible pointer type
7557 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7558 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7559 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7560 ///
7561 /// As a result, the code for dealing with pointers is more complex than the
7562 /// C99 spec dictates.
7563 ///
7564 /// Sets 'Kind' for any result kind except Incompatible.
7565 Sema::AssignConvertType
7566 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7567                                  CastKind &Kind, bool ConvertRHS) {
7568   QualType RHSType = RHS.get()->getType();
7569   QualType OrigLHSType = LHSType;
7570 
7571   // Get canonical types.  We're not formatting these types, just comparing
7572   // them.
7573   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7574   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7575 
7576   // Common case: no conversion required.
7577   if (LHSType == RHSType) {
7578     Kind = CK_NoOp;
7579     return Compatible;
7580   }
7581 
7582   // If we have an atomic type, try a non-atomic assignment, then just add an
7583   // atomic qualification step.
7584   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7585     Sema::AssignConvertType result =
7586       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7587     if (result != Compatible)
7588       return result;
7589     if (Kind != CK_NoOp && ConvertRHS)
7590       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7591     Kind = CK_NonAtomicToAtomic;
7592     return Compatible;
7593   }
7594 
7595   // If the left-hand side is a reference type, then we are in a
7596   // (rare!) case where we've allowed the use of references in C,
7597   // e.g., as a parameter type in a built-in function. In this case,
7598   // just make sure that the type referenced is compatible with the
7599   // right-hand side type. The caller is responsible for adjusting
7600   // LHSType so that the resulting expression does not have reference
7601   // type.
7602   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7603     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7604       Kind = CK_LValueBitCast;
7605       return Compatible;
7606     }
7607     return Incompatible;
7608   }
7609 
7610   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7611   // to the same ExtVector type.
7612   if (LHSType->isExtVectorType()) {
7613     if (RHSType->isExtVectorType())
7614       return Incompatible;
7615     if (RHSType->isArithmeticType()) {
7616       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7617       if (ConvertRHS)
7618         RHS = prepareVectorSplat(LHSType, RHS.get());
7619       Kind = CK_VectorSplat;
7620       return Compatible;
7621     }
7622   }
7623 
7624   // Conversions to or from vector type.
7625   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7626     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7627       // Allow assignments of an AltiVec vector type to an equivalent GCC
7628       // vector type and vice versa
7629       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7630         Kind = CK_BitCast;
7631         return Compatible;
7632       }
7633 
7634       // If we are allowing lax vector conversions, and LHS and RHS are both
7635       // vectors, the total size only needs to be the same. This is a bitcast;
7636       // no bits are changed but the result type is different.
7637       if (isLaxVectorConversion(RHSType, LHSType)) {
7638         Kind = CK_BitCast;
7639         return IncompatibleVectors;
7640       }
7641     }
7642 
7643     // When the RHS comes from another lax conversion (e.g. binops between
7644     // scalars and vectors) the result is canonicalized as a vector. When the
7645     // LHS is also a vector, the lax is allowed by the condition above. Handle
7646     // the case where LHS is a scalar.
7647     if (LHSType->isScalarType()) {
7648       const VectorType *VecType = RHSType->getAs<VectorType>();
7649       if (VecType && VecType->getNumElements() == 1 &&
7650           isLaxVectorConversion(RHSType, LHSType)) {
7651         ExprResult *VecExpr = &RHS;
7652         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7653         Kind = CK_BitCast;
7654         return Compatible;
7655       }
7656     }
7657 
7658     return Incompatible;
7659   }
7660 
7661   // Diagnose attempts to convert between __float128 and long double where
7662   // such conversions currently can't be handled.
7663   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7664     return Incompatible;
7665 
7666   // Disallow assigning a _Complex to a real type in C++ mode since it simply
7667   // discards the imaginary part.
7668   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7669       !LHSType->getAs<ComplexType>())
7670     return Incompatible;
7671 
7672   // Arithmetic conversions.
7673   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7674       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7675     if (ConvertRHS)
7676       Kind = PrepareScalarCast(RHS, LHSType);
7677     return Compatible;
7678   }
7679 
7680   // Conversions to normal pointers.
7681   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7682     // U* -> T*
7683     if (isa<PointerType>(RHSType)) {
7684       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7685       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7686       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7687       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7688     }
7689 
7690     // int -> T*
7691     if (RHSType->isIntegerType()) {
7692       Kind = CK_IntegralToPointer; // FIXME: null?
7693       return IntToPointer;
7694     }
7695 
7696     // C pointers are not compatible with ObjC object pointers,
7697     // with two exceptions:
7698     if (isa<ObjCObjectPointerType>(RHSType)) {
7699       //  - conversions to void*
7700       if (LHSPointer->getPointeeType()->isVoidType()) {
7701         Kind = CK_BitCast;
7702         return Compatible;
7703       }
7704 
7705       //  - conversions from 'Class' to the redefinition type
7706       if (RHSType->isObjCClassType() &&
7707           Context.hasSameType(LHSType,
7708                               Context.getObjCClassRedefinitionType())) {
7709         Kind = CK_BitCast;
7710         return Compatible;
7711       }
7712 
7713       Kind = CK_BitCast;
7714       return IncompatiblePointer;
7715     }
7716 
7717     // U^ -> void*
7718     if (RHSType->getAs<BlockPointerType>()) {
7719       if (LHSPointer->getPointeeType()->isVoidType()) {
7720         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7721         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7722                                 ->getPointeeType()
7723                                 .getAddressSpace();
7724         Kind =
7725             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7726         return Compatible;
7727       }
7728     }
7729 
7730     return Incompatible;
7731   }
7732 
7733   // Conversions to block pointers.
7734   if (isa<BlockPointerType>(LHSType)) {
7735     // U^ -> T^
7736     if (RHSType->isBlockPointerType()) {
7737       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7738                               ->getPointeeType()
7739                               .getAddressSpace();
7740       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7741                               ->getPointeeType()
7742                               .getAddressSpace();
7743       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7744       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7745     }
7746 
7747     // int or null -> T^
7748     if (RHSType->isIntegerType()) {
7749       Kind = CK_IntegralToPointer; // FIXME: null
7750       return IntToBlockPointer;
7751     }
7752 
7753     // id -> T^
7754     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7755       Kind = CK_AnyPointerToBlockPointerCast;
7756       return Compatible;
7757     }
7758 
7759     // void* -> T^
7760     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7761       if (RHSPT->getPointeeType()->isVoidType()) {
7762         Kind = CK_AnyPointerToBlockPointerCast;
7763         return Compatible;
7764       }
7765 
7766     return Incompatible;
7767   }
7768 
7769   // Conversions to Objective-C pointers.
7770   if (isa<ObjCObjectPointerType>(LHSType)) {
7771     // A* -> B*
7772     if (RHSType->isObjCObjectPointerType()) {
7773       Kind = CK_BitCast;
7774       Sema::AssignConvertType result =
7775         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7776       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7777           result == Compatible &&
7778           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7779         result = IncompatibleObjCWeakRef;
7780       return result;
7781     }
7782 
7783     // int or null -> A*
7784     if (RHSType->isIntegerType()) {
7785       Kind = CK_IntegralToPointer; // FIXME: null
7786       return IntToPointer;
7787     }
7788 
7789     // In general, C pointers are not compatible with ObjC object pointers,
7790     // with two exceptions:
7791     if (isa<PointerType>(RHSType)) {
7792       Kind = CK_CPointerToObjCPointerCast;
7793 
7794       //  - conversions from 'void*'
7795       if (RHSType->isVoidPointerType()) {
7796         return Compatible;
7797       }
7798 
7799       //  - conversions to 'Class' from its redefinition type
7800       if (LHSType->isObjCClassType() &&
7801           Context.hasSameType(RHSType,
7802                               Context.getObjCClassRedefinitionType())) {
7803         return Compatible;
7804       }
7805 
7806       return IncompatiblePointer;
7807     }
7808 
7809     // Only under strict condition T^ is compatible with an Objective-C pointer.
7810     if (RHSType->isBlockPointerType() &&
7811         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7812       if (ConvertRHS)
7813         maybeExtendBlockObject(RHS);
7814       Kind = CK_BlockPointerToObjCPointerCast;
7815       return Compatible;
7816     }
7817 
7818     return Incompatible;
7819   }
7820 
7821   // Conversions from pointers that are not covered by the above.
7822   if (isa<PointerType>(RHSType)) {
7823     // T* -> _Bool
7824     if (LHSType == Context.BoolTy) {
7825       Kind = CK_PointerToBoolean;
7826       return Compatible;
7827     }
7828 
7829     // T* -> int
7830     if (LHSType->isIntegerType()) {
7831       Kind = CK_PointerToIntegral;
7832       return PointerToInt;
7833     }
7834 
7835     return Incompatible;
7836   }
7837 
7838   // Conversions from Objective-C pointers that are not covered by the above.
7839   if (isa<ObjCObjectPointerType>(RHSType)) {
7840     // T* -> _Bool
7841     if (LHSType == Context.BoolTy) {
7842       Kind = CK_PointerToBoolean;
7843       return Compatible;
7844     }
7845 
7846     // T* -> int
7847     if (LHSType->isIntegerType()) {
7848       Kind = CK_PointerToIntegral;
7849       return PointerToInt;
7850     }
7851 
7852     return Incompatible;
7853   }
7854 
7855   // struct A -> struct B
7856   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7857     if (Context.typesAreCompatible(LHSType, RHSType)) {
7858       Kind = CK_NoOp;
7859       return Compatible;
7860     }
7861   }
7862 
7863   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7864     Kind = CK_IntToOCLSampler;
7865     return Compatible;
7866   }
7867 
7868   return Incompatible;
7869 }
7870 
7871 /// Constructs a transparent union from an expression that is
7872 /// used to initialize the transparent union.
7873 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7874                                       ExprResult &EResult, QualType UnionType,
7875                                       FieldDecl *Field) {
7876   // Build an initializer list that designates the appropriate member
7877   // of the transparent union.
7878   Expr *E = EResult.get();
7879   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7880                                                    E, SourceLocation());
7881   Initializer->setType(UnionType);
7882   Initializer->setInitializedFieldInUnion(Field);
7883 
7884   // Build a compound literal constructing a value of the transparent
7885   // union type from this initializer list.
7886   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7887   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7888                                         VK_RValue, Initializer, false);
7889 }
7890 
7891 Sema::AssignConvertType
7892 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7893                                                ExprResult &RHS) {
7894   QualType RHSType = RHS.get()->getType();
7895 
7896   // If the ArgType is a Union type, we want to handle a potential
7897   // transparent_union GCC extension.
7898   const RecordType *UT = ArgType->getAsUnionType();
7899   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7900     return Incompatible;
7901 
7902   // The field to initialize within the transparent union.
7903   RecordDecl *UD = UT->getDecl();
7904   FieldDecl *InitField = nullptr;
7905   // It's compatible if the expression matches any of the fields.
7906   for (auto *it : UD->fields()) {
7907     if (it->getType()->isPointerType()) {
7908       // If the transparent union contains a pointer type, we allow:
7909       // 1) void pointer
7910       // 2) null pointer constant
7911       if (RHSType->isPointerType())
7912         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7913           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7914           InitField = it;
7915           break;
7916         }
7917 
7918       if (RHS.get()->isNullPointerConstant(Context,
7919                                            Expr::NPC_ValueDependentIsNull)) {
7920         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7921                                 CK_NullToPointer);
7922         InitField = it;
7923         break;
7924       }
7925     }
7926 
7927     CastKind Kind;
7928     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7929           == Compatible) {
7930       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7931       InitField = it;
7932       break;
7933     }
7934   }
7935 
7936   if (!InitField)
7937     return Incompatible;
7938 
7939   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7940   return Compatible;
7941 }
7942 
7943 Sema::AssignConvertType
7944 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7945                                        bool Diagnose,
7946                                        bool DiagnoseCFAudited,
7947                                        bool ConvertRHS) {
7948   // We need to be able to tell the caller whether we diagnosed a problem, if
7949   // they ask us to issue diagnostics.
7950   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7951 
7952   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7953   // we can't avoid *all* modifications at the moment, so we need some somewhere
7954   // to put the updated value.
7955   ExprResult LocalRHS = CallerRHS;
7956   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7957 
7958   if (getLangOpts().CPlusPlus) {
7959     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7960       // C++ 5.17p3: If the left operand is not of class type, the
7961       // expression is implicitly converted (C++ 4) to the
7962       // cv-unqualified type of the left operand.
7963       QualType RHSType = RHS.get()->getType();
7964       if (Diagnose) {
7965         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7966                                         AA_Assigning);
7967       } else {
7968         ImplicitConversionSequence ICS =
7969             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7970                                   /*SuppressUserConversions=*/false,
7971                                   /*AllowExplicit=*/false,
7972                                   /*InOverloadResolution=*/false,
7973                                   /*CStyle=*/false,
7974                                   /*AllowObjCWritebackConversion=*/false);
7975         if (ICS.isFailure())
7976           return Incompatible;
7977         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7978                                         ICS, AA_Assigning);
7979       }
7980       if (RHS.isInvalid())
7981         return Incompatible;
7982       Sema::AssignConvertType result = Compatible;
7983       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7984           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7985         result = IncompatibleObjCWeakRef;
7986       return result;
7987     }
7988 
7989     // FIXME: Currently, we fall through and treat C++ classes like C
7990     // structures.
7991     // FIXME: We also fall through for atomics; not sure what should
7992     // happen there, though.
7993   } else if (RHS.get()->getType() == Context.OverloadTy) {
7994     // As a set of extensions to C, we support overloading on functions. These
7995     // functions need to be resolved here.
7996     DeclAccessPair DAP;
7997     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7998             RHS.get(), LHSType, /*Complain=*/false, DAP))
7999       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8000     else
8001       return Incompatible;
8002   }
8003 
8004   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8005   // a null pointer constant.
8006   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8007        LHSType->isBlockPointerType()) &&
8008       RHS.get()->isNullPointerConstant(Context,
8009                                        Expr::NPC_ValueDependentIsNull)) {
8010     if (Diagnose || ConvertRHS) {
8011       CastKind Kind;
8012       CXXCastPath Path;
8013       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8014                              /*IgnoreBaseAccess=*/false, Diagnose);
8015       if (ConvertRHS)
8016         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8017     }
8018     return Compatible;
8019   }
8020 
8021   // This check seems unnatural, however it is necessary to ensure the proper
8022   // conversion of functions/arrays. If the conversion were done for all
8023   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8024   // expressions that suppress this implicit conversion (&, sizeof).
8025   //
8026   // Suppress this for references: C++ 8.5.3p5.
8027   if (!LHSType->isReferenceType()) {
8028     // FIXME: We potentially allocate here even if ConvertRHS is false.
8029     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8030     if (RHS.isInvalid())
8031       return Incompatible;
8032   }
8033 
8034   Expr *PRE = RHS.get()->IgnoreParenCasts();
8035   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
8036     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
8037     if (PDecl && !PDecl->hasDefinition()) {
8038       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl;
8039       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
8040     }
8041   }
8042 
8043   CastKind Kind;
8044   Sema::AssignConvertType result =
8045     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8046 
8047   // C99 6.5.16.1p2: The value of the right operand is converted to the
8048   // type of the assignment expression.
8049   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8050   // so that we can use references in built-in functions even in C.
8051   // The getNonReferenceType() call makes sure that the resulting expression
8052   // does not have reference type.
8053   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8054     QualType Ty = LHSType.getNonLValueExprType(Context);
8055     Expr *E = RHS.get();
8056 
8057     // Check for various Objective-C errors. If we are not reporting
8058     // diagnostics and just checking for errors, e.g., during overload
8059     // resolution, return Incompatible to indicate the failure.
8060     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8061         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8062                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8063       if (!Diagnose)
8064         return Incompatible;
8065     }
8066     if (getLangOpts().ObjC1 &&
8067         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8068                                            E->getType(), E, Diagnose) ||
8069          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8070       if (!Diagnose)
8071         return Incompatible;
8072       // Replace the expression with a corrected version and continue so we
8073       // can find further errors.
8074       RHS = E;
8075       return Compatible;
8076     }
8077 
8078     if (ConvertRHS)
8079       RHS = ImpCastExprToType(E, Ty, Kind);
8080   }
8081   return result;
8082 }
8083 
8084 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8085                                ExprResult &RHS) {
8086   Diag(Loc, diag::err_typecheck_invalid_operands)
8087     << LHS.get()->getType() << RHS.get()->getType()
8088     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8089   return QualType();
8090 }
8091 
8092 // Diagnose cases where a scalar was implicitly converted to a vector and
8093 // diagnose the underlying types. Otherwise, diagnose the error
8094 // as invalid vector logical operands for non-C++ cases.
8095 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8096                                             ExprResult &RHS) {
8097   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8098   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8099 
8100   bool LHSNatVec = LHSType->isVectorType();
8101   bool RHSNatVec = RHSType->isVectorType();
8102 
8103   if (!(LHSNatVec && RHSNatVec)) {
8104     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8105     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8106     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8107         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8108         << Vector->getSourceRange();
8109     return QualType();
8110   }
8111 
8112   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8113       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8114       << RHS.get()->getSourceRange();
8115 
8116   return QualType();
8117 }
8118 
8119 /// Try to convert a value of non-vector type to a vector type by converting
8120 /// the type to the element type of the vector and then performing a splat.
8121 /// If the language is OpenCL, we only use conversions that promote scalar
8122 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8123 /// for float->int.
8124 ///
8125 /// OpenCL V2.0 6.2.6.p2:
8126 /// An error shall occur if any scalar operand type has greater rank
8127 /// than the type of the vector element.
8128 ///
8129 /// \param scalar - if non-null, actually perform the conversions
8130 /// \return true if the operation fails (but without diagnosing the failure)
8131 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8132                                      QualType scalarTy,
8133                                      QualType vectorEltTy,
8134                                      QualType vectorTy,
8135                                      unsigned &DiagID) {
8136   // The conversion to apply to the scalar before splatting it,
8137   // if necessary.
8138   CastKind scalarCast = CK_NoOp;
8139 
8140   if (vectorEltTy->isIntegralType(S.Context)) {
8141     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8142         (scalarTy->isIntegerType() &&
8143          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8144       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8145       return true;
8146     }
8147     if (!scalarTy->isIntegralType(S.Context))
8148       return true;
8149     scalarCast = CK_IntegralCast;
8150   } else if (vectorEltTy->isRealFloatingType()) {
8151     if (scalarTy->isRealFloatingType()) {
8152       if (S.getLangOpts().OpenCL &&
8153           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8154         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8155         return true;
8156       }
8157       scalarCast = CK_FloatingCast;
8158     }
8159     else if (scalarTy->isIntegralType(S.Context))
8160       scalarCast = CK_IntegralToFloating;
8161     else
8162       return true;
8163   } else {
8164     return true;
8165   }
8166 
8167   // Adjust scalar if desired.
8168   if (scalar) {
8169     if (scalarCast != CK_NoOp)
8170       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8171     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8172   }
8173   return false;
8174 }
8175 
8176 /// Convert vector E to a vector with the same number of elements but different
8177 /// element type.
8178 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8179   const auto *VecTy = E->getType()->getAs<VectorType>();
8180   assert(VecTy && "Expression E must be a vector");
8181   QualType NewVecTy = S.Context.getVectorType(ElementType,
8182                                               VecTy->getNumElements(),
8183                                               VecTy->getVectorKind());
8184 
8185   // Look through the implicit cast. Return the subexpression if its type is
8186   // NewVecTy.
8187   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8188     if (ICE->getSubExpr()->getType() == NewVecTy)
8189       return ICE->getSubExpr();
8190 
8191   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8192   return S.ImpCastExprToType(E, NewVecTy, Cast);
8193 }
8194 
8195 /// Test if a (constant) integer Int can be casted to another integer type
8196 /// IntTy without losing precision.
8197 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8198                                       QualType OtherIntTy) {
8199   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8200 
8201   // Reject cases where the value of the Int is unknown as that would
8202   // possibly cause truncation, but accept cases where the scalar can be
8203   // demoted without loss of precision.
8204   llvm::APSInt Result;
8205   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8206   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8207   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8208   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8209 
8210   if (CstInt) {
8211     // If the scalar is constant and is of a higher order and has more active
8212     // bits that the vector element type, reject it.
8213     unsigned NumBits = IntSigned
8214                            ? (Result.isNegative() ? Result.getMinSignedBits()
8215                                                   : Result.getActiveBits())
8216                            : Result.getActiveBits();
8217     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8218       return true;
8219 
8220     // If the signedness of the scalar type and the vector element type
8221     // differs and the number of bits is greater than that of the vector
8222     // element reject it.
8223     return (IntSigned != OtherIntSigned &&
8224             NumBits > S.Context.getIntWidth(OtherIntTy));
8225   }
8226 
8227   // Reject cases where the value of the scalar is not constant and it's
8228   // order is greater than that of the vector element type.
8229   return (Order < 0);
8230 }
8231 
8232 /// Test if a (constant) integer Int can be casted to floating point type
8233 /// FloatTy without losing precision.
8234 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8235                                      QualType FloatTy) {
8236   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8237 
8238   // Determine if the integer constant can be expressed as a floating point
8239   // number of the appropriate type.
8240   llvm::APSInt Result;
8241   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8242   uint64_t Bits = 0;
8243   if (CstInt) {
8244     // Reject constants that would be truncated if they were converted to
8245     // the floating point type. Test by simple to/from conversion.
8246     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8247     //        could be avoided if there was a convertFromAPInt method
8248     //        which could signal back if implicit truncation occurred.
8249     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8250     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8251                            llvm::APFloat::rmTowardZero);
8252     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8253                              !IntTy->hasSignedIntegerRepresentation());
8254     bool Ignored = false;
8255     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8256                            &Ignored);
8257     if (Result != ConvertBack)
8258       return true;
8259   } else {
8260     // Reject types that cannot be fully encoded into the mantissa of
8261     // the float.
8262     Bits = S.Context.getTypeSize(IntTy);
8263     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8264         S.Context.getFloatTypeSemantics(FloatTy));
8265     if (Bits > FloatPrec)
8266       return true;
8267   }
8268 
8269   return false;
8270 }
8271 
8272 /// Attempt to convert and splat Scalar into a vector whose types matches
8273 /// Vector following GCC conversion rules. The rule is that implicit
8274 /// conversion can occur when Scalar can be casted to match Vector's element
8275 /// type without causing truncation of Scalar.
8276 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8277                                         ExprResult *Vector) {
8278   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8279   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8280   const VectorType *VT = VectorTy->getAs<VectorType>();
8281 
8282   assert(!isa<ExtVectorType>(VT) &&
8283          "ExtVectorTypes should not be handled here!");
8284 
8285   QualType VectorEltTy = VT->getElementType();
8286 
8287   // Reject cases where the vector element type or the scalar element type are
8288   // not integral or floating point types.
8289   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8290     return true;
8291 
8292   // The conversion to apply to the scalar before splatting it,
8293   // if necessary.
8294   CastKind ScalarCast = CK_NoOp;
8295 
8296   // Accept cases where the vector elements are integers and the scalar is
8297   // an integer.
8298   // FIXME: Notionally if the scalar was a floating point value with a precise
8299   //        integral representation, we could cast it to an appropriate integer
8300   //        type and then perform the rest of the checks here. GCC will perform
8301   //        this conversion in some cases as determined by the input language.
8302   //        We should accept it on a language independent basis.
8303   if (VectorEltTy->isIntegralType(S.Context) &&
8304       ScalarTy->isIntegralType(S.Context) &&
8305       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8306 
8307     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8308       return true;
8309 
8310     ScalarCast = CK_IntegralCast;
8311   } else if (VectorEltTy->isRealFloatingType()) {
8312     if (ScalarTy->isRealFloatingType()) {
8313 
8314       // Reject cases where the scalar type is not a constant and has a higher
8315       // Order than the vector element type.
8316       llvm::APFloat Result(0.0);
8317       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8318       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8319       if (!CstScalar && Order < 0)
8320         return true;
8321 
8322       // If the scalar cannot be safely casted to the vector element type,
8323       // reject it.
8324       if (CstScalar) {
8325         bool Truncated = false;
8326         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8327                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8328         if (Truncated)
8329           return true;
8330       }
8331 
8332       ScalarCast = CK_FloatingCast;
8333     } else if (ScalarTy->isIntegralType(S.Context)) {
8334       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8335         return true;
8336 
8337       ScalarCast = CK_IntegralToFloating;
8338     } else
8339       return true;
8340   }
8341 
8342   // Adjust scalar if desired.
8343   if (Scalar) {
8344     if (ScalarCast != CK_NoOp)
8345       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8346     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8347   }
8348   return false;
8349 }
8350 
8351 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8352                                    SourceLocation Loc, bool IsCompAssign,
8353                                    bool AllowBothBool,
8354                                    bool AllowBoolConversions) {
8355   if (!IsCompAssign) {
8356     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8357     if (LHS.isInvalid())
8358       return QualType();
8359   }
8360   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8361   if (RHS.isInvalid())
8362     return QualType();
8363 
8364   // For conversion purposes, we ignore any qualifiers.
8365   // For example, "const float" and "float" are equivalent.
8366   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8367   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8368 
8369   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8370   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8371   assert(LHSVecType || RHSVecType);
8372 
8373   // AltiVec-style "vector bool op vector bool" combinations are allowed
8374   // for some operators but not others.
8375   if (!AllowBothBool &&
8376       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8377       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8378     return InvalidOperands(Loc, LHS, RHS);
8379 
8380   // If the vector types are identical, return.
8381   if (Context.hasSameType(LHSType, RHSType))
8382     return LHSType;
8383 
8384   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8385   if (LHSVecType && RHSVecType &&
8386       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8387     if (isa<ExtVectorType>(LHSVecType)) {
8388       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8389       return LHSType;
8390     }
8391 
8392     if (!IsCompAssign)
8393       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8394     return RHSType;
8395   }
8396 
8397   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8398   // can be mixed, with the result being the non-bool type.  The non-bool
8399   // operand must have integer element type.
8400   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8401       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8402       (Context.getTypeSize(LHSVecType->getElementType()) ==
8403        Context.getTypeSize(RHSVecType->getElementType()))) {
8404     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8405         LHSVecType->getElementType()->isIntegerType() &&
8406         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8407       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8408       return LHSType;
8409     }
8410     if (!IsCompAssign &&
8411         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8412         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8413         RHSVecType->getElementType()->isIntegerType()) {
8414       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8415       return RHSType;
8416     }
8417   }
8418 
8419   // If there's a vector type and a scalar, try to convert the scalar to
8420   // the vector element type and splat.
8421   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8422   if (!RHSVecType) {
8423     if (isa<ExtVectorType>(LHSVecType)) {
8424       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8425                                     LHSVecType->getElementType(), LHSType,
8426                                     DiagID))
8427         return LHSType;
8428     } else {
8429       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8430         return LHSType;
8431     }
8432   }
8433   if (!LHSVecType) {
8434     if (isa<ExtVectorType>(RHSVecType)) {
8435       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8436                                     LHSType, RHSVecType->getElementType(),
8437                                     RHSType, DiagID))
8438         return RHSType;
8439     } else {
8440       if (LHS.get()->getValueKind() == VK_LValue ||
8441           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8442         return RHSType;
8443     }
8444   }
8445 
8446   // FIXME: The code below also handles conversion between vectors and
8447   // non-scalars, we should break this down into fine grained specific checks
8448   // and emit proper diagnostics.
8449   QualType VecType = LHSVecType ? LHSType : RHSType;
8450   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8451   QualType OtherType = LHSVecType ? RHSType : LHSType;
8452   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8453   if (isLaxVectorConversion(OtherType, VecType)) {
8454     // If we're allowing lax vector conversions, only the total (data) size
8455     // needs to be the same. For non compound assignment, if one of the types is
8456     // scalar, the result is always the vector type.
8457     if (!IsCompAssign) {
8458       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8459       return VecType;
8460     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8461     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8462     // type. Note that this is already done by non-compound assignments in
8463     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8464     // <1 x T> -> T. The result is also a vector type.
8465     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8466                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8467       ExprResult *RHSExpr = &RHS;
8468       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8469       return VecType;
8470     }
8471   }
8472 
8473   // Okay, the expression is invalid.
8474 
8475   // If there's a non-vector, non-real operand, diagnose that.
8476   if ((!RHSVecType && !RHSType->isRealType()) ||
8477       (!LHSVecType && !LHSType->isRealType())) {
8478     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8479       << LHSType << RHSType
8480       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8481     return QualType();
8482   }
8483 
8484   // OpenCL V1.1 6.2.6.p1:
8485   // If the operands are of more than one vector type, then an error shall
8486   // occur. Implicit conversions between vector types are not permitted, per
8487   // section 6.2.1.
8488   if (getLangOpts().OpenCL &&
8489       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8490       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8491     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8492                                                            << RHSType;
8493     return QualType();
8494   }
8495 
8496 
8497   // If there is a vector type that is not a ExtVector and a scalar, we reach
8498   // this point if scalar could not be converted to the vector's element type
8499   // without truncation.
8500   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8501       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8502     QualType Scalar = LHSVecType ? RHSType : LHSType;
8503     QualType Vector = LHSVecType ? LHSType : RHSType;
8504     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8505     Diag(Loc,
8506          diag::err_typecheck_vector_not_convertable_implict_truncation)
8507         << ScalarOrVector << Scalar << Vector;
8508 
8509     return QualType();
8510   }
8511 
8512   // Otherwise, use the generic diagnostic.
8513   Diag(Loc, DiagID)
8514     << LHSType << RHSType
8515     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8516   return QualType();
8517 }
8518 
8519 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8520 // expression.  These are mainly cases where the null pointer is used as an
8521 // integer instead of a pointer.
8522 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8523                                 SourceLocation Loc, bool IsCompare) {
8524   // The canonical way to check for a GNU null is with isNullPointerConstant,
8525   // but we use a bit of a hack here for speed; this is a relatively
8526   // hot path, and isNullPointerConstant is slow.
8527   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8528   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8529 
8530   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8531 
8532   // Avoid analyzing cases where the result will either be invalid (and
8533   // diagnosed as such) or entirely valid and not something to warn about.
8534   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8535       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8536     return;
8537 
8538   // Comparison operations would not make sense with a null pointer no matter
8539   // what the other expression is.
8540   if (!IsCompare) {
8541     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8542         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8543         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8544     return;
8545   }
8546 
8547   // The rest of the operations only make sense with a null pointer
8548   // if the other expression is a pointer.
8549   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8550       NonNullType->canDecayToPointerType())
8551     return;
8552 
8553   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8554       << LHSNull /* LHS is NULL */ << NonNullType
8555       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8556 }
8557 
8558 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8559                                                ExprResult &RHS,
8560                                                SourceLocation Loc, bool IsDiv) {
8561   // Check for division/remainder by zero.
8562   llvm::APSInt RHSValue;
8563   if (!RHS.get()->isValueDependent() &&
8564       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8565     S.DiagRuntimeBehavior(Loc, RHS.get(),
8566                           S.PDiag(diag::warn_remainder_division_by_zero)
8567                             << IsDiv << RHS.get()->getSourceRange());
8568 }
8569 
8570 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8571                                            SourceLocation Loc,
8572                                            bool IsCompAssign, bool IsDiv) {
8573   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8574 
8575   if (LHS.get()->getType()->isVectorType() ||
8576       RHS.get()->getType()->isVectorType())
8577     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8578                                /*AllowBothBool*/getLangOpts().AltiVec,
8579                                /*AllowBoolConversions*/false);
8580 
8581   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8582   if (LHS.isInvalid() || RHS.isInvalid())
8583     return QualType();
8584 
8585 
8586   if (compType.isNull() || !compType->isArithmeticType())
8587     return InvalidOperands(Loc, LHS, RHS);
8588   if (IsDiv)
8589     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8590   return compType;
8591 }
8592 
8593 QualType Sema::CheckRemainderOperands(
8594   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8595   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8596 
8597   if (LHS.get()->getType()->isVectorType() ||
8598       RHS.get()->getType()->isVectorType()) {
8599     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8600         RHS.get()->getType()->hasIntegerRepresentation())
8601       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8602                                  /*AllowBothBool*/getLangOpts().AltiVec,
8603                                  /*AllowBoolConversions*/false);
8604     return InvalidOperands(Loc, LHS, RHS);
8605   }
8606 
8607   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8608   if (LHS.isInvalid() || RHS.isInvalid())
8609     return QualType();
8610 
8611   if (compType.isNull() || !compType->isIntegerType())
8612     return InvalidOperands(Loc, LHS, RHS);
8613   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8614   return compType;
8615 }
8616 
8617 /// Diagnose invalid arithmetic on two void pointers.
8618 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8619                                                 Expr *LHSExpr, Expr *RHSExpr) {
8620   S.Diag(Loc, S.getLangOpts().CPlusPlus
8621                 ? diag::err_typecheck_pointer_arith_void_type
8622                 : diag::ext_gnu_void_ptr)
8623     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8624                             << RHSExpr->getSourceRange();
8625 }
8626 
8627 /// Diagnose invalid arithmetic on a void pointer.
8628 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8629                                             Expr *Pointer) {
8630   S.Diag(Loc, S.getLangOpts().CPlusPlus
8631                 ? diag::err_typecheck_pointer_arith_void_type
8632                 : diag::ext_gnu_void_ptr)
8633     << 0 /* one pointer */ << Pointer->getSourceRange();
8634 }
8635 
8636 /// Diagnose invalid arithmetic on a null pointer.
8637 ///
8638 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8639 /// idiom, which we recognize as a GNU extension.
8640 ///
8641 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8642                                             Expr *Pointer, bool IsGNUIdiom) {
8643   if (IsGNUIdiom)
8644     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8645       << Pointer->getSourceRange();
8646   else
8647     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8648       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8649 }
8650 
8651 /// Diagnose invalid arithmetic on two function pointers.
8652 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8653                                                     Expr *LHS, Expr *RHS) {
8654   assert(LHS->getType()->isAnyPointerType());
8655   assert(RHS->getType()->isAnyPointerType());
8656   S.Diag(Loc, S.getLangOpts().CPlusPlus
8657                 ? diag::err_typecheck_pointer_arith_function_type
8658                 : diag::ext_gnu_ptr_func_arith)
8659     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8660     // We only show the second type if it differs from the first.
8661     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8662                                                    RHS->getType())
8663     << RHS->getType()->getPointeeType()
8664     << LHS->getSourceRange() << RHS->getSourceRange();
8665 }
8666 
8667 /// Diagnose invalid arithmetic on a function pointer.
8668 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8669                                                 Expr *Pointer) {
8670   assert(Pointer->getType()->isAnyPointerType());
8671   S.Diag(Loc, S.getLangOpts().CPlusPlus
8672                 ? diag::err_typecheck_pointer_arith_function_type
8673                 : diag::ext_gnu_ptr_func_arith)
8674     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8675     << 0 /* one pointer, so only one type */
8676     << Pointer->getSourceRange();
8677 }
8678 
8679 /// Emit error if Operand is incomplete pointer type
8680 ///
8681 /// \returns True if pointer has incomplete type
8682 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8683                                                  Expr *Operand) {
8684   QualType ResType = Operand->getType();
8685   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8686     ResType = ResAtomicType->getValueType();
8687 
8688   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8689   QualType PointeeTy = ResType->getPointeeType();
8690   return S.RequireCompleteType(Loc, PointeeTy,
8691                                diag::err_typecheck_arithmetic_incomplete_type,
8692                                PointeeTy, Operand->getSourceRange());
8693 }
8694 
8695 /// Check the validity of an arithmetic pointer operand.
8696 ///
8697 /// If the operand has pointer type, this code will check for pointer types
8698 /// which are invalid in arithmetic operations. These will be diagnosed
8699 /// appropriately, including whether or not the use is supported as an
8700 /// extension.
8701 ///
8702 /// \returns True when the operand is valid to use (even if as an extension).
8703 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8704                                             Expr *Operand) {
8705   QualType ResType = Operand->getType();
8706   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8707     ResType = ResAtomicType->getValueType();
8708 
8709   if (!ResType->isAnyPointerType()) return true;
8710 
8711   QualType PointeeTy = ResType->getPointeeType();
8712   if (PointeeTy->isVoidType()) {
8713     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8714     return !S.getLangOpts().CPlusPlus;
8715   }
8716   if (PointeeTy->isFunctionType()) {
8717     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8718     return !S.getLangOpts().CPlusPlus;
8719   }
8720 
8721   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8722 
8723   return true;
8724 }
8725 
8726 /// Check the validity of a binary arithmetic operation w.r.t. pointer
8727 /// operands.
8728 ///
8729 /// This routine will diagnose any invalid arithmetic on pointer operands much
8730 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8731 /// for emitting a single diagnostic even for operations where both LHS and RHS
8732 /// are (potentially problematic) pointers.
8733 ///
8734 /// \returns True when the operand is valid to use (even if as an extension).
8735 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8736                                                 Expr *LHSExpr, Expr *RHSExpr) {
8737   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8738   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8739   if (!isLHSPointer && !isRHSPointer) return true;
8740 
8741   QualType LHSPointeeTy, RHSPointeeTy;
8742   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8743   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8744 
8745   // if both are pointers check if operation is valid wrt address spaces
8746   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8747     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8748     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8749     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8750       S.Diag(Loc,
8751              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8752           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8753           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8754       return false;
8755     }
8756   }
8757 
8758   // Check for arithmetic on pointers to incomplete types.
8759   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8760   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8761   if (isLHSVoidPtr || isRHSVoidPtr) {
8762     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8763     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8764     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8765 
8766     return !S.getLangOpts().CPlusPlus;
8767   }
8768 
8769   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8770   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8771   if (isLHSFuncPtr || isRHSFuncPtr) {
8772     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8773     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8774                                                                 RHSExpr);
8775     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8776 
8777     return !S.getLangOpts().CPlusPlus;
8778   }
8779 
8780   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8781     return false;
8782   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8783     return false;
8784 
8785   return true;
8786 }
8787 
8788 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8789 /// literal.
8790 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8791                                   Expr *LHSExpr, Expr *RHSExpr) {
8792   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8793   Expr* IndexExpr = RHSExpr;
8794   if (!StrExpr) {
8795     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8796     IndexExpr = LHSExpr;
8797   }
8798 
8799   bool IsStringPlusInt = StrExpr &&
8800       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8801   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8802     return;
8803 
8804   llvm::APSInt index;
8805   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8806     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8807     if (index.isNonNegative() &&
8808         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8809                               index.isUnsigned()))
8810       return;
8811   }
8812 
8813   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8814   Self.Diag(OpLoc, diag::warn_string_plus_int)
8815       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8816 
8817   // Only print a fixit for "str" + int, not for int + "str".
8818   if (IndexExpr == RHSExpr) {
8819     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8820     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8821         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8822         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8823         << FixItHint::CreateInsertion(EndLoc, "]");
8824   } else
8825     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8826 }
8827 
8828 /// Emit a warning when adding a char literal to a string.
8829 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8830                                    Expr *LHSExpr, Expr *RHSExpr) {
8831   const Expr *StringRefExpr = LHSExpr;
8832   const CharacterLiteral *CharExpr =
8833       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8834 
8835   if (!CharExpr) {
8836     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8837     StringRefExpr = RHSExpr;
8838   }
8839 
8840   if (!CharExpr || !StringRefExpr)
8841     return;
8842 
8843   const QualType StringType = StringRefExpr->getType();
8844 
8845   // Return if not a PointerType.
8846   if (!StringType->isAnyPointerType())
8847     return;
8848 
8849   // Return if not a CharacterType.
8850   if (!StringType->getPointeeType()->isAnyCharacterType())
8851     return;
8852 
8853   ASTContext &Ctx = Self.getASTContext();
8854   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8855 
8856   const QualType CharType = CharExpr->getType();
8857   if (!CharType->isAnyCharacterType() &&
8858       CharType->isIntegerType() &&
8859       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8860     Self.Diag(OpLoc, diag::warn_string_plus_char)
8861         << DiagRange << Ctx.CharTy;
8862   } else {
8863     Self.Diag(OpLoc, diag::warn_string_plus_char)
8864         << DiagRange << CharExpr->getType();
8865   }
8866 
8867   // Only print a fixit for str + char, not for char + str.
8868   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8869     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8870     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8871         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8872         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8873         << FixItHint::CreateInsertion(EndLoc, "]");
8874   } else {
8875     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8876   }
8877 }
8878 
8879 /// Emit error when two pointers are incompatible.
8880 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8881                                            Expr *LHSExpr, Expr *RHSExpr) {
8882   assert(LHSExpr->getType()->isAnyPointerType());
8883   assert(RHSExpr->getType()->isAnyPointerType());
8884   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8885     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8886     << RHSExpr->getSourceRange();
8887 }
8888 
8889 // C99 6.5.6
8890 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8891                                      SourceLocation Loc, BinaryOperatorKind Opc,
8892                                      QualType* CompLHSTy) {
8893   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8894 
8895   if (LHS.get()->getType()->isVectorType() ||
8896       RHS.get()->getType()->isVectorType()) {
8897     QualType compType = CheckVectorOperands(
8898         LHS, RHS, Loc, CompLHSTy,
8899         /*AllowBothBool*/getLangOpts().AltiVec,
8900         /*AllowBoolConversions*/getLangOpts().ZVector);
8901     if (CompLHSTy) *CompLHSTy = compType;
8902     return compType;
8903   }
8904 
8905   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8906   if (LHS.isInvalid() || RHS.isInvalid())
8907     return QualType();
8908 
8909   // Diagnose "string literal" '+' int and string '+' "char literal".
8910   if (Opc == BO_Add) {
8911     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8912     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8913   }
8914 
8915   // handle the common case first (both operands are arithmetic).
8916   if (!compType.isNull() && compType->isArithmeticType()) {
8917     if (CompLHSTy) *CompLHSTy = compType;
8918     return compType;
8919   }
8920 
8921   // Type-checking.  Ultimately the pointer's going to be in PExp;
8922   // note that we bias towards the LHS being the pointer.
8923   Expr *PExp = LHS.get(), *IExp = RHS.get();
8924 
8925   bool isObjCPointer;
8926   if (PExp->getType()->isPointerType()) {
8927     isObjCPointer = false;
8928   } else if (PExp->getType()->isObjCObjectPointerType()) {
8929     isObjCPointer = true;
8930   } else {
8931     std::swap(PExp, IExp);
8932     if (PExp->getType()->isPointerType()) {
8933       isObjCPointer = false;
8934     } else if (PExp->getType()->isObjCObjectPointerType()) {
8935       isObjCPointer = true;
8936     } else {
8937       return InvalidOperands(Loc, LHS, RHS);
8938     }
8939   }
8940   assert(PExp->getType()->isAnyPointerType());
8941 
8942   if (!IExp->getType()->isIntegerType())
8943     return InvalidOperands(Loc, LHS, RHS);
8944 
8945   // Adding to a null pointer results in undefined behavior.
8946   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
8947           Context, Expr::NPC_ValueDependentIsNotNull)) {
8948     // In C++ adding zero to a null pointer is defined.
8949     llvm::APSInt KnownVal;
8950     if (!getLangOpts().CPlusPlus ||
8951         (!IExp->isValueDependent() &&
8952          (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
8953       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
8954       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
8955           Context, BO_Add, PExp, IExp);
8956       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
8957     }
8958   }
8959 
8960   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8961     return QualType();
8962 
8963   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8964     return QualType();
8965 
8966   // Check array bounds for pointer arithemtic
8967   CheckArrayAccess(PExp, IExp);
8968 
8969   if (CompLHSTy) {
8970     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8971     if (LHSTy.isNull()) {
8972       LHSTy = LHS.get()->getType();
8973       if (LHSTy->isPromotableIntegerType())
8974         LHSTy = Context.getPromotedIntegerType(LHSTy);
8975     }
8976     *CompLHSTy = LHSTy;
8977   }
8978 
8979   return PExp->getType();
8980 }
8981 
8982 // C99 6.5.6
8983 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8984                                         SourceLocation Loc,
8985                                         QualType* CompLHSTy) {
8986   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8987 
8988   if (LHS.get()->getType()->isVectorType() ||
8989       RHS.get()->getType()->isVectorType()) {
8990     QualType compType = CheckVectorOperands(
8991         LHS, RHS, Loc, CompLHSTy,
8992         /*AllowBothBool*/getLangOpts().AltiVec,
8993         /*AllowBoolConversions*/getLangOpts().ZVector);
8994     if (CompLHSTy) *CompLHSTy = compType;
8995     return compType;
8996   }
8997 
8998   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8999   if (LHS.isInvalid() || RHS.isInvalid())
9000     return QualType();
9001 
9002   // Enforce type constraints: C99 6.5.6p3.
9003 
9004   // Handle the common case first (both operands are arithmetic).
9005   if (!compType.isNull() && compType->isArithmeticType()) {
9006     if (CompLHSTy) *CompLHSTy = compType;
9007     return compType;
9008   }
9009 
9010   // Either ptr - int   or   ptr - ptr.
9011   if (LHS.get()->getType()->isAnyPointerType()) {
9012     QualType lpointee = LHS.get()->getType()->getPointeeType();
9013 
9014     // Diagnose bad cases where we step over interface counts.
9015     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9016         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9017       return QualType();
9018 
9019     // The result type of a pointer-int computation is the pointer type.
9020     if (RHS.get()->getType()->isIntegerType()) {
9021       // Subtracting from a null pointer should produce a warning.
9022       // The last argument to the diagnose call says this doesn't match the
9023       // GNU int-to-pointer idiom.
9024       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9025                                            Expr::NPC_ValueDependentIsNotNull)) {
9026         // In C++ adding zero to a null pointer is defined.
9027         llvm::APSInt KnownVal;
9028         if (!getLangOpts().CPlusPlus ||
9029             (!RHS.get()->isValueDependent() &&
9030              (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9031           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9032         }
9033       }
9034 
9035       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9036         return QualType();
9037 
9038       // Check array bounds for pointer arithemtic
9039       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9040                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9041 
9042       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9043       return LHS.get()->getType();
9044     }
9045 
9046     // Handle pointer-pointer subtractions.
9047     if (const PointerType *RHSPTy
9048           = RHS.get()->getType()->getAs<PointerType>()) {
9049       QualType rpointee = RHSPTy->getPointeeType();
9050 
9051       if (getLangOpts().CPlusPlus) {
9052         // Pointee types must be the same: C++ [expr.add]
9053         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9054           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9055         }
9056       } else {
9057         // Pointee types must be compatible C99 6.5.6p3
9058         if (!Context.typesAreCompatible(
9059                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9060                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9061           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9062           return QualType();
9063         }
9064       }
9065 
9066       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9067                                                LHS.get(), RHS.get()))
9068         return QualType();
9069 
9070       // FIXME: Add warnings for nullptr - ptr.
9071 
9072       // The pointee type may have zero size.  As an extension, a structure or
9073       // union may have zero size or an array may have zero length.  In this
9074       // case subtraction does not make sense.
9075       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9076         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9077         if (ElementSize.isZero()) {
9078           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9079             << rpointee.getUnqualifiedType()
9080             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9081         }
9082       }
9083 
9084       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9085       return Context.getPointerDiffType();
9086     }
9087   }
9088 
9089   return InvalidOperands(Loc, LHS, RHS);
9090 }
9091 
9092 static bool isScopedEnumerationType(QualType T) {
9093   if (const EnumType *ET = T->getAs<EnumType>())
9094     return ET->getDecl()->isScoped();
9095   return false;
9096 }
9097 
9098 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9099                                    SourceLocation Loc, BinaryOperatorKind Opc,
9100                                    QualType LHSType) {
9101   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9102   // so skip remaining warnings as we don't want to modify values within Sema.
9103   if (S.getLangOpts().OpenCL)
9104     return;
9105 
9106   llvm::APSInt Right;
9107   // Check right/shifter operand
9108   if (RHS.get()->isValueDependent() ||
9109       !RHS.get()->EvaluateAsInt(Right, S.Context))
9110     return;
9111 
9112   if (Right.isNegative()) {
9113     S.DiagRuntimeBehavior(Loc, RHS.get(),
9114                           S.PDiag(diag::warn_shift_negative)
9115                             << RHS.get()->getSourceRange());
9116     return;
9117   }
9118   llvm::APInt LeftBits(Right.getBitWidth(),
9119                        S.Context.getTypeSize(LHS.get()->getType()));
9120   if (Right.uge(LeftBits)) {
9121     S.DiagRuntimeBehavior(Loc, RHS.get(),
9122                           S.PDiag(diag::warn_shift_gt_typewidth)
9123                             << RHS.get()->getSourceRange());
9124     return;
9125   }
9126   if (Opc != BO_Shl)
9127     return;
9128 
9129   // When left shifting an ICE which is signed, we can check for overflow which
9130   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9131   // integers have defined behavior modulo one more than the maximum value
9132   // representable in the result type, so never warn for those.
9133   llvm::APSInt Left;
9134   if (LHS.get()->isValueDependent() ||
9135       LHSType->hasUnsignedIntegerRepresentation() ||
9136       !LHS.get()->EvaluateAsInt(Left, S.Context))
9137     return;
9138 
9139   // If LHS does not have a signed type and non-negative value
9140   // then, the behavior is undefined. Warn about it.
9141   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9142     S.DiagRuntimeBehavior(Loc, LHS.get(),
9143                           S.PDiag(diag::warn_shift_lhs_negative)
9144                             << LHS.get()->getSourceRange());
9145     return;
9146   }
9147 
9148   llvm::APInt ResultBits =
9149       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9150   if (LeftBits.uge(ResultBits))
9151     return;
9152   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9153   Result = Result.shl(Right);
9154 
9155   // Print the bit representation of the signed integer as an unsigned
9156   // hexadecimal number.
9157   SmallString<40> HexResult;
9158   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9159 
9160   // If we are only missing a sign bit, this is less likely to result in actual
9161   // bugs -- if the result is cast back to an unsigned type, it will have the
9162   // expected value. Thus we place this behind a different warning that can be
9163   // turned off separately if needed.
9164   if (LeftBits == ResultBits - 1) {
9165     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9166         << HexResult << LHSType
9167         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9168     return;
9169   }
9170 
9171   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9172     << HexResult.str() << Result.getMinSignedBits() << LHSType
9173     << Left.getBitWidth() << LHS.get()->getSourceRange()
9174     << RHS.get()->getSourceRange();
9175 }
9176 
9177 /// Return the resulting type when a vector is shifted
9178 ///        by a scalar or vector shift amount.
9179 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9180                                  SourceLocation Loc, bool IsCompAssign) {
9181   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9182   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9183       !LHS.get()->getType()->isVectorType()) {
9184     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9185       << RHS.get()->getType() << LHS.get()->getType()
9186       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9187     return QualType();
9188   }
9189 
9190   if (!IsCompAssign) {
9191     LHS = S.UsualUnaryConversions(LHS.get());
9192     if (LHS.isInvalid()) return QualType();
9193   }
9194 
9195   RHS = S.UsualUnaryConversions(RHS.get());
9196   if (RHS.isInvalid()) return QualType();
9197 
9198   QualType LHSType = LHS.get()->getType();
9199   // Note that LHS might be a scalar because the routine calls not only in
9200   // OpenCL case.
9201   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9202   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9203 
9204   // Note that RHS might not be a vector.
9205   QualType RHSType = RHS.get()->getType();
9206   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9207   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9208 
9209   // The operands need to be integers.
9210   if (!LHSEleType->isIntegerType()) {
9211     S.Diag(Loc, diag::err_typecheck_expect_int)
9212       << LHS.get()->getType() << LHS.get()->getSourceRange();
9213     return QualType();
9214   }
9215 
9216   if (!RHSEleType->isIntegerType()) {
9217     S.Diag(Loc, diag::err_typecheck_expect_int)
9218       << RHS.get()->getType() << RHS.get()->getSourceRange();
9219     return QualType();
9220   }
9221 
9222   if (!LHSVecTy) {
9223     assert(RHSVecTy);
9224     if (IsCompAssign)
9225       return RHSType;
9226     if (LHSEleType != RHSEleType) {
9227       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9228       LHSEleType = RHSEleType;
9229     }
9230     QualType VecTy =
9231         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9232     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9233     LHSType = VecTy;
9234   } else if (RHSVecTy) {
9235     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9236     // are applied component-wise. So if RHS is a vector, then ensure
9237     // that the number of elements is the same as LHS...
9238     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9239       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9240         << LHS.get()->getType() << RHS.get()->getType()
9241         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9242       return QualType();
9243     }
9244     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9245       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9246       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9247       if (LHSBT != RHSBT &&
9248           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9249         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9250             << LHS.get()->getType() << RHS.get()->getType()
9251             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9252       }
9253     }
9254   } else {
9255     // ...else expand RHS to match the number of elements in LHS.
9256     QualType VecTy =
9257       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9258     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9259   }
9260 
9261   return LHSType;
9262 }
9263 
9264 // C99 6.5.7
9265 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9266                                   SourceLocation Loc, BinaryOperatorKind Opc,
9267                                   bool IsCompAssign) {
9268   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9269 
9270   // Vector shifts promote their scalar inputs to vector type.
9271   if (LHS.get()->getType()->isVectorType() ||
9272       RHS.get()->getType()->isVectorType()) {
9273     if (LangOpts.ZVector) {
9274       // The shift operators for the z vector extensions work basically
9275       // like general shifts, except that neither the LHS nor the RHS is
9276       // allowed to be a "vector bool".
9277       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9278         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9279           return InvalidOperands(Loc, LHS, RHS);
9280       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9281         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9282           return InvalidOperands(Loc, LHS, RHS);
9283     }
9284     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9285   }
9286 
9287   // Shifts don't perform usual arithmetic conversions, they just do integer
9288   // promotions on each operand. C99 6.5.7p3
9289 
9290   // For the LHS, do usual unary conversions, but then reset them away
9291   // if this is a compound assignment.
9292   ExprResult OldLHS = LHS;
9293   LHS = UsualUnaryConversions(LHS.get());
9294   if (LHS.isInvalid())
9295     return QualType();
9296   QualType LHSType = LHS.get()->getType();
9297   if (IsCompAssign) LHS = OldLHS;
9298 
9299   // The RHS is simpler.
9300   RHS = UsualUnaryConversions(RHS.get());
9301   if (RHS.isInvalid())
9302     return QualType();
9303   QualType RHSType = RHS.get()->getType();
9304 
9305   // C99 6.5.7p2: Each of the operands shall have integer type.
9306   if (!LHSType->hasIntegerRepresentation() ||
9307       !RHSType->hasIntegerRepresentation())
9308     return InvalidOperands(Loc, LHS, RHS);
9309 
9310   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9311   // hasIntegerRepresentation() above instead of this.
9312   if (isScopedEnumerationType(LHSType) ||
9313       isScopedEnumerationType(RHSType)) {
9314     return InvalidOperands(Loc, LHS, RHS);
9315   }
9316   // Sanity-check shift operands
9317   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9318 
9319   // "The type of the result is that of the promoted left operand."
9320   return LHSType;
9321 }
9322 
9323 /// If two different enums are compared, raise a warning.
9324 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9325                                 Expr *RHS) {
9326   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9327   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9328 
9329   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9330   if (!LHSEnumType)
9331     return;
9332   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9333   if (!RHSEnumType)
9334     return;
9335 
9336   // Ignore anonymous enums.
9337   if (!LHSEnumType->getDecl()->getIdentifier() &&
9338       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9339     return;
9340   if (!RHSEnumType->getDecl()->getIdentifier() &&
9341       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9342     return;
9343 
9344   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9345     return;
9346 
9347   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9348       << LHSStrippedType << RHSStrippedType
9349       << LHS->getSourceRange() << RHS->getSourceRange();
9350 }
9351 
9352 /// Diagnose bad pointer comparisons.
9353 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9354                                               ExprResult &LHS, ExprResult &RHS,
9355                                               bool IsError) {
9356   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9357                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9358     << LHS.get()->getType() << RHS.get()->getType()
9359     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9360 }
9361 
9362 /// Returns false if the pointers are converted to a composite type,
9363 /// true otherwise.
9364 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9365                                            ExprResult &LHS, ExprResult &RHS) {
9366   // C++ [expr.rel]p2:
9367   //   [...] Pointer conversions (4.10) and qualification
9368   //   conversions (4.4) are performed on pointer operands (or on
9369   //   a pointer operand and a null pointer constant) to bring
9370   //   them to their composite pointer type. [...]
9371   //
9372   // C++ [expr.eq]p1 uses the same notion for (in)equality
9373   // comparisons of pointers.
9374 
9375   QualType LHSType = LHS.get()->getType();
9376   QualType RHSType = RHS.get()->getType();
9377   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9378          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9379 
9380   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9381   if (T.isNull()) {
9382     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9383         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9384       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9385     else
9386       S.InvalidOperands(Loc, LHS, RHS);
9387     return true;
9388   }
9389 
9390   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9391   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9392   return false;
9393 }
9394 
9395 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9396                                                     ExprResult &LHS,
9397                                                     ExprResult &RHS,
9398                                                     bool IsError) {
9399   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9400                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9401     << LHS.get()->getType() << RHS.get()->getType()
9402     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9403 }
9404 
9405 static bool isObjCObjectLiteral(ExprResult &E) {
9406   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9407   case Stmt::ObjCArrayLiteralClass:
9408   case Stmt::ObjCDictionaryLiteralClass:
9409   case Stmt::ObjCStringLiteralClass:
9410   case Stmt::ObjCBoxedExprClass:
9411     return true;
9412   default:
9413     // Note that ObjCBoolLiteral is NOT an object literal!
9414     return false;
9415   }
9416 }
9417 
9418 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9419   const ObjCObjectPointerType *Type =
9420     LHS->getType()->getAs<ObjCObjectPointerType>();
9421 
9422   // If this is not actually an Objective-C object, bail out.
9423   if (!Type)
9424     return false;
9425 
9426   // Get the LHS object's interface type.
9427   QualType InterfaceType = Type->getPointeeType();
9428 
9429   // If the RHS isn't an Objective-C object, bail out.
9430   if (!RHS->getType()->isObjCObjectPointerType())
9431     return false;
9432 
9433   // Try to find the -isEqual: method.
9434   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9435   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9436                                                       InterfaceType,
9437                                                       /*instance=*/true);
9438   if (!Method) {
9439     if (Type->isObjCIdType()) {
9440       // For 'id', just check the global pool.
9441       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9442                                                   /*receiverId=*/true);
9443     } else {
9444       // Check protocols.
9445       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9446                                              /*instance=*/true);
9447     }
9448   }
9449 
9450   if (!Method)
9451     return false;
9452 
9453   QualType T = Method->parameters()[0]->getType();
9454   if (!T->isObjCObjectPointerType())
9455     return false;
9456 
9457   QualType R = Method->getReturnType();
9458   if (!R->isScalarType())
9459     return false;
9460 
9461   return true;
9462 }
9463 
9464 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9465   FromE = FromE->IgnoreParenImpCasts();
9466   switch (FromE->getStmtClass()) {
9467     default:
9468       break;
9469     case Stmt::ObjCStringLiteralClass:
9470       // "string literal"
9471       return LK_String;
9472     case Stmt::ObjCArrayLiteralClass:
9473       // "array literal"
9474       return LK_Array;
9475     case Stmt::ObjCDictionaryLiteralClass:
9476       // "dictionary literal"
9477       return LK_Dictionary;
9478     case Stmt::BlockExprClass:
9479       return LK_Block;
9480     case Stmt::ObjCBoxedExprClass: {
9481       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9482       switch (Inner->getStmtClass()) {
9483         case Stmt::IntegerLiteralClass:
9484         case Stmt::FloatingLiteralClass:
9485         case Stmt::CharacterLiteralClass:
9486         case Stmt::ObjCBoolLiteralExprClass:
9487         case Stmt::CXXBoolLiteralExprClass:
9488           // "numeric literal"
9489           return LK_Numeric;
9490         case Stmt::ImplicitCastExprClass: {
9491           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9492           // Boolean literals can be represented by implicit casts.
9493           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9494             return LK_Numeric;
9495           break;
9496         }
9497         default:
9498           break;
9499       }
9500       return LK_Boxed;
9501     }
9502   }
9503   return LK_None;
9504 }
9505 
9506 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9507                                           ExprResult &LHS, ExprResult &RHS,
9508                                           BinaryOperator::Opcode Opc){
9509   Expr *Literal;
9510   Expr *Other;
9511   if (isObjCObjectLiteral(LHS)) {
9512     Literal = LHS.get();
9513     Other = RHS.get();
9514   } else {
9515     Literal = RHS.get();
9516     Other = LHS.get();
9517   }
9518 
9519   // Don't warn on comparisons against nil.
9520   Other = Other->IgnoreParenCasts();
9521   if (Other->isNullPointerConstant(S.getASTContext(),
9522                                    Expr::NPC_ValueDependentIsNotNull))
9523     return;
9524 
9525   // This should be kept in sync with warn_objc_literal_comparison.
9526   // LK_String should always be after the other literals, since it has its own
9527   // warning flag.
9528   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9529   assert(LiteralKind != Sema::LK_Block);
9530   if (LiteralKind == Sema::LK_None) {
9531     llvm_unreachable("Unknown Objective-C object literal kind");
9532   }
9533 
9534   if (LiteralKind == Sema::LK_String)
9535     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9536       << Literal->getSourceRange();
9537   else
9538     S.Diag(Loc, diag::warn_objc_literal_comparison)
9539       << LiteralKind << Literal->getSourceRange();
9540 
9541   if (BinaryOperator::isEqualityOp(Opc) &&
9542       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9543     SourceLocation Start = LHS.get()->getLocStart();
9544     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9545     CharSourceRange OpRange =
9546       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9547 
9548     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9549       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9550       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9551       << FixItHint::CreateInsertion(End, "]");
9552   }
9553 }
9554 
9555 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9556 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9557                                            ExprResult &RHS, SourceLocation Loc,
9558                                            BinaryOperatorKind Opc) {
9559   // Check that left hand side is !something.
9560   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9561   if (!UO || UO->getOpcode() != UO_LNot) return;
9562 
9563   // Only check if the right hand side is non-bool arithmetic type.
9564   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9565 
9566   // Make sure that the something in !something is not bool.
9567   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9568   if (SubExpr->isKnownToHaveBooleanValue()) return;
9569 
9570   // Emit warning.
9571   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9572   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9573       << Loc << IsBitwiseOp;
9574 
9575   // First note suggest !(x < y)
9576   SourceLocation FirstOpen = SubExpr->getLocStart();
9577   SourceLocation FirstClose = RHS.get()->getLocEnd();
9578   FirstClose = S.getLocForEndOfToken(FirstClose);
9579   if (FirstClose.isInvalid())
9580     FirstOpen = SourceLocation();
9581   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9582       << IsBitwiseOp
9583       << FixItHint::CreateInsertion(FirstOpen, "(")
9584       << FixItHint::CreateInsertion(FirstClose, ")");
9585 
9586   // Second note suggests (!x) < y
9587   SourceLocation SecondOpen = LHS.get()->getLocStart();
9588   SourceLocation SecondClose = LHS.get()->getLocEnd();
9589   SecondClose = S.getLocForEndOfToken(SecondClose);
9590   if (SecondClose.isInvalid())
9591     SecondOpen = SourceLocation();
9592   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9593       << FixItHint::CreateInsertion(SecondOpen, "(")
9594       << FixItHint::CreateInsertion(SecondClose, ")");
9595 }
9596 
9597 // Get the decl for a simple expression: a reference to a variable,
9598 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9599 static ValueDecl *getCompareDecl(Expr *E) {
9600   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9601     return DR->getDecl();
9602   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9603     if (Ivar->isFreeIvar())
9604       return Ivar->getDecl();
9605   }
9606   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9607     if (Mem->isImplicitAccess())
9608       return Mem->getMemberDecl();
9609   }
9610   return nullptr;
9611 }
9612 
9613 /// Diagnose some forms of syntactically-obvious tautological comparison.
9614 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9615                                            Expr *LHS, Expr *RHS,
9616                                            BinaryOperatorKind Opc) {
9617   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9618   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9619 
9620   QualType LHSType = LHS->getType();
9621   QualType RHSType = RHS->getType();
9622   if (LHSType->hasFloatingRepresentation() ||
9623       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9624       LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() ||
9625       S.inTemplateInstantiation())
9626     return;
9627 
9628   // Comparisons between two array types are ill-formed for operator<=>, so
9629   // we shouldn't emit any additional warnings about it.
9630   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
9631     return;
9632 
9633   // For non-floating point types, check for self-comparisons of the form
9634   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9635   // often indicate logic errors in the program.
9636   //
9637   // NOTE: Don't warn about comparison expressions resulting from macro
9638   // expansion. Also don't warn about comparisons which are only self
9639   // comparisons within a template instantiation. The warnings should catch
9640   // obvious cases in the definition of the template anyways. The idea is to
9641   // warn when the typed comparison operator will always evaluate to the same
9642   // result.
9643   ValueDecl *DL = getCompareDecl(LHSStripped);
9644   ValueDecl *DR = getCompareDecl(RHSStripped);
9645   if (DL && DR && declaresSameEntity(DL, DR)) {
9646     StringRef Result;
9647     switch (Opc) {
9648     case BO_EQ: case BO_LE: case BO_GE:
9649       Result = "true";
9650       break;
9651     case BO_NE: case BO_LT: case BO_GT:
9652       Result = "false";
9653       break;
9654     case BO_Cmp:
9655       Result = "'std::strong_ordering::equal'";
9656       break;
9657     default:
9658       break;
9659     }
9660     S.DiagRuntimeBehavior(Loc, nullptr,
9661                           S.PDiag(diag::warn_comparison_always)
9662                               << 0 /*self-comparison*/ << !Result.empty()
9663                               << Result);
9664   } else if (DL && DR &&
9665              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9666              !DL->isWeak() && !DR->isWeak()) {
9667     // What is it always going to evaluate to?
9668     StringRef Result;
9669     switch(Opc) {
9670     case BO_EQ: // e.g. array1 == array2
9671       Result = "false";
9672       break;
9673     case BO_NE: // e.g. array1 != array2
9674       Result = "true";
9675       break;
9676     default: // e.g. array1 <= array2
9677       // The best we can say is 'a constant'
9678       break;
9679     }
9680     S.DiagRuntimeBehavior(Loc, nullptr,
9681                           S.PDiag(diag::warn_comparison_always)
9682                               << 1 /*array comparison*/
9683                               << !Result.empty() << Result);
9684   }
9685 
9686   if (isa<CastExpr>(LHSStripped))
9687     LHSStripped = LHSStripped->IgnoreParenCasts();
9688   if (isa<CastExpr>(RHSStripped))
9689     RHSStripped = RHSStripped->IgnoreParenCasts();
9690 
9691   // Warn about comparisons against a string constant (unless the other
9692   // operand is null); the user probably wants strcmp.
9693   Expr *LiteralString = nullptr;
9694   Expr *LiteralStringStripped = nullptr;
9695   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9696       !RHSStripped->isNullPointerConstant(S.Context,
9697                                           Expr::NPC_ValueDependentIsNull)) {
9698     LiteralString = LHS;
9699     LiteralStringStripped = LHSStripped;
9700   } else if ((isa<StringLiteral>(RHSStripped) ||
9701               isa<ObjCEncodeExpr>(RHSStripped)) &&
9702              !LHSStripped->isNullPointerConstant(S.Context,
9703                                           Expr::NPC_ValueDependentIsNull)) {
9704     LiteralString = RHS;
9705     LiteralStringStripped = RHSStripped;
9706   }
9707 
9708   if (LiteralString) {
9709     S.DiagRuntimeBehavior(Loc, nullptr,
9710                           S.PDiag(diag::warn_stringcompare)
9711                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
9712                               << LiteralString->getSourceRange());
9713   }
9714 }
9715 
9716 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
9717   switch (CK) {
9718   default: {
9719 #ifndef NDEBUG
9720     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
9721                  << "\n";
9722 #endif
9723     llvm_unreachable("unhandled cast kind");
9724   }
9725   case CK_UserDefinedConversion:
9726     return ICK_Identity;
9727   case CK_LValueToRValue:
9728     return ICK_Lvalue_To_Rvalue;
9729   case CK_ArrayToPointerDecay:
9730     return ICK_Array_To_Pointer;
9731   case CK_FunctionToPointerDecay:
9732     return ICK_Function_To_Pointer;
9733   case CK_IntegralCast:
9734     return ICK_Integral_Conversion;
9735   case CK_FloatingCast:
9736     return ICK_Floating_Conversion;
9737   case CK_IntegralToFloating:
9738   case CK_FloatingToIntegral:
9739     return ICK_Floating_Integral;
9740   case CK_IntegralComplexCast:
9741   case CK_FloatingComplexCast:
9742   case CK_FloatingComplexToIntegralComplex:
9743   case CK_IntegralComplexToFloatingComplex:
9744     return ICK_Complex_Conversion;
9745   case CK_FloatingComplexToReal:
9746   case CK_FloatingRealToComplex:
9747   case CK_IntegralComplexToReal:
9748   case CK_IntegralRealToComplex:
9749     return ICK_Complex_Real;
9750   }
9751 }
9752 
9753 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
9754                                              QualType FromType,
9755                                              SourceLocation Loc) {
9756   // Check for a narrowing implicit conversion.
9757   StandardConversionSequence SCS;
9758   SCS.setAsIdentityConversion();
9759   SCS.setToType(0, FromType);
9760   SCS.setToType(1, ToType);
9761   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9762     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
9763 
9764   APValue PreNarrowingValue;
9765   QualType PreNarrowingType;
9766   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
9767                                PreNarrowingType,
9768                                /*IgnoreFloatToIntegralConversion*/ true)) {
9769   case NK_Dependent_Narrowing:
9770     // Implicit conversion to a narrower type, but the expression is
9771     // value-dependent so we can't tell whether it's actually narrowing.
9772   case NK_Not_Narrowing:
9773     return false;
9774 
9775   case NK_Constant_Narrowing:
9776     // Implicit conversion to a narrower type, and the value is not a constant
9777     // expression.
9778     S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9779         << /*Constant*/ 1
9780         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
9781     return true;
9782 
9783   case NK_Variable_Narrowing:
9784     // Implicit conversion to a narrower type, and the value is not a constant
9785     // expression.
9786   case NK_Type_Narrowing:
9787     S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9788         << /*Constant*/ 0 << FromType << ToType;
9789     // TODO: It's not a constant expression, but what if the user intended it
9790     // to be? Can we produce notes to help them figure out why it isn't?
9791     return true;
9792   }
9793   llvm_unreachable("unhandled case in switch");
9794 }
9795 
9796 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
9797                                                          ExprResult &LHS,
9798                                                          ExprResult &RHS,
9799                                                          SourceLocation Loc) {
9800   using CCT = ComparisonCategoryType;
9801 
9802   QualType LHSType = LHS.get()->getType();
9803   QualType RHSType = RHS.get()->getType();
9804   // Dig out the original argument type and expression before implicit casts
9805   // were applied. These are the types/expressions we need to check the
9806   // [expr.spaceship] requirements against.
9807   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
9808   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
9809   QualType LHSStrippedType = LHSStripped.get()->getType();
9810   QualType RHSStrippedType = RHSStripped.get()->getType();
9811 
9812   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
9813   // other is not, the program is ill-formed.
9814   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
9815     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9816     return QualType();
9817   }
9818 
9819   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
9820                     RHSStrippedType->isEnumeralType();
9821   if (NumEnumArgs == 1) {
9822     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
9823     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
9824     if (OtherTy->hasFloatingRepresentation()) {
9825       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9826       return QualType();
9827     }
9828   }
9829   if (NumEnumArgs == 2) {
9830     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
9831     // type E, the operator yields the result of converting the operands
9832     // to the underlying type of E and applying <=> to the converted operands.
9833     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
9834       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9835       return QualType();
9836     }
9837     QualType IntType =
9838         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
9839     assert(IntType->isArithmeticType());
9840 
9841     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
9842     // promote the boolean type, and all other promotable integer types, to
9843     // avoid this.
9844     if (IntType->isPromotableIntegerType())
9845       IntType = S.Context.getPromotedIntegerType(IntType);
9846 
9847     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
9848     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
9849     LHSType = RHSType = IntType;
9850   }
9851 
9852   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
9853   // usual arithmetic conversions are applied to the operands.
9854   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
9855   if (LHS.isInvalid() || RHS.isInvalid())
9856     return QualType();
9857   if (Type.isNull())
9858     return S.InvalidOperands(Loc, LHS, RHS);
9859   assert(Type->isArithmeticType() || Type->isEnumeralType());
9860 
9861   bool HasNarrowing = checkThreeWayNarrowingConversion(
9862       S, Type, LHS.get(), LHSType, LHS.get()->getLocStart());
9863   HasNarrowing |= checkThreeWayNarrowingConversion(
9864       S, Type, RHS.get(), RHSType, RHS.get()->getLocStart());
9865   if (HasNarrowing)
9866     return QualType();
9867 
9868   assert(!Type.isNull() && "composite type for <=> has not been set");
9869 
9870   auto TypeKind = [&]() {
9871     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
9872       if (CT->getElementType()->hasFloatingRepresentation())
9873         return CCT::WeakEquality;
9874       return CCT::StrongEquality;
9875     }
9876     if (Type->isIntegralOrEnumerationType())
9877       return CCT::StrongOrdering;
9878     if (Type->hasFloatingRepresentation())
9879       return CCT::PartialOrdering;
9880     llvm_unreachable("other types are unimplemented");
9881   }();
9882 
9883   return S.CheckComparisonCategoryType(TypeKind, Loc);
9884 }
9885 
9886 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
9887                                                  ExprResult &RHS,
9888                                                  SourceLocation Loc,
9889                                                  BinaryOperatorKind Opc) {
9890   if (Opc == BO_Cmp)
9891     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
9892 
9893   // C99 6.5.8p3 / C99 6.5.9p4
9894   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
9895   if (LHS.isInvalid() || RHS.isInvalid())
9896     return QualType();
9897   if (Type.isNull())
9898     return S.InvalidOperands(Loc, LHS, RHS);
9899   assert(Type->isArithmeticType() || Type->isEnumeralType());
9900 
9901   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
9902 
9903   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
9904     return S.InvalidOperands(Loc, LHS, RHS);
9905 
9906   // Check for comparisons of floating point operands using != and ==.
9907   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
9908     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
9909 
9910   // The result of comparisons is 'bool' in C++, 'int' in C.
9911   return S.Context.getLogicalOperationType();
9912 }
9913 
9914 // C99 6.5.8, C++ [expr.rel]
9915 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9916                                     SourceLocation Loc,
9917                                     BinaryOperatorKind Opc) {
9918   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
9919   bool IsThreeWay = Opc == BO_Cmp;
9920   auto IsAnyPointerType = [](ExprResult E) {
9921     QualType Ty = E.get()->getType();
9922     return Ty->isPointerType() || Ty->isMemberPointerType();
9923   };
9924 
9925   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
9926   // type, array-to-pointer, ..., conversions are performed on both operands to
9927   // bring them to their composite type.
9928   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
9929   // any type-related checks.
9930   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
9931     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9932     if (LHS.isInvalid())
9933       return QualType();
9934     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9935     if (RHS.isInvalid())
9936       return QualType();
9937   } else {
9938     LHS = DefaultLvalueConversion(LHS.get());
9939     if (LHS.isInvalid())
9940       return QualType();
9941     RHS = DefaultLvalueConversion(RHS.get());
9942     if (RHS.isInvalid())
9943       return QualType();
9944   }
9945 
9946   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9947 
9948   // Handle vector comparisons separately.
9949   if (LHS.get()->getType()->isVectorType() ||
9950       RHS.get()->getType()->isVectorType())
9951     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
9952 
9953   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9954   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
9955 
9956   QualType LHSType = LHS.get()->getType();
9957   QualType RHSType = RHS.get()->getType();
9958   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
9959       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
9960     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
9961 
9962   const Expr::NullPointerConstantKind LHSNullKind =
9963       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9964   const Expr::NullPointerConstantKind RHSNullKind =
9965       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9966   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9967   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9968 
9969   auto computeResultTy = [&]() {
9970     if (Opc != BO_Cmp)
9971       return Context.getLogicalOperationType();
9972     assert(getLangOpts().CPlusPlus);
9973     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
9974 
9975     QualType CompositeTy = LHS.get()->getType();
9976     assert(!CompositeTy->isReferenceType());
9977 
9978     auto buildResultTy = [&](ComparisonCategoryType Kind) {
9979       return CheckComparisonCategoryType(Kind, Loc);
9980     };
9981 
9982     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
9983     // pointer type, a pointer-to-member type, or std::nullptr_t, the
9984     // result is of type std::strong_equality
9985     if (CompositeTy->isFunctionPointerType() ||
9986         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
9987       // FIXME: consider making the function pointer case produce
9988       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
9989       // and direction polls
9990       return buildResultTy(ComparisonCategoryType::StrongEquality);
9991 
9992     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
9993     // pointer type, p <=> q is of type std::strong_ordering.
9994     if (CompositeTy->isPointerType()) {
9995       // P0946R0: Comparisons between a null pointer constant and an object
9996       // pointer result in std::strong_equality
9997       if (LHSIsNull != RHSIsNull)
9998         return buildResultTy(ComparisonCategoryType::StrongEquality);
9999       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10000     }
10001     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10002     // TODO: Extend support for operator<=> to ObjC types.
10003     return InvalidOperands(Loc, LHS, RHS);
10004   };
10005 
10006 
10007   if (!IsRelational && LHSIsNull != RHSIsNull) {
10008     bool IsEquality = Opc == BO_EQ;
10009     if (RHSIsNull)
10010       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10011                                    RHS.get()->getSourceRange());
10012     else
10013       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10014                                    LHS.get()->getSourceRange());
10015   }
10016 
10017   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10018       (RHSType->isIntegerType() && !RHSIsNull)) {
10019     // Skip normal pointer conversion checks in this case; we have better
10020     // diagnostics for this below.
10021   } else if (getLangOpts().CPlusPlus) {
10022     // Equality comparison of a function pointer to a void pointer is invalid,
10023     // but we allow it as an extension.
10024     // FIXME: If we really want to allow this, should it be part of composite
10025     // pointer type computation so it works in conditionals too?
10026     if (!IsRelational &&
10027         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10028          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10029       // This is a gcc extension compatibility comparison.
10030       // In a SFINAE context, we treat this as a hard error to maintain
10031       // conformance with the C++ standard.
10032       diagnoseFunctionPointerToVoidComparison(
10033           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10034 
10035       if (isSFINAEContext())
10036         return QualType();
10037 
10038       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10039       return computeResultTy();
10040     }
10041 
10042     // C++ [expr.eq]p2:
10043     //   If at least one operand is a pointer [...] bring them to their
10044     //   composite pointer type.
10045     // C++ [expr.spaceship]p6
10046     //  If at least one of the operands is of pointer type, [...] bring them
10047     //  to their composite pointer type.
10048     // C++ [expr.rel]p2:
10049     //   If both operands are pointers, [...] bring them to their composite
10050     //   pointer type.
10051     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10052             (IsRelational ? 2 : 1) &&
10053         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10054                                          RHSType->isObjCObjectPointerType()))) {
10055       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10056         return QualType();
10057       return computeResultTy();
10058     }
10059   } else if (LHSType->isPointerType() &&
10060              RHSType->isPointerType()) { // C99 6.5.8p2
10061     // All of the following pointer-related warnings are GCC extensions, except
10062     // when handling null pointer constants.
10063     QualType LCanPointeeTy =
10064       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10065     QualType RCanPointeeTy =
10066       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10067 
10068     // C99 6.5.9p2 and C99 6.5.8p2
10069     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10070                                    RCanPointeeTy.getUnqualifiedType())) {
10071       // Valid unless a relational comparison of function pointers
10072       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10073         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10074           << LHSType << RHSType << LHS.get()->getSourceRange()
10075           << RHS.get()->getSourceRange();
10076       }
10077     } else if (!IsRelational &&
10078                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10079       // Valid unless comparison between non-null pointer and function pointer
10080       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10081           && !LHSIsNull && !RHSIsNull)
10082         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10083                                                 /*isError*/false);
10084     } else {
10085       // Invalid
10086       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10087     }
10088     if (LCanPointeeTy != RCanPointeeTy) {
10089       // Treat NULL constant as a special case in OpenCL.
10090       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10091         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10092         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10093           Diag(Loc,
10094                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10095               << LHSType << RHSType << 0 /* comparison */
10096               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10097         }
10098       }
10099       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10100       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10101       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10102                                                : CK_BitCast;
10103       if (LHSIsNull && !RHSIsNull)
10104         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10105       else
10106         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10107     }
10108     return computeResultTy();
10109   }
10110 
10111   if (getLangOpts().CPlusPlus) {
10112     // C++ [expr.eq]p4:
10113     //   Two operands of type std::nullptr_t or one operand of type
10114     //   std::nullptr_t and the other a null pointer constant compare equal.
10115     if (!IsRelational && LHSIsNull && RHSIsNull) {
10116       if (LHSType->isNullPtrType()) {
10117         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10118         return computeResultTy();
10119       }
10120       if (RHSType->isNullPtrType()) {
10121         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10122         return computeResultTy();
10123       }
10124     }
10125 
10126     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10127     // These aren't covered by the composite pointer type rules.
10128     if (!IsRelational && RHSType->isNullPtrType() &&
10129         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10130       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10131       return computeResultTy();
10132     }
10133     if (!IsRelational && LHSType->isNullPtrType() &&
10134         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10135       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10136       return computeResultTy();
10137     }
10138 
10139     if (IsRelational &&
10140         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10141          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10142       // HACK: Relational comparison of nullptr_t against a pointer type is
10143       // invalid per DR583, but we allow it within std::less<> and friends,
10144       // since otherwise common uses of it break.
10145       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10146       // friends to have std::nullptr_t overload candidates.
10147       DeclContext *DC = CurContext;
10148       if (isa<FunctionDecl>(DC))
10149         DC = DC->getParent();
10150       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10151         if (CTSD->isInStdNamespace() &&
10152             llvm::StringSwitch<bool>(CTSD->getName())
10153                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10154                 .Default(false)) {
10155           if (RHSType->isNullPtrType())
10156             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10157           else
10158             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10159           return computeResultTy();
10160         }
10161       }
10162     }
10163 
10164     // C++ [expr.eq]p2:
10165     //   If at least one operand is a pointer to member, [...] bring them to
10166     //   their composite pointer type.
10167     if (!IsRelational &&
10168         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10169       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10170         return QualType();
10171       else
10172         return computeResultTy();
10173     }
10174   }
10175 
10176   // Handle block pointer types.
10177   if (!IsRelational && LHSType->isBlockPointerType() &&
10178       RHSType->isBlockPointerType()) {
10179     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10180     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10181 
10182     if (!LHSIsNull && !RHSIsNull &&
10183         !Context.typesAreCompatible(lpointee, rpointee)) {
10184       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10185         << LHSType << RHSType << LHS.get()->getSourceRange()
10186         << RHS.get()->getSourceRange();
10187     }
10188     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10189     return computeResultTy();
10190   }
10191 
10192   // Allow block pointers to be compared with null pointer constants.
10193   if (!IsRelational
10194       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10195           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10196     if (!LHSIsNull && !RHSIsNull) {
10197       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10198              ->getPointeeType()->isVoidType())
10199             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10200                 ->getPointeeType()->isVoidType())))
10201         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10202           << LHSType << RHSType << LHS.get()->getSourceRange()
10203           << RHS.get()->getSourceRange();
10204     }
10205     if (LHSIsNull && !RHSIsNull)
10206       LHS = ImpCastExprToType(LHS.get(), RHSType,
10207                               RHSType->isPointerType() ? CK_BitCast
10208                                 : CK_AnyPointerToBlockPointerCast);
10209     else
10210       RHS = ImpCastExprToType(RHS.get(), LHSType,
10211                               LHSType->isPointerType() ? CK_BitCast
10212                                 : CK_AnyPointerToBlockPointerCast);
10213     return computeResultTy();
10214   }
10215 
10216   if (LHSType->isObjCObjectPointerType() ||
10217       RHSType->isObjCObjectPointerType()) {
10218     const PointerType *LPT = LHSType->getAs<PointerType>();
10219     const PointerType *RPT = RHSType->getAs<PointerType>();
10220     if (LPT || RPT) {
10221       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10222       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10223 
10224       if (!LPtrToVoid && !RPtrToVoid &&
10225           !Context.typesAreCompatible(LHSType, RHSType)) {
10226         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10227                                           /*isError*/false);
10228       }
10229       if (LHSIsNull && !RHSIsNull) {
10230         Expr *E = LHS.get();
10231         if (getLangOpts().ObjCAutoRefCount)
10232           CheckObjCConversion(SourceRange(), RHSType, E,
10233                               CCK_ImplicitConversion);
10234         LHS = ImpCastExprToType(E, RHSType,
10235                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10236       }
10237       else {
10238         Expr *E = RHS.get();
10239         if (getLangOpts().ObjCAutoRefCount)
10240           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10241                               /*Diagnose=*/true,
10242                               /*DiagnoseCFAudited=*/false, Opc);
10243         RHS = ImpCastExprToType(E, LHSType,
10244                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10245       }
10246       return computeResultTy();
10247     }
10248     if (LHSType->isObjCObjectPointerType() &&
10249         RHSType->isObjCObjectPointerType()) {
10250       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10251         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10252                                           /*isError*/false);
10253       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10254         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10255 
10256       if (LHSIsNull && !RHSIsNull)
10257         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10258       else
10259         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10260       return computeResultTy();
10261     }
10262 
10263     if (!IsRelational && LHSType->isBlockPointerType() &&
10264         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10265       LHS = ImpCastExprToType(LHS.get(), RHSType,
10266                               CK_BlockPointerToObjCPointerCast);
10267       return computeResultTy();
10268     } else if (!IsRelational &&
10269                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10270                RHSType->isBlockPointerType()) {
10271       RHS = ImpCastExprToType(RHS.get(), LHSType,
10272                               CK_BlockPointerToObjCPointerCast);
10273       return computeResultTy();
10274     }
10275   }
10276   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10277       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10278     unsigned DiagID = 0;
10279     bool isError = false;
10280     if (LangOpts.DebuggerSupport) {
10281       // Under a debugger, allow the comparison of pointers to integers,
10282       // since users tend to want to compare addresses.
10283     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10284                (RHSIsNull && RHSType->isIntegerType())) {
10285       if (IsRelational) {
10286         isError = getLangOpts().CPlusPlus;
10287         DiagID =
10288           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10289                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10290       }
10291     } else if (getLangOpts().CPlusPlus) {
10292       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10293       isError = true;
10294     } else if (IsRelational)
10295       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10296     else
10297       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10298 
10299     if (DiagID) {
10300       Diag(Loc, DiagID)
10301         << LHSType << RHSType << LHS.get()->getSourceRange()
10302         << RHS.get()->getSourceRange();
10303       if (isError)
10304         return QualType();
10305     }
10306 
10307     if (LHSType->isIntegerType())
10308       LHS = ImpCastExprToType(LHS.get(), RHSType,
10309                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10310     else
10311       RHS = ImpCastExprToType(RHS.get(), LHSType,
10312                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10313     return computeResultTy();
10314   }
10315 
10316   // Handle block pointers.
10317   if (!IsRelational && RHSIsNull
10318       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10319     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10320     return computeResultTy();
10321   }
10322   if (!IsRelational && LHSIsNull
10323       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10324     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10325     return computeResultTy();
10326   }
10327 
10328   if (getLangOpts().OpenCLVersion >= 200) {
10329     if (LHSIsNull && RHSType->isQueueT()) {
10330       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10331       return computeResultTy();
10332     }
10333 
10334     if (LHSType->isQueueT() && RHSIsNull) {
10335       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10336       return computeResultTy();
10337     }
10338   }
10339 
10340   return InvalidOperands(Loc, LHS, RHS);
10341 }
10342 
10343 // Return a signed ext_vector_type that is of identical size and number of
10344 // elements. For floating point vectors, return an integer type of identical
10345 // size and number of elements. In the non ext_vector_type case, search from
10346 // the largest type to the smallest type to avoid cases where long long == long,
10347 // where long gets picked over long long.
10348 QualType Sema::GetSignedVectorType(QualType V) {
10349   const VectorType *VTy = V->getAs<VectorType>();
10350   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10351 
10352   if (isa<ExtVectorType>(VTy)) {
10353     if (TypeSize == Context.getTypeSize(Context.CharTy))
10354       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10355     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10356       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10357     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10358       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10359     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10360       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10361     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10362            "Unhandled vector element size in vector compare");
10363     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10364   }
10365 
10366   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10367     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10368                                  VectorType::GenericVector);
10369   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10370     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10371                                  VectorType::GenericVector);
10372   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10373     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10374                                  VectorType::GenericVector);
10375   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10376     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10377                                  VectorType::GenericVector);
10378   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10379          "Unhandled vector element size in vector compare");
10380   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10381                                VectorType::GenericVector);
10382 }
10383 
10384 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10385 /// operates on extended vector types.  Instead of producing an IntTy result,
10386 /// like a scalar comparison, a vector comparison produces a vector of integer
10387 /// types.
10388 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10389                                           SourceLocation Loc,
10390                                           BinaryOperatorKind Opc) {
10391   // Check to make sure we're operating on vectors of the same type and width,
10392   // Allowing one side to be a scalar of element type.
10393   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10394                               /*AllowBothBool*/true,
10395                               /*AllowBoolConversions*/getLangOpts().ZVector);
10396   if (vType.isNull())
10397     return vType;
10398 
10399   QualType LHSType = LHS.get()->getType();
10400 
10401   // If AltiVec, the comparison results in a numeric type, i.e.
10402   // bool for C++, int for C
10403   if (getLangOpts().AltiVec &&
10404       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10405     return Context.getLogicalOperationType();
10406 
10407   // For non-floating point types, check for self-comparisons of the form
10408   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10409   // often indicate logic errors in the program.
10410   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10411 
10412   // Check for comparisons of floating point operands using != and ==.
10413   if (BinaryOperator::isEqualityOp(Opc) &&
10414       LHSType->hasFloatingRepresentation()) {
10415     assert(RHS.get()->getType()->hasFloatingRepresentation());
10416     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10417   }
10418 
10419   // Return a signed type for the vector.
10420   return GetSignedVectorType(vType);
10421 }
10422 
10423 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10424                                           SourceLocation Loc) {
10425   // Ensure that either both operands are of the same vector type, or
10426   // one operand is of a vector type and the other is of its element type.
10427   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10428                                        /*AllowBothBool*/true,
10429                                        /*AllowBoolConversions*/false);
10430   if (vType.isNull())
10431     return InvalidOperands(Loc, LHS, RHS);
10432   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10433       vType->hasFloatingRepresentation())
10434     return InvalidOperands(Loc, LHS, RHS);
10435   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10436   //        usage of the logical operators && and || with vectors in C. This
10437   //        check could be notionally dropped.
10438   if (!getLangOpts().CPlusPlus &&
10439       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10440     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10441 
10442   return GetSignedVectorType(LHS.get()->getType());
10443 }
10444 
10445 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10446                                            SourceLocation Loc,
10447                                            BinaryOperatorKind Opc) {
10448   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10449 
10450   bool IsCompAssign =
10451       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10452 
10453   if (LHS.get()->getType()->isVectorType() ||
10454       RHS.get()->getType()->isVectorType()) {
10455     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10456         RHS.get()->getType()->hasIntegerRepresentation())
10457       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10458                         /*AllowBothBool*/true,
10459                         /*AllowBoolConversions*/getLangOpts().ZVector);
10460     return InvalidOperands(Loc, LHS, RHS);
10461   }
10462 
10463   if (Opc == BO_And)
10464     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10465 
10466   ExprResult LHSResult = LHS, RHSResult = RHS;
10467   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10468                                                  IsCompAssign);
10469   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10470     return QualType();
10471   LHS = LHSResult.get();
10472   RHS = RHSResult.get();
10473 
10474   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10475     return compType;
10476   return InvalidOperands(Loc, LHS, RHS);
10477 }
10478 
10479 // C99 6.5.[13,14]
10480 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10481                                            SourceLocation Loc,
10482                                            BinaryOperatorKind Opc) {
10483   // Check vector operands differently.
10484   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10485     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10486 
10487   // Diagnose cases where the user write a logical and/or but probably meant a
10488   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10489   // is a constant.
10490   if (LHS.get()->getType()->isIntegerType() &&
10491       !LHS.get()->getType()->isBooleanType() &&
10492       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10493       // Don't warn in macros or template instantiations.
10494       !Loc.isMacroID() && !inTemplateInstantiation()) {
10495     // If the RHS can be constant folded, and if it constant folds to something
10496     // that isn't 0 or 1 (which indicate a potential logical operation that
10497     // happened to fold to true/false) then warn.
10498     // Parens on the RHS are ignored.
10499     llvm::APSInt Result;
10500     if (RHS.get()->EvaluateAsInt(Result, Context))
10501       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10502            !RHS.get()->getExprLoc().isMacroID()) ||
10503           (Result != 0 && Result != 1)) {
10504         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10505           << RHS.get()->getSourceRange()
10506           << (Opc == BO_LAnd ? "&&" : "||");
10507         // Suggest replacing the logical operator with the bitwise version
10508         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10509             << (Opc == BO_LAnd ? "&" : "|")
10510             << FixItHint::CreateReplacement(SourceRange(
10511                                                  Loc, getLocForEndOfToken(Loc)),
10512                                             Opc == BO_LAnd ? "&" : "|");
10513         if (Opc == BO_LAnd)
10514           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10515           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10516               << FixItHint::CreateRemoval(
10517                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10518                               RHS.get()->getLocEnd()));
10519       }
10520   }
10521 
10522   if (!Context.getLangOpts().CPlusPlus) {
10523     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10524     // not operate on the built-in scalar and vector float types.
10525     if (Context.getLangOpts().OpenCL &&
10526         Context.getLangOpts().OpenCLVersion < 120) {
10527       if (LHS.get()->getType()->isFloatingType() ||
10528           RHS.get()->getType()->isFloatingType())
10529         return InvalidOperands(Loc, LHS, RHS);
10530     }
10531 
10532     LHS = UsualUnaryConversions(LHS.get());
10533     if (LHS.isInvalid())
10534       return QualType();
10535 
10536     RHS = UsualUnaryConversions(RHS.get());
10537     if (RHS.isInvalid())
10538       return QualType();
10539 
10540     if (!LHS.get()->getType()->isScalarType() ||
10541         !RHS.get()->getType()->isScalarType())
10542       return InvalidOperands(Loc, LHS, RHS);
10543 
10544     return Context.IntTy;
10545   }
10546 
10547   // The following is safe because we only use this method for
10548   // non-overloadable operands.
10549 
10550   // C++ [expr.log.and]p1
10551   // C++ [expr.log.or]p1
10552   // The operands are both contextually converted to type bool.
10553   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10554   if (LHSRes.isInvalid())
10555     return InvalidOperands(Loc, LHS, RHS);
10556   LHS = LHSRes;
10557 
10558   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10559   if (RHSRes.isInvalid())
10560     return InvalidOperands(Loc, LHS, RHS);
10561   RHS = RHSRes;
10562 
10563   // C++ [expr.log.and]p2
10564   // C++ [expr.log.or]p2
10565   // The result is a bool.
10566   return Context.BoolTy;
10567 }
10568 
10569 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10570   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10571   if (!ME) return false;
10572   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10573   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10574       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10575   if (!Base) return false;
10576   return Base->getMethodDecl() != nullptr;
10577 }
10578 
10579 /// Is the given expression (which must be 'const') a reference to a
10580 /// variable which was originally non-const, but which has become
10581 /// 'const' due to being captured within a block?
10582 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10583 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10584   assert(E->isLValue() && E->getType().isConstQualified());
10585   E = E->IgnoreParens();
10586 
10587   // Must be a reference to a declaration from an enclosing scope.
10588   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10589   if (!DRE) return NCCK_None;
10590   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10591 
10592   // The declaration must be a variable which is not declared 'const'.
10593   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10594   if (!var) return NCCK_None;
10595   if (var->getType().isConstQualified()) return NCCK_None;
10596   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10597 
10598   // Decide whether the first capture was for a block or a lambda.
10599   DeclContext *DC = S.CurContext, *Prev = nullptr;
10600   // Decide whether the first capture was for a block or a lambda.
10601   while (DC) {
10602     // For init-capture, it is possible that the variable belongs to the
10603     // template pattern of the current context.
10604     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10605       if (var->isInitCapture() &&
10606           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10607         break;
10608     if (DC == var->getDeclContext())
10609       break;
10610     Prev = DC;
10611     DC = DC->getParent();
10612   }
10613   // Unless we have an init-capture, we've gone one step too far.
10614   if (!var->isInitCapture())
10615     DC = Prev;
10616   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10617 }
10618 
10619 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10620   Ty = Ty.getNonReferenceType();
10621   if (IsDereference && Ty->isPointerType())
10622     Ty = Ty->getPointeeType();
10623   return !Ty.isConstQualified();
10624 }
10625 
10626 // Update err_typecheck_assign_const and note_typecheck_assign_const
10627 // when this enum is changed.
10628 enum {
10629   ConstFunction,
10630   ConstVariable,
10631   ConstMember,
10632   ConstMethod,
10633   NestedConstMember,
10634   ConstUnknown,  // Keep as last element
10635 };
10636 
10637 /// Emit the "read-only variable not assignable" error and print notes to give
10638 /// more information about why the variable is not assignable, such as pointing
10639 /// to the declaration of a const variable, showing that a method is const, or
10640 /// that the function is returning a const reference.
10641 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10642                                     SourceLocation Loc) {
10643   SourceRange ExprRange = E->getSourceRange();
10644 
10645   // Only emit one error on the first const found.  All other consts will emit
10646   // a note to the error.
10647   bool DiagnosticEmitted = false;
10648 
10649   // Track if the current expression is the result of a dereference, and if the
10650   // next checked expression is the result of a dereference.
10651   bool IsDereference = false;
10652   bool NextIsDereference = false;
10653 
10654   // Loop to process MemberExpr chains.
10655   while (true) {
10656     IsDereference = NextIsDereference;
10657 
10658     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10659     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10660       NextIsDereference = ME->isArrow();
10661       const ValueDecl *VD = ME->getMemberDecl();
10662       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10663         // Mutable fields can be modified even if the class is const.
10664         if (Field->isMutable()) {
10665           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10666           break;
10667         }
10668 
10669         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10670           if (!DiagnosticEmitted) {
10671             S.Diag(Loc, diag::err_typecheck_assign_const)
10672                 << ExprRange << ConstMember << false /*static*/ << Field
10673                 << Field->getType();
10674             DiagnosticEmitted = true;
10675           }
10676           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10677               << ConstMember << false /*static*/ << Field << Field->getType()
10678               << Field->getSourceRange();
10679         }
10680         E = ME->getBase();
10681         continue;
10682       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10683         if (VDecl->getType().isConstQualified()) {
10684           if (!DiagnosticEmitted) {
10685             S.Diag(Loc, diag::err_typecheck_assign_const)
10686                 << ExprRange << ConstMember << true /*static*/ << VDecl
10687                 << VDecl->getType();
10688             DiagnosticEmitted = true;
10689           }
10690           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10691               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10692               << VDecl->getSourceRange();
10693         }
10694         // Static fields do not inherit constness from parents.
10695         break;
10696       }
10697       break; // End MemberExpr
10698     } else if (const ArraySubscriptExpr *ASE =
10699                    dyn_cast<ArraySubscriptExpr>(E)) {
10700       E = ASE->getBase()->IgnoreParenImpCasts();
10701       continue;
10702     } else if (const ExtVectorElementExpr *EVE =
10703                    dyn_cast<ExtVectorElementExpr>(E)) {
10704       E = EVE->getBase()->IgnoreParenImpCasts();
10705       continue;
10706     }
10707     break;
10708   }
10709 
10710   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10711     // Function calls
10712     const FunctionDecl *FD = CE->getDirectCallee();
10713     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10714       if (!DiagnosticEmitted) {
10715         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10716                                                       << ConstFunction << FD;
10717         DiagnosticEmitted = true;
10718       }
10719       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10720              diag::note_typecheck_assign_const)
10721           << ConstFunction << FD << FD->getReturnType()
10722           << FD->getReturnTypeSourceRange();
10723     }
10724   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10725     // Point to variable declaration.
10726     if (const ValueDecl *VD = DRE->getDecl()) {
10727       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10728         if (!DiagnosticEmitted) {
10729           S.Diag(Loc, diag::err_typecheck_assign_const)
10730               << ExprRange << ConstVariable << VD << VD->getType();
10731           DiagnosticEmitted = true;
10732         }
10733         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10734             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10735       }
10736     }
10737   } else if (isa<CXXThisExpr>(E)) {
10738     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10739       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10740         if (MD->isConst()) {
10741           if (!DiagnosticEmitted) {
10742             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10743                                                           << ConstMethod << MD;
10744             DiagnosticEmitted = true;
10745           }
10746           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10747               << ConstMethod << MD << MD->getSourceRange();
10748         }
10749       }
10750     }
10751   }
10752 
10753   if (DiagnosticEmitted)
10754     return;
10755 
10756   // Can't determine a more specific message, so display the generic error.
10757   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10758 }
10759 
10760 enum OriginalExprKind {
10761   OEK_Variable,
10762   OEK_Member,
10763   OEK_LValue
10764 };
10765 
10766 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
10767                                          const RecordType *Ty,
10768                                          SourceLocation Loc, SourceRange Range,
10769                                          OriginalExprKind OEK,
10770                                          bool &DiagnosticEmitted,
10771                                          bool IsNested = false) {
10772   // We walk the record hierarchy breadth-first to ensure that we print
10773   // diagnostics in field nesting order.
10774   // First, check every field for constness.
10775   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10776     if (Field->getType().isConstQualified()) {
10777       if (!DiagnosticEmitted) {
10778         S.Diag(Loc, diag::err_typecheck_assign_const)
10779             << Range << NestedConstMember << OEK << VD
10780             << IsNested << Field;
10781         DiagnosticEmitted = true;
10782       }
10783       S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
10784           << NestedConstMember << IsNested << Field
10785           << Field->getType() << Field->getSourceRange();
10786     }
10787   }
10788   // Then, recurse.
10789   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10790     QualType FTy = Field->getType();
10791     if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
10792       DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
10793                                    OEK, DiagnosticEmitted, true);
10794   }
10795 }
10796 
10797 /// Emit an error for the case where a record we are trying to assign to has a
10798 /// const-qualified field somewhere in its hierarchy.
10799 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
10800                                          SourceLocation Loc) {
10801   QualType Ty = E->getType();
10802   assert(Ty->isRecordType() && "lvalue was not record?");
10803   SourceRange Range = E->getSourceRange();
10804   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
10805   bool DiagEmitted = false;
10806 
10807   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10808     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
10809             Range, OEK_Member, DiagEmitted);
10810   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10811     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
10812             Range, OEK_Variable, DiagEmitted);
10813   else
10814     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
10815             Range, OEK_LValue, DiagEmitted);
10816   if (!DiagEmitted)
10817     DiagnoseConstAssignment(S, E, Loc);
10818 }
10819 
10820 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10821 /// emit an error and return true.  If so, return false.
10822 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10823   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10824 
10825   S.CheckShadowingDeclModification(E, Loc);
10826 
10827   SourceLocation OrigLoc = Loc;
10828   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10829                                                               &Loc);
10830   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10831     IsLV = Expr::MLV_InvalidMessageExpression;
10832   if (IsLV == Expr::MLV_Valid)
10833     return false;
10834 
10835   unsigned DiagID = 0;
10836   bool NeedType = false;
10837   switch (IsLV) { // C99 6.5.16p2
10838   case Expr::MLV_ConstQualified:
10839     // Use a specialized diagnostic when we're assigning to an object
10840     // from an enclosing function or block.
10841     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10842       if (NCCK == NCCK_Block)
10843         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10844       else
10845         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10846       break;
10847     }
10848 
10849     // In ARC, use some specialized diagnostics for occasions where we
10850     // infer 'const'.  These are always pseudo-strong variables.
10851     if (S.getLangOpts().ObjCAutoRefCount) {
10852       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10853       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10854         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10855 
10856         // Use the normal diagnostic if it's pseudo-__strong but the
10857         // user actually wrote 'const'.
10858         if (var->isARCPseudoStrong() &&
10859             (!var->getTypeSourceInfo() ||
10860              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10861           // There are two pseudo-strong cases:
10862           //  - self
10863           ObjCMethodDecl *method = S.getCurMethodDecl();
10864           if (method && var == method->getSelfDecl())
10865             DiagID = method->isClassMethod()
10866               ? diag::err_typecheck_arc_assign_self_class_method
10867               : diag::err_typecheck_arc_assign_self;
10868 
10869           //  - fast enumeration variables
10870           else
10871             DiagID = diag::err_typecheck_arr_assign_enumeration;
10872 
10873           SourceRange Assign;
10874           if (Loc != OrigLoc)
10875             Assign = SourceRange(OrigLoc, OrigLoc);
10876           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10877           // We need to preserve the AST regardless, so migration tool
10878           // can do its job.
10879           return false;
10880         }
10881       }
10882     }
10883 
10884     // If none of the special cases above are triggered, then this is a
10885     // simple const assignment.
10886     if (DiagID == 0) {
10887       DiagnoseConstAssignment(S, E, Loc);
10888       return true;
10889     }
10890 
10891     break;
10892   case Expr::MLV_ConstAddrSpace:
10893     DiagnoseConstAssignment(S, E, Loc);
10894     return true;
10895   case Expr::MLV_ConstQualifiedField:
10896     DiagnoseRecursiveConstFields(S, E, Loc);
10897     return true;
10898   case Expr::MLV_ArrayType:
10899   case Expr::MLV_ArrayTemporary:
10900     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10901     NeedType = true;
10902     break;
10903   case Expr::MLV_NotObjectType:
10904     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10905     NeedType = true;
10906     break;
10907   case Expr::MLV_LValueCast:
10908     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10909     break;
10910   case Expr::MLV_Valid:
10911     llvm_unreachable("did not take early return for MLV_Valid");
10912   case Expr::MLV_InvalidExpression:
10913   case Expr::MLV_MemberFunction:
10914   case Expr::MLV_ClassTemporary:
10915     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10916     break;
10917   case Expr::MLV_IncompleteType:
10918   case Expr::MLV_IncompleteVoidType:
10919     return S.RequireCompleteType(Loc, E->getType(),
10920              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10921   case Expr::MLV_DuplicateVectorComponents:
10922     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10923     break;
10924   case Expr::MLV_NoSetterProperty:
10925     llvm_unreachable("readonly properties should be processed differently");
10926   case Expr::MLV_InvalidMessageExpression:
10927     DiagID = diag::err_readonly_message_assignment;
10928     break;
10929   case Expr::MLV_SubObjCPropertySetting:
10930     DiagID = diag::err_no_subobject_property_setting;
10931     break;
10932   }
10933 
10934   SourceRange Assign;
10935   if (Loc != OrigLoc)
10936     Assign = SourceRange(OrigLoc, OrigLoc);
10937   if (NeedType)
10938     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10939   else
10940     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10941   return true;
10942 }
10943 
10944 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10945                                          SourceLocation Loc,
10946                                          Sema &Sema) {
10947   if (Sema.inTemplateInstantiation())
10948     return;
10949   if (Sema.isUnevaluatedContext())
10950     return;
10951   if (Loc.isInvalid() || Loc.isMacroID())
10952     return;
10953   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
10954     return;
10955 
10956   // C / C++ fields
10957   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10958   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10959   if (ML && MR) {
10960     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
10961       return;
10962     const ValueDecl *LHSDecl =
10963         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
10964     const ValueDecl *RHSDecl =
10965         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
10966     if (LHSDecl != RHSDecl)
10967       return;
10968     if (LHSDecl->getType().isVolatileQualified())
10969       return;
10970     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10971       if (RefTy->getPointeeType().isVolatileQualified())
10972         return;
10973 
10974     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10975   }
10976 
10977   // Objective-C instance variables
10978   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10979   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10980   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10981     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10982     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10983     if (RL && RR && RL->getDecl() == RR->getDecl())
10984       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10985   }
10986 }
10987 
10988 // C99 6.5.16.1
10989 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10990                                        SourceLocation Loc,
10991                                        QualType CompoundType) {
10992   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10993 
10994   // Verify that LHS is a modifiable lvalue, and emit error if not.
10995   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10996     return QualType();
10997 
10998   QualType LHSType = LHSExpr->getType();
10999   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11000                                              CompoundType;
11001   // OpenCL v1.2 s6.1.1.1 p2:
11002   // The half data type can only be used to declare a pointer to a buffer that
11003   // contains half values
11004   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11005     LHSType->isHalfType()) {
11006     Diag(Loc, diag::err_opencl_half_load_store) << 1
11007         << LHSType.getUnqualifiedType();
11008     return QualType();
11009   }
11010 
11011   AssignConvertType ConvTy;
11012   if (CompoundType.isNull()) {
11013     Expr *RHSCheck = RHS.get();
11014 
11015     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11016 
11017     QualType LHSTy(LHSType);
11018     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11019     if (RHS.isInvalid())
11020       return QualType();
11021     // Special case of NSObject attributes on c-style pointer types.
11022     if (ConvTy == IncompatiblePointer &&
11023         ((Context.isObjCNSObjectType(LHSType) &&
11024           RHSType->isObjCObjectPointerType()) ||
11025          (Context.isObjCNSObjectType(RHSType) &&
11026           LHSType->isObjCObjectPointerType())))
11027       ConvTy = Compatible;
11028 
11029     if (ConvTy == Compatible &&
11030         LHSType->isObjCObjectType())
11031         Diag(Loc, diag::err_objc_object_assignment)
11032           << LHSType;
11033 
11034     // If the RHS is a unary plus or minus, check to see if they = and + are
11035     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11036     // instead of "x += 4".
11037     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11038       RHSCheck = ICE->getSubExpr();
11039     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11040       if ((UO->getOpcode() == UO_Plus ||
11041            UO->getOpcode() == UO_Minus) &&
11042           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11043           // Only if the two operators are exactly adjacent.
11044           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11045           // And there is a space or other character before the subexpr of the
11046           // unary +/-.  We don't want to warn on "x=-1".
11047           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
11048           UO->getSubExpr()->getLocStart().isFileID()) {
11049         Diag(Loc, diag::warn_not_compound_assign)
11050           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11051           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11052       }
11053     }
11054 
11055     if (ConvTy == Compatible) {
11056       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11057         // Warn about retain cycles where a block captures the LHS, but
11058         // not if the LHS is a simple variable into which the block is
11059         // being stored...unless that variable can be captured by reference!
11060         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11061         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11062         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11063           checkRetainCycles(LHSExpr, RHS.get());
11064       }
11065 
11066       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11067           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11068         // It is safe to assign a weak reference into a strong variable.
11069         // Although this code can still have problems:
11070         //   id x = self.weakProp;
11071         //   id y = self.weakProp;
11072         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11073         // paths through the function. This should be revisited if
11074         // -Wrepeated-use-of-weak is made flow-sensitive.
11075         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11076         // variable, which will be valid for the current autorelease scope.
11077         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11078                              RHS.get()->getLocStart()))
11079           getCurFunction()->markSafeWeakUse(RHS.get());
11080 
11081       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11082         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11083       }
11084     }
11085   } else {
11086     // Compound assignment "x += y"
11087     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11088   }
11089 
11090   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11091                                RHS.get(), AA_Assigning))
11092     return QualType();
11093 
11094   CheckForNullPointerDereference(*this, LHSExpr);
11095 
11096   // C99 6.5.16p3: The type of an assignment expression is the type of the
11097   // left operand unless the left operand has qualified type, in which case
11098   // it is the unqualified version of the type of the left operand.
11099   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11100   // is converted to the type of the assignment expression (above).
11101   // C++ 5.17p1: the type of the assignment expression is that of its left
11102   // operand.
11103   return (getLangOpts().CPlusPlus
11104           ? LHSType : LHSType.getUnqualifiedType());
11105 }
11106 
11107 // Only ignore explicit casts to void.
11108 static bool IgnoreCommaOperand(const Expr *E) {
11109   E = E->IgnoreParens();
11110 
11111   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11112     if (CE->getCastKind() == CK_ToVoid) {
11113       return true;
11114     }
11115   }
11116 
11117   return false;
11118 }
11119 
11120 // Look for instances where it is likely the comma operator is confused with
11121 // another operator.  There is a whitelist of acceptable expressions for the
11122 // left hand side of the comma operator, otherwise emit a warning.
11123 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11124   // No warnings in macros
11125   if (Loc.isMacroID())
11126     return;
11127 
11128   // Don't warn in template instantiations.
11129   if (inTemplateInstantiation())
11130     return;
11131 
11132   // Scope isn't fine-grained enough to whitelist the specific cases, so
11133   // instead, skip more than needed, then call back into here with the
11134   // CommaVisitor in SemaStmt.cpp.
11135   // The whitelisted locations are the initialization and increment portions
11136   // of a for loop.  The additional checks are on the condition of
11137   // if statements, do/while loops, and for loops.
11138   const unsigned ForIncrementFlags =
11139       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
11140   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11141   const unsigned ScopeFlags = getCurScope()->getFlags();
11142   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11143       (ScopeFlags & ForInitFlags) == ForInitFlags)
11144     return;
11145 
11146   // If there are multiple comma operators used together, get the RHS of the
11147   // of the comma operator as the LHS.
11148   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11149     if (BO->getOpcode() != BO_Comma)
11150       break;
11151     LHS = BO->getRHS();
11152   }
11153 
11154   // Only allow some expressions on LHS to not warn.
11155   if (IgnoreCommaOperand(LHS))
11156     return;
11157 
11158   Diag(Loc, diag::warn_comma_operator);
11159   Diag(LHS->getLocStart(), diag::note_cast_to_void)
11160       << LHS->getSourceRange()
11161       << FixItHint::CreateInsertion(LHS->getLocStart(),
11162                                     LangOpts.CPlusPlus ? "static_cast<void>("
11163                                                        : "(void)(")
11164       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
11165                                     ")");
11166 }
11167 
11168 // C99 6.5.17
11169 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11170                                    SourceLocation Loc) {
11171   LHS = S.CheckPlaceholderExpr(LHS.get());
11172   RHS = S.CheckPlaceholderExpr(RHS.get());
11173   if (LHS.isInvalid() || RHS.isInvalid())
11174     return QualType();
11175 
11176   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11177   // operands, but not unary promotions.
11178   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11179 
11180   // So we treat the LHS as a ignored value, and in C++ we allow the
11181   // containing site to determine what should be done with the RHS.
11182   LHS = S.IgnoredValueConversions(LHS.get());
11183   if (LHS.isInvalid())
11184     return QualType();
11185 
11186   S.DiagnoseUnusedExprResult(LHS.get());
11187 
11188   if (!S.getLangOpts().CPlusPlus) {
11189     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11190     if (RHS.isInvalid())
11191       return QualType();
11192     if (!RHS.get()->getType()->isVoidType())
11193       S.RequireCompleteType(Loc, RHS.get()->getType(),
11194                             diag::err_incomplete_type);
11195   }
11196 
11197   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11198     S.DiagnoseCommaOperator(LHS.get(), Loc);
11199 
11200   return RHS.get()->getType();
11201 }
11202 
11203 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11204 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11205 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11206                                                ExprValueKind &VK,
11207                                                ExprObjectKind &OK,
11208                                                SourceLocation OpLoc,
11209                                                bool IsInc, bool IsPrefix) {
11210   if (Op->isTypeDependent())
11211     return S.Context.DependentTy;
11212 
11213   QualType ResType = Op->getType();
11214   // Atomic types can be used for increment / decrement where the non-atomic
11215   // versions can, so ignore the _Atomic() specifier for the purpose of
11216   // checking.
11217   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11218     ResType = ResAtomicType->getValueType();
11219 
11220   assert(!ResType.isNull() && "no type for increment/decrement expression");
11221 
11222   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11223     // Decrement of bool is not allowed.
11224     if (!IsInc) {
11225       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11226       return QualType();
11227     }
11228     // Increment of bool sets it to true, but is deprecated.
11229     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11230                                               : diag::warn_increment_bool)
11231       << Op->getSourceRange();
11232   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11233     // Error on enum increments and decrements in C++ mode
11234     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11235     return QualType();
11236   } else if (ResType->isRealType()) {
11237     // OK!
11238   } else if (ResType->isPointerType()) {
11239     // C99 6.5.2.4p2, 6.5.6p2
11240     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11241       return QualType();
11242   } else if (ResType->isObjCObjectPointerType()) {
11243     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11244     // Otherwise, we just need a complete type.
11245     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11246         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11247       return QualType();
11248   } else if (ResType->isAnyComplexType()) {
11249     // C99 does not support ++/-- on complex types, we allow as an extension.
11250     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11251       << ResType << Op->getSourceRange();
11252   } else if (ResType->isPlaceholderType()) {
11253     ExprResult PR = S.CheckPlaceholderExpr(Op);
11254     if (PR.isInvalid()) return QualType();
11255     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11256                                           IsInc, IsPrefix);
11257   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11258     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11259   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11260              (ResType->getAs<VectorType>()->getVectorKind() !=
11261               VectorType::AltiVecBool)) {
11262     // The z vector extensions allow ++ and -- for non-bool vectors.
11263   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11264             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11265     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11266   } else {
11267     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11268       << ResType << int(IsInc) << Op->getSourceRange();
11269     return QualType();
11270   }
11271   // At this point, we know we have a real, complex or pointer type.
11272   // Now make sure the operand is a modifiable lvalue.
11273   if (CheckForModifiableLvalue(Op, OpLoc, S))
11274     return QualType();
11275   // In C++, a prefix increment is the same type as the operand. Otherwise
11276   // (in C or with postfix), the increment is the unqualified type of the
11277   // operand.
11278   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11279     VK = VK_LValue;
11280     OK = Op->getObjectKind();
11281     return ResType;
11282   } else {
11283     VK = VK_RValue;
11284     return ResType.getUnqualifiedType();
11285   }
11286 }
11287 
11288 
11289 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11290 /// This routine allows us to typecheck complex/recursive expressions
11291 /// where the declaration is needed for type checking. We only need to
11292 /// handle cases when the expression references a function designator
11293 /// or is an lvalue. Here are some examples:
11294 ///  - &(x) => x
11295 ///  - &*****f => f for f a function designator.
11296 ///  - &s.xx => s
11297 ///  - &s.zz[1].yy -> s, if zz is an array
11298 ///  - *(x + 1) -> x, if x is an array
11299 ///  - &"123"[2] -> 0
11300 ///  - & __real__ x -> x
11301 static ValueDecl *getPrimaryDecl(Expr *E) {
11302   switch (E->getStmtClass()) {
11303   case Stmt::DeclRefExprClass:
11304     return cast<DeclRefExpr>(E)->getDecl();
11305   case Stmt::MemberExprClass:
11306     // If this is an arrow operator, the address is an offset from
11307     // the base's value, so the object the base refers to is
11308     // irrelevant.
11309     if (cast<MemberExpr>(E)->isArrow())
11310       return nullptr;
11311     // Otherwise, the expression refers to a part of the base
11312     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11313   case Stmt::ArraySubscriptExprClass: {
11314     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11315     // promotion of register arrays earlier.
11316     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11317     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11318       if (ICE->getSubExpr()->getType()->isArrayType())
11319         return getPrimaryDecl(ICE->getSubExpr());
11320     }
11321     return nullptr;
11322   }
11323   case Stmt::UnaryOperatorClass: {
11324     UnaryOperator *UO = cast<UnaryOperator>(E);
11325 
11326     switch(UO->getOpcode()) {
11327     case UO_Real:
11328     case UO_Imag:
11329     case UO_Extension:
11330       return getPrimaryDecl(UO->getSubExpr());
11331     default:
11332       return nullptr;
11333     }
11334   }
11335   case Stmt::ParenExprClass:
11336     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11337   case Stmt::ImplicitCastExprClass:
11338     // If the result of an implicit cast is an l-value, we care about
11339     // the sub-expression; otherwise, the result here doesn't matter.
11340     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11341   default:
11342     return nullptr;
11343   }
11344 }
11345 
11346 namespace {
11347   enum {
11348     AO_Bit_Field = 0,
11349     AO_Vector_Element = 1,
11350     AO_Property_Expansion = 2,
11351     AO_Register_Variable = 3,
11352     AO_No_Error = 4
11353   };
11354 }
11355 /// Diagnose invalid operand for address of operations.
11356 ///
11357 /// \param Type The type of operand which cannot have its address taken.
11358 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11359                                          Expr *E, unsigned Type) {
11360   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11361 }
11362 
11363 /// CheckAddressOfOperand - The operand of & must be either a function
11364 /// designator or an lvalue designating an object. If it is an lvalue, the
11365 /// object cannot be declared with storage class register or be a bit field.
11366 /// Note: The usual conversions are *not* applied to the operand of the &
11367 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11368 /// In C++, the operand might be an overloaded function name, in which case
11369 /// we allow the '&' but retain the overloaded-function type.
11370 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11371   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11372     if (PTy->getKind() == BuiltinType::Overload) {
11373       Expr *E = OrigOp.get()->IgnoreParens();
11374       if (!isa<OverloadExpr>(E)) {
11375         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11376         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11377           << OrigOp.get()->getSourceRange();
11378         return QualType();
11379       }
11380 
11381       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11382       if (isa<UnresolvedMemberExpr>(Ovl))
11383         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11384           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11385             << OrigOp.get()->getSourceRange();
11386           return QualType();
11387         }
11388 
11389       return Context.OverloadTy;
11390     }
11391 
11392     if (PTy->getKind() == BuiltinType::UnknownAny)
11393       return Context.UnknownAnyTy;
11394 
11395     if (PTy->getKind() == BuiltinType::BoundMember) {
11396       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11397         << OrigOp.get()->getSourceRange();
11398       return QualType();
11399     }
11400 
11401     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11402     if (OrigOp.isInvalid()) return QualType();
11403   }
11404 
11405   if (OrigOp.get()->isTypeDependent())
11406     return Context.DependentTy;
11407 
11408   assert(!OrigOp.get()->getType()->isPlaceholderType());
11409 
11410   // Make sure to ignore parentheses in subsequent checks
11411   Expr *op = OrigOp.get()->IgnoreParens();
11412 
11413   // In OpenCL captures for blocks called as lambda functions
11414   // are located in the private address space. Blocks used in
11415   // enqueue_kernel can be located in a different address space
11416   // depending on a vendor implementation. Thus preventing
11417   // taking an address of the capture to avoid invalid AS casts.
11418   if (LangOpts.OpenCL) {
11419     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11420     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11421       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11422       return QualType();
11423     }
11424   }
11425 
11426   if (getLangOpts().C99) {
11427     // Implement C99-only parts of addressof rules.
11428     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11429       if (uOp->getOpcode() == UO_Deref)
11430         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11431         // (assuming the deref expression is valid).
11432         return uOp->getSubExpr()->getType();
11433     }
11434     // Technically, there should be a check for array subscript
11435     // expressions here, but the result of one is always an lvalue anyway.
11436   }
11437   ValueDecl *dcl = getPrimaryDecl(op);
11438 
11439   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11440     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11441                                            op->getLocStart()))
11442       return QualType();
11443 
11444   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11445   unsigned AddressOfError = AO_No_Error;
11446 
11447   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11448     bool sfinae = (bool)isSFINAEContext();
11449     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11450                                   : diag::ext_typecheck_addrof_temporary)
11451       << op->getType() << op->getSourceRange();
11452     if (sfinae)
11453       return QualType();
11454     // Materialize the temporary as an lvalue so that we can take its address.
11455     OrigOp = op =
11456         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11457   } else if (isa<ObjCSelectorExpr>(op)) {
11458     return Context.getPointerType(op->getType());
11459   } else if (lval == Expr::LV_MemberFunction) {
11460     // If it's an instance method, make a member pointer.
11461     // The expression must have exactly the form &A::foo.
11462 
11463     // If the underlying expression isn't a decl ref, give up.
11464     if (!isa<DeclRefExpr>(op)) {
11465       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11466         << OrigOp.get()->getSourceRange();
11467       return QualType();
11468     }
11469     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11470     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11471 
11472     // The id-expression was parenthesized.
11473     if (OrigOp.get() != DRE) {
11474       Diag(OpLoc, diag::err_parens_pointer_member_function)
11475         << OrigOp.get()->getSourceRange();
11476 
11477     // The method was named without a qualifier.
11478     } else if (!DRE->getQualifier()) {
11479       if (MD->getParent()->getName().empty())
11480         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11481           << op->getSourceRange();
11482       else {
11483         SmallString<32> Str;
11484         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11485         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11486           << op->getSourceRange()
11487           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11488       }
11489     }
11490 
11491     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11492     if (isa<CXXDestructorDecl>(MD))
11493       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11494 
11495     QualType MPTy = Context.getMemberPointerType(
11496         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11497     // Under the MS ABI, lock down the inheritance model now.
11498     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11499       (void)isCompleteType(OpLoc, MPTy);
11500     return MPTy;
11501   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11502     // C99 6.5.3.2p1
11503     // The operand must be either an l-value or a function designator
11504     if (!op->getType()->isFunctionType()) {
11505       // Use a special diagnostic for loads from property references.
11506       if (isa<PseudoObjectExpr>(op)) {
11507         AddressOfError = AO_Property_Expansion;
11508       } else {
11509         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11510           << op->getType() << op->getSourceRange();
11511         return QualType();
11512       }
11513     }
11514   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11515     // The operand cannot be a bit-field
11516     AddressOfError = AO_Bit_Field;
11517   } else if (op->getObjectKind() == OK_VectorComponent) {
11518     // The operand cannot be an element of a vector
11519     AddressOfError = AO_Vector_Element;
11520   } else if (dcl) { // C99 6.5.3.2p1
11521     // We have an lvalue with a decl. Make sure the decl is not declared
11522     // with the register storage-class specifier.
11523     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11524       // in C++ it is not error to take address of a register
11525       // variable (c++03 7.1.1P3)
11526       if (vd->getStorageClass() == SC_Register &&
11527           !getLangOpts().CPlusPlus) {
11528         AddressOfError = AO_Register_Variable;
11529       }
11530     } else if (isa<MSPropertyDecl>(dcl)) {
11531       AddressOfError = AO_Property_Expansion;
11532     } else if (isa<FunctionTemplateDecl>(dcl)) {
11533       return Context.OverloadTy;
11534     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11535       // Okay: we can take the address of a field.
11536       // Could be a pointer to member, though, if there is an explicit
11537       // scope qualifier for the class.
11538       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11539         DeclContext *Ctx = dcl->getDeclContext();
11540         if (Ctx && Ctx->isRecord()) {
11541           if (dcl->getType()->isReferenceType()) {
11542             Diag(OpLoc,
11543                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11544               << dcl->getDeclName() << dcl->getType();
11545             return QualType();
11546           }
11547 
11548           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11549             Ctx = Ctx->getParent();
11550 
11551           QualType MPTy = Context.getMemberPointerType(
11552               op->getType(),
11553               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11554           // Under the MS ABI, lock down the inheritance model now.
11555           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11556             (void)isCompleteType(OpLoc, MPTy);
11557           return MPTy;
11558         }
11559       }
11560     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11561                !isa<BindingDecl>(dcl))
11562       llvm_unreachable("Unknown/unexpected decl type");
11563   }
11564 
11565   if (AddressOfError != AO_No_Error) {
11566     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11567     return QualType();
11568   }
11569 
11570   if (lval == Expr::LV_IncompleteVoidType) {
11571     // Taking the address of a void variable is technically illegal, but we
11572     // allow it in cases which are otherwise valid.
11573     // Example: "extern void x; void* y = &x;".
11574     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11575   }
11576 
11577   // If the operand has type "type", the result has type "pointer to type".
11578   if (op->getType()->isObjCObjectType())
11579     return Context.getObjCObjectPointerType(op->getType());
11580 
11581   CheckAddressOfPackedMember(op);
11582 
11583   return Context.getPointerType(op->getType());
11584 }
11585 
11586 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11587   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11588   if (!DRE)
11589     return;
11590   const Decl *D = DRE->getDecl();
11591   if (!D)
11592     return;
11593   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11594   if (!Param)
11595     return;
11596   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11597     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11598       return;
11599   if (FunctionScopeInfo *FD = S.getCurFunction())
11600     if (!FD->ModifiedNonNullParams.count(Param))
11601       FD->ModifiedNonNullParams.insert(Param);
11602 }
11603 
11604 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11605 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11606                                         SourceLocation OpLoc) {
11607   if (Op->isTypeDependent())
11608     return S.Context.DependentTy;
11609 
11610   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11611   if (ConvResult.isInvalid())
11612     return QualType();
11613   Op = ConvResult.get();
11614   QualType OpTy = Op->getType();
11615   QualType Result;
11616 
11617   if (isa<CXXReinterpretCastExpr>(Op)) {
11618     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11619     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11620                                      Op->getSourceRange());
11621   }
11622 
11623   if (const PointerType *PT = OpTy->getAs<PointerType>())
11624   {
11625     Result = PT->getPointeeType();
11626   }
11627   else if (const ObjCObjectPointerType *OPT =
11628              OpTy->getAs<ObjCObjectPointerType>())
11629     Result = OPT->getPointeeType();
11630   else {
11631     ExprResult PR = S.CheckPlaceholderExpr(Op);
11632     if (PR.isInvalid()) return QualType();
11633     if (PR.get() != Op)
11634       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11635   }
11636 
11637   if (Result.isNull()) {
11638     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11639       << OpTy << Op->getSourceRange();
11640     return QualType();
11641   }
11642 
11643   // Note that per both C89 and C99, indirection is always legal, even if Result
11644   // is an incomplete type or void.  It would be possible to warn about
11645   // dereferencing a void pointer, but it's completely well-defined, and such a
11646   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11647   // for pointers to 'void' but is fine for any other pointer type:
11648   //
11649   // C++ [expr.unary.op]p1:
11650   //   [...] the expression to which [the unary * operator] is applied shall
11651   //   be a pointer to an object type, or a pointer to a function type
11652   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11653     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11654       << OpTy << Op->getSourceRange();
11655 
11656   // Dereferences are usually l-values...
11657   VK = VK_LValue;
11658 
11659   // ...except that certain expressions are never l-values in C.
11660   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11661     VK = VK_RValue;
11662 
11663   return Result;
11664 }
11665 
11666 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11667   BinaryOperatorKind Opc;
11668   switch (Kind) {
11669   default: llvm_unreachable("Unknown binop!");
11670   case tok::periodstar:           Opc = BO_PtrMemD; break;
11671   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11672   case tok::star:                 Opc = BO_Mul; break;
11673   case tok::slash:                Opc = BO_Div; break;
11674   case tok::percent:              Opc = BO_Rem; break;
11675   case tok::plus:                 Opc = BO_Add; break;
11676   case tok::minus:                Opc = BO_Sub; break;
11677   case tok::lessless:             Opc = BO_Shl; break;
11678   case tok::greatergreater:       Opc = BO_Shr; break;
11679   case tok::lessequal:            Opc = BO_LE; break;
11680   case tok::less:                 Opc = BO_LT; break;
11681   case tok::greaterequal:         Opc = BO_GE; break;
11682   case tok::greater:              Opc = BO_GT; break;
11683   case tok::exclaimequal:         Opc = BO_NE; break;
11684   case tok::equalequal:           Opc = BO_EQ; break;
11685   case tok::spaceship:            Opc = BO_Cmp; break;
11686   case tok::amp:                  Opc = BO_And; break;
11687   case tok::caret:                Opc = BO_Xor; break;
11688   case tok::pipe:                 Opc = BO_Or; break;
11689   case tok::ampamp:               Opc = BO_LAnd; break;
11690   case tok::pipepipe:             Opc = BO_LOr; break;
11691   case tok::equal:                Opc = BO_Assign; break;
11692   case tok::starequal:            Opc = BO_MulAssign; break;
11693   case tok::slashequal:           Opc = BO_DivAssign; break;
11694   case tok::percentequal:         Opc = BO_RemAssign; break;
11695   case tok::plusequal:            Opc = BO_AddAssign; break;
11696   case tok::minusequal:           Opc = BO_SubAssign; break;
11697   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11698   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11699   case tok::ampequal:             Opc = BO_AndAssign; break;
11700   case tok::caretequal:           Opc = BO_XorAssign; break;
11701   case tok::pipeequal:            Opc = BO_OrAssign; break;
11702   case tok::comma:                Opc = BO_Comma; break;
11703   }
11704   return Opc;
11705 }
11706 
11707 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11708   tok::TokenKind Kind) {
11709   UnaryOperatorKind Opc;
11710   switch (Kind) {
11711   default: llvm_unreachable("Unknown unary op!");
11712   case tok::plusplus:     Opc = UO_PreInc; break;
11713   case tok::minusminus:   Opc = UO_PreDec; break;
11714   case tok::amp:          Opc = UO_AddrOf; break;
11715   case tok::star:         Opc = UO_Deref; break;
11716   case tok::plus:         Opc = UO_Plus; break;
11717   case tok::minus:        Opc = UO_Minus; break;
11718   case tok::tilde:        Opc = UO_Not; break;
11719   case tok::exclaim:      Opc = UO_LNot; break;
11720   case tok::kw___real:    Opc = UO_Real; break;
11721   case tok::kw___imag:    Opc = UO_Imag; break;
11722   case tok::kw___extension__: Opc = UO_Extension; break;
11723   }
11724   return Opc;
11725 }
11726 
11727 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11728 /// This warning suppressed in the event of macro expansions.
11729 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11730                                    SourceLocation OpLoc, bool IsBuiltin) {
11731   if (S.inTemplateInstantiation())
11732     return;
11733   if (S.isUnevaluatedContext())
11734     return;
11735   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11736     return;
11737   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11738   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11739   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11740   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11741   if (!LHSDeclRef || !RHSDeclRef ||
11742       LHSDeclRef->getLocation().isMacroID() ||
11743       RHSDeclRef->getLocation().isMacroID())
11744     return;
11745   const ValueDecl *LHSDecl =
11746     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11747   const ValueDecl *RHSDecl =
11748     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11749   if (LHSDecl != RHSDecl)
11750     return;
11751   if (LHSDecl->getType().isVolatileQualified())
11752     return;
11753   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11754     if (RefTy->getPointeeType().isVolatileQualified())
11755       return;
11756 
11757   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
11758                           : diag::warn_self_assignment_overloaded)
11759       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
11760       << RHSExpr->getSourceRange();
11761 }
11762 
11763 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11764 /// is usually indicative of introspection within the Objective-C pointer.
11765 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11766                                           SourceLocation OpLoc) {
11767   if (!S.getLangOpts().ObjC1)
11768     return;
11769 
11770   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11771   const Expr *LHS = L.get();
11772   const Expr *RHS = R.get();
11773 
11774   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11775     ObjCPointerExpr = LHS;
11776     OtherExpr = RHS;
11777   }
11778   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11779     ObjCPointerExpr = RHS;
11780     OtherExpr = LHS;
11781   }
11782 
11783   // This warning is deliberately made very specific to reduce false
11784   // positives with logic that uses '&' for hashing.  This logic mainly
11785   // looks for code trying to introspect into tagged pointers, which
11786   // code should generally never do.
11787   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11788     unsigned Diag = diag::warn_objc_pointer_masking;
11789     // Determine if we are introspecting the result of performSelectorXXX.
11790     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11791     // Special case messages to -performSelector and friends, which
11792     // can return non-pointer values boxed in a pointer value.
11793     // Some clients may wish to silence warnings in this subcase.
11794     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11795       Selector S = ME->getSelector();
11796       StringRef SelArg0 = S.getNameForSlot(0);
11797       if (SelArg0.startswith("performSelector"))
11798         Diag = diag::warn_objc_pointer_masking_performSelector;
11799     }
11800 
11801     S.Diag(OpLoc, Diag)
11802       << ObjCPointerExpr->getSourceRange();
11803   }
11804 }
11805 
11806 static NamedDecl *getDeclFromExpr(Expr *E) {
11807   if (!E)
11808     return nullptr;
11809   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11810     return DRE->getDecl();
11811   if (auto *ME = dyn_cast<MemberExpr>(E))
11812     return ME->getMemberDecl();
11813   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11814     return IRE->getDecl();
11815   return nullptr;
11816 }
11817 
11818 // This helper function promotes a binary operator's operands (which are of a
11819 // half vector type) to a vector of floats and then truncates the result to
11820 // a vector of either half or short.
11821 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
11822                                       BinaryOperatorKind Opc, QualType ResultTy,
11823                                       ExprValueKind VK, ExprObjectKind OK,
11824                                       bool IsCompAssign, SourceLocation OpLoc,
11825                                       FPOptions FPFeatures) {
11826   auto &Context = S.getASTContext();
11827   assert((isVector(ResultTy, Context.HalfTy) ||
11828           isVector(ResultTy, Context.ShortTy)) &&
11829          "Result must be a vector of half or short");
11830   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
11831          isVector(RHS.get()->getType(), Context.HalfTy) &&
11832          "both operands expected to be a half vector");
11833 
11834   RHS = convertVector(RHS.get(), Context.FloatTy, S);
11835   QualType BinOpResTy = RHS.get()->getType();
11836 
11837   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
11838   // change BinOpResTy to a vector of ints.
11839   if (isVector(ResultTy, Context.ShortTy))
11840     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
11841 
11842   if (IsCompAssign)
11843     return new (Context) CompoundAssignOperator(
11844         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
11845         OpLoc, FPFeatures);
11846 
11847   LHS = convertVector(LHS.get(), Context.FloatTy, S);
11848   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
11849                                           VK, OK, OpLoc, FPFeatures);
11850   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
11851 }
11852 
11853 static std::pair<ExprResult, ExprResult>
11854 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
11855                            Expr *RHSExpr) {
11856   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11857   if (!S.getLangOpts().CPlusPlus) {
11858     // C cannot handle TypoExpr nodes on either side of a binop because it
11859     // doesn't handle dependent types properly, so make sure any TypoExprs have
11860     // been dealt with before checking the operands.
11861     LHS = S.CorrectDelayedTyposInExpr(LHS);
11862     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
11863       if (Opc != BO_Assign)
11864         return ExprResult(E);
11865       // Avoid correcting the RHS to the same Expr as the LHS.
11866       Decl *D = getDeclFromExpr(E);
11867       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11868     });
11869   }
11870   return std::make_pair(LHS, RHS);
11871 }
11872 
11873 /// Returns true if conversion between vectors of halfs and vectors of floats
11874 /// is needed.
11875 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
11876                                      QualType SrcType) {
11877   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
11878          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
11879          isVector(SrcType, Ctx.HalfTy);
11880 }
11881 
11882 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11883 /// operator @p Opc at location @c TokLoc. This routine only supports
11884 /// built-in operations; ActOnBinOp handles overloaded operators.
11885 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11886                                     BinaryOperatorKind Opc,
11887                                     Expr *LHSExpr, Expr *RHSExpr) {
11888   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11889     // The syntax only allows initializer lists on the RHS of assignment,
11890     // so we don't need to worry about accepting invalid code for
11891     // non-assignment operators.
11892     // C++11 5.17p9:
11893     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11894     //   of x = {} is x = T().
11895     InitializationKind Kind = InitializationKind::CreateDirectList(
11896         RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd());
11897     InitializedEntity Entity =
11898         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11899     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11900     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11901     if (Init.isInvalid())
11902       return Init;
11903     RHSExpr = Init.get();
11904   }
11905 
11906   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11907   QualType ResultTy;     // Result type of the binary operator.
11908   // The following two variables are used for compound assignment operators
11909   QualType CompLHSTy;    // Type of LHS after promotions for computation
11910   QualType CompResultTy; // Type of computation result
11911   ExprValueKind VK = VK_RValue;
11912   ExprObjectKind OK = OK_Ordinary;
11913   bool ConvertHalfVec = false;
11914 
11915   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
11916   if (!LHS.isUsable() || !RHS.isUsable())
11917     return ExprError();
11918 
11919   if (getLangOpts().OpenCL) {
11920     QualType LHSTy = LHSExpr->getType();
11921     QualType RHSTy = RHSExpr->getType();
11922     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11923     // the ATOMIC_VAR_INIT macro.
11924     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11925       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11926       if (BO_Assign == Opc)
11927         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11928       else
11929         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11930       return ExprError();
11931     }
11932 
11933     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11934     // only with a builtin functions and therefore should be disallowed here.
11935     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11936         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11937         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11938         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11939       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11940       return ExprError();
11941     }
11942   }
11943 
11944   switch (Opc) {
11945   case BO_Assign:
11946     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11947     if (getLangOpts().CPlusPlus &&
11948         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11949       VK = LHS.get()->getValueKind();
11950       OK = LHS.get()->getObjectKind();
11951     }
11952     if (!ResultTy.isNull()) {
11953       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
11954       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11955     }
11956     RecordModifiableNonNullParam(*this, LHS.get());
11957     break;
11958   case BO_PtrMemD:
11959   case BO_PtrMemI:
11960     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11961                                             Opc == BO_PtrMemI);
11962     break;
11963   case BO_Mul:
11964   case BO_Div:
11965     ConvertHalfVec = true;
11966     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11967                                            Opc == BO_Div);
11968     break;
11969   case BO_Rem:
11970     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11971     break;
11972   case BO_Add:
11973     ConvertHalfVec = true;
11974     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11975     break;
11976   case BO_Sub:
11977     ConvertHalfVec = true;
11978     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11979     break;
11980   case BO_Shl:
11981   case BO_Shr:
11982     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11983     break;
11984   case BO_LE:
11985   case BO_LT:
11986   case BO_GE:
11987   case BO_GT:
11988     ConvertHalfVec = true;
11989     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
11990     break;
11991   case BO_EQ:
11992   case BO_NE:
11993     ConvertHalfVec = true;
11994     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
11995     break;
11996   case BO_Cmp:
11997     ConvertHalfVec = true;
11998     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
11999     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12000     break;
12001   case BO_And:
12002     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12003     LLVM_FALLTHROUGH;
12004   case BO_Xor:
12005   case BO_Or:
12006     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12007     break;
12008   case BO_LAnd:
12009   case BO_LOr:
12010     ConvertHalfVec = true;
12011     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12012     break;
12013   case BO_MulAssign:
12014   case BO_DivAssign:
12015     ConvertHalfVec = true;
12016     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12017                                                Opc == BO_DivAssign);
12018     CompLHSTy = CompResultTy;
12019     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12020       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12021     break;
12022   case BO_RemAssign:
12023     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12024     CompLHSTy = CompResultTy;
12025     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12026       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12027     break;
12028   case BO_AddAssign:
12029     ConvertHalfVec = true;
12030     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12031     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12032       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12033     break;
12034   case BO_SubAssign:
12035     ConvertHalfVec = true;
12036     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12037     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12038       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12039     break;
12040   case BO_ShlAssign:
12041   case BO_ShrAssign:
12042     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12043     CompLHSTy = CompResultTy;
12044     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12045       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12046     break;
12047   case BO_AndAssign:
12048   case BO_OrAssign: // fallthrough
12049     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12050     LLVM_FALLTHROUGH;
12051   case BO_XorAssign:
12052     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12053     CompLHSTy = CompResultTy;
12054     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12055       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12056     break;
12057   case BO_Comma:
12058     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12059     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12060       VK = RHS.get()->getValueKind();
12061       OK = RHS.get()->getObjectKind();
12062     }
12063     break;
12064   }
12065   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12066     return ExprError();
12067 
12068   // Some of the binary operations require promoting operands of half vector to
12069   // float vectors and truncating the result back to half vector. For now, we do
12070   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12071   // arm64).
12072   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12073          isVector(LHS.get()->getType(), Context.HalfTy) &&
12074          "both sides are half vectors or neither sides are");
12075   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12076                                             LHS.get()->getType());
12077 
12078   // Check for array bounds violations for both sides of the BinaryOperator
12079   CheckArrayAccess(LHS.get());
12080   CheckArrayAccess(RHS.get());
12081 
12082   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12083     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12084                                                  &Context.Idents.get("object_setClass"),
12085                                                  SourceLocation(), LookupOrdinaryName);
12086     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12087       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
12088       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
12089       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
12090       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
12091       FixItHint::CreateInsertion(RHSLocEnd, ")");
12092     }
12093     else
12094       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12095   }
12096   else if (const ObjCIvarRefExpr *OIRE =
12097            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12098     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12099 
12100   // Opc is not a compound assignment if CompResultTy is null.
12101   if (CompResultTy.isNull()) {
12102     if (ConvertHalfVec)
12103       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12104                                  OpLoc, FPFeatures);
12105     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12106                                         OK, OpLoc, FPFeatures);
12107   }
12108 
12109   // Handle compound assignments.
12110   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12111       OK_ObjCProperty) {
12112     VK = VK_LValue;
12113     OK = LHS.get()->getObjectKind();
12114   }
12115 
12116   if (ConvertHalfVec)
12117     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12118                                OpLoc, FPFeatures);
12119 
12120   return new (Context) CompoundAssignOperator(
12121       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12122       OpLoc, FPFeatures);
12123 }
12124 
12125 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12126 /// operators are mixed in a way that suggests that the programmer forgot that
12127 /// comparison operators have higher precedence. The most typical example of
12128 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12129 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12130                                       SourceLocation OpLoc, Expr *LHSExpr,
12131                                       Expr *RHSExpr) {
12132   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12133   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12134 
12135   // Check that one of the sides is a comparison operator and the other isn't.
12136   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12137   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12138   if (isLeftComp == isRightComp)
12139     return;
12140 
12141   // Bitwise operations are sometimes used as eager logical ops.
12142   // Don't diagnose this.
12143   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12144   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12145   if (isLeftBitwise || isRightBitwise)
12146     return;
12147 
12148   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
12149                                                    OpLoc)
12150                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
12151   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12152   SourceRange ParensRange = isLeftComp ?
12153       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
12154     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
12155 
12156   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12157     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12158   SuggestParentheses(Self, OpLoc,
12159     Self.PDiag(diag::note_precedence_silence) << OpStr,
12160     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12161   SuggestParentheses(Self, OpLoc,
12162     Self.PDiag(diag::note_precedence_bitwise_first)
12163       << BinaryOperator::getOpcodeStr(Opc),
12164     ParensRange);
12165 }
12166 
12167 /// It accepts a '&&' expr that is inside a '||' one.
12168 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12169 /// in parentheses.
12170 static void
12171 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12172                                        BinaryOperator *Bop) {
12173   assert(Bop->getOpcode() == BO_LAnd);
12174   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12175       << Bop->getSourceRange() << OpLoc;
12176   SuggestParentheses(Self, Bop->getOperatorLoc(),
12177     Self.PDiag(diag::note_precedence_silence)
12178       << Bop->getOpcodeStr(),
12179     Bop->getSourceRange());
12180 }
12181 
12182 /// Returns true if the given expression can be evaluated as a constant
12183 /// 'true'.
12184 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12185   bool Res;
12186   return !E->isValueDependent() &&
12187          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12188 }
12189 
12190 /// Returns true if the given expression can be evaluated as a constant
12191 /// 'false'.
12192 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12193   bool Res;
12194   return !E->isValueDependent() &&
12195          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12196 }
12197 
12198 /// Look for '&&' in the left hand of a '||' expr.
12199 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12200                                              Expr *LHSExpr, Expr *RHSExpr) {
12201   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12202     if (Bop->getOpcode() == BO_LAnd) {
12203       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12204       if (EvaluatesAsFalse(S, RHSExpr))
12205         return;
12206       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12207       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12208         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12209     } else if (Bop->getOpcode() == BO_LOr) {
12210       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12211         // If it's "a || b && 1 || c" we didn't warn earlier for
12212         // "a || b && 1", but warn now.
12213         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12214           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12215       }
12216     }
12217   }
12218 }
12219 
12220 /// Look for '&&' in the right hand of a '||' expr.
12221 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12222                                              Expr *LHSExpr, Expr *RHSExpr) {
12223   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12224     if (Bop->getOpcode() == BO_LAnd) {
12225       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12226       if (EvaluatesAsFalse(S, LHSExpr))
12227         return;
12228       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12229       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12230         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12231     }
12232   }
12233 }
12234 
12235 /// Look for bitwise op in the left or right hand of a bitwise op with
12236 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12237 /// the '&' expression in parentheses.
12238 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12239                                          SourceLocation OpLoc, Expr *SubExpr) {
12240   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12241     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12242       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12243         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12244         << Bop->getSourceRange() << OpLoc;
12245       SuggestParentheses(S, Bop->getOperatorLoc(),
12246         S.PDiag(diag::note_precedence_silence)
12247           << Bop->getOpcodeStr(),
12248         Bop->getSourceRange());
12249     }
12250   }
12251 }
12252 
12253 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12254                                     Expr *SubExpr, StringRef Shift) {
12255   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12256     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12257       StringRef Op = Bop->getOpcodeStr();
12258       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12259           << Bop->getSourceRange() << OpLoc << Shift << Op;
12260       SuggestParentheses(S, Bop->getOperatorLoc(),
12261           S.PDiag(diag::note_precedence_silence) << Op,
12262           Bop->getSourceRange());
12263     }
12264   }
12265 }
12266 
12267 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12268                                  Expr *LHSExpr, Expr *RHSExpr) {
12269   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12270   if (!OCE)
12271     return;
12272 
12273   FunctionDecl *FD = OCE->getDirectCallee();
12274   if (!FD || !FD->isOverloadedOperator())
12275     return;
12276 
12277   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12278   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12279     return;
12280 
12281   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12282       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12283       << (Kind == OO_LessLess);
12284   SuggestParentheses(S, OCE->getOperatorLoc(),
12285                      S.PDiag(diag::note_precedence_silence)
12286                          << (Kind == OO_LessLess ? "<<" : ">>"),
12287                      OCE->getSourceRange());
12288   SuggestParentheses(S, OpLoc,
12289                      S.PDiag(diag::note_evaluate_comparison_first),
12290                      SourceRange(OCE->getArg(1)->getLocStart(),
12291                                  RHSExpr->getLocEnd()));
12292 }
12293 
12294 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12295 /// precedence.
12296 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12297                                     SourceLocation OpLoc, Expr *LHSExpr,
12298                                     Expr *RHSExpr){
12299   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12300   if (BinaryOperator::isBitwiseOp(Opc))
12301     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12302 
12303   // Diagnose "arg1 & arg2 | arg3"
12304   if ((Opc == BO_Or || Opc == BO_Xor) &&
12305       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12306     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12307     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12308   }
12309 
12310   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12311   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12312   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12313     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12314     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12315   }
12316 
12317   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12318       || Opc == BO_Shr) {
12319     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12320     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12321     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12322   }
12323 
12324   // Warn on overloaded shift operators and comparisons, such as:
12325   // cout << 5 == 4;
12326   if (BinaryOperator::isComparisonOp(Opc))
12327     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12328 }
12329 
12330 // Binary Operators.  'Tok' is the token for the operator.
12331 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12332                             tok::TokenKind Kind,
12333                             Expr *LHSExpr, Expr *RHSExpr) {
12334   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12335   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12336   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12337 
12338   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12339   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12340 
12341   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12342 }
12343 
12344 /// Build an overloaded binary operator expression in the given scope.
12345 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12346                                        BinaryOperatorKind Opc,
12347                                        Expr *LHS, Expr *RHS) {
12348   switch (Opc) {
12349   case BO_Assign:
12350   case BO_DivAssign:
12351   case BO_RemAssign:
12352   case BO_SubAssign:
12353   case BO_AndAssign:
12354   case BO_OrAssign:
12355   case BO_XorAssign:
12356     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12357     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12358     break;
12359   default:
12360     break;
12361   }
12362 
12363   // Find all of the overloaded operators visible from this
12364   // point. We perform both an operator-name lookup from the local
12365   // scope and an argument-dependent lookup based on the types of
12366   // the arguments.
12367   UnresolvedSet<16> Functions;
12368   OverloadedOperatorKind OverOp
12369     = BinaryOperator::getOverloadedOperator(Opc);
12370   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12371     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12372                                    RHS->getType(), Functions);
12373 
12374   // Build the (potentially-overloaded, potentially-dependent)
12375   // binary operation.
12376   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12377 }
12378 
12379 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12380                             BinaryOperatorKind Opc,
12381                             Expr *LHSExpr, Expr *RHSExpr) {
12382   ExprResult LHS, RHS;
12383   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12384   if (!LHS.isUsable() || !RHS.isUsable())
12385     return ExprError();
12386   LHSExpr = LHS.get();
12387   RHSExpr = RHS.get();
12388 
12389   // We want to end up calling one of checkPseudoObjectAssignment
12390   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12391   // both expressions are overloadable or either is type-dependent),
12392   // or CreateBuiltinBinOp (in any other case).  We also want to get
12393   // any placeholder types out of the way.
12394 
12395   // Handle pseudo-objects in the LHS.
12396   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12397     // Assignments with a pseudo-object l-value need special analysis.
12398     if (pty->getKind() == BuiltinType::PseudoObject &&
12399         BinaryOperator::isAssignmentOp(Opc))
12400       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12401 
12402     // Don't resolve overloads if the other type is overloadable.
12403     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12404       // We can't actually test that if we still have a placeholder,
12405       // though.  Fortunately, none of the exceptions we see in that
12406       // code below are valid when the LHS is an overload set.  Note
12407       // that an overload set can be dependently-typed, but it never
12408       // instantiates to having an overloadable type.
12409       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12410       if (resolvedRHS.isInvalid()) return ExprError();
12411       RHSExpr = resolvedRHS.get();
12412 
12413       if (RHSExpr->isTypeDependent() ||
12414           RHSExpr->getType()->isOverloadableType())
12415         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12416     }
12417 
12418     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12419     // template, diagnose the missing 'template' keyword instead of diagnosing
12420     // an invalid use of a bound member function.
12421     //
12422     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12423     // to C++1z [over.over]/1.4, but we already checked for that case above.
12424     if (Opc == BO_LT && inTemplateInstantiation() &&
12425         (pty->getKind() == BuiltinType::BoundMember ||
12426          pty->getKind() == BuiltinType::Overload)) {
12427       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12428       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12429           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12430             return isa<FunctionTemplateDecl>(ND);
12431           })) {
12432         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12433                                 : OE->getNameLoc(),
12434              diag::err_template_kw_missing)
12435           << OE->getName().getAsString() << "";
12436         return ExprError();
12437       }
12438     }
12439 
12440     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12441     if (LHS.isInvalid()) return ExprError();
12442     LHSExpr = LHS.get();
12443   }
12444 
12445   // Handle pseudo-objects in the RHS.
12446   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12447     // An overload in the RHS can potentially be resolved by the type
12448     // being assigned to.
12449     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12450       if (getLangOpts().CPlusPlus &&
12451           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12452            LHSExpr->getType()->isOverloadableType()))
12453         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12454 
12455       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12456     }
12457 
12458     // Don't resolve overloads if the other type is overloadable.
12459     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12460         LHSExpr->getType()->isOverloadableType())
12461       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12462 
12463     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12464     if (!resolvedRHS.isUsable()) return ExprError();
12465     RHSExpr = resolvedRHS.get();
12466   }
12467 
12468   if (getLangOpts().CPlusPlus) {
12469     // If either expression is type-dependent, always build an
12470     // overloaded op.
12471     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12472       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12473 
12474     // Otherwise, build an overloaded op if either expression has an
12475     // overloadable type.
12476     if (LHSExpr->getType()->isOverloadableType() ||
12477         RHSExpr->getType()->isOverloadableType())
12478       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12479   }
12480 
12481   // Build a built-in binary operation.
12482   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12483 }
12484 
12485 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12486   if (T.isNull() || T->isDependentType())
12487     return false;
12488 
12489   if (!T->isPromotableIntegerType())
12490     return true;
12491 
12492   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12493 }
12494 
12495 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12496                                       UnaryOperatorKind Opc,
12497                                       Expr *InputExpr) {
12498   ExprResult Input = InputExpr;
12499   ExprValueKind VK = VK_RValue;
12500   ExprObjectKind OK = OK_Ordinary;
12501   QualType resultType;
12502   bool CanOverflow = false;
12503 
12504   bool ConvertHalfVec = false;
12505   if (getLangOpts().OpenCL) {
12506     QualType Ty = InputExpr->getType();
12507     // The only legal unary operation for atomics is '&'.
12508     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12509     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12510     // only with a builtin functions and therefore should be disallowed here.
12511         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12512         || Ty->isBlockPointerType())) {
12513       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12514                        << InputExpr->getType()
12515                        << Input.get()->getSourceRange());
12516     }
12517   }
12518   switch (Opc) {
12519   case UO_PreInc:
12520   case UO_PreDec:
12521   case UO_PostInc:
12522   case UO_PostDec:
12523     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12524                                                 OpLoc,
12525                                                 Opc == UO_PreInc ||
12526                                                 Opc == UO_PostInc,
12527                                                 Opc == UO_PreInc ||
12528                                                 Opc == UO_PreDec);
12529     CanOverflow = isOverflowingIntegerType(Context, resultType);
12530     break;
12531   case UO_AddrOf:
12532     resultType = CheckAddressOfOperand(Input, OpLoc);
12533     RecordModifiableNonNullParam(*this, InputExpr);
12534     break;
12535   case UO_Deref: {
12536     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12537     if (Input.isInvalid()) return ExprError();
12538     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12539     break;
12540   }
12541   case UO_Plus:
12542   case UO_Minus:
12543     CanOverflow = Opc == UO_Minus &&
12544                   isOverflowingIntegerType(Context, Input.get()->getType());
12545     Input = UsualUnaryConversions(Input.get());
12546     if (Input.isInvalid()) return ExprError();
12547     // Unary plus and minus require promoting an operand of half vector to a
12548     // float vector and truncating the result back to a half vector. For now, we
12549     // do this only when HalfArgsAndReturns is set (that is, when the target is
12550     // arm or arm64).
12551     ConvertHalfVec =
12552         needsConversionOfHalfVec(true, Context, Input.get()->getType());
12553 
12554     // If the operand is a half vector, promote it to a float vector.
12555     if (ConvertHalfVec)
12556       Input = convertVector(Input.get(), Context.FloatTy, *this);
12557     resultType = Input.get()->getType();
12558     if (resultType->isDependentType())
12559       break;
12560     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12561       break;
12562     else if (resultType->isVectorType() &&
12563              // The z vector extensions don't allow + or - with bool vectors.
12564              (!Context.getLangOpts().ZVector ||
12565               resultType->getAs<VectorType>()->getVectorKind() !=
12566               VectorType::AltiVecBool))
12567       break;
12568     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12569              Opc == UO_Plus &&
12570              resultType->isPointerType())
12571       break;
12572 
12573     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12574       << resultType << Input.get()->getSourceRange());
12575 
12576   case UO_Not: // bitwise complement
12577     Input = UsualUnaryConversions(Input.get());
12578     if (Input.isInvalid())
12579       return ExprError();
12580     resultType = Input.get()->getType();
12581 
12582     if (resultType->isDependentType())
12583       break;
12584     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12585     if (resultType->isComplexType() || resultType->isComplexIntegerType())
12586       // C99 does not support '~' for complex conjugation.
12587       Diag(OpLoc, diag::ext_integer_complement_complex)
12588           << resultType << Input.get()->getSourceRange();
12589     else if (resultType->hasIntegerRepresentation())
12590       break;
12591     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12592       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12593       // on vector float types.
12594       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12595       if (!T->isIntegerType())
12596         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12597                           << resultType << Input.get()->getSourceRange());
12598     } else {
12599       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12600                        << resultType << Input.get()->getSourceRange());
12601     }
12602     break;
12603 
12604   case UO_LNot: // logical negation
12605     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12606     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12607     if (Input.isInvalid()) return ExprError();
12608     resultType = Input.get()->getType();
12609 
12610     // Though we still have to promote half FP to float...
12611     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12612       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12613       resultType = Context.FloatTy;
12614     }
12615 
12616     if (resultType->isDependentType())
12617       break;
12618     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12619       // C99 6.5.3.3p1: ok, fallthrough;
12620       if (Context.getLangOpts().CPlusPlus) {
12621         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12622         // operand contextually converted to bool.
12623         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12624                                   ScalarTypeToBooleanCastKind(resultType));
12625       } else if (Context.getLangOpts().OpenCL &&
12626                  Context.getLangOpts().OpenCLVersion < 120) {
12627         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12628         // operate on scalar float types.
12629         if (!resultType->isIntegerType() && !resultType->isPointerType())
12630           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12631                            << resultType << Input.get()->getSourceRange());
12632       }
12633     } else if (resultType->isExtVectorType()) {
12634       if (Context.getLangOpts().OpenCL &&
12635           Context.getLangOpts().OpenCLVersion < 120) {
12636         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12637         // operate on vector float types.
12638         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12639         if (!T->isIntegerType())
12640           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12641                            << resultType << Input.get()->getSourceRange());
12642       }
12643       // Vector logical not returns the signed variant of the operand type.
12644       resultType = GetSignedVectorType(resultType);
12645       break;
12646     } else {
12647       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12648       //        type in C++. We should allow that here too.
12649       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12650         << resultType << Input.get()->getSourceRange());
12651     }
12652 
12653     // LNot always has type int. C99 6.5.3.3p5.
12654     // In C++, it's bool. C++ 5.3.1p8
12655     resultType = Context.getLogicalOperationType();
12656     break;
12657   case UO_Real:
12658   case UO_Imag:
12659     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12660     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12661     // complex l-values to ordinary l-values and all other values to r-values.
12662     if (Input.isInvalid()) return ExprError();
12663     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12664       if (Input.get()->getValueKind() != VK_RValue &&
12665           Input.get()->getObjectKind() == OK_Ordinary)
12666         VK = Input.get()->getValueKind();
12667     } else if (!getLangOpts().CPlusPlus) {
12668       // In C, a volatile scalar is read by __imag. In C++, it is not.
12669       Input = DefaultLvalueConversion(Input.get());
12670     }
12671     break;
12672   case UO_Extension:
12673     resultType = Input.get()->getType();
12674     VK = Input.get()->getValueKind();
12675     OK = Input.get()->getObjectKind();
12676     break;
12677   case UO_Coawait:
12678     // It's unnecessary to represent the pass-through operator co_await in the
12679     // AST; just return the input expression instead.
12680     assert(!Input.get()->getType()->isDependentType() &&
12681                    "the co_await expression must be non-dependant before "
12682                    "building operator co_await");
12683     return Input;
12684   }
12685   if (resultType.isNull() || Input.isInvalid())
12686     return ExprError();
12687 
12688   // Check for array bounds violations in the operand of the UnaryOperator,
12689   // except for the '*' and '&' operators that have to be handled specially
12690   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12691   // that are explicitly defined as valid by the standard).
12692   if (Opc != UO_AddrOf && Opc != UO_Deref)
12693     CheckArrayAccess(Input.get());
12694 
12695   auto *UO = new (Context)
12696       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12697   // Convert the result back to a half vector.
12698   if (ConvertHalfVec)
12699     return convertVector(UO, Context.HalfTy, *this);
12700   return UO;
12701 }
12702 
12703 /// Determine whether the given expression is a qualified member
12704 /// access expression, of a form that could be turned into a pointer to member
12705 /// with the address-of operator.
12706 static bool isQualifiedMemberAccess(Expr *E) {
12707   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12708     if (!DRE->getQualifier())
12709       return false;
12710 
12711     ValueDecl *VD = DRE->getDecl();
12712     if (!VD->isCXXClassMember())
12713       return false;
12714 
12715     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12716       return true;
12717     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12718       return Method->isInstance();
12719 
12720     return false;
12721   }
12722 
12723   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12724     if (!ULE->getQualifier())
12725       return false;
12726 
12727     for (NamedDecl *D : ULE->decls()) {
12728       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12729         if (Method->isInstance())
12730           return true;
12731       } else {
12732         // Overload set does not contain methods.
12733         break;
12734       }
12735     }
12736 
12737     return false;
12738   }
12739 
12740   return false;
12741 }
12742 
12743 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12744                               UnaryOperatorKind Opc, Expr *Input) {
12745   // First things first: handle placeholders so that the
12746   // overloaded-operator check considers the right type.
12747   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12748     // Increment and decrement of pseudo-object references.
12749     if (pty->getKind() == BuiltinType::PseudoObject &&
12750         UnaryOperator::isIncrementDecrementOp(Opc))
12751       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12752 
12753     // extension is always a builtin operator.
12754     if (Opc == UO_Extension)
12755       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12756 
12757     // & gets special logic for several kinds of placeholder.
12758     // The builtin code knows what to do.
12759     if (Opc == UO_AddrOf &&
12760         (pty->getKind() == BuiltinType::Overload ||
12761          pty->getKind() == BuiltinType::UnknownAny ||
12762          pty->getKind() == BuiltinType::BoundMember))
12763       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12764 
12765     // Anything else needs to be handled now.
12766     ExprResult Result = CheckPlaceholderExpr(Input);
12767     if (Result.isInvalid()) return ExprError();
12768     Input = Result.get();
12769   }
12770 
12771   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12772       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12773       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12774     // Find all of the overloaded operators visible from this
12775     // point. We perform both an operator-name lookup from the local
12776     // scope and an argument-dependent lookup based on the types of
12777     // the arguments.
12778     UnresolvedSet<16> Functions;
12779     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12780     if (S && OverOp != OO_None)
12781       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12782                                    Functions);
12783 
12784     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12785   }
12786 
12787   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12788 }
12789 
12790 // Unary Operators.  'Tok' is the token for the operator.
12791 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12792                               tok::TokenKind Op, Expr *Input) {
12793   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12794 }
12795 
12796 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12797 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12798                                 LabelDecl *TheDecl) {
12799   TheDecl->markUsed(Context);
12800   // Create the AST node.  The address of a label always has type 'void*'.
12801   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12802                                      Context.getPointerType(Context.VoidTy));
12803 }
12804 
12805 /// Given the last statement in a statement-expression, check whether
12806 /// the result is a producing expression (like a call to an
12807 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12808 /// release out of the full-expression.  Otherwise, return null.
12809 /// Cannot fail.
12810 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12811   // Should always be wrapped with one of these.
12812   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12813   if (!cleanups) return nullptr;
12814 
12815   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12816   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12817     return nullptr;
12818 
12819   // Splice out the cast.  This shouldn't modify any interesting
12820   // features of the statement.
12821   Expr *producer = cast->getSubExpr();
12822   assert(producer->getType() == cast->getType());
12823   assert(producer->getValueKind() == cast->getValueKind());
12824   cleanups->setSubExpr(producer);
12825   return cleanups;
12826 }
12827 
12828 void Sema::ActOnStartStmtExpr() {
12829   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12830 }
12831 
12832 void Sema::ActOnStmtExprError() {
12833   // Note that function is also called by TreeTransform when leaving a
12834   // StmtExpr scope without rebuilding anything.
12835 
12836   DiscardCleanupsInEvaluationContext();
12837   PopExpressionEvaluationContext();
12838 }
12839 
12840 ExprResult
12841 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12842                     SourceLocation RPLoc) { // "({..})"
12843   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12844   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12845 
12846   if (hasAnyUnrecoverableErrorsInThisFunction())
12847     DiscardCleanupsInEvaluationContext();
12848   assert(!Cleanup.exprNeedsCleanups() &&
12849          "cleanups within StmtExpr not correctly bound!");
12850   PopExpressionEvaluationContext();
12851 
12852   // FIXME: there are a variety of strange constraints to enforce here, for
12853   // example, it is not possible to goto into a stmt expression apparently.
12854   // More semantic analysis is needed.
12855 
12856   // If there are sub-stmts in the compound stmt, take the type of the last one
12857   // as the type of the stmtexpr.
12858   QualType Ty = Context.VoidTy;
12859   bool StmtExprMayBindToTemp = false;
12860   if (!Compound->body_empty()) {
12861     Stmt *LastStmt = Compound->body_back();
12862     LabelStmt *LastLabelStmt = nullptr;
12863     // If LastStmt is a label, skip down through into the body.
12864     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12865       LastLabelStmt = Label;
12866       LastStmt = Label->getSubStmt();
12867     }
12868 
12869     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12870       // Do function/array conversion on the last expression, but not
12871       // lvalue-to-rvalue.  However, initialize an unqualified type.
12872       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12873       if (LastExpr.isInvalid())
12874         return ExprError();
12875       Ty = LastExpr.get()->getType().getUnqualifiedType();
12876 
12877       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12878         // In ARC, if the final expression ends in a consume, splice
12879         // the consume out and bind it later.  In the alternate case
12880         // (when dealing with a retainable type), the result
12881         // initialization will create a produce.  In both cases the
12882         // result will be +1, and we'll need to balance that out with
12883         // a bind.
12884         if (Expr *rebuiltLastStmt
12885               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12886           LastExpr = rebuiltLastStmt;
12887         } else {
12888           LastExpr = PerformCopyInitialization(
12889                             InitializedEntity::InitializeResult(LPLoc,
12890                                                                 Ty,
12891                                                                 false),
12892                                                    SourceLocation(),
12893                                                LastExpr);
12894         }
12895 
12896         if (LastExpr.isInvalid())
12897           return ExprError();
12898         if (LastExpr.get() != nullptr) {
12899           if (!LastLabelStmt)
12900             Compound->setLastStmt(LastExpr.get());
12901           else
12902             LastLabelStmt->setSubStmt(LastExpr.get());
12903           StmtExprMayBindToTemp = true;
12904         }
12905       }
12906     }
12907   }
12908 
12909   // FIXME: Check that expression type is complete/non-abstract; statement
12910   // expressions are not lvalues.
12911   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12912   if (StmtExprMayBindToTemp)
12913     return MaybeBindToTemporary(ResStmtExpr);
12914   return ResStmtExpr;
12915 }
12916 
12917 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12918                                       TypeSourceInfo *TInfo,
12919                                       ArrayRef<OffsetOfComponent> Components,
12920                                       SourceLocation RParenLoc) {
12921   QualType ArgTy = TInfo->getType();
12922   bool Dependent = ArgTy->isDependentType();
12923   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12924 
12925   // We must have at least one component that refers to the type, and the first
12926   // one is known to be a field designator.  Verify that the ArgTy represents
12927   // a struct/union/class.
12928   if (!Dependent && !ArgTy->isRecordType())
12929     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12930                        << ArgTy << TypeRange);
12931 
12932   // Type must be complete per C99 7.17p3 because a declaring a variable
12933   // with an incomplete type would be ill-formed.
12934   if (!Dependent
12935       && RequireCompleteType(BuiltinLoc, ArgTy,
12936                              diag::err_offsetof_incomplete_type, TypeRange))
12937     return ExprError();
12938 
12939   bool DidWarnAboutNonPOD = false;
12940   QualType CurrentType = ArgTy;
12941   SmallVector<OffsetOfNode, 4> Comps;
12942   SmallVector<Expr*, 4> Exprs;
12943   for (const OffsetOfComponent &OC : Components) {
12944     if (OC.isBrackets) {
12945       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12946       if (!CurrentType->isDependentType()) {
12947         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12948         if(!AT)
12949           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12950                            << CurrentType);
12951         CurrentType = AT->getElementType();
12952       } else
12953         CurrentType = Context.DependentTy;
12954 
12955       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12956       if (IdxRval.isInvalid())
12957         return ExprError();
12958       Expr *Idx = IdxRval.get();
12959 
12960       // The expression must be an integral expression.
12961       // FIXME: An integral constant expression?
12962       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12963           !Idx->getType()->isIntegerType())
12964         return ExprError(Diag(Idx->getLocStart(),
12965                               diag::err_typecheck_subscript_not_integer)
12966                          << Idx->getSourceRange());
12967 
12968       // Record this array index.
12969       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12970       Exprs.push_back(Idx);
12971       continue;
12972     }
12973 
12974     // Offset of a field.
12975     if (CurrentType->isDependentType()) {
12976       // We have the offset of a field, but we can't look into the dependent
12977       // type. Just record the identifier of the field.
12978       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12979       CurrentType = Context.DependentTy;
12980       continue;
12981     }
12982 
12983     // We need to have a complete type to look into.
12984     if (RequireCompleteType(OC.LocStart, CurrentType,
12985                             diag::err_offsetof_incomplete_type))
12986       return ExprError();
12987 
12988     // Look for the designated field.
12989     const RecordType *RC = CurrentType->getAs<RecordType>();
12990     if (!RC)
12991       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12992                        << CurrentType);
12993     RecordDecl *RD = RC->getDecl();
12994 
12995     // C++ [lib.support.types]p5:
12996     //   The macro offsetof accepts a restricted set of type arguments in this
12997     //   International Standard. type shall be a POD structure or a POD union
12998     //   (clause 9).
12999     // C++11 [support.types]p4:
13000     //   If type is not a standard-layout class (Clause 9), the results are
13001     //   undefined.
13002     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13003       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13004       unsigned DiagID =
13005         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13006                             : diag::ext_offsetof_non_pod_type;
13007 
13008       if (!IsSafe && !DidWarnAboutNonPOD &&
13009           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13010                               PDiag(DiagID)
13011                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13012                               << CurrentType))
13013         DidWarnAboutNonPOD = true;
13014     }
13015 
13016     // Look for the field.
13017     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13018     LookupQualifiedName(R, RD);
13019     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13020     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13021     if (!MemberDecl) {
13022       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13023         MemberDecl = IndirectMemberDecl->getAnonField();
13024     }
13025 
13026     if (!MemberDecl)
13027       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13028                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13029                                                               OC.LocEnd));
13030 
13031     // C99 7.17p3:
13032     //   (If the specified member is a bit-field, the behavior is undefined.)
13033     //
13034     // We diagnose this as an error.
13035     if (MemberDecl->isBitField()) {
13036       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13037         << MemberDecl->getDeclName()
13038         << SourceRange(BuiltinLoc, RParenLoc);
13039       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13040       return ExprError();
13041     }
13042 
13043     RecordDecl *Parent = MemberDecl->getParent();
13044     if (IndirectMemberDecl)
13045       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13046 
13047     // If the member was found in a base class, introduce OffsetOfNodes for
13048     // the base class indirections.
13049     CXXBasePaths Paths;
13050     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13051                       Paths)) {
13052       if (Paths.getDetectedVirtual()) {
13053         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13054           << MemberDecl->getDeclName()
13055           << SourceRange(BuiltinLoc, RParenLoc);
13056         return ExprError();
13057       }
13058 
13059       CXXBasePath &Path = Paths.front();
13060       for (const CXXBasePathElement &B : Path)
13061         Comps.push_back(OffsetOfNode(B.Base));
13062     }
13063 
13064     if (IndirectMemberDecl) {
13065       for (auto *FI : IndirectMemberDecl->chain()) {
13066         assert(isa<FieldDecl>(FI));
13067         Comps.push_back(OffsetOfNode(OC.LocStart,
13068                                      cast<FieldDecl>(FI), OC.LocEnd));
13069       }
13070     } else
13071       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13072 
13073     CurrentType = MemberDecl->getType().getNonReferenceType();
13074   }
13075 
13076   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13077                               Comps, Exprs, RParenLoc);
13078 }
13079 
13080 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13081                                       SourceLocation BuiltinLoc,
13082                                       SourceLocation TypeLoc,
13083                                       ParsedType ParsedArgTy,
13084                                       ArrayRef<OffsetOfComponent> Components,
13085                                       SourceLocation RParenLoc) {
13086 
13087   TypeSourceInfo *ArgTInfo;
13088   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13089   if (ArgTy.isNull())
13090     return ExprError();
13091 
13092   if (!ArgTInfo)
13093     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13094 
13095   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13096 }
13097 
13098 
13099 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13100                                  Expr *CondExpr,
13101                                  Expr *LHSExpr, Expr *RHSExpr,
13102                                  SourceLocation RPLoc) {
13103   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13104 
13105   ExprValueKind VK = VK_RValue;
13106   ExprObjectKind OK = OK_Ordinary;
13107   QualType resType;
13108   bool ValueDependent = false;
13109   bool CondIsTrue = false;
13110   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13111     resType = Context.DependentTy;
13112     ValueDependent = true;
13113   } else {
13114     // The conditional expression is required to be a constant expression.
13115     llvm::APSInt condEval(32);
13116     ExprResult CondICE
13117       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13118           diag::err_typecheck_choose_expr_requires_constant, false);
13119     if (CondICE.isInvalid())
13120       return ExprError();
13121     CondExpr = CondICE.get();
13122     CondIsTrue = condEval.getZExtValue();
13123 
13124     // If the condition is > zero, then the AST type is the same as the LSHExpr.
13125     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13126 
13127     resType = ActiveExpr->getType();
13128     ValueDependent = ActiveExpr->isValueDependent();
13129     VK = ActiveExpr->getValueKind();
13130     OK = ActiveExpr->getObjectKind();
13131   }
13132 
13133   return new (Context)
13134       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13135                  CondIsTrue, resType->isDependentType(), ValueDependent);
13136 }
13137 
13138 //===----------------------------------------------------------------------===//
13139 // Clang Extensions.
13140 //===----------------------------------------------------------------------===//
13141 
13142 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13143 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13144   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13145 
13146   if (LangOpts.CPlusPlus) {
13147     Decl *ManglingContextDecl;
13148     if (MangleNumberingContext *MCtx =
13149             getCurrentMangleNumberContext(Block->getDeclContext(),
13150                                           ManglingContextDecl)) {
13151       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13152       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13153     }
13154   }
13155 
13156   PushBlockScope(CurScope, Block);
13157   CurContext->addDecl(Block);
13158   if (CurScope)
13159     PushDeclContext(CurScope, Block);
13160   else
13161     CurContext = Block;
13162 
13163   getCurBlock()->HasImplicitReturnType = true;
13164 
13165   // Enter a new evaluation context to insulate the block from any
13166   // cleanups from the enclosing full-expression.
13167   PushExpressionEvaluationContext(
13168       ExpressionEvaluationContext::PotentiallyEvaluated);
13169 }
13170 
13171 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13172                                Scope *CurScope) {
13173   assert(ParamInfo.getIdentifier() == nullptr &&
13174          "block-id should have no identifier!");
13175   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13176   BlockScopeInfo *CurBlock = getCurBlock();
13177 
13178   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13179   QualType T = Sig->getType();
13180 
13181   // FIXME: We should allow unexpanded parameter packs here, but that would,
13182   // in turn, make the block expression contain unexpanded parameter packs.
13183   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13184     // Drop the parameters.
13185     FunctionProtoType::ExtProtoInfo EPI;
13186     EPI.HasTrailingReturn = false;
13187     EPI.TypeQuals |= DeclSpec::TQ_const;
13188     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13189     Sig = Context.getTrivialTypeSourceInfo(T);
13190   }
13191 
13192   // GetTypeForDeclarator always produces a function type for a block
13193   // literal signature.  Furthermore, it is always a FunctionProtoType
13194   // unless the function was written with a typedef.
13195   assert(T->isFunctionType() &&
13196          "GetTypeForDeclarator made a non-function block signature");
13197 
13198   // Look for an explicit signature in that function type.
13199   FunctionProtoTypeLoc ExplicitSignature;
13200 
13201   if ((ExplicitSignature =
13202            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13203 
13204     // Check whether that explicit signature was synthesized by
13205     // GetTypeForDeclarator.  If so, don't save that as part of the
13206     // written signature.
13207     if (ExplicitSignature.getLocalRangeBegin() ==
13208         ExplicitSignature.getLocalRangeEnd()) {
13209       // This would be much cheaper if we stored TypeLocs instead of
13210       // TypeSourceInfos.
13211       TypeLoc Result = ExplicitSignature.getReturnLoc();
13212       unsigned Size = Result.getFullDataSize();
13213       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13214       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13215 
13216       ExplicitSignature = FunctionProtoTypeLoc();
13217     }
13218   }
13219 
13220   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13221   CurBlock->FunctionType = T;
13222 
13223   const FunctionType *Fn = T->getAs<FunctionType>();
13224   QualType RetTy = Fn->getReturnType();
13225   bool isVariadic =
13226     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13227 
13228   CurBlock->TheDecl->setIsVariadic(isVariadic);
13229 
13230   // Context.DependentTy is used as a placeholder for a missing block
13231   // return type.  TODO:  what should we do with declarators like:
13232   //   ^ * { ... }
13233   // If the answer is "apply template argument deduction"....
13234   if (RetTy != Context.DependentTy) {
13235     CurBlock->ReturnType = RetTy;
13236     CurBlock->TheDecl->setBlockMissingReturnType(false);
13237     CurBlock->HasImplicitReturnType = false;
13238   }
13239 
13240   // Push block parameters from the declarator if we had them.
13241   SmallVector<ParmVarDecl*, 8> Params;
13242   if (ExplicitSignature) {
13243     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13244       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13245       if (Param->getIdentifier() == nullptr &&
13246           !Param->isImplicit() &&
13247           !Param->isInvalidDecl() &&
13248           !getLangOpts().CPlusPlus)
13249         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13250       Params.push_back(Param);
13251     }
13252 
13253   // Fake up parameter variables if we have a typedef, like
13254   //   ^ fntype { ... }
13255   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13256     for (const auto &I : Fn->param_types()) {
13257       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13258           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
13259       Params.push_back(Param);
13260     }
13261   }
13262 
13263   // Set the parameters on the block decl.
13264   if (!Params.empty()) {
13265     CurBlock->TheDecl->setParams(Params);
13266     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13267                              /*CheckParameterNames=*/false);
13268   }
13269 
13270   // Finally we can process decl attributes.
13271   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13272 
13273   // Put the parameter variables in scope.
13274   for (auto AI : CurBlock->TheDecl->parameters()) {
13275     AI->setOwningFunction(CurBlock->TheDecl);
13276 
13277     // If this has an identifier, add it to the scope stack.
13278     if (AI->getIdentifier()) {
13279       CheckShadow(CurBlock->TheScope, AI);
13280 
13281       PushOnScopeChains(AI, CurBlock->TheScope);
13282     }
13283   }
13284 }
13285 
13286 /// ActOnBlockError - If there is an error parsing a block, this callback
13287 /// is invoked to pop the information about the block from the action impl.
13288 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13289   // Leave the expression-evaluation context.
13290   DiscardCleanupsInEvaluationContext();
13291   PopExpressionEvaluationContext();
13292 
13293   // Pop off CurBlock, handle nested blocks.
13294   PopDeclContext();
13295   PopFunctionScopeInfo();
13296 }
13297 
13298 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13299 /// literal was successfully completed.  ^(int x){...}
13300 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13301                                     Stmt *Body, Scope *CurScope) {
13302   // If blocks are disabled, emit an error.
13303   if (!LangOpts.Blocks)
13304     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13305 
13306   // Leave the expression-evaluation context.
13307   if (hasAnyUnrecoverableErrorsInThisFunction())
13308     DiscardCleanupsInEvaluationContext();
13309   assert(!Cleanup.exprNeedsCleanups() &&
13310          "cleanups within block not correctly bound!");
13311   PopExpressionEvaluationContext();
13312 
13313   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13314 
13315   if (BSI->HasImplicitReturnType)
13316     deduceClosureReturnType(*BSI);
13317 
13318   PopDeclContext();
13319 
13320   QualType RetTy = Context.VoidTy;
13321   if (!BSI->ReturnType.isNull())
13322     RetTy = BSI->ReturnType;
13323 
13324   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
13325   QualType BlockTy;
13326 
13327   // Set the captured variables on the block.
13328   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13329   SmallVector<BlockDecl::Capture, 4> Captures;
13330   for (Capture &Cap : BSI->Captures) {
13331     if (Cap.isThisCapture())
13332       continue;
13333     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13334                               Cap.isNested(), Cap.getInitExpr());
13335     Captures.push_back(NewCap);
13336   }
13337   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13338 
13339   // If the user wrote a function type in some form, try to use that.
13340   if (!BSI->FunctionType.isNull()) {
13341     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13342 
13343     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13344     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13345 
13346     // Turn protoless block types into nullary block types.
13347     if (isa<FunctionNoProtoType>(FTy)) {
13348       FunctionProtoType::ExtProtoInfo EPI;
13349       EPI.ExtInfo = Ext;
13350       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13351 
13352     // Otherwise, if we don't need to change anything about the function type,
13353     // preserve its sugar structure.
13354     } else if (FTy->getReturnType() == RetTy &&
13355                (!NoReturn || FTy->getNoReturnAttr())) {
13356       BlockTy = BSI->FunctionType;
13357 
13358     // Otherwise, make the minimal modifications to the function type.
13359     } else {
13360       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13361       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13362       EPI.TypeQuals = 0; // FIXME: silently?
13363       EPI.ExtInfo = Ext;
13364       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13365     }
13366 
13367   // If we don't have a function type, just build one from nothing.
13368   } else {
13369     FunctionProtoType::ExtProtoInfo EPI;
13370     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13371     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13372   }
13373 
13374   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
13375   BlockTy = Context.getBlockPointerType(BlockTy);
13376 
13377   // If needed, diagnose invalid gotos and switches in the block.
13378   if (getCurFunction()->NeedsScopeChecking() &&
13379       !PP.isCodeCompletionEnabled())
13380     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13381 
13382   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
13383 
13384   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13385     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
13386 
13387   // Try to apply the named return value optimization. We have to check again
13388   // if we can do this, though, because blocks keep return statements around
13389   // to deduce an implicit return type.
13390   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13391       !BSI->TheDecl->isDependentContext())
13392     computeNRVO(Body, BSI);
13393 
13394   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
13395   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13396   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13397 
13398   // If the block isn't obviously global, i.e. it captures anything at
13399   // all, then we need to do a few things in the surrounding context:
13400   if (Result->getBlockDecl()->hasCaptures()) {
13401     // First, this expression has a new cleanup object.
13402     ExprCleanupObjects.push_back(Result->getBlockDecl());
13403     Cleanup.setExprNeedsCleanups(true);
13404 
13405     // It also gets a branch-protected scope if any of the captured
13406     // variables needs destruction.
13407     for (const auto &CI : Result->getBlockDecl()->captures()) {
13408       const VarDecl *var = CI.getVariable();
13409       if (var->getType().isDestructedType() != QualType::DK_none) {
13410         setFunctionHasBranchProtectedScope();
13411         break;
13412       }
13413     }
13414   }
13415 
13416   return Result;
13417 }
13418 
13419 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13420                             SourceLocation RPLoc) {
13421   TypeSourceInfo *TInfo;
13422   GetTypeFromParser(Ty, &TInfo);
13423   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13424 }
13425 
13426 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13427                                 Expr *E, TypeSourceInfo *TInfo,
13428                                 SourceLocation RPLoc) {
13429   Expr *OrigExpr = E;
13430   bool IsMS = false;
13431 
13432   // CUDA device code does not support varargs.
13433   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13434     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13435       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13436       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13437         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
13438     }
13439   }
13440 
13441   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13442   // as Microsoft ABI on an actual Microsoft platform, where
13443   // __builtin_ms_va_list and __builtin_va_list are the same.)
13444   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13445       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13446     QualType MSVaListType = Context.getBuiltinMSVaListType();
13447     if (Context.hasSameType(MSVaListType, E->getType())) {
13448       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13449         return ExprError();
13450       IsMS = true;
13451     }
13452   }
13453 
13454   // Get the va_list type
13455   QualType VaListType = Context.getBuiltinVaListType();
13456   if (!IsMS) {
13457     if (VaListType->isArrayType()) {
13458       // Deal with implicit array decay; for example, on x86-64,
13459       // va_list is an array, but it's supposed to decay to
13460       // a pointer for va_arg.
13461       VaListType = Context.getArrayDecayedType(VaListType);
13462       // Make sure the input expression also decays appropriately.
13463       ExprResult Result = UsualUnaryConversions(E);
13464       if (Result.isInvalid())
13465         return ExprError();
13466       E = Result.get();
13467     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13468       // If va_list is a record type and we are compiling in C++ mode,
13469       // check the argument using reference binding.
13470       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13471           Context, Context.getLValueReferenceType(VaListType), false);
13472       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13473       if (Init.isInvalid())
13474         return ExprError();
13475       E = Init.getAs<Expr>();
13476     } else {
13477       // Otherwise, the va_list argument must be an l-value because
13478       // it is modified by va_arg.
13479       if (!E->isTypeDependent() &&
13480           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13481         return ExprError();
13482     }
13483   }
13484 
13485   if (!IsMS && !E->isTypeDependent() &&
13486       !Context.hasSameType(VaListType, E->getType()))
13487     return ExprError(Diag(E->getLocStart(),
13488                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
13489       << OrigExpr->getType() << E->getSourceRange());
13490 
13491   if (!TInfo->getType()->isDependentType()) {
13492     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13493                             diag::err_second_parameter_to_va_arg_incomplete,
13494                             TInfo->getTypeLoc()))
13495       return ExprError();
13496 
13497     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13498                                TInfo->getType(),
13499                                diag::err_second_parameter_to_va_arg_abstract,
13500                                TInfo->getTypeLoc()))
13501       return ExprError();
13502 
13503     if (!TInfo->getType().isPODType(Context)) {
13504       Diag(TInfo->getTypeLoc().getBeginLoc(),
13505            TInfo->getType()->isObjCLifetimeType()
13506              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13507              : diag::warn_second_parameter_to_va_arg_not_pod)
13508         << TInfo->getType()
13509         << TInfo->getTypeLoc().getSourceRange();
13510     }
13511 
13512     // Check for va_arg where arguments of the given type will be promoted
13513     // (i.e. this va_arg is guaranteed to have undefined behavior).
13514     QualType PromoteType;
13515     if (TInfo->getType()->isPromotableIntegerType()) {
13516       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13517       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13518         PromoteType = QualType();
13519     }
13520     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13521       PromoteType = Context.DoubleTy;
13522     if (!PromoteType.isNull())
13523       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13524                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13525                           << TInfo->getType()
13526                           << PromoteType
13527                           << TInfo->getTypeLoc().getSourceRange());
13528   }
13529 
13530   QualType T = TInfo->getType().getNonLValueExprType(Context);
13531   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13532 }
13533 
13534 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13535   // The type of __null will be int or long, depending on the size of
13536   // pointers on the target.
13537   QualType Ty;
13538   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13539   if (pw == Context.getTargetInfo().getIntWidth())
13540     Ty = Context.IntTy;
13541   else if (pw == Context.getTargetInfo().getLongWidth())
13542     Ty = Context.LongTy;
13543   else if (pw == Context.getTargetInfo().getLongLongWidth())
13544     Ty = Context.LongLongTy;
13545   else {
13546     llvm_unreachable("I don't know size of pointer!");
13547   }
13548 
13549   return new (Context) GNUNullExpr(Ty, TokenLoc);
13550 }
13551 
13552 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13553                                               bool Diagnose) {
13554   if (!getLangOpts().ObjC1)
13555     return false;
13556 
13557   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13558   if (!PT)
13559     return false;
13560 
13561   if (!PT->isObjCIdType()) {
13562     // Check if the destination is the 'NSString' interface.
13563     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13564     if (!ID || !ID->getIdentifier()->isStr("NSString"))
13565       return false;
13566   }
13567 
13568   // Ignore any parens, implicit casts (should only be
13569   // array-to-pointer decays), and not-so-opaque values.  The last is
13570   // important for making this trigger for property assignments.
13571   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13572   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13573     if (OV->getSourceExpr())
13574       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13575 
13576   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13577   if (!SL || !SL->isAscii())
13578     return false;
13579   if (Diagnose) {
13580     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
13581       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
13582     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
13583   }
13584   return true;
13585 }
13586 
13587 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13588                                               const Expr *SrcExpr) {
13589   if (!DstType->isFunctionPointerType() ||
13590       !SrcExpr->getType()->isFunctionType())
13591     return false;
13592 
13593   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13594   if (!DRE)
13595     return false;
13596 
13597   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13598   if (!FD)
13599     return false;
13600 
13601   return !S.checkAddressOfFunctionIsAvailable(FD,
13602                                               /*Complain=*/true,
13603                                               SrcExpr->getLocStart());
13604 }
13605 
13606 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13607                                     SourceLocation Loc,
13608                                     QualType DstType, QualType SrcType,
13609                                     Expr *SrcExpr, AssignmentAction Action,
13610                                     bool *Complained) {
13611   if (Complained)
13612     *Complained = false;
13613 
13614   // Decode the result (notice that AST's are still created for extensions).
13615   bool CheckInferredResultType = false;
13616   bool isInvalid = false;
13617   unsigned DiagKind = 0;
13618   FixItHint Hint;
13619   ConversionFixItGenerator ConvHints;
13620   bool MayHaveConvFixit = false;
13621   bool MayHaveFunctionDiff = false;
13622   const ObjCInterfaceDecl *IFace = nullptr;
13623   const ObjCProtocolDecl *PDecl = nullptr;
13624 
13625   switch (ConvTy) {
13626   case Compatible:
13627       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13628       return false;
13629 
13630   case PointerToInt:
13631     DiagKind = diag::ext_typecheck_convert_pointer_int;
13632     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13633     MayHaveConvFixit = true;
13634     break;
13635   case IntToPointer:
13636     DiagKind = diag::ext_typecheck_convert_int_pointer;
13637     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13638     MayHaveConvFixit = true;
13639     break;
13640   case IncompatiblePointer:
13641     if (Action == AA_Passing_CFAudited)
13642       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13643     else if (SrcType->isFunctionPointerType() &&
13644              DstType->isFunctionPointerType())
13645       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13646     else
13647       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13648 
13649     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13650       SrcType->isObjCObjectPointerType();
13651     if (Hint.isNull() && !CheckInferredResultType) {
13652       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13653     }
13654     else if (CheckInferredResultType) {
13655       SrcType = SrcType.getUnqualifiedType();
13656       DstType = DstType.getUnqualifiedType();
13657     }
13658     MayHaveConvFixit = true;
13659     break;
13660   case IncompatiblePointerSign:
13661     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13662     break;
13663   case FunctionVoidPointer:
13664     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13665     break;
13666   case IncompatiblePointerDiscardsQualifiers: {
13667     // Perform array-to-pointer decay if necessary.
13668     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13669 
13670     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13671     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13672     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13673       DiagKind = diag::err_typecheck_incompatible_address_space;
13674       break;
13675 
13676     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13677       DiagKind = diag::err_typecheck_incompatible_ownership;
13678       break;
13679     }
13680 
13681     llvm_unreachable("unknown error case for discarding qualifiers!");
13682     // fallthrough
13683   }
13684   case CompatiblePointerDiscardsQualifiers:
13685     // If the qualifiers lost were because we were applying the
13686     // (deprecated) C++ conversion from a string literal to a char*
13687     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13688     // Ideally, this check would be performed in
13689     // checkPointerTypesForAssignment. However, that would require a
13690     // bit of refactoring (so that the second argument is an
13691     // expression, rather than a type), which should be done as part
13692     // of a larger effort to fix checkPointerTypesForAssignment for
13693     // C++ semantics.
13694     if (getLangOpts().CPlusPlus &&
13695         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13696       return false;
13697     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13698     break;
13699   case IncompatibleNestedPointerQualifiers:
13700     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13701     break;
13702   case IntToBlockPointer:
13703     DiagKind = diag::err_int_to_block_pointer;
13704     break;
13705   case IncompatibleBlockPointer:
13706     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13707     break;
13708   case IncompatibleObjCQualifiedId: {
13709     if (SrcType->isObjCQualifiedIdType()) {
13710       const ObjCObjectPointerType *srcOPT =
13711                 SrcType->getAs<ObjCObjectPointerType>();
13712       for (auto *srcProto : srcOPT->quals()) {
13713         PDecl = srcProto;
13714         break;
13715       }
13716       if (const ObjCInterfaceType *IFaceT =
13717             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13718         IFace = IFaceT->getDecl();
13719     }
13720     else if (DstType->isObjCQualifiedIdType()) {
13721       const ObjCObjectPointerType *dstOPT =
13722         DstType->getAs<ObjCObjectPointerType>();
13723       for (auto *dstProto : dstOPT->quals()) {
13724         PDecl = dstProto;
13725         break;
13726       }
13727       if (const ObjCInterfaceType *IFaceT =
13728             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13729         IFace = IFaceT->getDecl();
13730     }
13731     DiagKind = diag::warn_incompatible_qualified_id;
13732     break;
13733   }
13734   case IncompatibleVectors:
13735     DiagKind = diag::warn_incompatible_vectors;
13736     break;
13737   case IncompatibleObjCWeakRef:
13738     DiagKind = diag::err_arc_weak_unavailable_assign;
13739     break;
13740   case Incompatible:
13741     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13742       if (Complained)
13743         *Complained = true;
13744       return true;
13745     }
13746 
13747     DiagKind = diag::err_typecheck_convert_incompatible;
13748     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13749     MayHaveConvFixit = true;
13750     isInvalid = true;
13751     MayHaveFunctionDiff = true;
13752     break;
13753   }
13754 
13755   QualType FirstType, SecondType;
13756   switch (Action) {
13757   case AA_Assigning:
13758   case AA_Initializing:
13759     // The destination type comes first.
13760     FirstType = DstType;
13761     SecondType = SrcType;
13762     break;
13763 
13764   case AA_Returning:
13765   case AA_Passing:
13766   case AA_Passing_CFAudited:
13767   case AA_Converting:
13768   case AA_Sending:
13769   case AA_Casting:
13770     // The source type comes first.
13771     FirstType = SrcType;
13772     SecondType = DstType;
13773     break;
13774   }
13775 
13776   PartialDiagnostic FDiag = PDiag(DiagKind);
13777   if (Action == AA_Passing_CFAudited)
13778     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13779   else
13780     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13781 
13782   // If we can fix the conversion, suggest the FixIts.
13783   assert(ConvHints.isNull() || Hint.isNull());
13784   if (!ConvHints.isNull()) {
13785     for (FixItHint &H : ConvHints.Hints)
13786       FDiag << H;
13787   } else {
13788     FDiag << Hint;
13789   }
13790   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13791 
13792   if (MayHaveFunctionDiff)
13793     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13794 
13795   Diag(Loc, FDiag);
13796   if (DiagKind == diag::warn_incompatible_qualified_id &&
13797       PDecl && IFace && !IFace->hasDefinition())
13798       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13799         << IFace << PDecl;
13800 
13801   if (SecondType == Context.OverloadTy)
13802     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13803                               FirstType, /*TakingAddress=*/true);
13804 
13805   if (CheckInferredResultType)
13806     EmitRelatedResultTypeNote(SrcExpr);
13807 
13808   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13809     EmitRelatedResultTypeNoteForReturn(DstType);
13810 
13811   if (Complained)
13812     *Complained = true;
13813   return isInvalid;
13814 }
13815 
13816 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13817                                                  llvm::APSInt *Result) {
13818   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13819   public:
13820     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13821       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13822     }
13823   } Diagnoser;
13824 
13825   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13826 }
13827 
13828 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13829                                                  llvm::APSInt *Result,
13830                                                  unsigned DiagID,
13831                                                  bool AllowFold) {
13832   class IDDiagnoser : public VerifyICEDiagnoser {
13833     unsigned DiagID;
13834 
13835   public:
13836     IDDiagnoser(unsigned DiagID)
13837       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13838 
13839     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13840       S.Diag(Loc, DiagID) << SR;
13841     }
13842   } Diagnoser(DiagID);
13843 
13844   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13845 }
13846 
13847 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13848                                             SourceRange SR) {
13849   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13850 }
13851 
13852 ExprResult
13853 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13854                                       VerifyICEDiagnoser &Diagnoser,
13855                                       bool AllowFold) {
13856   SourceLocation DiagLoc = E->getLocStart();
13857 
13858   if (getLangOpts().CPlusPlus11) {
13859     // C++11 [expr.const]p5:
13860     //   If an expression of literal class type is used in a context where an
13861     //   integral constant expression is required, then that class type shall
13862     //   have a single non-explicit conversion function to an integral or
13863     //   unscoped enumeration type
13864     ExprResult Converted;
13865     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13866     public:
13867       CXX11ConvertDiagnoser(bool Silent)
13868           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13869                                 Silent, true) {}
13870 
13871       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13872                                            QualType T) override {
13873         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13874       }
13875 
13876       SemaDiagnosticBuilder diagnoseIncomplete(
13877           Sema &S, SourceLocation Loc, QualType T) override {
13878         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13879       }
13880 
13881       SemaDiagnosticBuilder diagnoseExplicitConv(
13882           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13883         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13884       }
13885 
13886       SemaDiagnosticBuilder noteExplicitConv(
13887           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13888         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13889                  << ConvTy->isEnumeralType() << ConvTy;
13890       }
13891 
13892       SemaDiagnosticBuilder diagnoseAmbiguous(
13893           Sema &S, SourceLocation Loc, QualType T) override {
13894         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13895       }
13896 
13897       SemaDiagnosticBuilder noteAmbiguous(
13898           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13899         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13900                  << ConvTy->isEnumeralType() << ConvTy;
13901       }
13902 
13903       SemaDiagnosticBuilder diagnoseConversion(
13904           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13905         llvm_unreachable("conversion functions are permitted");
13906       }
13907     } ConvertDiagnoser(Diagnoser.Suppress);
13908 
13909     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13910                                                     ConvertDiagnoser);
13911     if (Converted.isInvalid())
13912       return Converted;
13913     E = Converted.get();
13914     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13915       return ExprError();
13916   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13917     // An ICE must be of integral or unscoped enumeration type.
13918     if (!Diagnoser.Suppress)
13919       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13920     return ExprError();
13921   }
13922 
13923   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13924   // in the non-ICE case.
13925   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13926     if (Result)
13927       *Result = E->EvaluateKnownConstInt(Context);
13928     return E;
13929   }
13930 
13931   Expr::EvalResult EvalResult;
13932   SmallVector<PartialDiagnosticAt, 8> Notes;
13933   EvalResult.Diag = &Notes;
13934 
13935   // Try to evaluate the expression, and produce diagnostics explaining why it's
13936   // not a constant expression as a side-effect.
13937   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13938                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13939 
13940   // In C++11, we can rely on diagnostics being produced for any expression
13941   // which is not a constant expression. If no diagnostics were produced, then
13942   // this is a constant expression.
13943   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13944     if (Result)
13945       *Result = EvalResult.Val.getInt();
13946     return E;
13947   }
13948 
13949   // If our only note is the usual "invalid subexpression" note, just point
13950   // the caret at its location rather than producing an essentially
13951   // redundant note.
13952   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13953         diag::note_invalid_subexpr_in_const_expr) {
13954     DiagLoc = Notes[0].first;
13955     Notes.clear();
13956   }
13957 
13958   if (!Folded || !AllowFold) {
13959     if (!Diagnoser.Suppress) {
13960       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13961       for (const PartialDiagnosticAt &Note : Notes)
13962         Diag(Note.first, Note.second);
13963     }
13964 
13965     return ExprError();
13966   }
13967 
13968   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13969   for (const PartialDiagnosticAt &Note : Notes)
13970     Diag(Note.first, Note.second);
13971 
13972   if (Result)
13973     *Result = EvalResult.Val.getInt();
13974   return E;
13975 }
13976 
13977 namespace {
13978   // Handle the case where we conclude a expression which we speculatively
13979   // considered to be unevaluated is actually evaluated.
13980   class TransformToPE : public TreeTransform<TransformToPE> {
13981     typedef TreeTransform<TransformToPE> BaseTransform;
13982 
13983   public:
13984     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13985 
13986     // Make sure we redo semantic analysis
13987     bool AlwaysRebuild() { return true; }
13988 
13989     // Make sure we handle LabelStmts correctly.
13990     // FIXME: This does the right thing, but maybe we need a more general
13991     // fix to TreeTransform?
13992     StmtResult TransformLabelStmt(LabelStmt *S) {
13993       S->getDecl()->setStmt(nullptr);
13994       return BaseTransform::TransformLabelStmt(S);
13995     }
13996 
13997     // We need to special-case DeclRefExprs referring to FieldDecls which
13998     // are not part of a member pointer formation; normal TreeTransforming
13999     // doesn't catch this case because of the way we represent them in the AST.
14000     // FIXME: This is a bit ugly; is it really the best way to handle this
14001     // case?
14002     //
14003     // Error on DeclRefExprs referring to FieldDecls.
14004     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14005       if (isa<FieldDecl>(E->getDecl()) &&
14006           !SemaRef.isUnevaluatedContext())
14007         return SemaRef.Diag(E->getLocation(),
14008                             diag::err_invalid_non_static_member_use)
14009             << E->getDecl() << E->getSourceRange();
14010 
14011       return BaseTransform::TransformDeclRefExpr(E);
14012     }
14013 
14014     // Exception: filter out member pointer formation
14015     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14016       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14017         return E;
14018 
14019       return BaseTransform::TransformUnaryOperator(E);
14020     }
14021 
14022     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14023       // Lambdas never need to be transformed.
14024       return E;
14025     }
14026   };
14027 }
14028 
14029 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14030   assert(isUnevaluatedContext() &&
14031          "Should only transform unevaluated expressions");
14032   ExprEvalContexts.back().Context =
14033       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14034   if (isUnevaluatedContext())
14035     return E;
14036   return TransformToPE(*this).TransformExpr(E);
14037 }
14038 
14039 void
14040 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
14041                                       Decl *LambdaContextDecl,
14042                                       bool IsDecltype) {
14043   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14044                                 LambdaContextDecl, IsDecltype);
14045   Cleanup.reset();
14046   if (!MaybeODRUseExprs.empty())
14047     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14048 }
14049 
14050 void
14051 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
14052                                       ReuseLambdaContextDecl_t,
14053                                       bool IsDecltype) {
14054   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14055   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
14056 }
14057 
14058 void Sema::PopExpressionEvaluationContext() {
14059   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14060   unsigned NumTypos = Rec.NumTypos;
14061 
14062   if (!Rec.Lambdas.empty()) {
14063     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14064       unsigned D;
14065       if (Rec.isUnevaluated()) {
14066         // C++11 [expr.prim.lambda]p2:
14067         //   A lambda-expression shall not appear in an unevaluated operand
14068         //   (Clause 5).
14069         D = diag::err_lambda_unevaluated_operand;
14070       } else {
14071         // C++1y [expr.const]p2:
14072         //   A conditional-expression e is a core constant expression unless the
14073         //   evaluation of e, following the rules of the abstract machine, would
14074         //   evaluate [...] a lambda-expression.
14075         D = diag::err_lambda_in_constant_expression;
14076       }
14077 
14078       // C++1z allows lambda expressions as core constant expressions.
14079       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
14080       // 1607) from appearing within template-arguments and array-bounds that
14081       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
14082       // unevaluated contexts) might lift some of these restrictions in a
14083       // future version.
14084       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17)
14085         for (const auto *L : Rec.Lambdas)
14086           Diag(L->getLocStart(), D);
14087     } else {
14088       // Mark the capture expressions odr-used. This was deferred
14089       // during lambda expression creation.
14090       for (auto *Lambda : Rec.Lambdas) {
14091         for (auto *C : Lambda->capture_inits())
14092           MarkDeclarationsReferencedInExpr(C);
14093       }
14094     }
14095   }
14096 
14097   // When are coming out of an unevaluated context, clear out any
14098   // temporaries that we may have created as part of the evaluation of
14099   // the expression in that context: they aren't relevant because they
14100   // will never be constructed.
14101   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14102     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14103                              ExprCleanupObjects.end());
14104     Cleanup = Rec.ParentCleanup;
14105     CleanupVarDeclMarking();
14106     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14107   // Otherwise, merge the contexts together.
14108   } else {
14109     Cleanup.mergeFrom(Rec.ParentCleanup);
14110     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14111                             Rec.SavedMaybeODRUseExprs.end());
14112   }
14113 
14114   // Pop the current expression evaluation context off the stack.
14115   ExprEvalContexts.pop_back();
14116 
14117   if (!ExprEvalContexts.empty())
14118     ExprEvalContexts.back().NumTypos += NumTypos;
14119   else
14120     assert(NumTypos == 0 && "There are outstanding typos after popping the "
14121                             "last ExpressionEvaluationContextRecord");
14122 }
14123 
14124 void Sema::DiscardCleanupsInEvaluationContext() {
14125   ExprCleanupObjects.erase(
14126          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14127          ExprCleanupObjects.end());
14128   Cleanup.reset();
14129   MaybeODRUseExprs.clear();
14130 }
14131 
14132 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14133   if (!E->getType()->isVariablyModifiedType())
14134     return E;
14135   return TransformToPotentiallyEvaluated(E);
14136 }
14137 
14138 /// Are we within a context in which some evaluation could be performed (be it
14139 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14140 /// captured by C++'s idea of an "unevaluated context".
14141 static bool isEvaluatableContext(Sema &SemaRef) {
14142   switch (SemaRef.ExprEvalContexts.back().Context) {
14143     case Sema::ExpressionEvaluationContext::Unevaluated:
14144     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14145     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14146       // Expressions in this context are never evaluated.
14147       return false;
14148 
14149     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14150     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14151     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14152       // Expressions in this context could be evaluated.
14153       return true;
14154 
14155     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14156       // Referenced declarations will only be used if the construct in the
14157       // containing expression is used, at which point we'll be given another
14158       // turn to mark them.
14159       return false;
14160   }
14161   llvm_unreachable("Invalid context");
14162 }
14163 
14164 /// Are we within a context in which references to resolved functions or to
14165 /// variables result in odr-use?
14166 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14167   // An expression in a template is not really an expression until it's been
14168   // instantiated, so it doesn't trigger odr-use.
14169   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14170     return false;
14171 
14172   switch (SemaRef.ExprEvalContexts.back().Context) {
14173     case Sema::ExpressionEvaluationContext::Unevaluated:
14174     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14175     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14176     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14177       return false;
14178 
14179     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14180     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14181       return true;
14182 
14183     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14184       return false;
14185   }
14186   llvm_unreachable("Invalid context");
14187 }
14188 
14189 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14190   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14191   return Func->isConstexpr() &&
14192          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14193 }
14194 
14195 /// Mark a function referenced, and check whether it is odr-used
14196 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14197 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14198                                   bool MightBeOdrUse) {
14199   assert(Func && "No function?");
14200 
14201   Func->setReferenced();
14202 
14203   // C++11 [basic.def.odr]p3:
14204   //   A function whose name appears as a potentially-evaluated expression is
14205   //   odr-used if it is the unique lookup result or the selected member of a
14206   //   set of overloaded functions [...].
14207   //
14208   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14209   // can just check that here.
14210   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14211 
14212   // Determine whether we require a function definition to exist, per
14213   // C++11 [temp.inst]p3:
14214   //   Unless a function template specialization has been explicitly
14215   //   instantiated or explicitly specialized, the function template
14216   //   specialization is implicitly instantiated when the specialization is
14217   //   referenced in a context that requires a function definition to exist.
14218   //
14219   // That is either when this is an odr-use, or when a usage of a constexpr
14220   // function occurs within an evaluatable context.
14221   bool NeedDefinition =
14222       OdrUse || (isEvaluatableContext(*this) &&
14223                  isImplicitlyDefinableConstexprFunction(Func));
14224 
14225   // C++14 [temp.expl.spec]p6:
14226   //   If a template [...] is explicitly specialized then that specialization
14227   //   shall be declared before the first use of that specialization that would
14228   //   cause an implicit instantiation to take place, in every translation unit
14229   //   in which such a use occurs
14230   if (NeedDefinition &&
14231       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14232        Func->getMemberSpecializationInfo()))
14233     checkSpecializationVisibility(Loc, Func);
14234 
14235   // C++14 [except.spec]p17:
14236   //   An exception-specification is considered to be needed when:
14237   //   - the function is odr-used or, if it appears in an unevaluated operand,
14238   //     would be odr-used if the expression were potentially-evaluated;
14239   //
14240   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14241   // function is a pure virtual function we're calling, and in that case the
14242   // function was selected by overload resolution and we need to resolve its
14243   // exception specification for a different reason.
14244   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14245   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14246     ResolveExceptionSpec(Loc, FPT);
14247 
14248   // If we don't need to mark the function as used, and we don't need to
14249   // try to provide a definition, there's nothing more to do.
14250   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14251       (!NeedDefinition || Func->getBody()))
14252     return;
14253 
14254   // Note that this declaration has been used.
14255   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14256     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14257     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14258       if (Constructor->isDefaultConstructor()) {
14259         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14260           return;
14261         DefineImplicitDefaultConstructor(Loc, Constructor);
14262       } else if (Constructor->isCopyConstructor()) {
14263         DefineImplicitCopyConstructor(Loc, Constructor);
14264       } else if (Constructor->isMoveConstructor()) {
14265         DefineImplicitMoveConstructor(Loc, Constructor);
14266       }
14267     } else if (Constructor->getInheritedConstructor()) {
14268       DefineInheritingConstructor(Loc, Constructor);
14269     }
14270   } else if (CXXDestructorDecl *Destructor =
14271                  dyn_cast<CXXDestructorDecl>(Func)) {
14272     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14273     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14274       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14275         return;
14276       DefineImplicitDestructor(Loc, Destructor);
14277     }
14278     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14279       MarkVTableUsed(Loc, Destructor->getParent());
14280   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14281     if (MethodDecl->isOverloadedOperator() &&
14282         MethodDecl->getOverloadedOperator() == OO_Equal) {
14283       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14284       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14285         if (MethodDecl->isCopyAssignmentOperator())
14286           DefineImplicitCopyAssignment(Loc, MethodDecl);
14287         else if (MethodDecl->isMoveAssignmentOperator())
14288           DefineImplicitMoveAssignment(Loc, MethodDecl);
14289       }
14290     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14291                MethodDecl->getParent()->isLambda()) {
14292       CXXConversionDecl *Conversion =
14293           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14294       if (Conversion->isLambdaToBlockPointerConversion())
14295         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14296       else
14297         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14298     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14299       MarkVTableUsed(Loc, MethodDecl->getParent());
14300   }
14301 
14302   // Recursive functions should be marked when used from another function.
14303   // FIXME: Is this really right?
14304   if (CurContext == Func) return;
14305 
14306   // Implicit instantiation of function templates and member functions of
14307   // class templates.
14308   if (Func->isImplicitlyInstantiable()) {
14309     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14310     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14311     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14312     if (FirstInstantiation) {
14313       PointOfInstantiation = Loc;
14314       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14315     } else if (TSK != TSK_ImplicitInstantiation) {
14316       // Use the point of use as the point of instantiation, instead of the
14317       // point of explicit instantiation (which we track as the actual point of
14318       // instantiation). This gives better backtraces in diagnostics.
14319       PointOfInstantiation = Loc;
14320     }
14321 
14322     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14323         Func->isConstexpr()) {
14324       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14325           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14326           CodeSynthesisContexts.size())
14327         PendingLocalImplicitInstantiations.push_back(
14328             std::make_pair(Func, PointOfInstantiation));
14329       else if (Func->isConstexpr())
14330         // Do not defer instantiations of constexpr functions, to avoid the
14331         // expression evaluator needing to call back into Sema if it sees a
14332         // call to such a function.
14333         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14334       else {
14335         Func->setInstantiationIsPending(true);
14336         PendingInstantiations.push_back(std::make_pair(Func,
14337                                                        PointOfInstantiation));
14338         // Notify the consumer that a function was implicitly instantiated.
14339         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14340       }
14341     }
14342   } else {
14343     // Walk redefinitions, as some of them may be instantiable.
14344     for (auto i : Func->redecls()) {
14345       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14346         MarkFunctionReferenced(Loc, i, OdrUse);
14347     }
14348   }
14349 
14350   if (!OdrUse) return;
14351 
14352   // Keep track of used but undefined functions.
14353   if (!Func->isDefined()) {
14354     if (mightHaveNonExternalLinkage(Func))
14355       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14356     else if (Func->getMostRecentDecl()->isInlined() &&
14357              !LangOpts.GNUInline &&
14358              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14359       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14360     else if (isExternalWithNoLinkageType(Func))
14361       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14362   }
14363 
14364   Func->markUsed(Context);
14365 }
14366 
14367 static void
14368 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14369                                    ValueDecl *var, DeclContext *DC) {
14370   DeclContext *VarDC = var->getDeclContext();
14371 
14372   //  If the parameter still belongs to the translation unit, then
14373   //  we're actually just using one parameter in the declaration of
14374   //  the next.
14375   if (isa<ParmVarDecl>(var) &&
14376       isa<TranslationUnitDecl>(VarDC))
14377     return;
14378 
14379   // For C code, don't diagnose about capture if we're not actually in code
14380   // right now; it's impossible to write a non-constant expression outside of
14381   // function context, so we'll get other (more useful) diagnostics later.
14382   //
14383   // For C++, things get a bit more nasty... it would be nice to suppress this
14384   // diagnostic for certain cases like using a local variable in an array bound
14385   // for a member of a local class, but the correct predicate is not obvious.
14386   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14387     return;
14388 
14389   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14390   unsigned ContextKind = 3; // unknown
14391   if (isa<CXXMethodDecl>(VarDC) &&
14392       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14393     ContextKind = 2;
14394   } else if (isa<FunctionDecl>(VarDC)) {
14395     ContextKind = 0;
14396   } else if (isa<BlockDecl>(VarDC)) {
14397     ContextKind = 1;
14398   }
14399 
14400   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14401     << var << ValueKind << ContextKind << VarDC;
14402   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14403       << var;
14404 
14405   // FIXME: Add additional diagnostic info about class etc. which prevents
14406   // capture.
14407 }
14408 
14409 
14410 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14411                                       bool &SubCapturesAreNested,
14412                                       QualType &CaptureType,
14413                                       QualType &DeclRefType) {
14414    // Check whether we've already captured it.
14415   if (CSI->CaptureMap.count(Var)) {
14416     // If we found a capture, any subcaptures are nested.
14417     SubCapturesAreNested = true;
14418 
14419     // Retrieve the capture type for this variable.
14420     CaptureType = CSI->getCapture(Var).getCaptureType();
14421 
14422     // Compute the type of an expression that refers to this variable.
14423     DeclRefType = CaptureType.getNonReferenceType();
14424 
14425     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14426     // are mutable in the sense that user can change their value - they are
14427     // private instances of the captured declarations.
14428     const Capture &Cap = CSI->getCapture(Var);
14429     if (Cap.isCopyCapture() &&
14430         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14431         !(isa<CapturedRegionScopeInfo>(CSI) &&
14432           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14433       DeclRefType.addConst();
14434     return true;
14435   }
14436   return false;
14437 }
14438 
14439 // Only block literals, captured statements, and lambda expressions can
14440 // capture; other scopes don't work.
14441 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14442                                  SourceLocation Loc,
14443                                  const bool Diagnose, Sema &S) {
14444   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14445     return getLambdaAwareParentOfDeclContext(DC);
14446   else if (Var->hasLocalStorage()) {
14447     if (Diagnose)
14448        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14449   }
14450   return nullptr;
14451 }
14452 
14453 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14454 // certain types of variables (unnamed, variably modified types etc.)
14455 // so check for eligibility.
14456 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14457                                  SourceLocation Loc,
14458                                  const bool Diagnose, Sema &S) {
14459 
14460   bool IsBlock = isa<BlockScopeInfo>(CSI);
14461   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14462 
14463   // Lambdas are not allowed to capture unnamed variables
14464   // (e.g. anonymous unions).
14465   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14466   // assuming that's the intent.
14467   if (IsLambda && !Var->getDeclName()) {
14468     if (Diagnose) {
14469       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14470       S.Diag(Var->getLocation(), diag::note_declared_at);
14471     }
14472     return false;
14473   }
14474 
14475   // Prohibit variably-modified types in blocks; they're difficult to deal with.
14476   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14477     if (Diagnose) {
14478       S.Diag(Loc, diag::err_ref_vm_type);
14479       S.Diag(Var->getLocation(), diag::note_previous_decl)
14480         << Var->getDeclName();
14481     }
14482     return false;
14483   }
14484   // Prohibit structs with flexible array members too.
14485   // We cannot capture what is in the tail end of the struct.
14486   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14487     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14488       if (Diagnose) {
14489         if (IsBlock)
14490           S.Diag(Loc, diag::err_ref_flexarray_type);
14491         else
14492           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14493             << Var->getDeclName();
14494         S.Diag(Var->getLocation(), diag::note_previous_decl)
14495           << Var->getDeclName();
14496       }
14497       return false;
14498     }
14499   }
14500   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14501   // Lambdas and captured statements are not allowed to capture __block
14502   // variables; they don't support the expected semantics.
14503   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14504     if (Diagnose) {
14505       S.Diag(Loc, diag::err_capture_block_variable)
14506         << Var->getDeclName() << !IsLambda;
14507       S.Diag(Var->getLocation(), diag::note_previous_decl)
14508         << Var->getDeclName();
14509     }
14510     return false;
14511   }
14512   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14513   if (S.getLangOpts().OpenCL && IsBlock &&
14514       Var->getType()->isBlockPointerType()) {
14515     if (Diagnose)
14516       S.Diag(Loc, diag::err_opencl_block_ref_block);
14517     return false;
14518   }
14519 
14520   return true;
14521 }
14522 
14523 // Returns true if the capture by block was successful.
14524 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14525                                  SourceLocation Loc,
14526                                  const bool BuildAndDiagnose,
14527                                  QualType &CaptureType,
14528                                  QualType &DeclRefType,
14529                                  const bool Nested,
14530                                  Sema &S) {
14531   Expr *CopyExpr = nullptr;
14532   bool ByRef = false;
14533 
14534   // Blocks are not allowed to capture arrays.
14535   if (CaptureType->isArrayType()) {
14536     if (BuildAndDiagnose) {
14537       S.Diag(Loc, diag::err_ref_array_type);
14538       S.Diag(Var->getLocation(), diag::note_previous_decl)
14539       << Var->getDeclName();
14540     }
14541     return false;
14542   }
14543 
14544   // Forbid the block-capture of autoreleasing variables.
14545   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14546     if (BuildAndDiagnose) {
14547       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14548         << /*block*/ 0;
14549       S.Diag(Var->getLocation(), diag::note_previous_decl)
14550         << Var->getDeclName();
14551     }
14552     return false;
14553   }
14554 
14555   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14556   if (const auto *PT = CaptureType->getAs<PointerType>()) {
14557     // This function finds out whether there is an AttributedType of kind
14558     // attr_objc_ownership in Ty. The existence of AttributedType of kind
14559     // attr_objc_ownership implies __autoreleasing was explicitly specified
14560     // rather than being added implicitly by the compiler.
14561     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14562       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14563         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
14564           return true;
14565 
14566         // Peel off AttributedTypes that are not of kind objc_ownership.
14567         Ty = AttrTy->getModifiedType();
14568       }
14569 
14570       return false;
14571     };
14572 
14573     QualType PointeeTy = PT->getPointeeType();
14574 
14575     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14576         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14577         !IsObjCOwnershipAttributedType(PointeeTy)) {
14578       if (BuildAndDiagnose) {
14579         SourceLocation VarLoc = Var->getLocation();
14580         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14581         {
14582           auto AddAutoreleaseNote =
14583               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
14584           // Provide a fix-it for the '__autoreleasing' keyword at the
14585           // appropriate location in the variable's type.
14586           if (const auto *TSI = Var->getTypeSourceInfo()) {
14587             PointerTypeLoc PTL =
14588                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
14589             if (PTL) {
14590               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
14591               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
14592                                                S.getLangOpts());
14593               if (Loc.isValid()) {
14594                 StringRef CharAtLoc = Lexer::getSourceText(
14595                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
14596                     S.getSourceManager(), S.getLangOpts());
14597                 AddAutoreleaseNote << FixItHint::CreateInsertion(
14598                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
14599                              ? " __autoreleasing "
14600                              : " __autoreleasing");
14601               }
14602             }
14603           }
14604         }
14605         S.Diag(VarLoc, diag::note_declare_parameter_strong);
14606       }
14607     }
14608   }
14609 
14610   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14611   if (HasBlocksAttr || CaptureType->isReferenceType() ||
14612       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
14613     // Block capture by reference does not change the capture or
14614     // declaration reference types.
14615     ByRef = true;
14616   } else {
14617     // Block capture by copy introduces 'const'.
14618     CaptureType = CaptureType.getNonReferenceType().withConst();
14619     DeclRefType = CaptureType;
14620 
14621     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14622       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14623         // The capture logic needs the destructor, so make sure we mark it.
14624         // Usually this is unnecessary because most local variables have
14625         // their destructors marked at declaration time, but parameters are
14626         // an exception because it's technically only the call site that
14627         // actually requires the destructor.
14628         if (isa<ParmVarDecl>(Var))
14629           S.FinalizeVarWithDestructor(Var, Record);
14630 
14631         // Enter a new evaluation context to insulate the copy
14632         // full-expression.
14633         EnterExpressionEvaluationContext scope(
14634             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14635 
14636         // According to the blocks spec, the capture of a variable from
14637         // the stack requires a const copy constructor.  This is not true
14638         // of the copy/move done to move a __block variable to the heap.
14639         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14640                                                   DeclRefType.withConst(),
14641                                                   VK_LValue, Loc);
14642 
14643         ExprResult Result
14644           = S.PerformCopyInitialization(
14645               InitializedEntity::InitializeBlock(Var->getLocation(),
14646                                                   CaptureType, false),
14647               Loc, DeclRef);
14648 
14649         // Build a full-expression copy expression if initialization
14650         // succeeded and used a non-trivial constructor.  Recover from
14651         // errors by pretending that the copy isn't necessary.
14652         if (!Result.isInvalid() &&
14653             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14654                 ->isTrivial()) {
14655           Result = S.MaybeCreateExprWithCleanups(Result);
14656           CopyExpr = Result.get();
14657         }
14658       }
14659     }
14660   }
14661 
14662   // Actually capture the variable.
14663   if (BuildAndDiagnose)
14664     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14665                     SourceLocation(), CaptureType, CopyExpr);
14666 
14667   return true;
14668 
14669 }
14670 
14671 
14672 /// Capture the given variable in the captured region.
14673 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14674                                     VarDecl *Var,
14675                                     SourceLocation Loc,
14676                                     const bool BuildAndDiagnose,
14677                                     QualType &CaptureType,
14678                                     QualType &DeclRefType,
14679                                     const bool RefersToCapturedVariable,
14680                                     Sema &S) {
14681   // By default, capture variables by reference.
14682   bool ByRef = true;
14683   // Using an LValue reference type is consistent with Lambdas (see below).
14684   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14685     if (S.isOpenMPCapturedDecl(Var)) {
14686       bool HasConst = DeclRefType.isConstQualified();
14687       DeclRefType = DeclRefType.getUnqualifiedType();
14688       // Don't lose diagnostics about assignments to const.
14689       if (HasConst)
14690         DeclRefType.addConst();
14691     }
14692     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14693   }
14694 
14695   if (ByRef)
14696     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14697   else
14698     CaptureType = DeclRefType;
14699 
14700   Expr *CopyExpr = nullptr;
14701   if (BuildAndDiagnose) {
14702     // The current implementation assumes that all variables are captured
14703     // by references. Since there is no capture by copy, no expression
14704     // evaluation will be needed.
14705     RecordDecl *RD = RSI->TheRecordDecl;
14706 
14707     FieldDecl *Field
14708       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14709                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14710                           nullptr, false, ICIS_NoInit);
14711     Field->setImplicit(true);
14712     Field->setAccess(AS_private);
14713     RD->addDecl(Field);
14714     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14715       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14716 
14717     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14718                                             DeclRefType, VK_LValue, Loc);
14719     Var->setReferenced(true);
14720     Var->markUsed(S.Context);
14721   }
14722 
14723   // Actually capture the variable.
14724   if (BuildAndDiagnose)
14725     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14726                     SourceLocation(), CaptureType, CopyExpr);
14727 
14728 
14729   return true;
14730 }
14731 
14732 /// Create a field within the lambda class for the variable
14733 /// being captured.
14734 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14735                                     QualType FieldType, QualType DeclRefType,
14736                                     SourceLocation Loc,
14737                                     bool RefersToCapturedVariable) {
14738   CXXRecordDecl *Lambda = LSI->Lambda;
14739 
14740   // Build the non-static data member.
14741   FieldDecl *Field
14742     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14743                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14744                         nullptr, false, ICIS_NoInit);
14745   Field->setImplicit(true);
14746   Field->setAccess(AS_private);
14747   Lambda->addDecl(Field);
14748 }
14749 
14750 /// Capture the given variable in the lambda.
14751 static bool captureInLambda(LambdaScopeInfo *LSI,
14752                             VarDecl *Var,
14753                             SourceLocation Loc,
14754                             const bool BuildAndDiagnose,
14755                             QualType &CaptureType,
14756                             QualType &DeclRefType,
14757                             const bool RefersToCapturedVariable,
14758                             const Sema::TryCaptureKind Kind,
14759                             SourceLocation EllipsisLoc,
14760                             const bool IsTopScope,
14761                             Sema &S) {
14762 
14763   // Determine whether we are capturing by reference or by value.
14764   bool ByRef = false;
14765   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14766     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14767   } else {
14768     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14769   }
14770 
14771   // Compute the type of the field that will capture this variable.
14772   if (ByRef) {
14773     // C++11 [expr.prim.lambda]p15:
14774     //   An entity is captured by reference if it is implicitly or
14775     //   explicitly captured but not captured by copy. It is
14776     //   unspecified whether additional unnamed non-static data
14777     //   members are declared in the closure type for entities
14778     //   captured by reference.
14779     //
14780     // FIXME: It is not clear whether we want to build an lvalue reference
14781     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14782     // to do the former, while EDG does the latter. Core issue 1249 will
14783     // clarify, but for now we follow GCC because it's a more permissive and
14784     // easily defensible position.
14785     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14786   } else {
14787     // C++11 [expr.prim.lambda]p14:
14788     //   For each entity captured by copy, an unnamed non-static
14789     //   data member is declared in the closure type. The
14790     //   declaration order of these members is unspecified. The type
14791     //   of such a data member is the type of the corresponding
14792     //   captured entity if the entity is not a reference to an
14793     //   object, or the referenced type otherwise. [Note: If the
14794     //   captured entity is a reference to a function, the
14795     //   corresponding data member is also a reference to a
14796     //   function. - end note ]
14797     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14798       if (!RefType->getPointeeType()->isFunctionType())
14799         CaptureType = RefType->getPointeeType();
14800     }
14801 
14802     // Forbid the lambda copy-capture of autoreleasing variables.
14803     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14804       if (BuildAndDiagnose) {
14805         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14806         S.Diag(Var->getLocation(), diag::note_previous_decl)
14807           << Var->getDeclName();
14808       }
14809       return false;
14810     }
14811 
14812     // Make sure that by-copy captures are of a complete and non-abstract type.
14813     if (BuildAndDiagnose) {
14814       if (!CaptureType->isDependentType() &&
14815           S.RequireCompleteType(Loc, CaptureType,
14816                                 diag::err_capture_of_incomplete_type,
14817                                 Var->getDeclName()))
14818         return false;
14819 
14820       if (S.RequireNonAbstractType(Loc, CaptureType,
14821                                    diag::err_capture_of_abstract_type))
14822         return false;
14823     }
14824   }
14825 
14826   // Capture this variable in the lambda.
14827   if (BuildAndDiagnose)
14828     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14829                             RefersToCapturedVariable);
14830 
14831   // Compute the type of a reference to this captured variable.
14832   if (ByRef)
14833     DeclRefType = CaptureType.getNonReferenceType();
14834   else {
14835     // C++ [expr.prim.lambda]p5:
14836     //   The closure type for a lambda-expression has a public inline
14837     //   function call operator [...]. This function call operator is
14838     //   declared const (9.3.1) if and only if the lambda-expression's
14839     //   parameter-declaration-clause is not followed by mutable.
14840     DeclRefType = CaptureType.getNonReferenceType();
14841     if (!LSI->Mutable && !CaptureType->isReferenceType())
14842       DeclRefType.addConst();
14843   }
14844 
14845   // Add the capture.
14846   if (BuildAndDiagnose)
14847     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14848                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14849 
14850   return true;
14851 }
14852 
14853 bool Sema::tryCaptureVariable(
14854     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14855     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14856     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14857   // An init-capture is notionally from the context surrounding its
14858   // declaration, but its parent DC is the lambda class.
14859   DeclContext *VarDC = Var->getDeclContext();
14860   if (Var->isInitCapture())
14861     VarDC = VarDC->getParent();
14862 
14863   DeclContext *DC = CurContext;
14864   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
14865       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
14866   // We need to sync up the Declaration Context with the
14867   // FunctionScopeIndexToStopAt
14868   if (FunctionScopeIndexToStopAt) {
14869     unsigned FSIndex = FunctionScopes.size() - 1;
14870     while (FSIndex != MaxFunctionScopesIndex) {
14871       DC = getLambdaAwareParentOfDeclContext(DC);
14872       --FSIndex;
14873     }
14874   }
14875 
14876 
14877   // If the variable is declared in the current context, there is no need to
14878   // capture it.
14879   if (VarDC == DC) return true;
14880 
14881   // Capture global variables if it is required to use private copy of this
14882   // variable.
14883   bool IsGlobal = !Var->hasLocalStorage();
14884   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
14885     return true;
14886   Var = Var->getCanonicalDecl();
14887 
14888   // Walk up the stack to determine whether we can capture the variable,
14889   // performing the "simple" checks that don't depend on type. We stop when
14890   // we've either hit the declared scope of the variable or find an existing
14891   // capture of that variable.  We start from the innermost capturing-entity
14892   // (the DC) and ensure that all intervening capturing-entities
14893   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14894   // declcontext can either capture the variable or have already captured
14895   // the variable.
14896   CaptureType = Var->getType();
14897   DeclRefType = CaptureType.getNonReferenceType();
14898   bool Nested = false;
14899   bool Explicit = (Kind != TryCapture_Implicit);
14900   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14901   do {
14902     // Only block literals, captured statements, and lambda expressions can
14903     // capture; other scopes don't work.
14904     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14905                                                               ExprLoc,
14906                                                               BuildAndDiagnose,
14907                                                               *this);
14908     // We need to check for the parent *first* because, if we *have*
14909     // private-captured a global variable, we need to recursively capture it in
14910     // intermediate blocks, lambdas, etc.
14911     if (!ParentDC) {
14912       if (IsGlobal) {
14913         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14914         break;
14915       }
14916       return true;
14917     }
14918 
14919     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14920     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14921 
14922 
14923     // Check whether we've already captured it.
14924     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14925                                              DeclRefType)) {
14926       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14927       break;
14928     }
14929     // If we are instantiating a generic lambda call operator body,
14930     // we do not want to capture new variables.  What was captured
14931     // during either a lambdas transformation or initial parsing
14932     // should be used.
14933     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14934       if (BuildAndDiagnose) {
14935         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14936         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14937           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14938           Diag(Var->getLocation(), diag::note_previous_decl)
14939              << Var->getDeclName();
14940           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14941         } else
14942           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14943       }
14944       return true;
14945     }
14946     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14947     // certain types of variables (unnamed, variably modified types etc.)
14948     // so check for eligibility.
14949     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14950        return true;
14951 
14952     // Try to capture variable-length arrays types.
14953     if (Var->getType()->isVariablyModifiedType()) {
14954       // We're going to walk down into the type and look for VLA
14955       // expressions.
14956       QualType QTy = Var->getType();
14957       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14958         QTy = PVD->getOriginalType();
14959       captureVariablyModifiedType(Context, QTy, CSI);
14960     }
14961 
14962     if (getLangOpts().OpenMP) {
14963       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14964         // OpenMP private variables should not be captured in outer scope, so
14965         // just break here. Similarly, global variables that are captured in a
14966         // target region should not be captured outside the scope of the region.
14967         if (RSI->CapRegionKind == CR_OpenMP) {
14968           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
14969           auto IsTargetCap = !IsOpenMPPrivateDecl &&
14970                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14971           // When we detect target captures we are looking from inside the
14972           // target region, therefore we need to propagate the capture from the
14973           // enclosing region. Therefore, the capture is not initially nested.
14974           if (IsTargetCap)
14975             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
14976 
14977           if (IsTargetCap || IsOpenMPPrivateDecl) {
14978             Nested = !IsTargetCap;
14979             DeclRefType = DeclRefType.getUnqualifiedType();
14980             CaptureType = Context.getLValueReferenceType(DeclRefType);
14981             break;
14982           }
14983         }
14984       }
14985     }
14986     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14987       // No capture-default, and this is not an explicit capture
14988       // so cannot capture this variable.
14989       if (BuildAndDiagnose) {
14990         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14991         Diag(Var->getLocation(), diag::note_previous_decl)
14992           << Var->getDeclName();
14993         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14994           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14995                diag::note_lambda_decl);
14996         // FIXME: If we error out because an outer lambda can not implicitly
14997         // capture a variable that an inner lambda explicitly captures, we
14998         // should have the inner lambda do the explicit capture - because
14999         // it makes for cleaner diagnostics later.  This would purely be done
15000         // so that the diagnostic does not misleadingly claim that a variable
15001         // can not be captured by a lambda implicitly even though it is captured
15002         // explicitly.  Suggestion:
15003         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15004         //    at the function head
15005         //  - cache the StartingDeclContext - this must be a lambda
15006         //  - captureInLambda in the innermost lambda the variable.
15007       }
15008       return true;
15009     }
15010 
15011     FunctionScopesIndex--;
15012     DC = ParentDC;
15013     Explicit = false;
15014   } while (!VarDC->Equals(DC));
15015 
15016   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15017   // computing the type of the capture at each step, checking type-specific
15018   // requirements, and adding captures if requested.
15019   // If the variable had already been captured previously, we start capturing
15020   // at the lambda nested within that one.
15021   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15022        ++I) {
15023     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15024 
15025     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15026       if (!captureInBlock(BSI, Var, ExprLoc,
15027                           BuildAndDiagnose, CaptureType,
15028                           DeclRefType, Nested, *this))
15029         return true;
15030       Nested = true;
15031     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15032       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15033                                    BuildAndDiagnose, CaptureType,
15034                                    DeclRefType, Nested, *this))
15035         return true;
15036       Nested = true;
15037     } else {
15038       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15039       if (!captureInLambda(LSI, Var, ExprLoc,
15040                            BuildAndDiagnose, CaptureType,
15041                            DeclRefType, Nested, Kind, EllipsisLoc,
15042                             /*IsTopScope*/I == N - 1, *this))
15043         return true;
15044       Nested = true;
15045     }
15046   }
15047   return false;
15048 }
15049 
15050 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15051                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15052   QualType CaptureType;
15053   QualType DeclRefType;
15054   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15055                             /*BuildAndDiagnose=*/true, CaptureType,
15056                             DeclRefType, nullptr);
15057 }
15058 
15059 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15060   QualType CaptureType;
15061   QualType DeclRefType;
15062   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15063                              /*BuildAndDiagnose=*/false, CaptureType,
15064                              DeclRefType, nullptr);
15065 }
15066 
15067 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15068   QualType CaptureType;
15069   QualType DeclRefType;
15070 
15071   // Determine whether we can capture this variable.
15072   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15073                          /*BuildAndDiagnose=*/false, CaptureType,
15074                          DeclRefType, nullptr))
15075     return QualType();
15076 
15077   return DeclRefType;
15078 }
15079 
15080 
15081 
15082 // If either the type of the variable or the initializer is dependent,
15083 // return false. Otherwise, determine whether the variable is a constant
15084 // expression. Use this if you need to know if a variable that might or
15085 // might not be dependent is truly a constant expression.
15086 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15087     ASTContext &Context) {
15088 
15089   if (Var->getType()->isDependentType())
15090     return false;
15091   const VarDecl *DefVD = nullptr;
15092   Var->getAnyInitializer(DefVD);
15093   if (!DefVD)
15094     return false;
15095   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15096   Expr *Init = cast<Expr>(Eval->Value);
15097   if (Init->isValueDependent())
15098     return false;
15099   return IsVariableAConstantExpression(Var, Context);
15100 }
15101 
15102 
15103 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15104   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15105   // an object that satisfies the requirements for appearing in a
15106   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15107   // is immediately applied."  This function handles the lvalue-to-rvalue
15108   // conversion part.
15109   MaybeODRUseExprs.erase(E->IgnoreParens());
15110 
15111   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15112   // to a variable that is a constant expression, and if so, identify it as
15113   // a reference to a variable that does not involve an odr-use of that
15114   // variable.
15115   if (LambdaScopeInfo *LSI = getCurLambda()) {
15116     Expr *SansParensExpr = E->IgnoreParens();
15117     VarDecl *Var = nullptr;
15118     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15119       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15120     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15121       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15122 
15123     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15124       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15125   }
15126 }
15127 
15128 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15129   Res = CorrectDelayedTyposInExpr(Res);
15130 
15131   if (!Res.isUsable())
15132     return Res;
15133 
15134   // If a constant-expression is a reference to a variable where we delay
15135   // deciding whether it is an odr-use, just assume we will apply the
15136   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15137   // (a non-type template argument), we have special handling anyway.
15138   UpdateMarkingForLValueToRValue(Res.get());
15139   return Res;
15140 }
15141 
15142 void Sema::CleanupVarDeclMarking() {
15143   for (Expr *E : MaybeODRUseExprs) {
15144     VarDecl *Var;
15145     SourceLocation Loc;
15146     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15147       Var = cast<VarDecl>(DRE->getDecl());
15148       Loc = DRE->getLocation();
15149     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15150       Var = cast<VarDecl>(ME->getMemberDecl());
15151       Loc = ME->getMemberLoc();
15152     } else {
15153       llvm_unreachable("Unexpected expression");
15154     }
15155 
15156     MarkVarDeclODRUsed(Var, Loc, *this,
15157                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15158   }
15159 
15160   MaybeODRUseExprs.clear();
15161 }
15162 
15163 
15164 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15165                                     VarDecl *Var, Expr *E) {
15166   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15167          "Invalid Expr argument to DoMarkVarDeclReferenced");
15168   Var->setReferenced();
15169 
15170   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15171 
15172   bool OdrUseContext = isOdrUseContext(SemaRef);
15173   bool UsableInConstantExpr =
15174       Var->isUsableInConstantExpressions(SemaRef.Context);
15175   bool NeedDefinition =
15176       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15177 
15178   VarTemplateSpecializationDecl *VarSpec =
15179       dyn_cast<VarTemplateSpecializationDecl>(Var);
15180   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15181          "Can't instantiate a partial template specialization.");
15182 
15183   // If this might be a member specialization of a static data member, check
15184   // the specialization is visible. We already did the checks for variable
15185   // template specializations when we created them.
15186   if (NeedDefinition && TSK != TSK_Undeclared &&
15187       !isa<VarTemplateSpecializationDecl>(Var))
15188     SemaRef.checkSpecializationVisibility(Loc, Var);
15189 
15190   // Perform implicit instantiation of static data members, static data member
15191   // templates of class templates, and variable template specializations. Delay
15192   // instantiations of variable templates, except for those that could be used
15193   // in a constant expression.
15194   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15195     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15196     // instantiation declaration if a variable is usable in a constant
15197     // expression (among other cases).
15198     bool TryInstantiating =
15199         TSK == TSK_ImplicitInstantiation ||
15200         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15201 
15202     if (TryInstantiating) {
15203       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15204       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15205       if (FirstInstantiation) {
15206         PointOfInstantiation = Loc;
15207         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15208       }
15209 
15210       bool InstantiationDependent = false;
15211       bool IsNonDependent =
15212           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15213                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15214                   : true;
15215 
15216       // Do not instantiate specializations that are still type-dependent.
15217       if (IsNonDependent) {
15218         if (UsableInConstantExpr) {
15219           // Do not defer instantiations of variables that could be used in a
15220           // constant expression.
15221           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15222         } else if (FirstInstantiation ||
15223                    isa<VarTemplateSpecializationDecl>(Var)) {
15224           // FIXME: For a specialization of a variable template, we don't
15225           // distinguish between "declaration and type implicitly instantiated"
15226           // and "implicit instantiation of definition requested", so we have
15227           // no direct way to avoid enqueueing the pending instantiation
15228           // multiple times.
15229           SemaRef.PendingInstantiations
15230               .push_back(std::make_pair(Var, PointOfInstantiation));
15231         }
15232       }
15233     }
15234   }
15235 
15236   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15237   // the requirements for appearing in a constant expression (5.19) and, if
15238   // it is an object, the lvalue-to-rvalue conversion (4.1)
15239   // is immediately applied."  We check the first part here, and
15240   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15241   // Note that we use the C++11 definition everywhere because nothing in
15242   // C++03 depends on whether we get the C++03 version correct. The second
15243   // part does not apply to references, since they are not objects.
15244   if (OdrUseContext && E &&
15245       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15246     // A reference initialized by a constant expression can never be
15247     // odr-used, so simply ignore it.
15248     if (!Var->getType()->isReferenceType() ||
15249         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15250       SemaRef.MaybeODRUseExprs.insert(E);
15251   } else if (OdrUseContext) {
15252     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15253                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15254   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15255     // If this is a dependent context, we don't need to mark variables as
15256     // odr-used, but we may still need to track them for lambda capture.
15257     // FIXME: Do we also need to do this inside dependent typeid expressions
15258     // (which are modeled as unevaluated at this point)?
15259     const bool RefersToEnclosingScope =
15260         (SemaRef.CurContext != Var->getDeclContext() &&
15261          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15262     if (RefersToEnclosingScope) {
15263       LambdaScopeInfo *const LSI =
15264           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15265       if (LSI && (!LSI->CallOperator ||
15266                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15267         // If a variable could potentially be odr-used, defer marking it so
15268         // until we finish analyzing the full expression for any
15269         // lvalue-to-rvalue
15270         // or discarded value conversions that would obviate odr-use.
15271         // Add it to the list of potential captures that will be analyzed
15272         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15273         // unless the variable is a reference that was initialized by a constant
15274         // expression (this will never need to be captured or odr-used).
15275         assert(E && "Capture variable should be used in an expression.");
15276         if (!Var->getType()->isReferenceType() ||
15277             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15278           LSI->addPotentialCapture(E->IgnoreParens());
15279       }
15280     }
15281   }
15282 }
15283 
15284 /// Mark a variable referenced, and check whether it is odr-used
15285 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15286 /// used directly for normal expressions referring to VarDecl.
15287 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15288   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15289 }
15290 
15291 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15292                                Decl *D, Expr *E, bool MightBeOdrUse) {
15293   if (SemaRef.isInOpenMPDeclareTargetContext())
15294     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15295 
15296   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15297     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15298     return;
15299   }
15300 
15301   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15302 
15303   // If this is a call to a method via a cast, also mark the method in the
15304   // derived class used in case codegen can devirtualize the call.
15305   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15306   if (!ME)
15307     return;
15308   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15309   if (!MD)
15310     return;
15311   // Only attempt to devirtualize if this is truly a virtual call.
15312   bool IsVirtualCall = MD->isVirtual() &&
15313                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15314   if (!IsVirtualCall)
15315     return;
15316 
15317   // If it's possible to devirtualize the call, mark the called function
15318   // referenced.
15319   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15320       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15321   if (DM)
15322     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15323 }
15324 
15325 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15326 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15327   // TODO: update this with DR# once a defect report is filed.
15328   // C++11 defect. The address of a pure member should not be an ODR use, even
15329   // if it's a qualified reference.
15330   bool OdrUse = true;
15331   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15332     if (Method->isVirtual() &&
15333         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15334       OdrUse = false;
15335   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15336 }
15337 
15338 /// Perform reference-marking and odr-use handling for a MemberExpr.
15339 void Sema::MarkMemberReferenced(MemberExpr *E) {
15340   // C++11 [basic.def.odr]p2:
15341   //   A non-overloaded function whose name appears as a potentially-evaluated
15342   //   expression or a member of a set of candidate functions, if selected by
15343   //   overload resolution when referred to from a potentially-evaluated
15344   //   expression, is odr-used, unless it is a pure virtual function and its
15345   //   name is not explicitly qualified.
15346   bool MightBeOdrUse = true;
15347   if (E->performsVirtualDispatch(getLangOpts())) {
15348     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15349       if (Method->isPure())
15350         MightBeOdrUse = false;
15351   }
15352   SourceLocation Loc = E->getMemberLoc().isValid() ?
15353                             E->getMemberLoc() : E->getLocStart();
15354   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15355 }
15356 
15357 /// Perform marking for a reference to an arbitrary declaration.  It
15358 /// marks the declaration referenced, and performs odr-use checking for
15359 /// functions and variables. This method should not be used when building a
15360 /// normal expression which refers to a variable.
15361 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15362                                  bool MightBeOdrUse) {
15363   if (MightBeOdrUse) {
15364     if (auto *VD = dyn_cast<VarDecl>(D)) {
15365       MarkVariableReferenced(Loc, VD);
15366       return;
15367     }
15368   }
15369   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15370     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15371     return;
15372   }
15373   D->setReferenced();
15374 }
15375 
15376 namespace {
15377   // Mark all of the declarations used by a type as referenced.
15378   // FIXME: Not fully implemented yet! We need to have a better understanding
15379   // of when we're entering a context we should not recurse into.
15380   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15381   // TreeTransforms rebuilding the type in a new context. Rather than
15382   // duplicating the TreeTransform logic, we should consider reusing it here.
15383   // Currently that causes problems when rebuilding LambdaExprs.
15384   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15385     Sema &S;
15386     SourceLocation Loc;
15387 
15388   public:
15389     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15390 
15391     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15392 
15393     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15394   };
15395 }
15396 
15397 bool MarkReferencedDecls::TraverseTemplateArgument(
15398     const TemplateArgument &Arg) {
15399   {
15400     // A non-type template argument is a constant-evaluated context.
15401     EnterExpressionEvaluationContext Evaluated(
15402         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15403     if (Arg.getKind() == TemplateArgument::Declaration) {
15404       if (Decl *D = Arg.getAsDecl())
15405         S.MarkAnyDeclReferenced(Loc, D, true);
15406     } else if (Arg.getKind() == TemplateArgument::Expression) {
15407       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15408     }
15409   }
15410 
15411   return Inherited::TraverseTemplateArgument(Arg);
15412 }
15413 
15414 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15415   MarkReferencedDecls Marker(*this, Loc);
15416   Marker.TraverseType(T);
15417 }
15418 
15419 namespace {
15420   /// Helper class that marks all of the declarations referenced by
15421   /// potentially-evaluated subexpressions as "referenced".
15422   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15423     Sema &S;
15424     bool SkipLocalVariables;
15425 
15426   public:
15427     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15428 
15429     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15430       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15431 
15432     void VisitDeclRefExpr(DeclRefExpr *E) {
15433       // If we were asked not to visit local variables, don't.
15434       if (SkipLocalVariables) {
15435         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15436           if (VD->hasLocalStorage())
15437             return;
15438       }
15439 
15440       S.MarkDeclRefReferenced(E);
15441     }
15442 
15443     void VisitMemberExpr(MemberExpr *E) {
15444       S.MarkMemberReferenced(E);
15445       Inherited::VisitMemberExpr(E);
15446     }
15447 
15448     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15449       S.MarkFunctionReferenced(E->getLocStart(),
15450             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
15451       Visit(E->getSubExpr());
15452     }
15453 
15454     void VisitCXXNewExpr(CXXNewExpr *E) {
15455       if (E->getOperatorNew())
15456         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
15457       if (E->getOperatorDelete())
15458         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15459       Inherited::VisitCXXNewExpr(E);
15460     }
15461 
15462     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15463       if (E->getOperatorDelete())
15464         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15465       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15466       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15467         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15468         S.MarkFunctionReferenced(E->getLocStart(),
15469                                     S.LookupDestructor(Record));
15470       }
15471 
15472       Inherited::VisitCXXDeleteExpr(E);
15473     }
15474 
15475     void VisitCXXConstructExpr(CXXConstructExpr *E) {
15476       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
15477       Inherited::VisitCXXConstructExpr(E);
15478     }
15479 
15480     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15481       Visit(E->getExpr());
15482     }
15483 
15484     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15485       Inherited::VisitImplicitCastExpr(E);
15486 
15487       if (E->getCastKind() == CK_LValueToRValue)
15488         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15489     }
15490   };
15491 }
15492 
15493 /// Mark any declarations that appear within this expression or any
15494 /// potentially-evaluated subexpressions as "referenced".
15495 ///
15496 /// \param SkipLocalVariables If true, don't mark local variables as
15497 /// 'referenced'.
15498 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15499                                             bool SkipLocalVariables) {
15500   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15501 }
15502 
15503 /// Emit a diagnostic that describes an effect on the run-time behavior
15504 /// of the program being compiled.
15505 ///
15506 /// This routine emits the given diagnostic when the code currently being
15507 /// type-checked is "potentially evaluated", meaning that there is a
15508 /// possibility that the code will actually be executable. Code in sizeof()
15509 /// expressions, code used only during overload resolution, etc., are not
15510 /// potentially evaluated. This routine will suppress such diagnostics or,
15511 /// in the absolutely nutty case of potentially potentially evaluated
15512 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15513 /// later.
15514 ///
15515 /// This routine should be used for all diagnostics that describe the run-time
15516 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15517 /// Failure to do so will likely result in spurious diagnostics or failures
15518 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15519 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15520                                const PartialDiagnostic &PD) {
15521   switch (ExprEvalContexts.back().Context) {
15522   case ExpressionEvaluationContext::Unevaluated:
15523   case ExpressionEvaluationContext::UnevaluatedList:
15524   case ExpressionEvaluationContext::UnevaluatedAbstract:
15525   case ExpressionEvaluationContext::DiscardedStatement:
15526     // The argument will never be evaluated, so don't complain.
15527     break;
15528 
15529   case ExpressionEvaluationContext::ConstantEvaluated:
15530     // Relevant diagnostics should be produced by constant evaluation.
15531     break;
15532 
15533   case ExpressionEvaluationContext::PotentiallyEvaluated:
15534   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15535     if (Statement && getCurFunctionOrMethodDecl()) {
15536       FunctionScopes.back()->PossiblyUnreachableDiags.
15537         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15538       return true;
15539     }
15540 
15541     // The initializer of a constexpr variable or of the first declaration of a
15542     // static data member is not syntactically a constant evaluated constant,
15543     // but nonetheless is always required to be a constant expression, so we
15544     // can skip diagnosing.
15545     // FIXME: Using the mangling context here is a hack.
15546     if (auto *VD = dyn_cast_or_null<VarDecl>(
15547             ExprEvalContexts.back().ManglingContextDecl)) {
15548       if (VD->isConstexpr() ||
15549           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15550         break;
15551       // FIXME: For any other kind of variable, we should build a CFG for its
15552       // initializer and check whether the context in question is reachable.
15553     }
15554 
15555     Diag(Loc, PD);
15556     return true;
15557   }
15558 
15559   return false;
15560 }
15561 
15562 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15563                                CallExpr *CE, FunctionDecl *FD) {
15564   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15565     return false;
15566 
15567   // If we're inside a decltype's expression, don't check for a valid return
15568   // type or construct temporaries until we know whether this is the last call.
15569   if (ExprEvalContexts.back().IsDecltype) {
15570     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15571     return false;
15572   }
15573 
15574   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15575     FunctionDecl *FD;
15576     CallExpr *CE;
15577 
15578   public:
15579     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15580       : FD(FD), CE(CE) { }
15581 
15582     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15583       if (!FD) {
15584         S.Diag(Loc, diag::err_call_incomplete_return)
15585           << T << CE->getSourceRange();
15586         return;
15587       }
15588 
15589       S.Diag(Loc, diag::err_call_function_incomplete_return)
15590         << CE->getSourceRange() << FD->getDeclName() << T;
15591       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15592           << FD->getDeclName();
15593     }
15594   } Diagnoser(FD, CE);
15595 
15596   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15597     return true;
15598 
15599   return false;
15600 }
15601 
15602 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15603 // will prevent this condition from triggering, which is what we want.
15604 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
15605   SourceLocation Loc;
15606 
15607   unsigned diagnostic = diag::warn_condition_is_assignment;
15608   bool IsOrAssign = false;
15609 
15610   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15611     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15612       return;
15613 
15614     IsOrAssign = Op->getOpcode() == BO_OrAssign;
15615 
15616     // Greylist some idioms by putting them into a warning subcategory.
15617     if (ObjCMessageExpr *ME
15618           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15619       Selector Sel = ME->getSelector();
15620 
15621       // self = [<foo> init...]
15622       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15623         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15624 
15625       // <foo> = [<bar> nextObject]
15626       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15627         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15628     }
15629 
15630     Loc = Op->getOperatorLoc();
15631   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15632     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15633       return;
15634 
15635     IsOrAssign = Op->getOperator() == OO_PipeEqual;
15636     Loc = Op->getOperatorLoc();
15637   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15638     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15639   else {
15640     // Not an assignment.
15641     return;
15642   }
15643 
15644   Diag(Loc, diagnostic) << E->getSourceRange();
15645 
15646   SourceLocation Open = E->getLocStart();
15647   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15648   Diag(Loc, diag::note_condition_assign_silence)
15649         << FixItHint::CreateInsertion(Open, "(")
15650         << FixItHint::CreateInsertion(Close, ")");
15651 
15652   if (IsOrAssign)
15653     Diag(Loc, diag::note_condition_or_assign_to_comparison)
15654       << FixItHint::CreateReplacement(Loc, "!=");
15655   else
15656     Diag(Loc, diag::note_condition_assign_to_comparison)
15657       << FixItHint::CreateReplacement(Loc, "==");
15658 }
15659 
15660 /// Redundant parentheses over an equality comparison can indicate
15661 /// that the user intended an assignment used as condition.
15662 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15663   // Don't warn if the parens came from a macro.
15664   SourceLocation parenLoc = ParenE->getLocStart();
15665   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15666     return;
15667   // Don't warn for dependent expressions.
15668   if (ParenE->isTypeDependent())
15669     return;
15670 
15671   Expr *E = ParenE->IgnoreParens();
15672 
15673   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15674     if (opE->getOpcode() == BO_EQ &&
15675         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15676                                                            == Expr::MLV_Valid) {
15677       SourceLocation Loc = opE->getOperatorLoc();
15678 
15679       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15680       SourceRange ParenERange = ParenE->getSourceRange();
15681       Diag(Loc, diag::note_equality_comparison_silence)
15682         << FixItHint::CreateRemoval(ParenERange.getBegin())
15683         << FixItHint::CreateRemoval(ParenERange.getEnd());
15684       Diag(Loc, diag::note_equality_comparison_to_assign)
15685         << FixItHint::CreateReplacement(Loc, "=");
15686     }
15687 }
15688 
15689 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15690                                        bool IsConstexpr) {
15691   DiagnoseAssignmentAsCondition(E);
15692   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15693     DiagnoseEqualityWithExtraParens(parenE);
15694 
15695   ExprResult result = CheckPlaceholderExpr(E);
15696   if (result.isInvalid()) return ExprError();
15697   E = result.get();
15698 
15699   if (!E->isTypeDependent()) {
15700     if (getLangOpts().CPlusPlus)
15701       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15702 
15703     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15704     if (ERes.isInvalid())
15705       return ExprError();
15706     E = ERes.get();
15707 
15708     QualType T = E->getType();
15709     if (!T->isScalarType()) { // C99 6.8.4.1p1
15710       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15711         << T << E->getSourceRange();
15712       return ExprError();
15713     }
15714     CheckBoolLikeConversion(E, Loc);
15715   }
15716 
15717   return E;
15718 }
15719 
15720 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15721                                            Expr *SubExpr, ConditionKind CK) {
15722   // Empty conditions are valid in for-statements.
15723   if (!SubExpr)
15724     return ConditionResult();
15725 
15726   ExprResult Cond;
15727   switch (CK) {
15728   case ConditionKind::Boolean:
15729     Cond = CheckBooleanCondition(Loc, SubExpr);
15730     break;
15731 
15732   case ConditionKind::ConstexprIf:
15733     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15734     break;
15735 
15736   case ConditionKind::Switch:
15737     Cond = CheckSwitchCondition(Loc, SubExpr);
15738     break;
15739   }
15740   if (Cond.isInvalid())
15741     return ConditionError();
15742 
15743   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15744   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15745   if (!FullExpr.get())
15746     return ConditionError();
15747 
15748   return ConditionResult(*this, nullptr, FullExpr,
15749                          CK == ConditionKind::ConstexprIf);
15750 }
15751 
15752 namespace {
15753   /// A visitor for rebuilding a call to an __unknown_any expression
15754   /// to have an appropriate type.
15755   struct RebuildUnknownAnyFunction
15756     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15757 
15758     Sema &S;
15759 
15760     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15761 
15762     ExprResult VisitStmt(Stmt *S) {
15763       llvm_unreachable("unexpected statement!");
15764     }
15765 
15766     ExprResult VisitExpr(Expr *E) {
15767       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15768         << E->getSourceRange();
15769       return ExprError();
15770     }
15771 
15772     /// Rebuild an expression which simply semantically wraps another
15773     /// expression which it shares the type and value kind of.
15774     template <class T> ExprResult rebuildSugarExpr(T *E) {
15775       ExprResult SubResult = Visit(E->getSubExpr());
15776       if (SubResult.isInvalid()) return ExprError();
15777 
15778       Expr *SubExpr = SubResult.get();
15779       E->setSubExpr(SubExpr);
15780       E->setType(SubExpr->getType());
15781       E->setValueKind(SubExpr->getValueKind());
15782       assert(E->getObjectKind() == OK_Ordinary);
15783       return E;
15784     }
15785 
15786     ExprResult VisitParenExpr(ParenExpr *E) {
15787       return rebuildSugarExpr(E);
15788     }
15789 
15790     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15791       return rebuildSugarExpr(E);
15792     }
15793 
15794     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15795       ExprResult SubResult = Visit(E->getSubExpr());
15796       if (SubResult.isInvalid()) return ExprError();
15797 
15798       Expr *SubExpr = SubResult.get();
15799       E->setSubExpr(SubExpr);
15800       E->setType(S.Context.getPointerType(SubExpr->getType()));
15801       assert(E->getValueKind() == VK_RValue);
15802       assert(E->getObjectKind() == OK_Ordinary);
15803       return E;
15804     }
15805 
15806     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15807       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15808 
15809       E->setType(VD->getType());
15810 
15811       assert(E->getValueKind() == VK_RValue);
15812       if (S.getLangOpts().CPlusPlus &&
15813           !(isa<CXXMethodDecl>(VD) &&
15814             cast<CXXMethodDecl>(VD)->isInstance()))
15815         E->setValueKind(VK_LValue);
15816 
15817       return E;
15818     }
15819 
15820     ExprResult VisitMemberExpr(MemberExpr *E) {
15821       return resolveDecl(E, E->getMemberDecl());
15822     }
15823 
15824     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15825       return resolveDecl(E, E->getDecl());
15826     }
15827   };
15828 }
15829 
15830 /// Given a function expression of unknown-any type, try to rebuild it
15831 /// to have a function type.
15832 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15833   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15834   if (Result.isInvalid()) return ExprError();
15835   return S.DefaultFunctionArrayConversion(Result.get());
15836 }
15837 
15838 namespace {
15839   /// A visitor for rebuilding an expression of type __unknown_anytype
15840   /// into one which resolves the type directly on the referring
15841   /// expression.  Strict preservation of the original source
15842   /// structure is not a goal.
15843   struct RebuildUnknownAnyExpr
15844     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15845 
15846     Sema &S;
15847 
15848     /// The current destination type.
15849     QualType DestType;
15850 
15851     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15852       : S(S), DestType(CastType) {}
15853 
15854     ExprResult VisitStmt(Stmt *S) {
15855       llvm_unreachable("unexpected statement!");
15856     }
15857 
15858     ExprResult VisitExpr(Expr *E) {
15859       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15860         << E->getSourceRange();
15861       return ExprError();
15862     }
15863 
15864     ExprResult VisitCallExpr(CallExpr *E);
15865     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15866 
15867     /// Rebuild an expression which simply semantically wraps another
15868     /// expression which it shares the type and value kind of.
15869     template <class T> ExprResult rebuildSugarExpr(T *E) {
15870       ExprResult SubResult = Visit(E->getSubExpr());
15871       if (SubResult.isInvalid()) return ExprError();
15872       Expr *SubExpr = SubResult.get();
15873       E->setSubExpr(SubExpr);
15874       E->setType(SubExpr->getType());
15875       E->setValueKind(SubExpr->getValueKind());
15876       assert(E->getObjectKind() == OK_Ordinary);
15877       return E;
15878     }
15879 
15880     ExprResult VisitParenExpr(ParenExpr *E) {
15881       return rebuildSugarExpr(E);
15882     }
15883 
15884     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15885       return rebuildSugarExpr(E);
15886     }
15887 
15888     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15889       const PointerType *Ptr = DestType->getAs<PointerType>();
15890       if (!Ptr) {
15891         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15892           << E->getSourceRange();
15893         return ExprError();
15894       }
15895 
15896       if (isa<CallExpr>(E->getSubExpr())) {
15897         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15898           << E->getSourceRange();
15899         return ExprError();
15900       }
15901 
15902       assert(E->getValueKind() == VK_RValue);
15903       assert(E->getObjectKind() == OK_Ordinary);
15904       E->setType(DestType);
15905 
15906       // Build the sub-expression as if it were an object of the pointee type.
15907       DestType = Ptr->getPointeeType();
15908       ExprResult SubResult = Visit(E->getSubExpr());
15909       if (SubResult.isInvalid()) return ExprError();
15910       E->setSubExpr(SubResult.get());
15911       return E;
15912     }
15913 
15914     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15915 
15916     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15917 
15918     ExprResult VisitMemberExpr(MemberExpr *E) {
15919       return resolveDecl(E, E->getMemberDecl());
15920     }
15921 
15922     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15923       return resolveDecl(E, E->getDecl());
15924     }
15925   };
15926 }
15927 
15928 /// Rebuilds a call expression which yielded __unknown_anytype.
15929 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15930   Expr *CalleeExpr = E->getCallee();
15931 
15932   enum FnKind {
15933     FK_MemberFunction,
15934     FK_FunctionPointer,
15935     FK_BlockPointer
15936   };
15937 
15938   FnKind Kind;
15939   QualType CalleeType = CalleeExpr->getType();
15940   if (CalleeType == S.Context.BoundMemberTy) {
15941     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15942     Kind = FK_MemberFunction;
15943     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15944   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15945     CalleeType = Ptr->getPointeeType();
15946     Kind = FK_FunctionPointer;
15947   } else {
15948     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15949     Kind = FK_BlockPointer;
15950   }
15951   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15952 
15953   // Verify that this is a legal result type of a function.
15954   if (DestType->isArrayType() || DestType->isFunctionType()) {
15955     unsigned diagID = diag::err_func_returning_array_function;
15956     if (Kind == FK_BlockPointer)
15957       diagID = diag::err_block_returning_array_function;
15958 
15959     S.Diag(E->getExprLoc(), diagID)
15960       << DestType->isFunctionType() << DestType;
15961     return ExprError();
15962   }
15963 
15964   // Otherwise, go ahead and set DestType as the call's result.
15965   E->setType(DestType.getNonLValueExprType(S.Context));
15966   E->setValueKind(Expr::getValueKindForType(DestType));
15967   assert(E->getObjectKind() == OK_Ordinary);
15968 
15969   // Rebuild the function type, replacing the result type with DestType.
15970   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15971   if (Proto) {
15972     // __unknown_anytype(...) is a special case used by the debugger when
15973     // it has no idea what a function's signature is.
15974     //
15975     // We want to build this call essentially under the K&R
15976     // unprototyped rules, but making a FunctionNoProtoType in C++
15977     // would foul up all sorts of assumptions.  However, we cannot
15978     // simply pass all arguments as variadic arguments, nor can we
15979     // portably just call the function under a non-variadic type; see
15980     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15981     // However, it turns out that in practice it is generally safe to
15982     // call a function declared as "A foo(B,C,D);" under the prototype
15983     // "A foo(B,C,D,...);".  The only known exception is with the
15984     // Windows ABI, where any variadic function is implicitly cdecl
15985     // regardless of its normal CC.  Therefore we change the parameter
15986     // types to match the types of the arguments.
15987     //
15988     // This is a hack, but it is far superior to moving the
15989     // corresponding target-specific code from IR-gen to Sema/AST.
15990 
15991     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15992     SmallVector<QualType, 8> ArgTypes;
15993     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15994       ArgTypes.reserve(E->getNumArgs());
15995       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15996         Expr *Arg = E->getArg(i);
15997         QualType ArgType = Arg->getType();
15998         if (E->isLValue()) {
15999           ArgType = S.Context.getLValueReferenceType(ArgType);
16000         } else if (E->isXValue()) {
16001           ArgType = S.Context.getRValueReferenceType(ArgType);
16002         }
16003         ArgTypes.push_back(ArgType);
16004       }
16005       ParamTypes = ArgTypes;
16006     }
16007     DestType = S.Context.getFunctionType(DestType, ParamTypes,
16008                                          Proto->getExtProtoInfo());
16009   } else {
16010     DestType = S.Context.getFunctionNoProtoType(DestType,
16011                                                 FnType->getExtInfo());
16012   }
16013 
16014   // Rebuild the appropriate pointer-to-function type.
16015   switch (Kind) {
16016   case FK_MemberFunction:
16017     // Nothing to do.
16018     break;
16019 
16020   case FK_FunctionPointer:
16021     DestType = S.Context.getPointerType(DestType);
16022     break;
16023 
16024   case FK_BlockPointer:
16025     DestType = S.Context.getBlockPointerType(DestType);
16026     break;
16027   }
16028 
16029   // Finally, we can recurse.
16030   ExprResult CalleeResult = Visit(CalleeExpr);
16031   if (!CalleeResult.isUsable()) return ExprError();
16032   E->setCallee(CalleeResult.get());
16033 
16034   // Bind a temporary if necessary.
16035   return S.MaybeBindToTemporary(E);
16036 }
16037 
16038 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16039   // Verify that this is a legal result type of a call.
16040   if (DestType->isArrayType() || DestType->isFunctionType()) {
16041     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16042       << DestType->isFunctionType() << DestType;
16043     return ExprError();
16044   }
16045 
16046   // Rewrite the method result type if available.
16047   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16048     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16049     Method->setReturnType(DestType);
16050   }
16051 
16052   // Change the type of the message.
16053   E->setType(DestType.getNonReferenceType());
16054   E->setValueKind(Expr::getValueKindForType(DestType));
16055 
16056   return S.MaybeBindToTemporary(E);
16057 }
16058 
16059 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16060   // The only case we should ever see here is a function-to-pointer decay.
16061   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16062     assert(E->getValueKind() == VK_RValue);
16063     assert(E->getObjectKind() == OK_Ordinary);
16064 
16065     E->setType(DestType);
16066 
16067     // Rebuild the sub-expression as the pointee (function) type.
16068     DestType = DestType->castAs<PointerType>()->getPointeeType();
16069 
16070     ExprResult Result = Visit(E->getSubExpr());
16071     if (!Result.isUsable()) return ExprError();
16072 
16073     E->setSubExpr(Result.get());
16074     return E;
16075   } else if (E->getCastKind() == CK_LValueToRValue) {
16076     assert(E->getValueKind() == VK_RValue);
16077     assert(E->getObjectKind() == OK_Ordinary);
16078 
16079     assert(isa<BlockPointerType>(E->getType()));
16080 
16081     E->setType(DestType);
16082 
16083     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16084     DestType = S.Context.getLValueReferenceType(DestType);
16085 
16086     ExprResult Result = Visit(E->getSubExpr());
16087     if (!Result.isUsable()) return ExprError();
16088 
16089     E->setSubExpr(Result.get());
16090     return E;
16091   } else {
16092     llvm_unreachable("Unhandled cast type!");
16093   }
16094 }
16095 
16096 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16097   ExprValueKind ValueKind = VK_LValue;
16098   QualType Type = DestType;
16099 
16100   // We know how to make this work for certain kinds of decls:
16101 
16102   //  - functions
16103   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16104     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16105       DestType = Ptr->getPointeeType();
16106       ExprResult Result = resolveDecl(E, VD);
16107       if (Result.isInvalid()) return ExprError();
16108       return S.ImpCastExprToType(Result.get(), Type,
16109                                  CK_FunctionToPointerDecay, VK_RValue);
16110     }
16111 
16112     if (!Type->isFunctionType()) {
16113       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16114         << VD << E->getSourceRange();
16115       return ExprError();
16116     }
16117     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16118       // We must match the FunctionDecl's type to the hack introduced in
16119       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16120       // type. See the lengthy commentary in that routine.
16121       QualType FDT = FD->getType();
16122       const FunctionType *FnType = FDT->castAs<FunctionType>();
16123       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16124       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16125       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16126         SourceLocation Loc = FD->getLocation();
16127         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
16128                                       FD->getDeclContext(),
16129                                       Loc, Loc, FD->getNameInfo().getName(),
16130                                       DestType, FD->getTypeSourceInfo(),
16131                                       SC_None, false/*isInlineSpecified*/,
16132                                       FD->hasPrototype(),
16133                                       false/*isConstexprSpecified*/);
16134 
16135         if (FD->getQualifier())
16136           NewFD->setQualifierInfo(FD->getQualifierLoc());
16137 
16138         SmallVector<ParmVarDecl*, 16> Params;
16139         for (const auto &AI : FT->param_types()) {
16140           ParmVarDecl *Param =
16141             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16142           Param->setScopeInfo(0, Params.size());
16143           Params.push_back(Param);
16144         }
16145         NewFD->setParams(Params);
16146         DRE->setDecl(NewFD);
16147         VD = DRE->getDecl();
16148       }
16149     }
16150 
16151     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16152       if (MD->isInstance()) {
16153         ValueKind = VK_RValue;
16154         Type = S.Context.BoundMemberTy;
16155       }
16156 
16157     // Function references aren't l-values in C.
16158     if (!S.getLangOpts().CPlusPlus)
16159       ValueKind = VK_RValue;
16160 
16161   //  - variables
16162   } else if (isa<VarDecl>(VD)) {
16163     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16164       Type = RefTy->getPointeeType();
16165     } else if (Type->isFunctionType()) {
16166       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16167         << VD << E->getSourceRange();
16168       return ExprError();
16169     }
16170 
16171   //  - nothing else
16172   } else {
16173     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16174       << VD << E->getSourceRange();
16175     return ExprError();
16176   }
16177 
16178   // Modifying the declaration like this is friendly to IR-gen but
16179   // also really dangerous.
16180   VD->setType(DestType);
16181   E->setType(Type);
16182   E->setValueKind(ValueKind);
16183   return E;
16184 }
16185 
16186 /// Check a cast of an unknown-any type.  We intentionally only
16187 /// trigger this for C-style casts.
16188 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16189                                      Expr *CastExpr, CastKind &CastKind,
16190                                      ExprValueKind &VK, CXXCastPath &Path) {
16191   // The type we're casting to must be either void or complete.
16192   if (!CastType->isVoidType() &&
16193       RequireCompleteType(TypeRange.getBegin(), CastType,
16194                           diag::err_typecheck_cast_to_incomplete))
16195     return ExprError();
16196 
16197   // Rewrite the casted expression from scratch.
16198   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16199   if (!result.isUsable()) return ExprError();
16200 
16201   CastExpr = result.get();
16202   VK = CastExpr->getValueKind();
16203   CastKind = CK_NoOp;
16204 
16205   return CastExpr;
16206 }
16207 
16208 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16209   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16210 }
16211 
16212 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16213                                     Expr *arg, QualType &paramType) {
16214   // If the syntactic form of the argument is not an explicit cast of
16215   // any sort, just do default argument promotion.
16216   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16217   if (!castArg) {
16218     ExprResult result = DefaultArgumentPromotion(arg);
16219     if (result.isInvalid()) return ExprError();
16220     paramType = result.get()->getType();
16221     return result;
16222   }
16223 
16224   // Otherwise, use the type that was written in the explicit cast.
16225   assert(!arg->hasPlaceholderType());
16226   paramType = castArg->getTypeAsWritten();
16227 
16228   // Copy-initialize a parameter of that type.
16229   InitializedEntity entity =
16230     InitializedEntity::InitializeParameter(Context, paramType,
16231                                            /*consumed*/ false);
16232   return PerformCopyInitialization(entity, callLoc, arg);
16233 }
16234 
16235 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16236   Expr *orig = E;
16237   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16238   while (true) {
16239     E = E->IgnoreParenImpCasts();
16240     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16241       E = call->getCallee();
16242       diagID = diag::err_uncasted_call_of_unknown_any;
16243     } else {
16244       break;
16245     }
16246   }
16247 
16248   SourceLocation loc;
16249   NamedDecl *d;
16250   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16251     loc = ref->getLocation();
16252     d = ref->getDecl();
16253   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16254     loc = mem->getMemberLoc();
16255     d = mem->getMemberDecl();
16256   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16257     diagID = diag::err_uncasted_call_of_unknown_any;
16258     loc = msg->getSelectorStartLoc();
16259     d = msg->getMethodDecl();
16260     if (!d) {
16261       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16262         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16263         << orig->getSourceRange();
16264       return ExprError();
16265     }
16266   } else {
16267     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16268       << E->getSourceRange();
16269     return ExprError();
16270   }
16271 
16272   S.Diag(loc, diagID) << d << orig->getSourceRange();
16273 
16274   // Never recoverable.
16275   return ExprError();
16276 }
16277 
16278 /// Check for operands with placeholder types and complain if found.
16279 /// Returns ExprError() if there was an error and no recovery was possible.
16280 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16281   if (!getLangOpts().CPlusPlus) {
16282     // C cannot handle TypoExpr nodes on either side of a binop because it
16283     // doesn't handle dependent types properly, so make sure any TypoExprs have
16284     // been dealt with before checking the operands.
16285     ExprResult Result = CorrectDelayedTyposInExpr(E);
16286     if (!Result.isUsable()) return ExprError();
16287     E = Result.get();
16288   }
16289 
16290   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16291   if (!placeholderType) return E;
16292 
16293   switch (placeholderType->getKind()) {
16294 
16295   // Overloaded expressions.
16296   case BuiltinType::Overload: {
16297     // Try to resolve a single function template specialization.
16298     // This is obligatory.
16299     ExprResult Result = E;
16300     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16301       return Result;
16302 
16303     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16304     // leaves Result unchanged on failure.
16305     Result = E;
16306     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16307       return Result;
16308 
16309     // If that failed, try to recover with a call.
16310     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16311                          /*complain*/ true);
16312     return Result;
16313   }
16314 
16315   // Bound member functions.
16316   case BuiltinType::BoundMember: {
16317     ExprResult result = E;
16318     const Expr *BME = E->IgnoreParens();
16319     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16320     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16321     if (isa<CXXPseudoDestructorExpr>(BME)) {
16322       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16323     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16324       if (ME->getMemberNameInfo().getName().getNameKind() ==
16325           DeclarationName::CXXDestructorName)
16326         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16327     }
16328     tryToRecoverWithCall(result, PD,
16329                          /*complain*/ true);
16330     return result;
16331   }
16332 
16333   // ARC unbridged casts.
16334   case BuiltinType::ARCUnbridgedCast: {
16335     Expr *realCast = stripARCUnbridgedCast(E);
16336     diagnoseARCUnbridgedCast(realCast);
16337     return realCast;
16338   }
16339 
16340   // Expressions of unknown type.
16341   case BuiltinType::UnknownAny:
16342     return diagnoseUnknownAnyExpr(*this, E);
16343 
16344   // Pseudo-objects.
16345   case BuiltinType::PseudoObject:
16346     return checkPseudoObjectRValue(E);
16347 
16348   case BuiltinType::BuiltinFn: {
16349     // Accept __noop without parens by implicitly converting it to a call expr.
16350     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16351     if (DRE) {
16352       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16353       if (FD->getBuiltinID() == Builtin::BI__noop) {
16354         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16355                               CK_BuiltinFnToFnPtr).get();
16356         return new (Context) CallExpr(Context, E, None, Context.IntTy,
16357                                       VK_RValue, SourceLocation());
16358       }
16359     }
16360 
16361     Diag(E->getLocStart(), diag::err_builtin_fn_use);
16362     return ExprError();
16363   }
16364 
16365   // Expressions of unknown type.
16366   case BuiltinType::OMPArraySection:
16367     Diag(E->getLocStart(), diag::err_omp_array_section_use);
16368     return ExprError();
16369 
16370   // Everything else should be impossible.
16371 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16372   case BuiltinType::Id:
16373 #include "clang/Basic/OpenCLImageTypes.def"
16374 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16375 #define PLACEHOLDER_TYPE(Id, SingletonId)
16376 #include "clang/AST/BuiltinTypes.def"
16377     break;
16378   }
16379 
16380   llvm_unreachable("invalid placeholder type!");
16381 }
16382 
16383 bool Sema::CheckCaseExpression(Expr *E) {
16384   if (E->isTypeDependent())
16385     return true;
16386   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16387     return E->getType()->isIntegralOrEnumerationType();
16388   return false;
16389 }
16390 
16391 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16392 ExprResult
16393 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16394   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16395          "Unknown Objective-C Boolean value!");
16396   QualType BoolT = Context.ObjCBuiltinBoolTy;
16397   if (!Context.getBOOLDecl()) {
16398     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16399                         Sema::LookupOrdinaryName);
16400     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16401       NamedDecl *ND = Result.getFoundDecl();
16402       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16403         Context.setBOOLDecl(TD);
16404     }
16405   }
16406   if (Context.getBOOLDecl())
16407     BoolT = Context.getBOOLType();
16408   return new (Context)
16409       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16410 }
16411 
16412 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16413     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16414     SourceLocation RParen) {
16415 
16416   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16417 
16418   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16419                            [&](const AvailabilitySpec &Spec) {
16420                              return Spec.getPlatform() == Platform;
16421                            });
16422 
16423   VersionTuple Version;
16424   if (Spec != AvailSpecs.end())
16425     Version = Spec->getVersion();
16426 
16427   // The use of `@available` in the enclosing function should be analyzed to
16428   // warn when it's used inappropriately (i.e. not if(@available)).
16429   if (getCurFunctionOrMethodDecl())
16430     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16431   else if (getCurBlock() || getCurLambda())
16432     getCurFunction()->HasPotentialAvailabilityViolations = true;
16433 
16434   return new (Context)
16435       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16436 }
16437