1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49 
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53   // See if this is an auto-typed variable whose initializer we are parsing.
54   if (ParsingInitForAutoVars.count(D))
55     return false;
56 
57   // See if this is a deleted function.
58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59     if (FD->isDeleted())
60       return false;
61 
62     // If the function has a deduced return type, and we can't deduce it,
63     // then we can't use it either.
64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66       return false;
67   }
68 
69   // See if this function is unavailable.
70   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72     return false;
73 
74   return true;
75 }
76 
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78   // Warn if this is used but marked unused.
79   if (const auto *A = D->getAttr<UnusedAttr>()) {
80     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81     // should diagnose them.
82     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84       if (DC && !DC->hasAttr<UnusedAttr>())
85         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86     }
87   }
88 }
89 
90 /// \brief Emit a note explaining that this function is deleted.
91 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
92   assert(Decl->isDeleted());
93 
94   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
95 
96   if (Method && Method->isDeleted() && Method->isDefaulted()) {
97     // If the method was explicitly defaulted, point at that declaration.
98     if (!Method->isImplicit())
99       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
100 
101     // Try to diagnose why this special member function was implicitly
102     // deleted. This might fail, if that reason no longer applies.
103     CXXSpecialMember CSM = getSpecialMember(Method);
104     if (CSM != CXXInvalid)
105       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
106 
107     return;
108   }
109 
110   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
111   if (Ctor && Ctor->isInheritingConstructor())
112     return NoteDeletedInheritingConstructor(Ctor);
113 
114   Diag(Decl->getLocation(), diag::note_availability_specified_here)
115     << Decl << true;
116 }
117 
118 /// \brief Determine whether a FunctionDecl was ever declared with an
119 /// explicit storage class.
120 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
121   for (auto I : D->redecls()) {
122     if (I->getStorageClass() != SC_None)
123       return true;
124   }
125   return false;
126 }
127 
128 /// \brief Check whether we're in an extern inline function and referring to a
129 /// variable or function with internal linkage (C11 6.7.4p3).
130 ///
131 /// This is only a warning because we used to silently accept this code, but
132 /// in many cases it will not behave correctly. This is not enabled in C++ mode
133 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
134 /// and so while there may still be user mistakes, most of the time we can't
135 /// prove that there are errors.
136 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
137                                                       const NamedDecl *D,
138                                                       SourceLocation Loc) {
139   // This is disabled under C++; there are too many ways for this to fire in
140   // contexts where the warning is a false positive, or where it is technically
141   // correct but benign.
142   if (S.getLangOpts().CPlusPlus)
143     return;
144 
145   // Check if this is an inlined function or method.
146   FunctionDecl *Current = S.getCurFunctionDecl();
147   if (!Current)
148     return;
149   if (!Current->isInlined())
150     return;
151   if (!Current->isExternallyVisible())
152     return;
153 
154   // Check if the decl has internal linkage.
155   if (D->getFormalLinkage() != InternalLinkage)
156     return;
157 
158   // Downgrade from ExtWarn to Extension if
159   //  (1) the supposedly external inline function is in the main file,
160   //      and probably won't be included anywhere else.
161   //  (2) the thing we're referencing is a pure function.
162   //  (3) the thing we're referencing is another inline function.
163   // This last can give us false negatives, but it's better than warning on
164   // wrappers for simple C library functions.
165   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
166   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
167   if (!DowngradeWarning && UsedFn)
168     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
169 
170   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
171                                : diag::ext_internal_in_extern_inline)
172     << /*IsVar=*/!UsedFn << D;
173 
174   S.MaybeSuggestAddingStaticToDecl(Current);
175 
176   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
177       << D;
178 }
179 
180 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
181   const FunctionDecl *First = Cur->getFirstDecl();
182 
183   // Suggest "static" on the function, if possible.
184   if (!hasAnyExplicitStorageClass(First)) {
185     SourceLocation DeclBegin = First->getSourceRange().getBegin();
186     Diag(DeclBegin, diag::note_convert_inline_to_static)
187       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
188   }
189 }
190 
191 /// \brief Determine whether the use of this declaration is valid, and
192 /// emit any corresponding diagnostics.
193 ///
194 /// This routine diagnoses various problems with referencing
195 /// declarations that can occur when using a declaration. For example,
196 /// it might warn if a deprecated or unavailable declaration is being
197 /// used, or produce an error (and return true) if a C++0x deleted
198 /// function is being used.
199 ///
200 /// \returns true if there was an error (this declaration cannot be
201 /// referenced), false otherwise.
202 ///
203 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
204                              const ObjCInterfaceDecl *UnknownObjCClass,
205                              bool ObjCPropertyAccess,
206                              bool AvoidPartialAvailabilityChecks) {
207   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
208     // If there were any diagnostics suppressed by template argument deduction,
209     // emit them now.
210     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
211     if (Pos != SuppressedDiagnostics.end()) {
212       for (const PartialDiagnosticAt &Suppressed : Pos->second)
213         Diag(Suppressed.first, Suppressed.second);
214 
215       // Clear out the list of suppressed diagnostics, so that we don't emit
216       // them again for this specialization. However, we don't obsolete this
217       // entry from the table, because we want to avoid ever emitting these
218       // diagnostics again.
219       Pos->second.clear();
220     }
221 
222     // C++ [basic.start.main]p3:
223     //   The function 'main' shall not be used within a program.
224     if (cast<FunctionDecl>(D)->isMain())
225       Diag(Loc, diag::ext_main_used);
226   }
227 
228   // See if this is an auto-typed variable whose initializer we are parsing.
229   if (ParsingInitForAutoVars.count(D)) {
230     if (isa<BindingDecl>(D)) {
231       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
232         << D->getDeclName();
233     } else {
234       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
235         << D->getDeclName() << cast<VarDecl>(D)->getType();
236     }
237     return true;
238   }
239 
240   // See if this is a deleted function.
241   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
242     if (FD->isDeleted()) {
243       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
244       if (Ctor && Ctor->isInheritingConstructor())
245         Diag(Loc, diag::err_deleted_inherited_ctor_use)
246             << Ctor->getParent()
247             << Ctor->getInheritedConstructor().getConstructor()->getParent();
248       else
249         Diag(Loc, diag::err_deleted_function_use);
250       NoteDeletedFunction(FD);
251       return true;
252     }
253 
254     // If the function has a deduced return type, and we can't deduce it,
255     // then we can't use it either.
256     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
257         DeduceReturnType(FD, Loc))
258       return true;
259 
260     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
261       return true;
262   }
263 
264   auto getReferencedObjCProp = [](const NamedDecl *D) ->
265                                       const ObjCPropertyDecl * {
266     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
267       return MD->findPropertyDecl();
268     return nullptr;
269   };
270   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
271     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
272       return true;
273   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
274       return true;
275   }
276 
277   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
278   // Only the variables omp_in and omp_out are allowed in the combiner.
279   // Only the variables omp_priv and omp_orig are allowed in the
280   // initializer-clause.
281   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
282   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
283       isa<VarDecl>(D)) {
284     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
285         << getCurFunction()->HasOMPDeclareReductionCombiner;
286     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
287     return true;
288   }
289 
290   DiagnoseAvailabilityOfDecl(D, Loc, UnknownObjCClass, ObjCPropertyAccess,
291                              AvoidPartialAvailabilityChecks);
292 
293   DiagnoseUnusedOfDecl(*this, D, Loc);
294 
295   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
296 
297   return false;
298 }
299 
300 /// \brief Retrieve the message suffix that should be added to a
301 /// diagnostic complaining about the given function being deleted or
302 /// unavailable.
303 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
304   std::string Message;
305   if (FD->getAvailability(&Message))
306     return ": " + Message;
307 
308   return std::string();
309 }
310 
311 /// DiagnoseSentinelCalls - This routine checks whether a call or
312 /// message-send is to a declaration with the sentinel attribute, and
313 /// if so, it checks that the requirements of the sentinel are
314 /// satisfied.
315 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
316                                  ArrayRef<Expr *> Args) {
317   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
318   if (!attr)
319     return;
320 
321   // The number of formal parameters of the declaration.
322   unsigned numFormalParams;
323 
324   // The kind of declaration.  This is also an index into a %select in
325   // the diagnostic.
326   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
327 
328   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
329     numFormalParams = MD->param_size();
330     calleeType = CT_Method;
331   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
332     numFormalParams = FD->param_size();
333     calleeType = CT_Function;
334   } else if (isa<VarDecl>(D)) {
335     QualType type = cast<ValueDecl>(D)->getType();
336     const FunctionType *fn = nullptr;
337     if (const PointerType *ptr = type->getAs<PointerType>()) {
338       fn = ptr->getPointeeType()->getAs<FunctionType>();
339       if (!fn) return;
340       calleeType = CT_Function;
341     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
342       fn = ptr->getPointeeType()->castAs<FunctionType>();
343       calleeType = CT_Block;
344     } else {
345       return;
346     }
347 
348     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
349       numFormalParams = proto->getNumParams();
350     } else {
351       numFormalParams = 0;
352     }
353   } else {
354     return;
355   }
356 
357   // "nullPos" is the number of formal parameters at the end which
358   // effectively count as part of the variadic arguments.  This is
359   // useful if you would prefer to not have *any* formal parameters,
360   // but the language forces you to have at least one.
361   unsigned nullPos = attr->getNullPos();
362   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
363   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
364 
365   // The number of arguments which should follow the sentinel.
366   unsigned numArgsAfterSentinel = attr->getSentinel();
367 
368   // If there aren't enough arguments for all the formal parameters,
369   // the sentinel, and the args after the sentinel, complain.
370   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
371     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
372     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
373     return;
374   }
375 
376   // Otherwise, find the sentinel expression.
377   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
378   if (!sentinelExpr) return;
379   if (sentinelExpr->isValueDependent()) return;
380   if (Context.isSentinelNullExpr(sentinelExpr)) return;
381 
382   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
383   // or 'NULL' if those are actually defined in the context.  Only use
384   // 'nil' for ObjC methods, where it's much more likely that the
385   // variadic arguments form a list of object pointers.
386   SourceLocation MissingNilLoc
387     = getLocForEndOfToken(sentinelExpr->getLocEnd());
388   std::string NullValue;
389   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
390     NullValue = "nil";
391   else if (getLangOpts().CPlusPlus11)
392     NullValue = "nullptr";
393   else if (PP.isMacroDefined("NULL"))
394     NullValue = "NULL";
395   else
396     NullValue = "(void*) 0";
397 
398   if (MissingNilLoc.isInvalid())
399     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
400   else
401     Diag(MissingNilLoc, diag::warn_missing_sentinel)
402       << int(calleeType)
403       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
404   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
405 }
406 
407 SourceRange Sema::getExprRange(Expr *E) const {
408   return E ? E->getSourceRange() : SourceRange();
409 }
410 
411 //===----------------------------------------------------------------------===//
412 //  Standard Promotions and Conversions
413 //===----------------------------------------------------------------------===//
414 
415 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
416 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
417   // Handle any placeholder expressions which made it here.
418   if (E->getType()->isPlaceholderType()) {
419     ExprResult result = CheckPlaceholderExpr(E);
420     if (result.isInvalid()) return ExprError();
421     E = result.get();
422   }
423 
424   QualType Ty = E->getType();
425   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
426 
427   if (Ty->isFunctionType()) {
428     // If we are here, we are not calling a function but taking
429     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
430     if (getLangOpts().OpenCL) {
431       if (Diagnose)
432         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
433       return ExprError();
434     }
435 
436     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
437       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
438         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
439           return ExprError();
440 
441     E = ImpCastExprToType(E, Context.getPointerType(Ty),
442                           CK_FunctionToPointerDecay).get();
443   } else if (Ty->isArrayType()) {
444     // In C90 mode, arrays only promote to pointers if the array expression is
445     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
446     // type 'array of type' is converted to an expression that has type 'pointer
447     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
448     // that has type 'array of type' ...".  The relevant change is "an lvalue"
449     // (C90) to "an expression" (C99).
450     //
451     // C++ 4.2p1:
452     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
453     // T" can be converted to an rvalue of type "pointer to T".
454     //
455     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
456       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
457                             CK_ArrayToPointerDecay).get();
458   }
459   return E;
460 }
461 
462 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
463   // Check to see if we are dereferencing a null pointer.  If so,
464   // and if not volatile-qualified, this is undefined behavior that the
465   // optimizer will delete, so warn about it.  People sometimes try to use this
466   // to get a deterministic trap and are surprised by clang's behavior.  This
467   // only handles the pattern "*null", which is a very syntactic check.
468   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
469     if (UO->getOpcode() == UO_Deref &&
470         UO->getSubExpr()->IgnoreParenCasts()->
471           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
472         !UO->getType().isVolatileQualified()) {
473     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
474                           S.PDiag(diag::warn_indirection_through_null)
475                             << UO->getSubExpr()->getSourceRange());
476     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
477                         S.PDiag(diag::note_indirection_through_null));
478   }
479 }
480 
481 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
482                                     SourceLocation AssignLoc,
483                                     const Expr* RHS) {
484   const ObjCIvarDecl *IV = OIRE->getDecl();
485   if (!IV)
486     return;
487 
488   DeclarationName MemberName = IV->getDeclName();
489   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
490   if (!Member || !Member->isStr("isa"))
491     return;
492 
493   const Expr *Base = OIRE->getBase();
494   QualType BaseType = Base->getType();
495   if (OIRE->isArrow())
496     BaseType = BaseType->getPointeeType();
497   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
498     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
499       ObjCInterfaceDecl *ClassDeclared = nullptr;
500       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
501       if (!ClassDeclared->getSuperClass()
502           && (*ClassDeclared->ivar_begin()) == IV) {
503         if (RHS) {
504           NamedDecl *ObjectSetClass =
505             S.LookupSingleName(S.TUScope,
506                                &S.Context.Idents.get("object_setClass"),
507                                SourceLocation(), S.LookupOrdinaryName);
508           if (ObjectSetClass) {
509             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
510             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
511             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
512             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
513                                                      AssignLoc), ",") <<
514             FixItHint::CreateInsertion(RHSLocEnd, ")");
515           }
516           else
517             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
518         } else {
519           NamedDecl *ObjectGetClass =
520             S.LookupSingleName(S.TUScope,
521                                &S.Context.Idents.get("object_getClass"),
522                                SourceLocation(), S.LookupOrdinaryName);
523           if (ObjectGetClass)
524             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
525             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
526             FixItHint::CreateReplacement(
527                                          SourceRange(OIRE->getOpLoc(),
528                                                      OIRE->getLocEnd()), ")");
529           else
530             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
531         }
532         S.Diag(IV->getLocation(), diag::note_ivar_decl);
533       }
534     }
535 }
536 
537 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
538   // Handle any placeholder expressions which made it here.
539   if (E->getType()->isPlaceholderType()) {
540     ExprResult result = CheckPlaceholderExpr(E);
541     if (result.isInvalid()) return ExprError();
542     E = result.get();
543   }
544 
545   // C++ [conv.lval]p1:
546   //   A glvalue of a non-function, non-array type T can be
547   //   converted to a prvalue.
548   if (!E->isGLValue()) return E;
549 
550   QualType T = E->getType();
551   assert(!T.isNull() && "r-value conversion on typeless expression?");
552 
553   // We don't want to throw lvalue-to-rvalue casts on top of
554   // expressions of certain types in C++.
555   if (getLangOpts().CPlusPlus &&
556       (E->getType() == Context.OverloadTy ||
557        T->isDependentType() ||
558        T->isRecordType()))
559     return E;
560 
561   // The C standard is actually really unclear on this point, and
562   // DR106 tells us what the result should be but not why.  It's
563   // generally best to say that void types just doesn't undergo
564   // lvalue-to-rvalue at all.  Note that expressions of unqualified
565   // 'void' type are never l-values, but qualified void can be.
566   if (T->isVoidType())
567     return E;
568 
569   // OpenCL usually rejects direct accesses to values of 'half' type.
570   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
571       T->isHalfType()) {
572     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
573       << 0 << T;
574     return ExprError();
575   }
576 
577   CheckForNullPointerDereference(*this, E);
578   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
579     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
580                                      &Context.Idents.get("object_getClass"),
581                                      SourceLocation(), LookupOrdinaryName);
582     if (ObjectGetClass)
583       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
584         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
585         FixItHint::CreateReplacement(
586                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
587     else
588       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
589   }
590   else if (const ObjCIvarRefExpr *OIRE =
591             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
592     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
593 
594   // C++ [conv.lval]p1:
595   //   [...] If T is a non-class type, the type of the prvalue is the
596   //   cv-unqualified version of T. Otherwise, the type of the
597   //   rvalue is T.
598   //
599   // C99 6.3.2.1p2:
600   //   If the lvalue has qualified type, the value has the unqualified
601   //   version of the type of the lvalue; otherwise, the value has the
602   //   type of the lvalue.
603   if (T.hasQualifiers())
604     T = T.getUnqualifiedType();
605 
606   // Under the MS ABI, lock down the inheritance model now.
607   if (T->isMemberPointerType() &&
608       Context.getTargetInfo().getCXXABI().isMicrosoft())
609     (void)isCompleteType(E->getExprLoc(), T);
610 
611   UpdateMarkingForLValueToRValue(E);
612 
613   // Loading a __weak object implicitly retains the value, so we need a cleanup to
614   // balance that.
615   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
616     Cleanup.setExprNeedsCleanups(true);
617 
618   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
619                                             nullptr, VK_RValue);
620 
621   // C11 6.3.2.1p2:
622   //   ... if the lvalue has atomic type, the value has the non-atomic version
623   //   of the type of the lvalue ...
624   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
625     T = Atomic->getValueType().getUnqualifiedType();
626     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
627                                    nullptr, VK_RValue);
628   }
629 
630   return Res;
631 }
632 
633 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
634   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
635   if (Res.isInvalid())
636     return ExprError();
637   Res = DefaultLvalueConversion(Res.get());
638   if (Res.isInvalid())
639     return ExprError();
640   return Res;
641 }
642 
643 /// CallExprUnaryConversions - a special case of an unary conversion
644 /// performed on a function designator of a call expression.
645 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
646   QualType Ty = E->getType();
647   ExprResult Res = E;
648   // Only do implicit cast for a function type, but not for a pointer
649   // to function type.
650   if (Ty->isFunctionType()) {
651     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
652                             CK_FunctionToPointerDecay).get();
653     if (Res.isInvalid())
654       return ExprError();
655   }
656   Res = DefaultLvalueConversion(Res.get());
657   if (Res.isInvalid())
658     return ExprError();
659   return Res.get();
660 }
661 
662 /// UsualUnaryConversions - Performs various conversions that are common to most
663 /// operators (C99 6.3). The conversions of array and function types are
664 /// sometimes suppressed. For example, the array->pointer conversion doesn't
665 /// apply if the array is an argument to the sizeof or address (&) operators.
666 /// In these instances, this routine should *not* be called.
667 ExprResult Sema::UsualUnaryConversions(Expr *E) {
668   // First, convert to an r-value.
669   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
670   if (Res.isInvalid())
671     return ExprError();
672   E = Res.get();
673 
674   QualType Ty = E->getType();
675   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
676 
677   // Half FP have to be promoted to float unless it is natively supported
678   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
679     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
680 
681   // Try to perform integral promotions if the object has a theoretically
682   // promotable type.
683   if (Ty->isIntegralOrUnscopedEnumerationType()) {
684     // C99 6.3.1.1p2:
685     //
686     //   The following may be used in an expression wherever an int or
687     //   unsigned int may be used:
688     //     - an object or expression with an integer type whose integer
689     //       conversion rank is less than or equal to the rank of int
690     //       and unsigned int.
691     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
692     //
693     //   If an int can represent all values of the original type, the
694     //   value is converted to an int; otherwise, it is converted to an
695     //   unsigned int. These are called the integer promotions. All
696     //   other types are unchanged by the integer promotions.
697 
698     QualType PTy = Context.isPromotableBitField(E);
699     if (!PTy.isNull()) {
700       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
701       return E;
702     }
703     if (Ty->isPromotableIntegerType()) {
704       QualType PT = Context.getPromotedIntegerType(Ty);
705       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
706       return E;
707     }
708   }
709   return E;
710 }
711 
712 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
713 /// do not have a prototype. Arguments that have type float or __fp16
714 /// are promoted to double. All other argument types are converted by
715 /// UsualUnaryConversions().
716 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
717   QualType Ty = E->getType();
718   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
719 
720   ExprResult Res = UsualUnaryConversions(E);
721   if (Res.isInvalid())
722     return ExprError();
723   E = Res.get();
724 
725   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
726   // double.
727   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
728   if (BTy && (BTy->getKind() == BuiltinType::Half ||
729               BTy->getKind() == BuiltinType::Float)) {
730     if (getLangOpts().OpenCL &&
731         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
732         if (BTy->getKind() == BuiltinType::Half) {
733             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
734         }
735     } else {
736       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
737     }
738   }
739 
740   // C++ performs lvalue-to-rvalue conversion as a default argument
741   // promotion, even on class types, but note:
742   //   C++11 [conv.lval]p2:
743   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
744   //     operand or a subexpression thereof the value contained in the
745   //     referenced object is not accessed. Otherwise, if the glvalue
746   //     has a class type, the conversion copy-initializes a temporary
747   //     of type T from the glvalue and the result of the conversion
748   //     is a prvalue for the temporary.
749   // FIXME: add some way to gate this entire thing for correctness in
750   // potentially potentially evaluated contexts.
751   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
752     ExprResult Temp = PerformCopyInitialization(
753                        InitializedEntity::InitializeTemporary(E->getType()),
754                                                 E->getExprLoc(), E);
755     if (Temp.isInvalid())
756       return ExprError();
757     E = Temp.get();
758   }
759 
760   return E;
761 }
762 
763 /// Determine the degree of POD-ness for an expression.
764 /// Incomplete types are considered POD, since this check can be performed
765 /// when we're in an unevaluated context.
766 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
767   if (Ty->isIncompleteType()) {
768     // C++11 [expr.call]p7:
769     //   After these conversions, if the argument does not have arithmetic,
770     //   enumeration, pointer, pointer to member, or class type, the program
771     //   is ill-formed.
772     //
773     // Since we've already performed array-to-pointer and function-to-pointer
774     // decay, the only such type in C++ is cv void. This also handles
775     // initializer lists as variadic arguments.
776     if (Ty->isVoidType())
777       return VAK_Invalid;
778 
779     if (Ty->isObjCObjectType())
780       return VAK_Invalid;
781     return VAK_Valid;
782   }
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     // Fall through.
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->isObjCObjectType())
846       DiagRuntimeBehavior(
847           E->getLocStart(), nullptr,
848           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
849             << Ty << CT);
850     else
851       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
852         << isa<InitListExpr>(E) << Ty << CT;
853     break;
854   }
855 }
856 
857 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
858 /// will create a trap if the resulting type is not a POD type.
859 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
860                                                   FunctionDecl *FDecl) {
861   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
862     // Strip the unbridged-cast placeholder expression off, if applicable.
863     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
864         (CT == VariadicMethod ||
865          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
866       E = stripARCUnbridgedCast(E);
867 
868     // Otherwise, do normal placeholder checking.
869     } else {
870       ExprResult ExprRes = CheckPlaceholderExpr(E);
871       if (ExprRes.isInvalid())
872         return ExprError();
873       E = ExprRes.get();
874     }
875   }
876 
877   ExprResult ExprRes = DefaultArgumentPromotion(E);
878   if (ExprRes.isInvalid())
879     return ExprError();
880   E = ExprRes.get();
881 
882   // Diagnostics regarding non-POD argument types are
883   // emitted along with format string checking in Sema::CheckFunctionCall().
884   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
885     // Turn this into a trap.
886     CXXScopeSpec SS;
887     SourceLocation TemplateKWLoc;
888     UnqualifiedId Name;
889     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
890                        E->getLocStart());
891     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
892                                           Name, true, false);
893     if (TrapFn.isInvalid())
894       return ExprError();
895 
896     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
897                                     E->getLocStart(), None,
898                                     E->getLocEnd());
899     if (Call.isInvalid())
900       return ExprError();
901 
902     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
903                                   Call.get(), E);
904     if (Comma.isInvalid())
905       return ExprError();
906     return Comma.get();
907   }
908 
909   if (!getLangOpts().CPlusPlus &&
910       RequireCompleteType(E->getExprLoc(), E->getType(),
911                           diag::err_call_incomplete_argument))
912     return ExprError();
913 
914   return E;
915 }
916 
917 /// \brief Converts an integer to complex float type.  Helper function of
918 /// UsualArithmeticConversions()
919 ///
920 /// \return false if the integer expression is an integer type and is
921 /// successfully converted to the complex type.
922 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
923                                                   ExprResult &ComplexExpr,
924                                                   QualType IntTy,
925                                                   QualType ComplexTy,
926                                                   bool SkipCast) {
927   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
928   if (SkipCast) return false;
929   if (IntTy->isIntegerType()) {
930     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
931     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
932     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
933                                   CK_FloatingRealToComplex);
934   } else {
935     assert(IntTy->isComplexIntegerType());
936     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
937                                   CK_IntegralComplexToFloatingComplex);
938   }
939   return false;
940 }
941 
942 /// \brief Handle arithmetic conversion with complex types.  Helper function of
943 /// UsualArithmeticConversions()
944 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
945                                              ExprResult &RHS, QualType LHSType,
946                                              QualType RHSType,
947                                              bool IsCompAssign) {
948   // if we have an integer operand, the result is the complex type.
949   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
950                                              /*skipCast*/false))
951     return LHSType;
952   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
953                                              /*skipCast*/IsCompAssign))
954     return RHSType;
955 
956   // This handles complex/complex, complex/float, or float/complex.
957   // When both operands are complex, the shorter operand is converted to the
958   // type of the longer, and that is the type of the result. This corresponds
959   // to what is done when combining two real floating-point operands.
960   // The fun begins when size promotion occur across type domains.
961   // From H&S 6.3.4: When one operand is complex and the other is a real
962   // floating-point type, the less precise type is converted, within it's
963   // real or complex domain, to the precision of the other type. For example,
964   // when combining a "long double" with a "double _Complex", the
965   // "double _Complex" is promoted to "long double _Complex".
966 
967   // Compute the rank of the two types, regardless of whether they are complex.
968   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
969 
970   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
971   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
972   QualType LHSElementType =
973       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
974   QualType RHSElementType =
975       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
976 
977   QualType ResultType = S.Context.getComplexType(LHSElementType);
978   if (Order < 0) {
979     // Promote the precision of the LHS if not an assignment.
980     ResultType = S.Context.getComplexType(RHSElementType);
981     if (!IsCompAssign) {
982       if (LHSComplexType)
983         LHS =
984             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
985       else
986         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
987     }
988   } else if (Order > 0) {
989     // Promote the precision of the RHS.
990     if (RHSComplexType)
991       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
992     else
993       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
994   }
995   return ResultType;
996 }
997 
998 /// \brief Hande arithmetic conversion from integer to float.  Helper function
999 /// of UsualArithmeticConversions()
1000 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1001                                            ExprResult &IntExpr,
1002                                            QualType FloatTy, QualType IntTy,
1003                                            bool ConvertFloat, bool ConvertInt) {
1004   if (IntTy->isIntegerType()) {
1005     if (ConvertInt)
1006       // Convert intExpr to the lhs floating point type.
1007       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1008                                     CK_IntegralToFloating);
1009     return FloatTy;
1010   }
1011 
1012   // Convert both sides to the appropriate complex float.
1013   assert(IntTy->isComplexIntegerType());
1014   QualType result = S.Context.getComplexType(FloatTy);
1015 
1016   // _Complex int -> _Complex float
1017   if (ConvertInt)
1018     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1019                                   CK_IntegralComplexToFloatingComplex);
1020 
1021   // float -> _Complex float
1022   if (ConvertFloat)
1023     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1024                                     CK_FloatingRealToComplex);
1025 
1026   return result;
1027 }
1028 
1029 /// \brief Handle arithmethic conversion with floating point types.  Helper
1030 /// function of UsualArithmeticConversions()
1031 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1032                                       ExprResult &RHS, QualType LHSType,
1033                                       QualType RHSType, bool IsCompAssign) {
1034   bool LHSFloat = LHSType->isRealFloatingType();
1035   bool RHSFloat = RHSType->isRealFloatingType();
1036 
1037   // If we have two real floating types, convert the smaller operand
1038   // to the bigger result.
1039   if (LHSFloat && RHSFloat) {
1040     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1041     if (order > 0) {
1042       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1043       return LHSType;
1044     }
1045 
1046     assert(order < 0 && "illegal float comparison");
1047     if (!IsCompAssign)
1048       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1049     return RHSType;
1050   }
1051 
1052   if (LHSFloat) {
1053     // Half FP has to be promoted to float unless it is natively supported
1054     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1055       LHSType = S.Context.FloatTy;
1056 
1057     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1058                                       /*convertFloat=*/!IsCompAssign,
1059                                       /*convertInt=*/ true);
1060   }
1061   assert(RHSFloat);
1062   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1063                                     /*convertInt=*/ true,
1064                                     /*convertFloat=*/!IsCompAssign);
1065 }
1066 
1067 /// \brief Diagnose attempts to convert between __float128 and long double if
1068 /// there is no support for such conversion. Helper function of
1069 /// UsualArithmeticConversions().
1070 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1071                                       QualType RHSType) {
1072   /*  No issue converting if at least one of the types is not a floating point
1073       type or the two types have the same rank.
1074   */
1075   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1076       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1077     return false;
1078 
1079   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1080          "The remaining types must be floating point types.");
1081 
1082   auto *LHSComplex = LHSType->getAs<ComplexType>();
1083   auto *RHSComplex = RHSType->getAs<ComplexType>();
1084 
1085   QualType LHSElemType = LHSComplex ?
1086     LHSComplex->getElementType() : LHSType;
1087   QualType RHSElemType = RHSComplex ?
1088     RHSComplex->getElementType() : RHSType;
1089 
1090   // No issue if the two types have the same representation
1091   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1092       &S.Context.getFloatTypeSemantics(RHSElemType))
1093     return false;
1094 
1095   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1096                                 RHSElemType == S.Context.LongDoubleTy);
1097   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1098                             RHSElemType == S.Context.Float128Ty);
1099 
1100   /* We've handled the situation where __float128 and long double have the same
1101      representation. The only other allowable conversion is if long double is
1102      really just double.
1103   */
1104   return Float128AndLongDouble &&
1105     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1106      &llvm::APFloat::IEEEdouble());
1107 }
1108 
1109 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1110 
1111 namespace {
1112 /// These helper callbacks are placed in an anonymous namespace to
1113 /// permit their use as function template parameters.
1114 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1115   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1116 }
1117 
1118 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1119   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1120                              CK_IntegralComplexCast);
1121 }
1122 }
1123 
1124 /// \brief Handle integer arithmetic conversions.  Helper function of
1125 /// UsualArithmeticConversions()
1126 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1127 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1128                                         ExprResult &RHS, QualType LHSType,
1129                                         QualType RHSType, bool IsCompAssign) {
1130   // The rules for this case are in C99 6.3.1.8
1131   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1132   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1133   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1134   if (LHSSigned == RHSSigned) {
1135     // Same signedness; use the higher-ranked type
1136     if (order >= 0) {
1137       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1138       return LHSType;
1139     } else if (!IsCompAssign)
1140       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1141     return RHSType;
1142   } else if (order != (LHSSigned ? 1 : -1)) {
1143     // The unsigned type has greater than or equal rank to the
1144     // signed type, so use the unsigned type
1145     if (RHSSigned) {
1146       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1147       return LHSType;
1148     } else if (!IsCompAssign)
1149       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1150     return RHSType;
1151   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1152     // The two types are different widths; if we are here, that
1153     // means the signed type is larger than the unsigned type, so
1154     // use the signed type.
1155     if (LHSSigned) {
1156       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1157       return LHSType;
1158     } else if (!IsCompAssign)
1159       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1160     return RHSType;
1161   } else {
1162     // The signed type is higher-ranked than the unsigned type,
1163     // but isn't actually any bigger (like unsigned int and long
1164     // on most 32-bit systems).  Use the unsigned type corresponding
1165     // to the signed type.
1166     QualType result =
1167       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1168     RHS = (*doRHSCast)(S, RHS.get(), result);
1169     if (!IsCompAssign)
1170       LHS = (*doLHSCast)(S, LHS.get(), result);
1171     return result;
1172   }
1173 }
1174 
1175 /// \brief Handle conversions with GCC complex int extension.  Helper function
1176 /// of UsualArithmeticConversions()
1177 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1178                                            ExprResult &RHS, QualType LHSType,
1179                                            QualType RHSType,
1180                                            bool IsCompAssign) {
1181   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1182   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1183 
1184   if (LHSComplexInt && RHSComplexInt) {
1185     QualType LHSEltType = LHSComplexInt->getElementType();
1186     QualType RHSEltType = RHSComplexInt->getElementType();
1187     QualType ScalarType =
1188       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1189         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1190 
1191     return S.Context.getComplexType(ScalarType);
1192   }
1193 
1194   if (LHSComplexInt) {
1195     QualType LHSEltType = LHSComplexInt->getElementType();
1196     QualType ScalarType =
1197       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1198         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1199     QualType ComplexType = S.Context.getComplexType(ScalarType);
1200     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1201                               CK_IntegralRealToComplex);
1202 
1203     return ComplexType;
1204   }
1205 
1206   assert(RHSComplexInt);
1207 
1208   QualType RHSEltType = RHSComplexInt->getElementType();
1209   QualType ScalarType =
1210     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1211       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1212   QualType ComplexType = S.Context.getComplexType(ScalarType);
1213 
1214   if (!IsCompAssign)
1215     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1216                               CK_IntegralRealToComplex);
1217   return ComplexType;
1218 }
1219 
1220 /// UsualArithmeticConversions - Performs various conversions that are common to
1221 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1222 /// routine returns the first non-arithmetic type found. The client is
1223 /// responsible for emitting appropriate error diagnostics.
1224 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1225                                           bool IsCompAssign) {
1226   if (!IsCompAssign) {
1227     LHS = UsualUnaryConversions(LHS.get());
1228     if (LHS.isInvalid())
1229       return QualType();
1230   }
1231 
1232   RHS = UsualUnaryConversions(RHS.get());
1233   if (RHS.isInvalid())
1234     return QualType();
1235 
1236   // For conversion purposes, we ignore any qualifiers.
1237   // For example, "const float" and "float" are equivalent.
1238   QualType LHSType =
1239     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1240   QualType RHSType =
1241     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1242 
1243   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1244   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1245     LHSType = AtomicLHS->getValueType();
1246 
1247   // If both types are identical, no conversion is needed.
1248   if (LHSType == RHSType)
1249     return LHSType;
1250 
1251   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1252   // The caller can deal with this (e.g. pointer + int).
1253   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1254     return QualType();
1255 
1256   // Apply unary and bitfield promotions to the LHS's type.
1257   QualType LHSUnpromotedType = LHSType;
1258   if (LHSType->isPromotableIntegerType())
1259     LHSType = Context.getPromotedIntegerType(LHSType);
1260   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1261   if (!LHSBitfieldPromoteTy.isNull())
1262     LHSType = LHSBitfieldPromoteTy;
1263   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1264     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1265 
1266   // If both types are identical, no conversion is needed.
1267   if (LHSType == RHSType)
1268     return LHSType;
1269 
1270   // At this point, we have two different arithmetic types.
1271 
1272   // Diagnose attempts to convert between __float128 and long double where
1273   // such conversions currently can't be handled.
1274   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1275     return QualType();
1276 
1277   // Handle complex types first (C99 6.3.1.8p1).
1278   if (LHSType->isComplexType() || RHSType->isComplexType())
1279     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1280                                         IsCompAssign);
1281 
1282   // Now handle "real" floating types (i.e. float, double, long double).
1283   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1284     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1285                                  IsCompAssign);
1286 
1287   // Handle GCC complex int extension.
1288   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1289     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1290                                       IsCompAssign);
1291 
1292   // Finally, we have two differing integer types.
1293   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1294            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1295 }
1296 
1297 
1298 //===----------------------------------------------------------------------===//
1299 //  Semantic Analysis for various Expression Types
1300 //===----------------------------------------------------------------------===//
1301 
1302 
1303 ExprResult
1304 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1305                                 SourceLocation DefaultLoc,
1306                                 SourceLocation RParenLoc,
1307                                 Expr *ControllingExpr,
1308                                 ArrayRef<ParsedType> ArgTypes,
1309                                 ArrayRef<Expr *> ArgExprs) {
1310   unsigned NumAssocs = ArgTypes.size();
1311   assert(NumAssocs == ArgExprs.size());
1312 
1313   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1314   for (unsigned i = 0; i < NumAssocs; ++i) {
1315     if (ArgTypes[i])
1316       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1317     else
1318       Types[i] = nullptr;
1319   }
1320 
1321   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1322                                              ControllingExpr,
1323                                              llvm::makeArrayRef(Types, NumAssocs),
1324                                              ArgExprs);
1325   delete [] Types;
1326   return ER;
1327 }
1328 
1329 ExprResult
1330 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1331                                  SourceLocation DefaultLoc,
1332                                  SourceLocation RParenLoc,
1333                                  Expr *ControllingExpr,
1334                                  ArrayRef<TypeSourceInfo *> Types,
1335                                  ArrayRef<Expr *> Exprs) {
1336   unsigned NumAssocs = Types.size();
1337   assert(NumAssocs == Exprs.size());
1338 
1339   // Decay and strip qualifiers for the controlling expression type, and handle
1340   // placeholder type replacement. See committee discussion from WG14 DR423.
1341   {
1342     EnterExpressionEvaluationContext Unevaluated(
1343         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1344     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1345     if (R.isInvalid())
1346       return ExprError();
1347     ControllingExpr = R.get();
1348   }
1349 
1350   // The controlling expression is an unevaluated operand, so side effects are
1351   // likely unintended.
1352   if (!inTemplateInstantiation() &&
1353       ControllingExpr->HasSideEffects(Context, false))
1354     Diag(ControllingExpr->getExprLoc(),
1355          diag::warn_side_effects_unevaluated_context);
1356 
1357   bool TypeErrorFound = false,
1358        IsResultDependent = ControllingExpr->isTypeDependent(),
1359        ContainsUnexpandedParameterPack
1360          = ControllingExpr->containsUnexpandedParameterPack();
1361 
1362   for (unsigned i = 0; i < NumAssocs; ++i) {
1363     if (Exprs[i]->containsUnexpandedParameterPack())
1364       ContainsUnexpandedParameterPack = true;
1365 
1366     if (Types[i]) {
1367       if (Types[i]->getType()->containsUnexpandedParameterPack())
1368         ContainsUnexpandedParameterPack = true;
1369 
1370       if (Types[i]->getType()->isDependentType()) {
1371         IsResultDependent = true;
1372       } else {
1373         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1374         // complete object type other than a variably modified type."
1375         unsigned D = 0;
1376         if (Types[i]->getType()->isIncompleteType())
1377           D = diag::err_assoc_type_incomplete;
1378         else if (!Types[i]->getType()->isObjectType())
1379           D = diag::err_assoc_type_nonobject;
1380         else if (Types[i]->getType()->isVariablyModifiedType())
1381           D = diag::err_assoc_type_variably_modified;
1382 
1383         if (D != 0) {
1384           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1385             << Types[i]->getTypeLoc().getSourceRange()
1386             << Types[i]->getType();
1387           TypeErrorFound = true;
1388         }
1389 
1390         // C11 6.5.1.1p2 "No two generic associations in the same generic
1391         // selection shall specify compatible types."
1392         for (unsigned j = i+1; j < NumAssocs; ++j)
1393           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1394               Context.typesAreCompatible(Types[i]->getType(),
1395                                          Types[j]->getType())) {
1396             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1397                  diag::err_assoc_compatible_types)
1398               << Types[j]->getTypeLoc().getSourceRange()
1399               << Types[j]->getType()
1400               << Types[i]->getType();
1401             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1402                  diag::note_compat_assoc)
1403               << Types[i]->getTypeLoc().getSourceRange()
1404               << Types[i]->getType();
1405             TypeErrorFound = true;
1406           }
1407       }
1408     }
1409   }
1410   if (TypeErrorFound)
1411     return ExprError();
1412 
1413   // If we determined that the generic selection is result-dependent, don't
1414   // try to compute the result expression.
1415   if (IsResultDependent)
1416     return new (Context) GenericSelectionExpr(
1417         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1418         ContainsUnexpandedParameterPack);
1419 
1420   SmallVector<unsigned, 1> CompatIndices;
1421   unsigned DefaultIndex = -1U;
1422   for (unsigned i = 0; i < NumAssocs; ++i) {
1423     if (!Types[i])
1424       DefaultIndex = i;
1425     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1426                                         Types[i]->getType()))
1427       CompatIndices.push_back(i);
1428   }
1429 
1430   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1431   // type compatible with at most one of the types named in its generic
1432   // association list."
1433   if (CompatIndices.size() > 1) {
1434     // We strip parens here because the controlling expression is typically
1435     // parenthesized in macro definitions.
1436     ControllingExpr = ControllingExpr->IgnoreParens();
1437     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1438       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1439       << (unsigned) CompatIndices.size();
1440     for (unsigned I : CompatIndices) {
1441       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1442            diag::note_compat_assoc)
1443         << Types[I]->getTypeLoc().getSourceRange()
1444         << Types[I]->getType();
1445     }
1446     return ExprError();
1447   }
1448 
1449   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1450   // its controlling expression shall have type compatible with exactly one of
1451   // the types named in its generic association list."
1452   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1453     // We strip parens here because the controlling expression is typically
1454     // parenthesized in macro definitions.
1455     ControllingExpr = ControllingExpr->IgnoreParens();
1456     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1457       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1458     return ExprError();
1459   }
1460 
1461   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1462   // type name that is compatible with the type of the controlling expression,
1463   // then the result expression of the generic selection is the expression
1464   // in that generic association. Otherwise, the result expression of the
1465   // generic selection is the expression in the default generic association."
1466   unsigned ResultIndex =
1467     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1468 
1469   return new (Context) GenericSelectionExpr(
1470       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1471       ContainsUnexpandedParameterPack, ResultIndex);
1472 }
1473 
1474 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1475 /// location of the token and the offset of the ud-suffix within it.
1476 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1477                                      unsigned Offset) {
1478   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1479                                         S.getLangOpts());
1480 }
1481 
1482 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1483 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1484 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1485                                                  IdentifierInfo *UDSuffix,
1486                                                  SourceLocation UDSuffixLoc,
1487                                                  ArrayRef<Expr*> Args,
1488                                                  SourceLocation LitEndLoc) {
1489   assert(Args.size() <= 2 && "too many arguments for literal operator");
1490 
1491   QualType ArgTy[2];
1492   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1493     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1494     if (ArgTy[ArgIdx]->isArrayType())
1495       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1496   }
1497 
1498   DeclarationName OpName =
1499     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1500   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1501   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1502 
1503   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1504   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1505                               /*AllowRaw*/false, /*AllowTemplate*/false,
1506                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1507     return ExprError();
1508 
1509   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1510 }
1511 
1512 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1513 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1514 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1515 /// multiple tokens.  However, the common case is that StringToks points to one
1516 /// string.
1517 ///
1518 ExprResult
1519 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1520   assert(!StringToks.empty() && "Must have at least one string!");
1521 
1522   StringLiteralParser Literal(StringToks, PP);
1523   if (Literal.hadError)
1524     return ExprError();
1525 
1526   SmallVector<SourceLocation, 4> StringTokLocs;
1527   for (const Token &Tok : StringToks)
1528     StringTokLocs.push_back(Tok.getLocation());
1529 
1530   QualType CharTy = Context.CharTy;
1531   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1532   if (Literal.isWide()) {
1533     CharTy = Context.getWideCharType();
1534     Kind = StringLiteral::Wide;
1535   } else if (Literal.isUTF8()) {
1536     Kind = StringLiteral::UTF8;
1537   } else if (Literal.isUTF16()) {
1538     CharTy = Context.Char16Ty;
1539     Kind = StringLiteral::UTF16;
1540   } else if (Literal.isUTF32()) {
1541     CharTy = Context.Char32Ty;
1542     Kind = StringLiteral::UTF32;
1543   } else if (Literal.isPascal()) {
1544     CharTy = Context.UnsignedCharTy;
1545   }
1546 
1547   QualType CharTyConst = CharTy;
1548   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1549   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1550     CharTyConst.addConst();
1551 
1552   // Get an array type for the string, according to C99 6.4.5.  This includes
1553   // the nul terminator character as well as the string length for pascal
1554   // strings.
1555   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1556                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1557                                  ArrayType::Normal, 0);
1558 
1559   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1560   if (getLangOpts().OpenCL) {
1561     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1562   }
1563 
1564   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1565   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1566                                              Kind, Literal.Pascal, StrTy,
1567                                              &StringTokLocs[0],
1568                                              StringTokLocs.size());
1569   if (Literal.getUDSuffix().empty())
1570     return Lit;
1571 
1572   // We're building a user-defined literal.
1573   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1574   SourceLocation UDSuffixLoc =
1575     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1576                    Literal.getUDSuffixOffset());
1577 
1578   // Make sure we're allowed user-defined literals here.
1579   if (!UDLScope)
1580     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1581 
1582   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1583   //   operator "" X (str, len)
1584   QualType SizeType = Context.getSizeType();
1585 
1586   DeclarationName OpName =
1587     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1588   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1589   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1590 
1591   QualType ArgTy[] = {
1592     Context.getArrayDecayedType(StrTy), SizeType
1593   };
1594 
1595   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1596   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1597                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1598                                 /*AllowStringTemplate*/true)) {
1599 
1600   case LOLR_Cooked: {
1601     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1602     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1603                                                     StringTokLocs[0]);
1604     Expr *Args[] = { Lit, LenArg };
1605 
1606     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1607   }
1608 
1609   case LOLR_StringTemplate: {
1610     TemplateArgumentListInfo ExplicitArgs;
1611 
1612     unsigned CharBits = Context.getIntWidth(CharTy);
1613     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1614     llvm::APSInt Value(CharBits, CharIsUnsigned);
1615 
1616     TemplateArgument TypeArg(CharTy);
1617     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1618     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1619 
1620     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1621       Value = Lit->getCodeUnit(I);
1622       TemplateArgument Arg(Context, Value, CharTy);
1623       TemplateArgumentLocInfo ArgInfo;
1624       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1625     }
1626     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1627                                     &ExplicitArgs);
1628   }
1629   case LOLR_Raw:
1630   case LOLR_Template:
1631     llvm_unreachable("unexpected literal operator lookup result");
1632   case LOLR_Error:
1633     return ExprError();
1634   }
1635   llvm_unreachable("unexpected literal operator lookup result");
1636 }
1637 
1638 ExprResult
1639 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1640                        SourceLocation Loc,
1641                        const CXXScopeSpec *SS) {
1642   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1643   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1644 }
1645 
1646 /// BuildDeclRefExpr - Build an expression that references a
1647 /// declaration that does not require a closure capture.
1648 ExprResult
1649 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1650                        const DeclarationNameInfo &NameInfo,
1651                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1652                        const TemplateArgumentListInfo *TemplateArgs) {
1653   bool RefersToCapturedVariable =
1654       isa<VarDecl>(D) &&
1655       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1656 
1657   DeclRefExpr *E;
1658   if (isa<VarTemplateSpecializationDecl>(D)) {
1659     VarTemplateSpecializationDecl *VarSpec =
1660         cast<VarTemplateSpecializationDecl>(D);
1661 
1662     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1663                                         : NestedNameSpecifierLoc(),
1664                             VarSpec->getTemplateKeywordLoc(), D,
1665                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1666                             FoundD, TemplateArgs);
1667   } else {
1668     assert(!TemplateArgs && "No template arguments for non-variable"
1669                             " template specialization references");
1670     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1671                                         : NestedNameSpecifierLoc(),
1672                             SourceLocation(), D, RefersToCapturedVariable,
1673                             NameInfo, Ty, VK, FoundD);
1674   }
1675 
1676   MarkDeclRefReferenced(E);
1677 
1678   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1679       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1680       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1681       recordUseOfEvaluatedWeak(E);
1682 
1683   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1684   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1685     FD = IFD->getAnonField();
1686   if (FD) {
1687     UnusedPrivateFields.remove(FD);
1688     // Just in case we're building an illegal pointer-to-member.
1689     if (FD->isBitField())
1690       E->setObjectKind(OK_BitField);
1691   }
1692 
1693   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1694   // designates a bit-field.
1695   if (auto *BD = dyn_cast<BindingDecl>(D))
1696     if (auto *BE = BD->getBinding())
1697       E->setObjectKind(BE->getObjectKind());
1698 
1699   return E;
1700 }
1701 
1702 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1703 /// possibly a list of template arguments.
1704 ///
1705 /// If this produces template arguments, it is permitted to call
1706 /// DecomposeTemplateName.
1707 ///
1708 /// This actually loses a lot of source location information for
1709 /// non-standard name kinds; we should consider preserving that in
1710 /// some way.
1711 void
1712 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1713                              TemplateArgumentListInfo &Buffer,
1714                              DeclarationNameInfo &NameInfo,
1715                              const TemplateArgumentListInfo *&TemplateArgs) {
1716   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1717     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1718     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1719 
1720     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1721                                        Id.TemplateId->NumArgs);
1722     translateTemplateArguments(TemplateArgsPtr, Buffer);
1723 
1724     TemplateName TName = Id.TemplateId->Template.get();
1725     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1726     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1727     TemplateArgs = &Buffer;
1728   } else {
1729     NameInfo = GetNameFromUnqualifiedId(Id);
1730     TemplateArgs = nullptr;
1731   }
1732 }
1733 
1734 static void emitEmptyLookupTypoDiagnostic(
1735     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1736     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1737     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1738   DeclContext *Ctx =
1739       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1740   if (!TC) {
1741     // Emit a special diagnostic for failed member lookups.
1742     // FIXME: computing the declaration context might fail here (?)
1743     if (Ctx)
1744       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1745                                                  << SS.getRange();
1746     else
1747       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1748     return;
1749   }
1750 
1751   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1752   bool DroppedSpecifier =
1753       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1754   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1755                         ? diag::note_implicit_param_decl
1756                         : diag::note_previous_decl;
1757   if (!Ctx)
1758     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1759                          SemaRef.PDiag(NoteID));
1760   else
1761     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1762                                  << Typo << Ctx << DroppedSpecifier
1763                                  << SS.getRange(),
1764                          SemaRef.PDiag(NoteID));
1765 }
1766 
1767 /// Diagnose an empty lookup.
1768 ///
1769 /// \return false if new lookup candidates were found
1770 bool
1771 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1772                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1773                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1774                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1775   DeclarationName Name = R.getLookupName();
1776 
1777   unsigned diagnostic = diag::err_undeclared_var_use;
1778   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1779   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1780       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1781       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1782     diagnostic = diag::err_undeclared_use;
1783     diagnostic_suggest = diag::err_undeclared_use_suggest;
1784   }
1785 
1786   // If the original lookup was an unqualified lookup, fake an
1787   // unqualified lookup.  This is useful when (for example) the
1788   // original lookup would not have found something because it was a
1789   // dependent name.
1790   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1791   while (DC) {
1792     if (isa<CXXRecordDecl>(DC)) {
1793       LookupQualifiedName(R, DC);
1794 
1795       if (!R.empty()) {
1796         // Don't give errors about ambiguities in this lookup.
1797         R.suppressDiagnostics();
1798 
1799         // During a default argument instantiation the CurContext points
1800         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1801         // function parameter list, hence add an explicit check.
1802         bool isDefaultArgument =
1803             !CodeSynthesisContexts.empty() &&
1804             CodeSynthesisContexts.back().Kind ==
1805                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1806         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1807         bool isInstance = CurMethod &&
1808                           CurMethod->isInstance() &&
1809                           DC == CurMethod->getParent() && !isDefaultArgument;
1810 
1811         // Give a code modification hint to insert 'this->'.
1812         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1813         // Actually quite difficult!
1814         if (getLangOpts().MSVCCompat)
1815           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1816         if (isInstance) {
1817           Diag(R.getNameLoc(), diagnostic) << Name
1818             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1819           CheckCXXThisCapture(R.getNameLoc());
1820         } else {
1821           Diag(R.getNameLoc(), diagnostic) << Name;
1822         }
1823 
1824         // Do we really want to note all of these?
1825         for (NamedDecl *D : R)
1826           Diag(D->getLocation(), diag::note_dependent_var_use);
1827 
1828         // Return true if we are inside a default argument instantiation
1829         // and the found name refers to an instance member function, otherwise
1830         // the function calling DiagnoseEmptyLookup will try to create an
1831         // implicit member call and this is wrong for default argument.
1832         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1833           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1834           return true;
1835         }
1836 
1837         // Tell the callee to try to recover.
1838         return false;
1839       }
1840 
1841       R.clear();
1842     }
1843 
1844     // In Microsoft mode, if we are performing lookup from within a friend
1845     // function definition declared at class scope then we must set
1846     // DC to the lexical parent to be able to search into the parent
1847     // class.
1848     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1849         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1850         DC->getLexicalParent()->isRecord())
1851       DC = DC->getLexicalParent();
1852     else
1853       DC = DC->getParent();
1854   }
1855 
1856   // We didn't find anything, so try to correct for a typo.
1857   TypoCorrection Corrected;
1858   if (S && Out) {
1859     SourceLocation TypoLoc = R.getNameLoc();
1860     assert(!ExplicitTemplateArgs &&
1861            "Diagnosing an empty lookup with explicit template args!");
1862     *Out = CorrectTypoDelayed(
1863         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1864         [=](const TypoCorrection &TC) {
1865           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1866                                         diagnostic, diagnostic_suggest);
1867         },
1868         nullptr, CTK_ErrorRecovery);
1869     if (*Out)
1870       return true;
1871   } else if (S && (Corrected =
1872                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1873                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1874     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1875     bool DroppedSpecifier =
1876         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1877     R.setLookupName(Corrected.getCorrection());
1878 
1879     bool AcceptableWithRecovery = false;
1880     bool AcceptableWithoutRecovery = false;
1881     NamedDecl *ND = Corrected.getFoundDecl();
1882     if (ND) {
1883       if (Corrected.isOverloaded()) {
1884         OverloadCandidateSet OCS(R.getNameLoc(),
1885                                  OverloadCandidateSet::CSK_Normal);
1886         OverloadCandidateSet::iterator Best;
1887         for (NamedDecl *CD : Corrected) {
1888           if (FunctionTemplateDecl *FTD =
1889                    dyn_cast<FunctionTemplateDecl>(CD))
1890             AddTemplateOverloadCandidate(
1891                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1892                 Args, OCS);
1893           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1894             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1895               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1896                                    Args, OCS);
1897         }
1898         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1899         case OR_Success:
1900           ND = Best->FoundDecl;
1901           Corrected.setCorrectionDecl(ND);
1902           break;
1903         default:
1904           // FIXME: Arbitrarily pick the first declaration for the note.
1905           Corrected.setCorrectionDecl(ND);
1906           break;
1907         }
1908       }
1909       R.addDecl(ND);
1910       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1911         CXXRecordDecl *Record = nullptr;
1912         if (Corrected.getCorrectionSpecifier()) {
1913           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1914           Record = Ty->getAsCXXRecordDecl();
1915         }
1916         if (!Record)
1917           Record = cast<CXXRecordDecl>(
1918               ND->getDeclContext()->getRedeclContext());
1919         R.setNamingClass(Record);
1920       }
1921 
1922       auto *UnderlyingND = ND->getUnderlyingDecl();
1923       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1924                                isa<FunctionTemplateDecl>(UnderlyingND);
1925       // FIXME: If we ended up with a typo for a type name or
1926       // Objective-C class name, we're in trouble because the parser
1927       // is in the wrong place to recover. Suggest the typo
1928       // correction, but don't make it a fix-it since we're not going
1929       // to recover well anyway.
1930       AcceptableWithoutRecovery =
1931           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1932     } else {
1933       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1934       // because we aren't able to recover.
1935       AcceptableWithoutRecovery = true;
1936     }
1937 
1938     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1939       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1940                             ? diag::note_implicit_param_decl
1941                             : diag::note_previous_decl;
1942       if (SS.isEmpty())
1943         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1944                      PDiag(NoteID), AcceptableWithRecovery);
1945       else
1946         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1947                                   << Name << computeDeclContext(SS, false)
1948                                   << DroppedSpecifier << SS.getRange(),
1949                      PDiag(NoteID), AcceptableWithRecovery);
1950 
1951       // Tell the callee whether to try to recover.
1952       return !AcceptableWithRecovery;
1953     }
1954   }
1955   R.clear();
1956 
1957   // Emit a special diagnostic for failed member lookups.
1958   // FIXME: computing the declaration context might fail here (?)
1959   if (!SS.isEmpty()) {
1960     Diag(R.getNameLoc(), diag::err_no_member)
1961       << Name << computeDeclContext(SS, false)
1962       << SS.getRange();
1963     return true;
1964   }
1965 
1966   // Give up, we can't recover.
1967   Diag(R.getNameLoc(), diagnostic) << Name;
1968   return true;
1969 }
1970 
1971 /// In Microsoft mode, if we are inside a template class whose parent class has
1972 /// dependent base classes, and we can't resolve an unqualified identifier, then
1973 /// assume the identifier is a member of a dependent base class.  We can only
1974 /// recover successfully in static methods, instance methods, and other contexts
1975 /// where 'this' is available.  This doesn't precisely match MSVC's
1976 /// instantiation model, but it's close enough.
1977 static Expr *
1978 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1979                                DeclarationNameInfo &NameInfo,
1980                                SourceLocation TemplateKWLoc,
1981                                const TemplateArgumentListInfo *TemplateArgs) {
1982   // Only try to recover from lookup into dependent bases in static methods or
1983   // contexts where 'this' is available.
1984   QualType ThisType = S.getCurrentThisType();
1985   const CXXRecordDecl *RD = nullptr;
1986   if (!ThisType.isNull())
1987     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1988   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1989     RD = MD->getParent();
1990   if (!RD || !RD->hasAnyDependentBases())
1991     return nullptr;
1992 
1993   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1994   // is available, suggest inserting 'this->' as a fixit.
1995   SourceLocation Loc = NameInfo.getLoc();
1996   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
1997   DB << NameInfo.getName() << RD;
1998 
1999   if (!ThisType.isNull()) {
2000     DB << FixItHint::CreateInsertion(Loc, "this->");
2001     return CXXDependentScopeMemberExpr::Create(
2002         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2003         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2004         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2005   }
2006 
2007   // Synthesize a fake NNS that points to the derived class.  This will
2008   // perform name lookup during template instantiation.
2009   CXXScopeSpec SS;
2010   auto *NNS =
2011       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2012   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2013   return DependentScopeDeclRefExpr::Create(
2014       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2015       TemplateArgs);
2016 }
2017 
2018 ExprResult
2019 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2020                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2021                         bool HasTrailingLParen, bool IsAddressOfOperand,
2022                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2023                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2024   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2025          "cannot be direct & operand and have a trailing lparen");
2026   if (SS.isInvalid())
2027     return ExprError();
2028 
2029   TemplateArgumentListInfo TemplateArgsBuffer;
2030 
2031   // Decompose the UnqualifiedId into the following data.
2032   DeclarationNameInfo NameInfo;
2033   const TemplateArgumentListInfo *TemplateArgs;
2034   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2035 
2036   DeclarationName Name = NameInfo.getName();
2037   IdentifierInfo *II = Name.getAsIdentifierInfo();
2038   SourceLocation NameLoc = NameInfo.getLoc();
2039 
2040   if (II && II->isEditorPlaceholder()) {
2041     // FIXME: When typed placeholders are supported we can create a typed
2042     // placeholder expression node.
2043     return ExprError();
2044   }
2045 
2046   // C++ [temp.dep.expr]p3:
2047   //   An id-expression is type-dependent if it contains:
2048   //     -- an identifier that was declared with a dependent type,
2049   //        (note: handled after lookup)
2050   //     -- a template-id that is dependent,
2051   //        (note: handled in BuildTemplateIdExpr)
2052   //     -- a conversion-function-id that specifies a dependent type,
2053   //     -- a nested-name-specifier that contains a class-name that
2054   //        names a dependent type.
2055   // Determine whether this is a member of an unknown specialization;
2056   // we need to handle these differently.
2057   bool DependentID = false;
2058   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2059       Name.getCXXNameType()->isDependentType()) {
2060     DependentID = true;
2061   } else if (SS.isSet()) {
2062     if (DeclContext *DC = computeDeclContext(SS, false)) {
2063       if (RequireCompleteDeclContext(SS, DC))
2064         return ExprError();
2065     } else {
2066       DependentID = true;
2067     }
2068   }
2069 
2070   if (DependentID)
2071     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2072                                       IsAddressOfOperand, TemplateArgs);
2073 
2074   // Perform the required lookup.
2075   LookupResult R(*this, NameInfo,
2076                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2077                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2078   if (TemplateArgs) {
2079     // Lookup the template name again to correctly establish the context in
2080     // which it was found. This is really unfortunate as we already did the
2081     // lookup to determine that it was a template name in the first place. If
2082     // this becomes a performance hit, we can work harder to preserve those
2083     // results until we get here but it's likely not worth it.
2084     bool MemberOfUnknownSpecialization;
2085     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2086                        MemberOfUnknownSpecialization);
2087 
2088     if (MemberOfUnknownSpecialization ||
2089         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2090       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2091                                         IsAddressOfOperand, TemplateArgs);
2092   } else {
2093     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2094     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2095 
2096     // If the result might be in a dependent base class, this is a dependent
2097     // id-expression.
2098     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2099       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2100                                         IsAddressOfOperand, TemplateArgs);
2101 
2102     // If this reference is in an Objective-C method, then we need to do
2103     // some special Objective-C lookup, too.
2104     if (IvarLookupFollowUp) {
2105       ExprResult E(LookupInObjCMethod(R, S, II, true));
2106       if (E.isInvalid())
2107         return ExprError();
2108 
2109       if (Expr *Ex = E.getAs<Expr>())
2110         return Ex;
2111     }
2112   }
2113 
2114   if (R.isAmbiguous())
2115     return ExprError();
2116 
2117   // This could be an implicitly declared function reference (legal in C90,
2118   // extension in C99, forbidden in C++).
2119   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2120     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2121     if (D) R.addDecl(D);
2122   }
2123 
2124   // Determine whether this name might be a candidate for
2125   // argument-dependent lookup.
2126   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2127 
2128   if (R.empty() && !ADL) {
2129     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2130       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2131                                                    TemplateKWLoc, TemplateArgs))
2132         return E;
2133     }
2134 
2135     // Don't diagnose an empty lookup for inline assembly.
2136     if (IsInlineAsmIdentifier)
2137       return ExprError();
2138 
2139     // If this name wasn't predeclared and if this is not a function
2140     // call, diagnose the problem.
2141     TypoExpr *TE = nullptr;
2142     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2143         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2144     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2145     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2146            "Typo correction callback misconfigured");
2147     if (CCC) {
2148       // Make sure the callback knows what the typo being diagnosed is.
2149       CCC->setTypoName(II);
2150       if (SS.isValid())
2151         CCC->setTypoNNS(SS.getScopeRep());
2152     }
2153     if (DiagnoseEmptyLookup(S, SS, R,
2154                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2155                             nullptr, None, &TE)) {
2156       if (TE && KeywordReplacement) {
2157         auto &State = getTypoExprState(TE);
2158         auto BestTC = State.Consumer->getNextCorrection();
2159         if (BestTC.isKeyword()) {
2160           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2161           if (State.DiagHandler)
2162             State.DiagHandler(BestTC);
2163           KeywordReplacement->startToken();
2164           KeywordReplacement->setKind(II->getTokenID());
2165           KeywordReplacement->setIdentifierInfo(II);
2166           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2167           // Clean up the state associated with the TypoExpr, since it has
2168           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2169           clearDelayedTypo(TE);
2170           // Signal that a correction to a keyword was performed by returning a
2171           // valid-but-null ExprResult.
2172           return (Expr*)nullptr;
2173         }
2174         State.Consumer->resetCorrectionStream();
2175       }
2176       return TE ? TE : ExprError();
2177     }
2178 
2179     assert(!R.empty() &&
2180            "DiagnoseEmptyLookup returned false but added no results");
2181 
2182     // If we found an Objective-C instance variable, let
2183     // LookupInObjCMethod build the appropriate expression to
2184     // reference the ivar.
2185     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2186       R.clear();
2187       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2188       // In a hopelessly buggy code, Objective-C instance variable
2189       // lookup fails and no expression will be built to reference it.
2190       if (!E.isInvalid() && !E.get())
2191         return ExprError();
2192       return E;
2193     }
2194   }
2195 
2196   // This is guaranteed from this point on.
2197   assert(!R.empty() || ADL);
2198 
2199   // Check whether this might be a C++ implicit instance member access.
2200   // C++ [class.mfct.non-static]p3:
2201   //   When an id-expression that is not part of a class member access
2202   //   syntax and not used to form a pointer to member is used in the
2203   //   body of a non-static member function of class X, if name lookup
2204   //   resolves the name in the id-expression to a non-static non-type
2205   //   member of some class C, the id-expression is transformed into a
2206   //   class member access expression using (*this) as the
2207   //   postfix-expression to the left of the . operator.
2208   //
2209   // But we don't actually need to do this for '&' operands if R
2210   // resolved to a function or overloaded function set, because the
2211   // expression is ill-formed if it actually works out to be a
2212   // non-static member function:
2213   //
2214   // C++ [expr.ref]p4:
2215   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2216   //   [t]he expression can be used only as the left-hand operand of a
2217   //   member function call.
2218   //
2219   // There are other safeguards against such uses, but it's important
2220   // to get this right here so that we don't end up making a
2221   // spuriously dependent expression if we're inside a dependent
2222   // instance method.
2223   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2224     bool MightBeImplicitMember;
2225     if (!IsAddressOfOperand)
2226       MightBeImplicitMember = true;
2227     else if (!SS.isEmpty())
2228       MightBeImplicitMember = false;
2229     else if (R.isOverloadedResult())
2230       MightBeImplicitMember = false;
2231     else if (R.isUnresolvableResult())
2232       MightBeImplicitMember = true;
2233     else
2234       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2235                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2236                               isa<MSPropertyDecl>(R.getFoundDecl());
2237 
2238     if (MightBeImplicitMember)
2239       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2240                                              R, TemplateArgs, S);
2241   }
2242 
2243   if (TemplateArgs || TemplateKWLoc.isValid()) {
2244 
2245     // In C++1y, if this is a variable template id, then check it
2246     // in BuildTemplateIdExpr().
2247     // The single lookup result must be a variable template declaration.
2248     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2249         Id.TemplateId->Kind == TNK_Var_template) {
2250       assert(R.getAsSingle<VarTemplateDecl>() &&
2251              "There should only be one declaration found.");
2252     }
2253 
2254     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2255   }
2256 
2257   return BuildDeclarationNameExpr(SS, R, ADL);
2258 }
2259 
2260 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2261 /// declaration name, generally during template instantiation.
2262 /// There's a large number of things which don't need to be done along
2263 /// this path.
2264 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2265     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2266     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2267   DeclContext *DC = computeDeclContext(SS, false);
2268   if (!DC)
2269     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2270                                      NameInfo, /*TemplateArgs=*/nullptr);
2271 
2272   if (RequireCompleteDeclContext(SS, DC))
2273     return ExprError();
2274 
2275   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2276   LookupQualifiedName(R, DC);
2277 
2278   if (R.isAmbiguous())
2279     return ExprError();
2280 
2281   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2282     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2283                                      NameInfo, /*TemplateArgs=*/nullptr);
2284 
2285   if (R.empty()) {
2286     Diag(NameInfo.getLoc(), diag::err_no_member)
2287       << NameInfo.getName() << DC << SS.getRange();
2288     return ExprError();
2289   }
2290 
2291   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2292     // Diagnose a missing typename if this resolved unambiguously to a type in
2293     // a dependent context.  If we can recover with a type, downgrade this to
2294     // a warning in Microsoft compatibility mode.
2295     unsigned DiagID = diag::err_typename_missing;
2296     if (RecoveryTSI && getLangOpts().MSVCCompat)
2297       DiagID = diag::ext_typename_missing;
2298     SourceLocation Loc = SS.getBeginLoc();
2299     auto D = Diag(Loc, DiagID);
2300     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2301       << SourceRange(Loc, NameInfo.getEndLoc());
2302 
2303     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2304     // context.
2305     if (!RecoveryTSI)
2306       return ExprError();
2307 
2308     // Only issue the fixit if we're prepared to recover.
2309     D << FixItHint::CreateInsertion(Loc, "typename ");
2310 
2311     // Recover by pretending this was an elaborated type.
2312     QualType Ty = Context.getTypeDeclType(TD);
2313     TypeLocBuilder TLB;
2314     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2315 
2316     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2317     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2318     QTL.setElaboratedKeywordLoc(SourceLocation());
2319     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2320 
2321     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2322 
2323     return ExprEmpty();
2324   }
2325 
2326   // Defend against this resolving to an implicit member access. We usually
2327   // won't get here if this might be a legitimate a class member (we end up in
2328   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2329   // a pointer-to-member or in an unevaluated context in C++11.
2330   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2331     return BuildPossibleImplicitMemberExpr(SS,
2332                                            /*TemplateKWLoc=*/SourceLocation(),
2333                                            R, /*TemplateArgs=*/nullptr, S);
2334 
2335   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2336 }
2337 
2338 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2339 /// detected that we're currently inside an ObjC method.  Perform some
2340 /// additional lookup.
2341 ///
2342 /// Ideally, most of this would be done by lookup, but there's
2343 /// actually quite a lot of extra work involved.
2344 ///
2345 /// Returns a null sentinel to indicate trivial success.
2346 ExprResult
2347 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2348                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2349   SourceLocation Loc = Lookup.getNameLoc();
2350   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2351 
2352   // Check for error condition which is already reported.
2353   if (!CurMethod)
2354     return ExprError();
2355 
2356   // There are two cases to handle here.  1) scoped lookup could have failed,
2357   // in which case we should look for an ivar.  2) scoped lookup could have
2358   // found a decl, but that decl is outside the current instance method (i.e.
2359   // a global variable).  In these two cases, we do a lookup for an ivar with
2360   // this name, if the lookup sucedes, we replace it our current decl.
2361 
2362   // If we're in a class method, we don't normally want to look for
2363   // ivars.  But if we don't find anything else, and there's an
2364   // ivar, that's an error.
2365   bool IsClassMethod = CurMethod->isClassMethod();
2366 
2367   bool LookForIvars;
2368   if (Lookup.empty())
2369     LookForIvars = true;
2370   else if (IsClassMethod)
2371     LookForIvars = false;
2372   else
2373     LookForIvars = (Lookup.isSingleResult() &&
2374                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2375   ObjCInterfaceDecl *IFace = nullptr;
2376   if (LookForIvars) {
2377     IFace = CurMethod->getClassInterface();
2378     ObjCInterfaceDecl *ClassDeclared;
2379     ObjCIvarDecl *IV = nullptr;
2380     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2381       // Diagnose using an ivar in a class method.
2382       if (IsClassMethod)
2383         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2384                          << IV->getDeclName());
2385 
2386       // If we're referencing an invalid decl, just return this as a silent
2387       // error node.  The error diagnostic was already emitted on the decl.
2388       if (IV->isInvalidDecl())
2389         return ExprError();
2390 
2391       // Check if referencing a field with __attribute__((deprecated)).
2392       if (DiagnoseUseOfDecl(IV, Loc))
2393         return ExprError();
2394 
2395       // Diagnose the use of an ivar outside of the declaring class.
2396       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2397           !declaresSameEntity(ClassDeclared, IFace) &&
2398           !getLangOpts().DebuggerSupport)
2399         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2400 
2401       // FIXME: This should use a new expr for a direct reference, don't
2402       // turn this into Self->ivar, just return a BareIVarExpr or something.
2403       IdentifierInfo &II = Context.Idents.get("self");
2404       UnqualifiedId SelfName;
2405       SelfName.setIdentifier(&II, SourceLocation());
2406       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2407       CXXScopeSpec SelfScopeSpec;
2408       SourceLocation TemplateKWLoc;
2409       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2410                                               SelfName, false, false);
2411       if (SelfExpr.isInvalid())
2412         return ExprError();
2413 
2414       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2415       if (SelfExpr.isInvalid())
2416         return ExprError();
2417 
2418       MarkAnyDeclReferenced(Loc, IV, true);
2419 
2420       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2421       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2422           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2423         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2424 
2425       ObjCIvarRefExpr *Result = new (Context)
2426           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2427                           IV->getLocation(), SelfExpr.get(), true, true);
2428 
2429       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2430         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2431           recordUseOfEvaluatedWeak(Result);
2432       }
2433       if (getLangOpts().ObjCAutoRefCount) {
2434         if (CurContext->isClosure())
2435           Diag(Loc, diag::warn_implicitly_retains_self)
2436             << FixItHint::CreateInsertion(Loc, "self->");
2437       }
2438 
2439       return Result;
2440     }
2441   } else if (CurMethod->isInstanceMethod()) {
2442     // We should warn if a local variable hides an ivar.
2443     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2444       ObjCInterfaceDecl *ClassDeclared;
2445       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2446         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2447             declaresSameEntity(IFace, ClassDeclared))
2448           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2449       }
2450     }
2451   } else if (Lookup.isSingleResult() &&
2452              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2453     // If accessing a stand-alone ivar in a class method, this is an error.
2454     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2455       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2456                        << IV->getDeclName());
2457   }
2458 
2459   if (Lookup.empty() && II && AllowBuiltinCreation) {
2460     // FIXME. Consolidate this with similar code in LookupName.
2461     if (unsigned BuiltinID = II->getBuiltinID()) {
2462       if (!(getLangOpts().CPlusPlus &&
2463             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2464         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2465                                            S, Lookup.isForRedeclaration(),
2466                                            Lookup.getNameLoc());
2467         if (D) Lookup.addDecl(D);
2468       }
2469     }
2470   }
2471   // Sentinel value saying that we didn't do anything special.
2472   return ExprResult((Expr *)nullptr);
2473 }
2474 
2475 /// \brief Cast a base object to a member's actual type.
2476 ///
2477 /// Logically this happens in three phases:
2478 ///
2479 /// * First we cast from the base type to the naming class.
2480 ///   The naming class is the class into which we were looking
2481 ///   when we found the member;  it's the qualifier type if a
2482 ///   qualifier was provided, and otherwise it's the base type.
2483 ///
2484 /// * Next we cast from the naming class to the declaring class.
2485 ///   If the member we found was brought into a class's scope by
2486 ///   a using declaration, this is that class;  otherwise it's
2487 ///   the class declaring the member.
2488 ///
2489 /// * Finally we cast from the declaring class to the "true"
2490 ///   declaring class of the member.  This conversion does not
2491 ///   obey access control.
2492 ExprResult
2493 Sema::PerformObjectMemberConversion(Expr *From,
2494                                     NestedNameSpecifier *Qualifier,
2495                                     NamedDecl *FoundDecl,
2496                                     NamedDecl *Member) {
2497   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2498   if (!RD)
2499     return From;
2500 
2501   QualType DestRecordType;
2502   QualType DestType;
2503   QualType FromRecordType;
2504   QualType FromType = From->getType();
2505   bool PointerConversions = false;
2506   if (isa<FieldDecl>(Member)) {
2507     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2508 
2509     if (FromType->getAs<PointerType>()) {
2510       DestType = Context.getPointerType(DestRecordType);
2511       FromRecordType = FromType->getPointeeType();
2512       PointerConversions = true;
2513     } else {
2514       DestType = DestRecordType;
2515       FromRecordType = FromType;
2516     }
2517   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2518     if (Method->isStatic())
2519       return From;
2520 
2521     DestType = Method->getThisType(Context);
2522     DestRecordType = DestType->getPointeeType();
2523 
2524     if (FromType->getAs<PointerType>()) {
2525       FromRecordType = FromType->getPointeeType();
2526       PointerConversions = true;
2527     } else {
2528       FromRecordType = FromType;
2529       DestType = DestRecordType;
2530     }
2531   } else {
2532     // No conversion necessary.
2533     return From;
2534   }
2535 
2536   if (DestType->isDependentType() || FromType->isDependentType())
2537     return From;
2538 
2539   // If the unqualified types are the same, no conversion is necessary.
2540   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2541     return From;
2542 
2543   SourceRange FromRange = From->getSourceRange();
2544   SourceLocation FromLoc = FromRange.getBegin();
2545 
2546   ExprValueKind VK = From->getValueKind();
2547 
2548   // C++ [class.member.lookup]p8:
2549   //   [...] Ambiguities can often be resolved by qualifying a name with its
2550   //   class name.
2551   //
2552   // If the member was a qualified name and the qualified referred to a
2553   // specific base subobject type, we'll cast to that intermediate type
2554   // first and then to the object in which the member is declared. That allows
2555   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2556   //
2557   //   class Base { public: int x; };
2558   //   class Derived1 : public Base { };
2559   //   class Derived2 : public Base { };
2560   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2561   //
2562   //   void VeryDerived::f() {
2563   //     x = 17; // error: ambiguous base subobjects
2564   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2565   //   }
2566   if (Qualifier && Qualifier->getAsType()) {
2567     QualType QType = QualType(Qualifier->getAsType(), 0);
2568     assert(QType->isRecordType() && "lookup done with non-record type");
2569 
2570     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2571 
2572     // In C++98, the qualifier type doesn't actually have to be a base
2573     // type of the object type, in which case we just ignore it.
2574     // Otherwise build the appropriate casts.
2575     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2576       CXXCastPath BasePath;
2577       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2578                                        FromLoc, FromRange, &BasePath))
2579         return ExprError();
2580 
2581       if (PointerConversions)
2582         QType = Context.getPointerType(QType);
2583       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2584                                VK, &BasePath).get();
2585 
2586       FromType = QType;
2587       FromRecordType = QRecordType;
2588 
2589       // If the qualifier type was the same as the destination type,
2590       // we're done.
2591       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2592         return From;
2593     }
2594   }
2595 
2596   bool IgnoreAccess = false;
2597 
2598   // If we actually found the member through a using declaration, cast
2599   // down to the using declaration's type.
2600   //
2601   // Pointer equality is fine here because only one declaration of a
2602   // class ever has member declarations.
2603   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2604     assert(isa<UsingShadowDecl>(FoundDecl));
2605     QualType URecordType = Context.getTypeDeclType(
2606                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2607 
2608     // We only need to do this if the naming-class to declaring-class
2609     // conversion is non-trivial.
2610     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2611       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2612       CXXCastPath BasePath;
2613       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2614                                        FromLoc, FromRange, &BasePath))
2615         return ExprError();
2616 
2617       QualType UType = URecordType;
2618       if (PointerConversions)
2619         UType = Context.getPointerType(UType);
2620       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2621                                VK, &BasePath).get();
2622       FromType = UType;
2623       FromRecordType = URecordType;
2624     }
2625 
2626     // We don't do access control for the conversion from the
2627     // declaring class to the true declaring class.
2628     IgnoreAccess = true;
2629   }
2630 
2631   CXXCastPath BasePath;
2632   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2633                                    FromLoc, FromRange, &BasePath,
2634                                    IgnoreAccess))
2635     return ExprError();
2636 
2637   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2638                            VK, &BasePath);
2639 }
2640 
2641 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2642                                       const LookupResult &R,
2643                                       bool HasTrailingLParen) {
2644   // Only when used directly as the postfix-expression of a call.
2645   if (!HasTrailingLParen)
2646     return false;
2647 
2648   // Never if a scope specifier was provided.
2649   if (SS.isSet())
2650     return false;
2651 
2652   // Only in C++ or ObjC++.
2653   if (!getLangOpts().CPlusPlus)
2654     return false;
2655 
2656   // Turn off ADL when we find certain kinds of declarations during
2657   // normal lookup:
2658   for (NamedDecl *D : R) {
2659     // C++0x [basic.lookup.argdep]p3:
2660     //     -- a declaration of a class member
2661     // Since using decls preserve this property, we check this on the
2662     // original decl.
2663     if (D->isCXXClassMember())
2664       return false;
2665 
2666     // C++0x [basic.lookup.argdep]p3:
2667     //     -- a block-scope function declaration that is not a
2668     //        using-declaration
2669     // NOTE: we also trigger this for function templates (in fact, we
2670     // don't check the decl type at all, since all other decl types
2671     // turn off ADL anyway).
2672     if (isa<UsingShadowDecl>(D))
2673       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2674     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2675       return false;
2676 
2677     // C++0x [basic.lookup.argdep]p3:
2678     //     -- a declaration that is neither a function or a function
2679     //        template
2680     // And also for builtin functions.
2681     if (isa<FunctionDecl>(D)) {
2682       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2683 
2684       // But also builtin functions.
2685       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2686         return false;
2687     } else if (!isa<FunctionTemplateDecl>(D))
2688       return false;
2689   }
2690 
2691   return true;
2692 }
2693 
2694 
2695 /// Diagnoses obvious problems with the use of the given declaration
2696 /// as an expression.  This is only actually called for lookups that
2697 /// were not overloaded, and it doesn't promise that the declaration
2698 /// will in fact be used.
2699 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2700   if (D->isInvalidDecl())
2701     return true;
2702 
2703   if (isa<TypedefNameDecl>(D)) {
2704     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2705     return true;
2706   }
2707 
2708   if (isa<ObjCInterfaceDecl>(D)) {
2709     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2710     return true;
2711   }
2712 
2713   if (isa<NamespaceDecl>(D)) {
2714     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2715     return true;
2716   }
2717 
2718   return false;
2719 }
2720 
2721 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2722                                           LookupResult &R, bool NeedsADL,
2723                                           bool AcceptInvalidDecl) {
2724   // If this is a single, fully-resolved result and we don't need ADL,
2725   // just build an ordinary singleton decl ref.
2726   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2727     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2728                                     R.getRepresentativeDecl(), nullptr,
2729                                     AcceptInvalidDecl);
2730 
2731   // We only need to check the declaration if there's exactly one
2732   // result, because in the overloaded case the results can only be
2733   // functions and function templates.
2734   if (R.isSingleResult() &&
2735       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2736     return ExprError();
2737 
2738   // Otherwise, just build an unresolved lookup expression.  Suppress
2739   // any lookup-related diagnostics; we'll hash these out later, when
2740   // we've picked a target.
2741   R.suppressDiagnostics();
2742 
2743   UnresolvedLookupExpr *ULE
2744     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2745                                    SS.getWithLocInContext(Context),
2746                                    R.getLookupNameInfo(),
2747                                    NeedsADL, R.isOverloadedResult(),
2748                                    R.begin(), R.end());
2749 
2750   return ULE;
2751 }
2752 
2753 static void
2754 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2755                                    ValueDecl *var, DeclContext *DC);
2756 
2757 /// \brief Complete semantic analysis for a reference to the given declaration.
2758 ExprResult Sema::BuildDeclarationNameExpr(
2759     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2760     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2761     bool AcceptInvalidDecl) {
2762   assert(D && "Cannot refer to a NULL declaration");
2763   assert(!isa<FunctionTemplateDecl>(D) &&
2764          "Cannot refer unambiguously to a function template");
2765 
2766   SourceLocation Loc = NameInfo.getLoc();
2767   if (CheckDeclInExpr(*this, Loc, D))
2768     return ExprError();
2769 
2770   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2771     // Specifically diagnose references to class templates that are missing
2772     // a template argument list.
2773     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2774                                            << Template << SS.getRange();
2775     Diag(Template->getLocation(), diag::note_template_decl_here);
2776     return ExprError();
2777   }
2778 
2779   // Make sure that we're referring to a value.
2780   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2781   if (!VD) {
2782     Diag(Loc, diag::err_ref_non_value)
2783       << D << SS.getRange();
2784     Diag(D->getLocation(), diag::note_declared_at);
2785     return ExprError();
2786   }
2787 
2788   // Check whether this declaration can be used. Note that we suppress
2789   // this check when we're going to perform argument-dependent lookup
2790   // on this function name, because this might not be the function
2791   // that overload resolution actually selects.
2792   if (DiagnoseUseOfDecl(VD, Loc))
2793     return ExprError();
2794 
2795   // Only create DeclRefExpr's for valid Decl's.
2796   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2797     return ExprError();
2798 
2799   // Handle members of anonymous structs and unions.  If we got here,
2800   // and the reference is to a class member indirect field, then this
2801   // must be the subject of a pointer-to-member expression.
2802   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2803     if (!indirectField->isCXXClassMember())
2804       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2805                                                       indirectField);
2806 
2807   {
2808     QualType type = VD->getType();
2809     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2810       // C++ [except.spec]p17:
2811       //   An exception-specification is considered to be needed when:
2812       //   - in an expression, the function is the unique lookup result or
2813       //     the selected member of a set of overloaded functions.
2814       ResolveExceptionSpec(Loc, FPT);
2815       type = VD->getType();
2816     }
2817     ExprValueKind valueKind = VK_RValue;
2818 
2819     switch (D->getKind()) {
2820     // Ignore all the non-ValueDecl kinds.
2821 #define ABSTRACT_DECL(kind)
2822 #define VALUE(type, base)
2823 #define DECL(type, base) \
2824     case Decl::type:
2825 #include "clang/AST/DeclNodes.inc"
2826       llvm_unreachable("invalid value decl kind");
2827 
2828     // These shouldn't make it here.
2829     case Decl::ObjCAtDefsField:
2830     case Decl::ObjCIvar:
2831       llvm_unreachable("forming non-member reference to ivar?");
2832 
2833     // Enum constants are always r-values and never references.
2834     // Unresolved using declarations are dependent.
2835     case Decl::EnumConstant:
2836     case Decl::UnresolvedUsingValue:
2837     case Decl::OMPDeclareReduction:
2838       valueKind = VK_RValue;
2839       break;
2840 
2841     // Fields and indirect fields that got here must be for
2842     // pointer-to-member expressions; we just call them l-values for
2843     // internal consistency, because this subexpression doesn't really
2844     // exist in the high-level semantics.
2845     case Decl::Field:
2846     case Decl::IndirectField:
2847       assert(getLangOpts().CPlusPlus &&
2848              "building reference to field in C?");
2849 
2850       // These can't have reference type in well-formed programs, but
2851       // for internal consistency we do this anyway.
2852       type = type.getNonReferenceType();
2853       valueKind = VK_LValue;
2854       break;
2855 
2856     // Non-type template parameters are either l-values or r-values
2857     // depending on the type.
2858     case Decl::NonTypeTemplateParm: {
2859       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2860         type = reftype->getPointeeType();
2861         valueKind = VK_LValue; // even if the parameter is an r-value reference
2862         break;
2863       }
2864 
2865       // For non-references, we need to strip qualifiers just in case
2866       // the template parameter was declared as 'const int' or whatever.
2867       valueKind = VK_RValue;
2868       type = type.getUnqualifiedType();
2869       break;
2870     }
2871 
2872     case Decl::Var:
2873     case Decl::VarTemplateSpecialization:
2874     case Decl::VarTemplatePartialSpecialization:
2875     case Decl::Decomposition:
2876     case Decl::OMPCapturedExpr:
2877       // In C, "extern void blah;" is valid and is an r-value.
2878       if (!getLangOpts().CPlusPlus &&
2879           !type.hasQualifiers() &&
2880           type->isVoidType()) {
2881         valueKind = VK_RValue;
2882         break;
2883       }
2884       // fallthrough
2885 
2886     case Decl::ImplicitParam:
2887     case Decl::ParmVar: {
2888       // These are always l-values.
2889       valueKind = VK_LValue;
2890       type = type.getNonReferenceType();
2891 
2892       // FIXME: Does the addition of const really only apply in
2893       // potentially-evaluated contexts? Since the variable isn't actually
2894       // captured in an unevaluated context, it seems that the answer is no.
2895       if (!isUnevaluatedContext()) {
2896         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2897         if (!CapturedType.isNull())
2898           type = CapturedType;
2899       }
2900 
2901       break;
2902     }
2903 
2904     case Decl::Binding: {
2905       // These are always lvalues.
2906       valueKind = VK_LValue;
2907       type = type.getNonReferenceType();
2908       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2909       // decides how that's supposed to work.
2910       auto *BD = cast<BindingDecl>(VD);
2911       if (BD->getDeclContext()->isFunctionOrMethod() &&
2912           BD->getDeclContext() != CurContext)
2913         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2914       break;
2915     }
2916 
2917     case Decl::Function: {
2918       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2919         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2920           type = Context.BuiltinFnTy;
2921           valueKind = VK_RValue;
2922           break;
2923         }
2924       }
2925 
2926       const FunctionType *fty = type->castAs<FunctionType>();
2927 
2928       // If we're referring to a function with an __unknown_anytype
2929       // result type, make the entire expression __unknown_anytype.
2930       if (fty->getReturnType() == Context.UnknownAnyTy) {
2931         type = Context.UnknownAnyTy;
2932         valueKind = VK_RValue;
2933         break;
2934       }
2935 
2936       // Functions are l-values in C++.
2937       if (getLangOpts().CPlusPlus) {
2938         valueKind = VK_LValue;
2939         break;
2940       }
2941 
2942       // C99 DR 316 says that, if a function type comes from a
2943       // function definition (without a prototype), that type is only
2944       // used for checking compatibility. Therefore, when referencing
2945       // the function, we pretend that we don't have the full function
2946       // type.
2947       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2948           isa<FunctionProtoType>(fty))
2949         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2950                                               fty->getExtInfo());
2951 
2952       // Functions are r-values in C.
2953       valueKind = VK_RValue;
2954       break;
2955     }
2956 
2957     case Decl::CXXDeductionGuide:
2958       llvm_unreachable("building reference to deduction guide");
2959 
2960     case Decl::MSProperty:
2961       valueKind = VK_LValue;
2962       break;
2963 
2964     case Decl::CXXMethod:
2965       // If we're referring to a method with an __unknown_anytype
2966       // result type, make the entire expression __unknown_anytype.
2967       // This should only be possible with a type written directly.
2968       if (const FunctionProtoType *proto
2969             = dyn_cast<FunctionProtoType>(VD->getType()))
2970         if (proto->getReturnType() == Context.UnknownAnyTy) {
2971           type = Context.UnknownAnyTy;
2972           valueKind = VK_RValue;
2973           break;
2974         }
2975 
2976       // C++ methods are l-values if static, r-values if non-static.
2977       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2978         valueKind = VK_LValue;
2979         break;
2980       }
2981       // fallthrough
2982 
2983     case Decl::CXXConversion:
2984     case Decl::CXXDestructor:
2985     case Decl::CXXConstructor:
2986       valueKind = VK_RValue;
2987       break;
2988     }
2989 
2990     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2991                             TemplateArgs);
2992   }
2993 }
2994 
2995 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2996                                     SmallString<32> &Target) {
2997   Target.resize(CharByteWidth * (Source.size() + 1));
2998   char *ResultPtr = &Target[0];
2999   const llvm::UTF8 *ErrorPtr;
3000   bool success =
3001       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3002   (void)success;
3003   assert(success);
3004   Target.resize(ResultPtr - &Target[0]);
3005 }
3006 
3007 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3008                                      PredefinedExpr::IdentType IT) {
3009   // Pick the current block, lambda, captured statement or function.
3010   Decl *currentDecl = nullptr;
3011   if (const BlockScopeInfo *BSI = getCurBlock())
3012     currentDecl = BSI->TheDecl;
3013   else if (const LambdaScopeInfo *LSI = getCurLambda())
3014     currentDecl = LSI->CallOperator;
3015   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3016     currentDecl = CSI->TheCapturedDecl;
3017   else
3018     currentDecl = getCurFunctionOrMethodDecl();
3019 
3020   if (!currentDecl) {
3021     Diag(Loc, diag::ext_predef_outside_function);
3022     currentDecl = Context.getTranslationUnitDecl();
3023   }
3024 
3025   QualType ResTy;
3026   StringLiteral *SL = nullptr;
3027   if (cast<DeclContext>(currentDecl)->isDependentContext())
3028     ResTy = Context.DependentTy;
3029   else {
3030     // Pre-defined identifiers are of type char[x], where x is the length of
3031     // the string.
3032     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3033     unsigned Length = Str.length();
3034 
3035     llvm::APInt LengthI(32, Length + 1);
3036     if (IT == PredefinedExpr::LFunction) {
3037       ResTy = Context.WideCharTy.withConst();
3038       SmallString<32> RawChars;
3039       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3040                               Str, RawChars);
3041       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3042                                            /*IndexTypeQuals*/ 0);
3043       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3044                                  /*Pascal*/ false, ResTy, Loc);
3045     } else {
3046       ResTy = Context.CharTy.withConst();
3047       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3048                                            /*IndexTypeQuals*/ 0);
3049       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3050                                  /*Pascal*/ false, ResTy, Loc);
3051     }
3052   }
3053 
3054   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3055 }
3056 
3057 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3058   PredefinedExpr::IdentType IT;
3059 
3060   switch (Kind) {
3061   default: llvm_unreachable("Unknown simple primary expr!");
3062   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3063   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3064   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3065   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3066   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3067   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3068   }
3069 
3070   return BuildPredefinedExpr(Loc, IT);
3071 }
3072 
3073 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3074   SmallString<16> CharBuffer;
3075   bool Invalid = false;
3076   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3077   if (Invalid)
3078     return ExprError();
3079 
3080   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3081                             PP, Tok.getKind());
3082   if (Literal.hadError())
3083     return ExprError();
3084 
3085   QualType Ty;
3086   if (Literal.isWide())
3087     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3088   else if (Literal.isUTF16())
3089     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3090   else if (Literal.isUTF32())
3091     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3092   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3093     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3094   else
3095     Ty = Context.CharTy;  // 'x' -> char in C++
3096 
3097   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3098   if (Literal.isWide())
3099     Kind = CharacterLiteral::Wide;
3100   else if (Literal.isUTF16())
3101     Kind = CharacterLiteral::UTF16;
3102   else if (Literal.isUTF32())
3103     Kind = CharacterLiteral::UTF32;
3104   else if (Literal.isUTF8())
3105     Kind = CharacterLiteral::UTF8;
3106 
3107   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3108                                              Tok.getLocation());
3109 
3110   if (Literal.getUDSuffix().empty())
3111     return Lit;
3112 
3113   // We're building a user-defined literal.
3114   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3115   SourceLocation UDSuffixLoc =
3116     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3117 
3118   // Make sure we're allowed user-defined literals here.
3119   if (!UDLScope)
3120     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3121 
3122   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3123   //   operator "" X (ch)
3124   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3125                                         Lit, Tok.getLocation());
3126 }
3127 
3128 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3129   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3130   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3131                                 Context.IntTy, Loc);
3132 }
3133 
3134 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3135                                   QualType Ty, SourceLocation Loc) {
3136   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3137 
3138   using llvm::APFloat;
3139   APFloat Val(Format);
3140 
3141   APFloat::opStatus result = Literal.GetFloatValue(Val);
3142 
3143   // Overflow is always an error, but underflow is only an error if
3144   // we underflowed to zero (APFloat reports denormals as underflow).
3145   if ((result & APFloat::opOverflow) ||
3146       ((result & APFloat::opUnderflow) && Val.isZero())) {
3147     unsigned diagnostic;
3148     SmallString<20> buffer;
3149     if (result & APFloat::opOverflow) {
3150       diagnostic = diag::warn_float_overflow;
3151       APFloat::getLargest(Format).toString(buffer);
3152     } else {
3153       diagnostic = diag::warn_float_underflow;
3154       APFloat::getSmallest(Format).toString(buffer);
3155     }
3156 
3157     S.Diag(Loc, diagnostic)
3158       << Ty
3159       << StringRef(buffer.data(), buffer.size());
3160   }
3161 
3162   bool isExact = (result == APFloat::opOK);
3163   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3164 }
3165 
3166 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3167   assert(E && "Invalid expression");
3168 
3169   if (E->isValueDependent())
3170     return false;
3171 
3172   QualType QT = E->getType();
3173   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3174     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3175     return true;
3176   }
3177 
3178   llvm::APSInt ValueAPS;
3179   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3180 
3181   if (R.isInvalid())
3182     return true;
3183 
3184   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3185   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3186     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3187         << ValueAPS.toString(10) << ValueIsPositive;
3188     return true;
3189   }
3190 
3191   return false;
3192 }
3193 
3194 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3195   // Fast path for a single digit (which is quite common).  A single digit
3196   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3197   if (Tok.getLength() == 1) {
3198     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3199     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3200   }
3201 
3202   SmallString<128> SpellingBuffer;
3203   // NumericLiteralParser wants to overread by one character.  Add padding to
3204   // the buffer in case the token is copied to the buffer.  If getSpelling()
3205   // returns a StringRef to the memory buffer, it should have a null char at
3206   // the EOF, so it is also safe.
3207   SpellingBuffer.resize(Tok.getLength() + 1);
3208 
3209   // Get the spelling of the token, which eliminates trigraphs, etc.
3210   bool Invalid = false;
3211   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3212   if (Invalid)
3213     return ExprError();
3214 
3215   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3216   if (Literal.hadError)
3217     return ExprError();
3218 
3219   if (Literal.hasUDSuffix()) {
3220     // We're building a user-defined literal.
3221     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3222     SourceLocation UDSuffixLoc =
3223       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3224 
3225     // Make sure we're allowed user-defined literals here.
3226     if (!UDLScope)
3227       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3228 
3229     QualType CookedTy;
3230     if (Literal.isFloatingLiteral()) {
3231       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3232       // long double, the literal is treated as a call of the form
3233       //   operator "" X (f L)
3234       CookedTy = Context.LongDoubleTy;
3235     } else {
3236       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3237       // unsigned long long, the literal is treated as a call of the form
3238       //   operator "" X (n ULL)
3239       CookedTy = Context.UnsignedLongLongTy;
3240     }
3241 
3242     DeclarationName OpName =
3243       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3244     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3245     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3246 
3247     SourceLocation TokLoc = Tok.getLocation();
3248 
3249     // Perform literal operator lookup to determine if we're building a raw
3250     // literal or a cooked one.
3251     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3252     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3253                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3254                                   /*AllowStringTemplate*/false)) {
3255     case LOLR_Error:
3256       return ExprError();
3257 
3258     case LOLR_Cooked: {
3259       Expr *Lit;
3260       if (Literal.isFloatingLiteral()) {
3261         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3262       } else {
3263         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3264         if (Literal.GetIntegerValue(ResultVal))
3265           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3266               << /* Unsigned */ 1;
3267         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3268                                      Tok.getLocation());
3269       }
3270       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3271     }
3272 
3273     case LOLR_Raw: {
3274       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3275       // literal is treated as a call of the form
3276       //   operator "" X ("n")
3277       unsigned Length = Literal.getUDSuffixOffset();
3278       QualType StrTy = Context.getConstantArrayType(
3279           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3280           ArrayType::Normal, 0);
3281       Expr *Lit = StringLiteral::Create(
3282           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3283           /*Pascal*/false, StrTy, &TokLoc, 1);
3284       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3285     }
3286 
3287     case LOLR_Template: {
3288       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3289       // template), L is treated as a call fo the form
3290       //   operator "" X <'c1', 'c2', ... 'ck'>()
3291       // where n is the source character sequence c1 c2 ... ck.
3292       TemplateArgumentListInfo ExplicitArgs;
3293       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3294       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3295       llvm::APSInt Value(CharBits, CharIsUnsigned);
3296       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3297         Value = TokSpelling[I];
3298         TemplateArgument Arg(Context, Value, Context.CharTy);
3299         TemplateArgumentLocInfo ArgInfo;
3300         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3301       }
3302       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3303                                       &ExplicitArgs);
3304     }
3305     case LOLR_StringTemplate:
3306       llvm_unreachable("unexpected literal operator lookup result");
3307     }
3308   }
3309 
3310   Expr *Res;
3311 
3312   if (Literal.isFloatingLiteral()) {
3313     QualType Ty;
3314     if (Literal.isHalf){
3315       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3316         Ty = Context.HalfTy;
3317       else {
3318         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3319         return ExprError();
3320       }
3321     } else if (Literal.isFloat)
3322       Ty = Context.FloatTy;
3323     else if (Literal.isLong)
3324       Ty = Context.LongDoubleTy;
3325     else if (Literal.isFloat128)
3326       Ty = Context.Float128Ty;
3327     else
3328       Ty = Context.DoubleTy;
3329 
3330     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3331 
3332     if (Ty == Context.DoubleTy) {
3333       if (getLangOpts().SinglePrecisionConstants) {
3334         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3335         if (BTy->getKind() != BuiltinType::Float) {
3336           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3337         }
3338       } else if (getLangOpts().OpenCL &&
3339                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3340         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3341         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3342         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3343       }
3344     }
3345   } else if (!Literal.isIntegerLiteral()) {
3346     return ExprError();
3347   } else {
3348     QualType Ty;
3349 
3350     // 'long long' is a C99 or C++11 feature.
3351     if (!getLangOpts().C99 && Literal.isLongLong) {
3352       if (getLangOpts().CPlusPlus)
3353         Diag(Tok.getLocation(),
3354              getLangOpts().CPlusPlus11 ?
3355              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3356       else
3357         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3358     }
3359 
3360     // Get the value in the widest-possible width.
3361     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3362     llvm::APInt ResultVal(MaxWidth, 0);
3363 
3364     if (Literal.GetIntegerValue(ResultVal)) {
3365       // If this value didn't fit into uintmax_t, error and force to ull.
3366       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3367           << /* Unsigned */ 1;
3368       Ty = Context.UnsignedLongLongTy;
3369       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3370              "long long is not intmax_t?");
3371     } else {
3372       // If this value fits into a ULL, try to figure out what else it fits into
3373       // according to the rules of C99 6.4.4.1p5.
3374 
3375       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3376       // be an unsigned int.
3377       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3378 
3379       // Check from smallest to largest, picking the smallest type we can.
3380       unsigned Width = 0;
3381 
3382       // Microsoft specific integer suffixes are explicitly sized.
3383       if (Literal.MicrosoftInteger) {
3384         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3385           Width = 8;
3386           Ty = Context.CharTy;
3387         } else {
3388           Width = Literal.MicrosoftInteger;
3389           Ty = Context.getIntTypeForBitwidth(Width,
3390                                              /*Signed=*/!Literal.isUnsigned);
3391         }
3392       }
3393 
3394       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3395         // Are int/unsigned possibilities?
3396         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3397 
3398         // Does it fit in a unsigned int?
3399         if (ResultVal.isIntN(IntSize)) {
3400           // Does it fit in a signed int?
3401           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3402             Ty = Context.IntTy;
3403           else if (AllowUnsigned)
3404             Ty = Context.UnsignedIntTy;
3405           Width = IntSize;
3406         }
3407       }
3408 
3409       // Are long/unsigned long possibilities?
3410       if (Ty.isNull() && !Literal.isLongLong) {
3411         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3412 
3413         // Does it fit in a unsigned long?
3414         if (ResultVal.isIntN(LongSize)) {
3415           // Does it fit in a signed long?
3416           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3417             Ty = Context.LongTy;
3418           else if (AllowUnsigned)
3419             Ty = Context.UnsignedLongTy;
3420           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3421           // is compatible.
3422           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3423             const unsigned LongLongSize =
3424                 Context.getTargetInfo().getLongLongWidth();
3425             Diag(Tok.getLocation(),
3426                  getLangOpts().CPlusPlus
3427                      ? Literal.isLong
3428                            ? diag::warn_old_implicitly_unsigned_long_cxx
3429                            : /*C++98 UB*/ diag::
3430                                  ext_old_implicitly_unsigned_long_cxx
3431                      : diag::warn_old_implicitly_unsigned_long)
3432                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3433                                             : /*will be ill-formed*/ 1);
3434             Ty = Context.UnsignedLongTy;
3435           }
3436           Width = LongSize;
3437         }
3438       }
3439 
3440       // Check long long if needed.
3441       if (Ty.isNull()) {
3442         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3443 
3444         // Does it fit in a unsigned long long?
3445         if (ResultVal.isIntN(LongLongSize)) {
3446           // Does it fit in a signed long long?
3447           // To be compatible with MSVC, hex integer literals ending with the
3448           // LL or i64 suffix are always signed in Microsoft mode.
3449           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3450               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3451             Ty = Context.LongLongTy;
3452           else if (AllowUnsigned)
3453             Ty = Context.UnsignedLongLongTy;
3454           Width = LongLongSize;
3455         }
3456       }
3457 
3458       // If we still couldn't decide a type, we probably have something that
3459       // does not fit in a signed long long, but has no U suffix.
3460       if (Ty.isNull()) {
3461         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3462         Ty = Context.UnsignedLongLongTy;
3463         Width = Context.getTargetInfo().getLongLongWidth();
3464       }
3465 
3466       if (ResultVal.getBitWidth() != Width)
3467         ResultVal = ResultVal.trunc(Width);
3468     }
3469     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3470   }
3471 
3472   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3473   if (Literal.isImaginary)
3474     Res = new (Context) ImaginaryLiteral(Res,
3475                                         Context.getComplexType(Res->getType()));
3476 
3477   return Res;
3478 }
3479 
3480 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3481   assert(E && "ActOnParenExpr() missing expr");
3482   return new (Context) ParenExpr(L, R, E);
3483 }
3484 
3485 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3486                                          SourceLocation Loc,
3487                                          SourceRange ArgRange) {
3488   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3489   // scalar or vector data type argument..."
3490   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3491   // type (C99 6.2.5p18) or void.
3492   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3493     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3494       << T << ArgRange;
3495     return true;
3496   }
3497 
3498   assert((T->isVoidType() || !T->isIncompleteType()) &&
3499          "Scalar types should always be complete");
3500   return false;
3501 }
3502 
3503 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3504                                            SourceLocation Loc,
3505                                            SourceRange ArgRange,
3506                                            UnaryExprOrTypeTrait TraitKind) {
3507   // Invalid types must be hard errors for SFINAE in C++.
3508   if (S.LangOpts.CPlusPlus)
3509     return true;
3510 
3511   // C99 6.5.3.4p1:
3512   if (T->isFunctionType() &&
3513       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3514     // sizeof(function)/alignof(function) is allowed as an extension.
3515     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3516       << TraitKind << ArgRange;
3517     return false;
3518   }
3519 
3520   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3521   // this is an error (OpenCL v1.1 s6.3.k)
3522   if (T->isVoidType()) {
3523     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3524                                         : diag::ext_sizeof_alignof_void_type;
3525     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3526     return false;
3527   }
3528 
3529   return true;
3530 }
3531 
3532 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3533                                              SourceLocation Loc,
3534                                              SourceRange ArgRange,
3535                                              UnaryExprOrTypeTrait TraitKind) {
3536   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3537   // runtime doesn't allow it.
3538   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3539     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3540       << T << (TraitKind == UETT_SizeOf)
3541       << ArgRange;
3542     return true;
3543   }
3544 
3545   return false;
3546 }
3547 
3548 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3549 /// pointer type is equal to T) and emit a warning if it is.
3550 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3551                                      Expr *E) {
3552   // Don't warn if the operation changed the type.
3553   if (T != E->getType())
3554     return;
3555 
3556   // Now look for array decays.
3557   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3558   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3559     return;
3560 
3561   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3562                                              << ICE->getType()
3563                                              << ICE->getSubExpr()->getType();
3564 }
3565 
3566 /// \brief Check the constraints on expression operands to unary type expression
3567 /// and type traits.
3568 ///
3569 /// Completes any types necessary and validates the constraints on the operand
3570 /// expression. The logic mostly mirrors the type-based overload, but may modify
3571 /// the expression as it completes the type for that expression through template
3572 /// instantiation, etc.
3573 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3574                                             UnaryExprOrTypeTrait ExprKind) {
3575   QualType ExprTy = E->getType();
3576   assert(!ExprTy->isReferenceType());
3577 
3578   if (ExprKind == UETT_VecStep)
3579     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3580                                         E->getSourceRange());
3581 
3582   // Whitelist some types as extensions
3583   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3584                                       E->getSourceRange(), ExprKind))
3585     return false;
3586 
3587   // 'alignof' applied to an expression only requires the base element type of
3588   // the expression to be complete. 'sizeof' requires the expression's type to
3589   // be complete (and will attempt to complete it if it's an array of unknown
3590   // bound).
3591   if (ExprKind == UETT_AlignOf) {
3592     if (RequireCompleteType(E->getExprLoc(),
3593                             Context.getBaseElementType(E->getType()),
3594                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3595                             E->getSourceRange()))
3596       return true;
3597   } else {
3598     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3599                                 ExprKind, E->getSourceRange()))
3600       return true;
3601   }
3602 
3603   // Completing the expression's type may have changed it.
3604   ExprTy = E->getType();
3605   assert(!ExprTy->isReferenceType());
3606 
3607   if (ExprTy->isFunctionType()) {
3608     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3609       << ExprKind << E->getSourceRange();
3610     return true;
3611   }
3612 
3613   // The operand for sizeof and alignof is in an unevaluated expression context,
3614   // so side effects could result in unintended consequences.
3615   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3616       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3617     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3618 
3619   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3620                                        E->getSourceRange(), ExprKind))
3621     return true;
3622 
3623   if (ExprKind == UETT_SizeOf) {
3624     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3625       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3626         QualType OType = PVD->getOriginalType();
3627         QualType Type = PVD->getType();
3628         if (Type->isPointerType() && OType->isArrayType()) {
3629           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3630             << Type << OType;
3631           Diag(PVD->getLocation(), diag::note_declared_at);
3632         }
3633       }
3634     }
3635 
3636     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3637     // decays into a pointer and returns an unintended result. This is most
3638     // likely a typo for "sizeof(array) op x".
3639     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3640       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3641                                BO->getLHS());
3642       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3643                                BO->getRHS());
3644     }
3645   }
3646 
3647   return false;
3648 }
3649 
3650 /// \brief Check the constraints on operands to unary expression and type
3651 /// traits.
3652 ///
3653 /// This will complete any types necessary, and validate the various constraints
3654 /// on those operands.
3655 ///
3656 /// The UsualUnaryConversions() function is *not* called by this routine.
3657 /// C99 6.3.2.1p[2-4] all state:
3658 ///   Except when it is the operand of the sizeof operator ...
3659 ///
3660 /// C++ [expr.sizeof]p4
3661 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3662 ///   standard conversions are not applied to the operand of sizeof.
3663 ///
3664 /// This policy is followed for all of the unary trait expressions.
3665 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3666                                             SourceLocation OpLoc,
3667                                             SourceRange ExprRange,
3668                                             UnaryExprOrTypeTrait ExprKind) {
3669   if (ExprType->isDependentType())
3670     return false;
3671 
3672   // C++ [expr.sizeof]p2:
3673   //     When applied to a reference or a reference type, the result
3674   //     is the size of the referenced type.
3675   // C++11 [expr.alignof]p3:
3676   //     When alignof is applied to a reference type, the result
3677   //     shall be the alignment of the referenced type.
3678   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3679     ExprType = Ref->getPointeeType();
3680 
3681   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3682   //   When alignof or _Alignof is applied to an array type, the result
3683   //   is the alignment of the element type.
3684   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3685     ExprType = Context.getBaseElementType(ExprType);
3686 
3687   if (ExprKind == UETT_VecStep)
3688     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3689 
3690   // Whitelist some types as extensions
3691   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3692                                       ExprKind))
3693     return false;
3694 
3695   if (RequireCompleteType(OpLoc, ExprType,
3696                           diag::err_sizeof_alignof_incomplete_type,
3697                           ExprKind, ExprRange))
3698     return true;
3699 
3700   if (ExprType->isFunctionType()) {
3701     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3702       << ExprKind << ExprRange;
3703     return true;
3704   }
3705 
3706   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3707                                        ExprKind))
3708     return true;
3709 
3710   return false;
3711 }
3712 
3713 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3714   E = E->IgnoreParens();
3715 
3716   // Cannot know anything else if the expression is dependent.
3717   if (E->isTypeDependent())
3718     return false;
3719 
3720   if (E->getObjectKind() == OK_BitField) {
3721     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3722        << 1 << E->getSourceRange();
3723     return true;
3724   }
3725 
3726   ValueDecl *D = nullptr;
3727   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3728     D = DRE->getDecl();
3729   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3730     D = ME->getMemberDecl();
3731   }
3732 
3733   // If it's a field, require the containing struct to have a
3734   // complete definition so that we can compute the layout.
3735   //
3736   // This can happen in C++11 onwards, either by naming the member
3737   // in a way that is not transformed into a member access expression
3738   // (in an unevaluated operand, for instance), or by naming the member
3739   // in a trailing-return-type.
3740   //
3741   // For the record, since __alignof__ on expressions is a GCC
3742   // extension, GCC seems to permit this but always gives the
3743   // nonsensical answer 0.
3744   //
3745   // We don't really need the layout here --- we could instead just
3746   // directly check for all the appropriate alignment-lowing
3747   // attributes --- but that would require duplicating a lot of
3748   // logic that just isn't worth duplicating for such a marginal
3749   // use-case.
3750   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3751     // Fast path this check, since we at least know the record has a
3752     // definition if we can find a member of it.
3753     if (!FD->getParent()->isCompleteDefinition()) {
3754       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3755         << E->getSourceRange();
3756       return true;
3757     }
3758 
3759     // Otherwise, if it's a field, and the field doesn't have
3760     // reference type, then it must have a complete type (or be a
3761     // flexible array member, which we explicitly want to
3762     // white-list anyway), which makes the following checks trivial.
3763     if (!FD->getType()->isReferenceType())
3764       return false;
3765   }
3766 
3767   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3768 }
3769 
3770 bool Sema::CheckVecStepExpr(Expr *E) {
3771   E = E->IgnoreParens();
3772 
3773   // Cannot know anything else if the expression is dependent.
3774   if (E->isTypeDependent())
3775     return false;
3776 
3777   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3778 }
3779 
3780 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3781                                         CapturingScopeInfo *CSI) {
3782   assert(T->isVariablyModifiedType());
3783   assert(CSI != nullptr);
3784 
3785   // We're going to walk down into the type and look for VLA expressions.
3786   do {
3787     const Type *Ty = T.getTypePtr();
3788     switch (Ty->getTypeClass()) {
3789 #define TYPE(Class, Base)
3790 #define ABSTRACT_TYPE(Class, Base)
3791 #define NON_CANONICAL_TYPE(Class, Base)
3792 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3793 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3794 #include "clang/AST/TypeNodes.def"
3795       T = QualType();
3796       break;
3797     // These types are never variably-modified.
3798     case Type::Builtin:
3799     case Type::Complex:
3800     case Type::Vector:
3801     case Type::ExtVector:
3802     case Type::Record:
3803     case Type::Enum:
3804     case Type::Elaborated:
3805     case Type::TemplateSpecialization:
3806     case Type::ObjCObject:
3807     case Type::ObjCInterface:
3808     case Type::ObjCObjectPointer:
3809     case Type::ObjCTypeParam:
3810     case Type::Pipe:
3811       llvm_unreachable("type class is never variably-modified!");
3812     case Type::Adjusted:
3813       T = cast<AdjustedType>(Ty)->getOriginalType();
3814       break;
3815     case Type::Decayed:
3816       T = cast<DecayedType>(Ty)->getPointeeType();
3817       break;
3818     case Type::Pointer:
3819       T = cast<PointerType>(Ty)->getPointeeType();
3820       break;
3821     case Type::BlockPointer:
3822       T = cast<BlockPointerType>(Ty)->getPointeeType();
3823       break;
3824     case Type::LValueReference:
3825     case Type::RValueReference:
3826       T = cast<ReferenceType>(Ty)->getPointeeType();
3827       break;
3828     case Type::MemberPointer:
3829       T = cast<MemberPointerType>(Ty)->getPointeeType();
3830       break;
3831     case Type::ConstantArray:
3832     case Type::IncompleteArray:
3833       // Losing element qualification here is fine.
3834       T = cast<ArrayType>(Ty)->getElementType();
3835       break;
3836     case Type::VariableArray: {
3837       // Losing element qualification here is fine.
3838       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3839 
3840       // Unknown size indication requires no size computation.
3841       // Otherwise, evaluate and record it.
3842       if (auto Size = VAT->getSizeExpr()) {
3843         if (!CSI->isVLATypeCaptured(VAT)) {
3844           RecordDecl *CapRecord = nullptr;
3845           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3846             CapRecord = LSI->Lambda;
3847           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3848             CapRecord = CRSI->TheRecordDecl;
3849           }
3850           if (CapRecord) {
3851             auto ExprLoc = Size->getExprLoc();
3852             auto SizeType = Context.getSizeType();
3853             // Build the non-static data member.
3854             auto Field =
3855                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3856                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3857                                   /*BW*/ nullptr, /*Mutable*/ false,
3858                                   /*InitStyle*/ ICIS_NoInit);
3859             Field->setImplicit(true);
3860             Field->setAccess(AS_private);
3861             Field->setCapturedVLAType(VAT);
3862             CapRecord->addDecl(Field);
3863 
3864             CSI->addVLATypeCapture(ExprLoc, SizeType);
3865           }
3866         }
3867       }
3868       T = VAT->getElementType();
3869       break;
3870     }
3871     case Type::FunctionProto:
3872     case Type::FunctionNoProto:
3873       T = cast<FunctionType>(Ty)->getReturnType();
3874       break;
3875     case Type::Paren:
3876     case Type::TypeOf:
3877     case Type::UnaryTransform:
3878     case Type::Attributed:
3879     case Type::SubstTemplateTypeParm:
3880     case Type::PackExpansion:
3881       // Keep walking after single level desugaring.
3882       T = T.getSingleStepDesugaredType(Context);
3883       break;
3884     case Type::Typedef:
3885       T = cast<TypedefType>(Ty)->desugar();
3886       break;
3887     case Type::Decltype:
3888       T = cast<DecltypeType>(Ty)->desugar();
3889       break;
3890     case Type::Auto:
3891     case Type::DeducedTemplateSpecialization:
3892       T = cast<DeducedType>(Ty)->getDeducedType();
3893       break;
3894     case Type::TypeOfExpr:
3895       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3896       break;
3897     case Type::Atomic:
3898       T = cast<AtomicType>(Ty)->getValueType();
3899       break;
3900     }
3901   } while (!T.isNull() && T->isVariablyModifiedType());
3902 }
3903 
3904 /// \brief Build a sizeof or alignof expression given a type operand.
3905 ExprResult
3906 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3907                                      SourceLocation OpLoc,
3908                                      UnaryExprOrTypeTrait ExprKind,
3909                                      SourceRange R) {
3910   if (!TInfo)
3911     return ExprError();
3912 
3913   QualType T = TInfo->getType();
3914 
3915   if (!T->isDependentType() &&
3916       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3917     return ExprError();
3918 
3919   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3920     if (auto *TT = T->getAs<TypedefType>()) {
3921       for (auto I = FunctionScopes.rbegin(),
3922                 E = std::prev(FunctionScopes.rend());
3923            I != E; ++I) {
3924         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3925         if (CSI == nullptr)
3926           break;
3927         DeclContext *DC = nullptr;
3928         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3929           DC = LSI->CallOperator;
3930         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3931           DC = CRSI->TheCapturedDecl;
3932         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3933           DC = BSI->TheDecl;
3934         if (DC) {
3935           if (DC->containsDecl(TT->getDecl()))
3936             break;
3937           captureVariablyModifiedType(Context, T, CSI);
3938         }
3939       }
3940     }
3941   }
3942 
3943   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3944   return new (Context) UnaryExprOrTypeTraitExpr(
3945       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3946 }
3947 
3948 /// \brief Build a sizeof or alignof expression given an expression
3949 /// operand.
3950 ExprResult
3951 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3952                                      UnaryExprOrTypeTrait ExprKind) {
3953   ExprResult PE = CheckPlaceholderExpr(E);
3954   if (PE.isInvalid())
3955     return ExprError();
3956 
3957   E = PE.get();
3958 
3959   // Verify that the operand is valid.
3960   bool isInvalid = false;
3961   if (E->isTypeDependent()) {
3962     // Delay type-checking for type-dependent expressions.
3963   } else if (ExprKind == UETT_AlignOf) {
3964     isInvalid = CheckAlignOfExpr(*this, E);
3965   } else if (ExprKind == UETT_VecStep) {
3966     isInvalid = CheckVecStepExpr(E);
3967   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3968       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3969       isInvalid = true;
3970   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3971     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3972     isInvalid = true;
3973   } else {
3974     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3975   }
3976 
3977   if (isInvalid)
3978     return ExprError();
3979 
3980   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3981     PE = TransformToPotentiallyEvaluated(E);
3982     if (PE.isInvalid()) return ExprError();
3983     E = PE.get();
3984   }
3985 
3986   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3987   return new (Context) UnaryExprOrTypeTraitExpr(
3988       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3989 }
3990 
3991 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3992 /// expr and the same for @c alignof and @c __alignof
3993 /// Note that the ArgRange is invalid if isType is false.
3994 ExprResult
3995 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3996                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3997                                     void *TyOrEx, SourceRange ArgRange) {
3998   // If error parsing type, ignore.
3999   if (!TyOrEx) return ExprError();
4000 
4001   if (IsType) {
4002     TypeSourceInfo *TInfo;
4003     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4004     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4005   }
4006 
4007   Expr *ArgEx = (Expr *)TyOrEx;
4008   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4009   return Result;
4010 }
4011 
4012 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4013                                      bool IsReal) {
4014   if (V.get()->isTypeDependent())
4015     return S.Context.DependentTy;
4016 
4017   // _Real and _Imag are only l-values for normal l-values.
4018   if (V.get()->getObjectKind() != OK_Ordinary) {
4019     V = S.DefaultLvalueConversion(V.get());
4020     if (V.isInvalid())
4021       return QualType();
4022   }
4023 
4024   // These operators return the element type of a complex type.
4025   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4026     return CT->getElementType();
4027 
4028   // Otherwise they pass through real integer and floating point types here.
4029   if (V.get()->getType()->isArithmeticType())
4030     return V.get()->getType();
4031 
4032   // Test for placeholders.
4033   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4034   if (PR.isInvalid()) return QualType();
4035   if (PR.get() != V.get()) {
4036     V = PR;
4037     return CheckRealImagOperand(S, V, Loc, IsReal);
4038   }
4039 
4040   // Reject anything else.
4041   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4042     << (IsReal ? "__real" : "__imag");
4043   return QualType();
4044 }
4045 
4046 
4047 
4048 ExprResult
4049 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4050                           tok::TokenKind Kind, Expr *Input) {
4051   UnaryOperatorKind Opc;
4052   switch (Kind) {
4053   default: llvm_unreachable("Unknown unary op!");
4054   case tok::plusplus:   Opc = UO_PostInc; break;
4055   case tok::minusminus: Opc = UO_PostDec; break;
4056   }
4057 
4058   // Since this might is a postfix expression, get rid of ParenListExprs.
4059   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4060   if (Result.isInvalid()) return ExprError();
4061   Input = Result.get();
4062 
4063   return BuildUnaryOp(S, OpLoc, Opc, Input);
4064 }
4065 
4066 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4067 ///
4068 /// \return true on error
4069 static bool checkArithmeticOnObjCPointer(Sema &S,
4070                                          SourceLocation opLoc,
4071                                          Expr *op) {
4072   assert(op->getType()->isObjCObjectPointerType());
4073   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4074       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4075     return false;
4076 
4077   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4078     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4079     << op->getSourceRange();
4080   return true;
4081 }
4082 
4083 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4084   auto *BaseNoParens = Base->IgnoreParens();
4085   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4086     return MSProp->getPropertyDecl()->getType()->isArrayType();
4087   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4088 }
4089 
4090 ExprResult
4091 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4092                               Expr *idx, SourceLocation rbLoc) {
4093   if (base && !base->getType().isNull() &&
4094       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4095     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4096                                     /*Length=*/nullptr, rbLoc);
4097 
4098   // Since this might be a postfix expression, get rid of ParenListExprs.
4099   if (isa<ParenListExpr>(base)) {
4100     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4101     if (result.isInvalid()) return ExprError();
4102     base = result.get();
4103   }
4104 
4105   // Handle any non-overload placeholder types in the base and index
4106   // expressions.  We can't handle overloads here because the other
4107   // operand might be an overloadable type, in which case the overload
4108   // resolution for the operator overload should get the first crack
4109   // at the overload.
4110   bool IsMSPropertySubscript = false;
4111   if (base->getType()->isNonOverloadPlaceholderType()) {
4112     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4113     if (!IsMSPropertySubscript) {
4114       ExprResult result = CheckPlaceholderExpr(base);
4115       if (result.isInvalid())
4116         return ExprError();
4117       base = result.get();
4118     }
4119   }
4120   if (idx->getType()->isNonOverloadPlaceholderType()) {
4121     ExprResult result = CheckPlaceholderExpr(idx);
4122     if (result.isInvalid()) return ExprError();
4123     idx = result.get();
4124   }
4125 
4126   // Build an unanalyzed expression if either operand is type-dependent.
4127   if (getLangOpts().CPlusPlus &&
4128       (base->isTypeDependent() || idx->isTypeDependent())) {
4129     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4130                                             VK_LValue, OK_Ordinary, rbLoc);
4131   }
4132 
4133   // MSDN, property (C++)
4134   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4135   // This attribute can also be used in the declaration of an empty array in a
4136   // class or structure definition. For example:
4137   // __declspec(property(get=GetX, put=PutX)) int x[];
4138   // The above statement indicates that x[] can be used with one or more array
4139   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4140   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4141   if (IsMSPropertySubscript) {
4142     // Build MS property subscript expression if base is MS property reference
4143     // or MS property subscript.
4144     return new (Context) MSPropertySubscriptExpr(
4145         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4146   }
4147 
4148   // Use C++ overloaded-operator rules if either operand has record
4149   // type.  The spec says to do this if either type is *overloadable*,
4150   // but enum types can't declare subscript operators or conversion
4151   // operators, so there's nothing interesting for overload resolution
4152   // to do if there aren't any record types involved.
4153   //
4154   // ObjC pointers have their own subscripting logic that is not tied
4155   // to overload resolution and so should not take this path.
4156   if (getLangOpts().CPlusPlus &&
4157       (base->getType()->isRecordType() ||
4158        (!base->getType()->isObjCObjectPointerType() &&
4159         idx->getType()->isRecordType()))) {
4160     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4161   }
4162 
4163   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4164 }
4165 
4166 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4167                                           Expr *LowerBound,
4168                                           SourceLocation ColonLoc, Expr *Length,
4169                                           SourceLocation RBLoc) {
4170   if (Base->getType()->isPlaceholderType() &&
4171       !Base->getType()->isSpecificPlaceholderType(
4172           BuiltinType::OMPArraySection)) {
4173     ExprResult Result = CheckPlaceholderExpr(Base);
4174     if (Result.isInvalid())
4175       return ExprError();
4176     Base = Result.get();
4177   }
4178   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4179     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4180     if (Result.isInvalid())
4181       return ExprError();
4182     Result = DefaultLvalueConversion(Result.get());
4183     if (Result.isInvalid())
4184       return ExprError();
4185     LowerBound = Result.get();
4186   }
4187   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4188     ExprResult Result = CheckPlaceholderExpr(Length);
4189     if (Result.isInvalid())
4190       return ExprError();
4191     Result = DefaultLvalueConversion(Result.get());
4192     if (Result.isInvalid())
4193       return ExprError();
4194     Length = Result.get();
4195   }
4196 
4197   // Build an unanalyzed expression if either operand is type-dependent.
4198   if (Base->isTypeDependent() ||
4199       (LowerBound &&
4200        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4201       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4202     return new (Context)
4203         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4204                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4205   }
4206 
4207   // Perform default conversions.
4208   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4209   QualType ResultTy;
4210   if (OriginalTy->isAnyPointerType()) {
4211     ResultTy = OriginalTy->getPointeeType();
4212   } else if (OriginalTy->isArrayType()) {
4213     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4214   } else {
4215     return ExprError(
4216         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4217         << Base->getSourceRange());
4218   }
4219   // C99 6.5.2.1p1
4220   if (LowerBound) {
4221     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4222                                                       LowerBound);
4223     if (Res.isInvalid())
4224       return ExprError(Diag(LowerBound->getExprLoc(),
4225                             diag::err_omp_typecheck_section_not_integer)
4226                        << 0 << LowerBound->getSourceRange());
4227     LowerBound = Res.get();
4228 
4229     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4230         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4231       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4232           << 0 << LowerBound->getSourceRange();
4233   }
4234   if (Length) {
4235     auto Res =
4236         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4237     if (Res.isInvalid())
4238       return ExprError(Diag(Length->getExprLoc(),
4239                             diag::err_omp_typecheck_section_not_integer)
4240                        << 1 << Length->getSourceRange());
4241     Length = Res.get();
4242 
4243     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4244         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4245       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4246           << 1 << Length->getSourceRange();
4247   }
4248 
4249   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4250   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4251   // type. Note that functions are not objects, and that (in C99 parlance)
4252   // incomplete types are not object types.
4253   if (ResultTy->isFunctionType()) {
4254     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4255         << ResultTy << Base->getSourceRange();
4256     return ExprError();
4257   }
4258 
4259   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4260                           diag::err_omp_section_incomplete_type, Base))
4261     return ExprError();
4262 
4263   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4264     llvm::APSInt LowerBoundValue;
4265     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4266       // OpenMP 4.5, [2.4 Array Sections]
4267       // The array section must be a subset of the original array.
4268       if (LowerBoundValue.isNegative()) {
4269         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4270             << LowerBound->getSourceRange();
4271         return ExprError();
4272       }
4273     }
4274   }
4275 
4276   if (Length) {
4277     llvm::APSInt LengthValue;
4278     if (Length->EvaluateAsInt(LengthValue, Context)) {
4279       // OpenMP 4.5, [2.4 Array Sections]
4280       // The length must evaluate to non-negative integers.
4281       if (LengthValue.isNegative()) {
4282         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4283             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4284             << Length->getSourceRange();
4285         return ExprError();
4286       }
4287     }
4288   } else if (ColonLoc.isValid() &&
4289              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4290                                       !OriginalTy->isVariableArrayType()))) {
4291     // OpenMP 4.5, [2.4 Array Sections]
4292     // When the size of the array dimension is not known, the length must be
4293     // specified explicitly.
4294     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4295         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4296     return ExprError();
4297   }
4298 
4299   if (!Base->getType()->isSpecificPlaceholderType(
4300           BuiltinType::OMPArraySection)) {
4301     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4302     if (Result.isInvalid())
4303       return ExprError();
4304     Base = Result.get();
4305   }
4306   return new (Context)
4307       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4308                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4309 }
4310 
4311 ExprResult
4312 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4313                                       Expr *Idx, SourceLocation RLoc) {
4314   Expr *LHSExp = Base;
4315   Expr *RHSExp = Idx;
4316 
4317   ExprValueKind VK = VK_LValue;
4318   ExprObjectKind OK = OK_Ordinary;
4319 
4320   // Per C++ core issue 1213, the result is an xvalue if either operand is
4321   // a non-lvalue array, and an lvalue otherwise.
4322   if (getLangOpts().CPlusPlus11 &&
4323       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4324        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4325     VK = VK_XValue;
4326 
4327   // Perform default conversions.
4328   if (!LHSExp->getType()->getAs<VectorType>()) {
4329     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4330     if (Result.isInvalid())
4331       return ExprError();
4332     LHSExp = Result.get();
4333   }
4334   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4335   if (Result.isInvalid())
4336     return ExprError();
4337   RHSExp = Result.get();
4338 
4339   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4340 
4341   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4342   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4343   // in the subscript position. As a result, we need to derive the array base
4344   // and index from the expression types.
4345   Expr *BaseExpr, *IndexExpr;
4346   QualType ResultType;
4347   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4348     BaseExpr = LHSExp;
4349     IndexExpr = RHSExp;
4350     ResultType = Context.DependentTy;
4351   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4352     BaseExpr = LHSExp;
4353     IndexExpr = RHSExp;
4354     ResultType = PTy->getPointeeType();
4355   } else if (const ObjCObjectPointerType *PTy =
4356                LHSTy->getAs<ObjCObjectPointerType>()) {
4357     BaseExpr = LHSExp;
4358     IndexExpr = RHSExp;
4359 
4360     // Use custom logic if this should be the pseudo-object subscript
4361     // expression.
4362     if (!LangOpts.isSubscriptPointerArithmetic())
4363       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4364                                           nullptr);
4365 
4366     ResultType = PTy->getPointeeType();
4367   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4368      // Handle the uncommon case of "123[Ptr]".
4369     BaseExpr = RHSExp;
4370     IndexExpr = LHSExp;
4371     ResultType = PTy->getPointeeType();
4372   } else if (const ObjCObjectPointerType *PTy =
4373                RHSTy->getAs<ObjCObjectPointerType>()) {
4374      // Handle the uncommon case of "123[Ptr]".
4375     BaseExpr = RHSExp;
4376     IndexExpr = LHSExp;
4377     ResultType = PTy->getPointeeType();
4378     if (!LangOpts.isSubscriptPointerArithmetic()) {
4379       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4380         << ResultType << BaseExpr->getSourceRange();
4381       return ExprError();
4382     }
4383   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4384     BaseExpr = LHSExp;    // vectors: V[123]
4385     IndexExpr = RHSExp;
4386     VK = LHSExp->getValueKind();
4387     if (VK != VK_RValue)
4388       OK = OK_VectorComponent;
4389 
4390     // FIXME: need to deal with const...
4391     ResultType = VTy->getElementType();
4392   } else if (LHSTy->isArrayType()) {
4393     // If we see an array that wasn't promoted by
4394     // DefaultFunctionArrayLvalueConversion, it must be an array that
4395     // wasn't promoted because of the C90 rule that doesn't
4396     // allow promoting non-lvalue arrays.  Warn, then
4397     // force the promotion here.
4398     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4399         LHSExp->getSourceRange();
4400     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4401                                CK_ArrayToPointerDecay).get();
4402     LHSTy = LHSExp->getType();
4403 
4404     BaseExpr = LHSExp;
4405     IndexExpr = RHSExp;
4406     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4407   } else if (RHSTy->isArrayType()) {
4408     // Same as previous, except for 123[f().a] case
4409     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4410         RHSExp->getSourceRange();
4411     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4412                                CK_ArrayToPointerDecay).get();
4413     RHSTy = RHSExp->getType();
4414 
4415     BaseExpr = RHSExp;
4416     IndexExpr = LHSExp;
4417     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4418   } else {
4419     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4420        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4421   }
4422   // C99 6.5.2.1p1
4423   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4424     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4425                      << IndexExpr->getSourceRange());
4426 
4427   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4428        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4429          && !IndexExpr->isTypeDependent())
4430     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4431 
4432   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4433   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4434   // type. Note that Functions are not objects, and that (in C99 parlance)
4435   // incomplete types are not object types.
4436   if (ResultType->isFunctionType()) {
4437     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4438       << ResultType << BaseExpr->getSourceRange();
4439     return ExprError();
4440   }
4441 
4442   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4443     // GNU extension: subscripting on pointer to void
4444     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4445       << BaseExpr->getSourceRange();
4446 
4447     // C forbids expressions of unqualified void type from being l-values.
4448     // See IsCForbiddenLValueType.
4449     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4450   } else if (!ResultType->isDependentType() &&
4451       RequireCompleteType(LLoc, ResultType,
4452                           diag::err_subscript_incomplete_type, BaseExpr))
4453     return ExprError();
4454 
4455   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4456          !ResultType.isCForbiddenLValueType());
4457 
4458   return new (Context)
4459       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4460 }
4461 
4462 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4463                                   ParmVarDecl *Param) {
4464   if (Param->hasUnparsedDefaultArg()) {
4465     Diag(CallLoc,
4466          diag::err_use_of_default_argument_to_function_declared_later) <<
4467       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4468     Diag(UnparsedDefaultArgLocs[Param],
4469          diag::note_default_argument_declared_here);
4470     return true;
4471   }
4472 
4473   if (Param->hasUninstantiatedDefaultArg()) {
4474     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4475 
4476     EnterExpressionEvaluationContext EvalContext(
4477         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4478 
4479     // Instantiate the expression.
4480     //
4481     // FIXME: Pass in a correct Pattern argument, otherwise
4482     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4483     //
4484     // template<typename T>
4485     // struct A {
4486     //   static int FooImpl();
4487     //
4488     //   template<typename Tp>
4489     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4490     //   // template argument list [[T], [Tp]], should be [[Tp]].
4491     //   friend A<Tp> Foo(int a);
4492     // };
4493     //
4494     // template<typename T>
4495     // A<T> Foo(int a = A<T>::FooImpl());
4496     MultiLevelTemplateArgumentList MutiLevelArgList
4497       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4498 
4499     InstantiatingTemplate Inst(*this, CallLoc, Param,
4500                                MutiLevelArgList.getInnermost());
4501     if (Inst.isInvalid())
4502       return true;
4503     if (Inst.isAlreadyInstantiating()) {
4504       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4505       Param->setInvalidDecl();
4506       return true;
4507     }
4508 
4509     ExprResult Result;
4510     {
4511       // C++ [dcl.fct.default]p5:
4512       //   The names in the [default argument] expression are bound, and
4513       //   the semantic constraints are checked, at the point where the
4514       //   default argument expression appears.
4515       ContextRAII SavedContext(*this, FD);
4516       LocalInstantiationScope Local(*this);
4517       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4518                                 /*DirectInit*/false);
4519     }
4520     if (Result.isInvalid())
4521       return true;
4522 
4523     // Check the expression as an initializer for the parameter.
4524     InitializedEntity Entity
4525       = InitializedEntity::InitializeParameter(Context, Param);
4526     InitializationKind Kind
4527       = InitializationKind::CreateCopy(Param->getLocation(),
4528              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4529     Expr *ResultE = Result.getAs<Expr>();
4530 
4531     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4532     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4533     if (Result.isInvalid())
4534       return true;
4535 
4536     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4537                                  Param->getOuterLocStart());
4538     if (Result.isInvalid())
4539       return true;
4540 
4541     // Remember the instantiated default argument.
4542     Param->setDefaultArg(Result.getAs<Expr>());
4543     if (ASTMutationListener *L = getASTMutationListener()) {
4544       L->DefaultArgumentInstantiated(Param);
4545     }
4546   }
4547 
4548   // If the default argument expression is not set yet, we are building it now.
4549   if (!Param->hasInit()) {
4550     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4551     Param->setInvalidDecl();
4552     return true;
4553   }
4554 
4555   // If the default expression creates temporaries, we need to
4556   // push them to the current stack of expression temporaries so they'll
4557   // be properly destroyed.
4558   // FIXME: We should really be rebuilding the default argument with new
4559   // bound temporaries; see the comment in PR5810.
4560   // We don't need to do that with block decls, though, because
4561   // blocks in default argument expression can never capture anything.
4562   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4563     // Set the "needs cleanups" bit regardless of whether there are
4564     // any explicit objects.
4565     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4566 
4567     // Append all the objects to the cleanup list.  Right now, this
4568     // should always be a no-op, because blocks in default argument
4569     // expressions should never be able to capture anything.
4570     assert(!Init->getNumObjects() &&
4571            "default argument expression has capturing blocks?");
4572   }
4573 
4574   // We already type-checked the argument, so we know it works.
4575   // Just mark all of the declarations in this potentially-evaluated expression
4576   // as being "referenced".
4577   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4578                                    /*SkipLocalVariables=*/true);
4579   return false;
4580 }
4581 
4582 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4583                                         FunctionDecl *FD, ParmVarDecl *Param) {
4584   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4585     return ExprError();
4586   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4587 }
4588 
4589 Sema::VariadicCallType
4590 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4591                           Expr *Fn) {
4592   if (Proto && Proto->isVariadic()) {
4593     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4594       return VariadicConstructor;
4595     else if (Fn && Fn->getType()->isBlockPointerType())
4596       return VariadicBlock;
4597     else if (FDecl) {
4598       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4599         if (Method->isInstance())
4600           return VariadicMethod;
4601     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4602       return VariadicMethod;
4603     return VariadicFunction;
4604   }
4605   return VariadicDoesNotApply;
4606 }
4607 
4608 namespace {
4609 class FunctionCallCCC : public FunctionCallFilterCCC {
4610 public:
4611   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4612                   unsigned NumArgs, MemberExpr *ME)
4613       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4614         FunctionName(FuncName) {}
4615 
4616   bool ValidateCandidate(const TypoCorrection &candidate) override {
4617     if (!candidate.getCorrectionSpecifier() ||
4618         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4619       return false;
4620     }
4621 
4622     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4623   }
4624 
4625 private:
4626   const IdentifierInfo *const FunctionName;
4627 };
4628 }
4629 
4630 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4631                                                FunctionDecl *FDecl,
4632                                                ArrayRef<Expr *> Args) {
4633   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4634   DeclarationName FuncName = FDecl->getDeclName();
4635   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4636 
4637   if (TypoCorrection Corrected = S.CorrectTypo(
4638           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4639           S.getScopeForContext(S.CurContext), nullptr,
4640           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4641                                              Args.size(), ME),
4642           Sema::CTK_ErrorRecovery)) {
4643     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4644       if (Corrected.isOverloaded()) {
4645         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4646         OverloadCandidateSet::iterator Best;
4647         for (NamedDecl *CD : Corrected) {
4648           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4649             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4650                                    OCS);
4651         }
4652         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4653         case OR_Success:
4654           ND = Best->FoundDecl;
4655           Corrected.setCorrectionDecl(ND);
4656           break;
4657         default:
4658           break;
4659         }
4660       }
4661       ND = ND->getUnderlyingDecl();
4662       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4663         return Corrected;
4664     }
4665   }
4666   return TypoCorrection();
4667 }
4668 
4669 /// ConvertArgumentsForCall - Converts the arguments specified in
4670 /// Args/NumArgs to the parameter types of the function FDecl with
4671 /// function prototype Proto. Call is the call expression itself, and
4672 /// Fn is the function expression. For a C++ member function, this
4673 /// routine does not attempt to convert the object argument. Returns
4674 /// true if the call is ill-formed.
4675 bool
4676 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4677                               FunctionDecl *FDecl,
4678                               const FunctionProtoType *Proto,
4679                               ArrayRef<Expr *> Args,
4680                               SourceLocation RParenLoc,
4681                               bool IsExecConfig) {
4682   // Bail out early if calling a builtin with custom typechecking.
4683   if (FDecl)
4684     if (unsigned ID = FDecl->getBuiltinID())
4685       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4686         return false;
4687 
4688   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4689   // assignment, to the types of the corresponding parameter, ...
4690   unsigned NumParams = Proto->getNumParams();
4691   bool Invalid = false;
4692   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4693   unsigned FnKind = Fn->getType()->isBlockPointerType()
4694                        ? 1 /* block */
4695                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4696                                        : 0 /* function */);
4697 
4698   // If too few arguments are available (and we don't have default
4699   // arguments for the remaining parameters), don't make the call.
4700   if (Args.size() < NumParams) {
4701     if (Args.size() < MinArgs) {
4702       TypoCorrection TC;
4703       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4704         unsigned diag_id =
4705             MinArgs == NumParams && !Proto->isVariadic()
4706                 ? diag::err_typecheck_call_too_few_args_suggest
4707                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4708         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4709                                         << static_cast<unsigned>(Args.size())
4710                                         << TC.getCorrectionRange());
4711       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4712         Diag(RParenLoc,
4713              MinArgs == NumParams && !Proto->isVariadic()
4714                  ? diag::err_typecheck_call_too_few_args_one
4715                  : diag::err_typecheck_call_too_few_args_at_least_one)
4716             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4717       else
4718         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4719                             ? diag::err_typecheck_call_too_few_args
4720                             : diag::err_typecheck_call_too_few_args_at_least)
4721             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4722             << Fn->getSourceRange();
4723 
4724       // Emit the location of the prototype.
4725       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4726         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4727           << FDecl;
4728 
4729       return true;
4730     }
4731     Call->setNumArgs(Context, NumParams);
4732   }
4733 
4734   // If too many are passed and not variadic, error on the extras and drop
4735   // them.
4736   if (Args.size() > NumParams) {
4737     if (!Proto->isVariadic()) {
4738       TypoCorrection TC;
4739       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4740         unsigned diag_id =
4741             MinArgs == NumParams && !Proto->isVariadic()
4742                 ? diag::err_typecheck_call_too_many_args_suggest
4743                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4744         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4745                                         << static_cast<unsigned>(Args.size())
4746                                         << TC.getCorrectionRange());
4747       } else if (NumParams == 1 && FDecl &&
4748                  FDecl->getParamDecl(0)->getDeclName())
4749         Diag(Args[NumParams]->getLocStart(),
4750              MinArgs == NumParams
4751                  ? diag::err_typecheck_call_too_many_args_one
4752                  : diag::err_typecheck_call_too_many_args_at_most_one)
4753             << FnKind << FDecl->getParamDecl(0)
4754             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4755             << SourceRange(Args[NumParams]->getLocStart(),
4756                            Args.back()->getLocEnd());
4757       else
4758         Diag(Args[NumParams]->getLocStart(),
4759              MinArgs == NumParams
4760                  ? diag::err_typecheck_call_too_many_args
4761                  : diag::err_typecheck_call_too_many_args_at_most)
4762             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4763             << Fn->getSourceRange()
4764             << SourceRange(Args[NumParams]->getLocStart(),
4765                            Args.back()->getLocEnd());
4766 
4767       // Emit the location of the prototype.
4768       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4769         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4770           << FDecl;
4771 
4772       // This deletes the extra arguments.
4773       Call->setNumArgs(Context, NumParams);
4774       return true;
4775     }
4776   }
4777   SmallVector<Expr *, 8> AllArgs;
4778   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4779 
4780   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4781                                    Proto, 0, Args, AllArgs, CallType);
4782   if (Invalid)
4783     return true;
4784   unsigned TotalNumArgs = AllArgs.size();
4785   for (unsigned i = 0; i < TotalNumArgs; ++i)
4786     Call->setArg(i, AllArgs[i]);
4787 
4788   return false;
4789 }
4790 
4791 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4792                                   const FunctionProtoType *Proto,
4793                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4794                                   SmallVectorImpl<Expr *> &AllArgs,
4795                                   VariadicCallType CallType, bool AllowExplicit,
4796                                   bool IsListInitialization) {
4797   unsigned NumParams = Proto->getNumParams();
4798   bool Invalid = false;
4799   size_t ArgIx = 0;
4800   // Continue to check argument types (even if we have too few/many args).
4801   for (unsigned i = FirstParam; i < NumParams; i++) {
4802     QualType ProtoArgType = Proto->getParamType(i);
4803 
4804     Expr *Arg;
4805     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4806     if (ArgIx < Args.size()) {
4807       Arg = Args[ArgIx++];
4808 
4809       if (RequireCompleteType(Arg->getLocStart(),
4810                               ProtoArgType,
4811                               diag::err_call_incomplete_argument, Arg))
4812         return true;
4813 
4814       // Strip the unbridged-cast placeholder expression off, if applicable.
4815       bool CFAudited = false;
4816       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4817           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4818           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4819         Arg = stripARCUnbridgedCast(Arg);
4820       else if (getLangOpts().ObjCAutoRefCount &&
4821                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4822                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4823         CFAudited = true;
4824 
4825       InitializedEntity Entity =
4826           Param ? InitializedEntity::InitializeParameter(Context, Param,
4827                                                          ProtoArgType)
4828                 : InitializedEntity::InitializeParameter(
4829                       Context, ProtoArgType, Proto->isParamConsumed(i));
4830 
4831       // Remember that parameter belongs to a CF audited API.
4832       if (CFAudited)
4833         Entity.setParameterCFAudited();
4834 
4835       ExprResult ArgE = PerformCopyInitialization(
4836           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4837       if (ArgE.isInvalid())
4838         return true;
4839 
4840       Arg = ArgE.getAs<Expr>();
4841     } else {
4842       assert(Param && "can't use default arguments without a known callee");
4843 
4844       ExprResult ArgExpr =
4845         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4846       if (ArgExpr.isInvalid())
4847         return true;
4848 
4849       Arg = ArgExpr.getAs<Expr>();
4850     }
4851 
4852     // Check for array bounds violations for each argument to the call. This
4853     // check only triggers warnings when the argument isn't a more complex Expr
4854     // with its own checking, such as a BinaryOperator.
4855     CheckArrayAccess(Arg);
4856 
4857     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4858     CheckStaticArrayArgument(CallLoc, Param, Arg);
4859 
4860     AllArgs.push_back(Arg);
4861   }
4862 
4863   // If this is a variadic call, handle args passed through "...".
4864   if (CallType != VariadicDoesNotApply) {
4865     // Assume that extern "C" functions with variadic arguments that
4866     // return __unknown_anytype aren't *really* variadic.
4867     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4868         FDecl->isExternC()) {
4869       for (Expr *A : Args.slice(ArgIx)) {
4870         QualType paramType; // ignored
4871         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4872         Invalid |= arg.isInvalid();
4873         AllArgs.push_back(arg.get());
4874       }
4875 
4876     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4877     } else {
4878       for (Expr *A : Args.slice(ArgIx)) {
4879         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4880         Invalid |= Arg.isInvalid();
4881         AllArgs.push_back(Arg.get());
4882       }
4883     }
4884 
4885     // Check for array bounds violations.
4886     for (Expr *A : Args.slice(ArgIx))
4887       CheckArrayAccess(A);
4888   }
4889   return Invalid;
4890 }
4891 
4892 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4893   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4894   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4895     TL = DTL.getOriginalLoc();
4896   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4897     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4898       << ATL.getLocalSourceRange();
4899 }
4900 
4901 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4902 /// array parameter, check that it is non-null, and that if it is formed by
4903 /// array-to-pointer decay, the underlying array is sufficiently large.
4904 ///
4905 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4906 /// array type derivation, then for each call to the function, the value of the
4907 /// corresponding actual argument shall provide access to the first element of
4908 /// an array with at least as many elements as specified by the size expression.
4909 void
4910 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4911                                ParmVarDecl *Param,
4912                                const Expr *ArgExpr) {
4913   // Static array parameters are not supported in C++.
4914   if (!Param || getLangOpts().CPlusPlus)
4915     return;
4916 
4917   QualType OrigTy = Param->getOriginalType();
4918 
4919   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4920   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4921     return;
4922 
4923   if (ArgExpr->isNullPointerConstant(Context,
4924                                      Expr::NPC_NeverValueDependent)) {
4925     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4926     DiagnoseCalleeStaticArrayParam(*this, Param);
4927     return;
4928   }
4929 
4930   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4931   if (!CAT)
4932     return;
4933 
4934   const ConstantArrayType *ArgCAT =
4935     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4936   if (!ArgCAT)
4937     return;
4938 
4939   if (ArgCAT->getSize().ult(CAT->getSize())) {
4940     Diag(CallLoc, diag::warn_static_array_too_small)
4941       << ArgExpr->getSourceRange()
4942       << (unsigned) ArgCAT->getSize().getZExtValue()
4943       << (unsigned) CAT->getSize().getZExtValue();
4944     DiagnoseCalleeStaticArrayParam(*this, Param);
4945   }
4946 }
4947 
4948 /// Given a function expression of unknown-any type, try to rebuild it
4949 /// to have a function type.
4950 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4951 
4952 /// Is the given type a placeholder that we need to lower out
4953 /// immediately during argument processing?
4954 static bool isPlaceholderToRemoveAsArg(QualType type) {
4955   // Placeholders are never sugared.
4956   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4957   if (!placeholder) return false;
4958 
4959   switch (placeholder->getKind()) {
4960   // Ignore all the non-placeholder types.
4961 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4962   case BuiltinType::Id:
4963 #include "clang/Basic/OpenCLImageTypes.def"
4964 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4965 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4966 #include "clang/AST/BuiltinTypes.def"
4967     return false;
4968 
4969   // We cannot lower out overload sets; they might validly be resolved
4970   // by the call machinery.
4971   case BuiltinType::Overload:
4972     return false;
4973 
4974   // Unbridged casts in ARC can be handled in some call positions and
4975   // should be left in place.
4976   case BuiltinType::ARCUnbridgedCast:
4977     return false;
4978 
4979   // Pseudo-objects should be converted as soon as possible.
4980   case BuiltinType::PseudoObject:
4981     return true;
4982 
4983   // The debugger mode could theoretically but currently does not try
4984   // to resolve unknown-typed arguments based on known parameter types.
4985   case BuiltinType::UnknownAny:
4986     return true;
4987 
4988   // These are always invalid as call arguments and should be reported.
4989   case BuiltinType::BoundMember:
4990   case BuiltinType::BuiltinFn:
4991   case BuiltinType::OMPArraySection:
4992     return true;
4993 
4994   }
4995   llvm_unreachable("bad builtin type kind");
4996 }
4997 
4998 /// Check an argument list for placeholders that we won't try to
4999 /// handle later.
5000 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5001   // Apply this processing to all the arguments at once instead of
5002   // dying at the first failure.
5003   bool hasInvalid = false;
5004   for (size_t i = 0, e = args.size(); i != e; i++) {
5005     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5006       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5007       if (result.isInvalid()) hasInvalid = true;
5008       else args[i] = result.get();
5009     } else if (hasInvalid) {
5010       (void)S.CorrectDelayedTyposInExpr(args[i]);
5011     }
5012   }
5013   return hasInvalid;
5014 }
5015 
5016 /// If a builtin function has a pointer argument with no explicit address
5017 /// space, then it should be able to accept a pointer to any address
5018 /// space as input.  In order to do this, we need to replace the
5019 /// standard builtin declaration with one that uses the same address space
5020 /// as the call.
5021 ///
5022 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5023 ///                  it does not contain any pointer arguments without
5024 ///                  an address space qualifer.  Otherwise the rewritten
5025 ///                  FunctionDecl is returned.
5026 /// TODO: Handle pointer return types.
5027 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5028                                                 const FunctionDecl *FDecl,
5029                                                 MultiExprArg ArgExprs) {
5030 
5031   QualType DeclType = FDecl->getType();
5032   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5033 
5034   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5035       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5036     return nullptr;
5037 
5038   bool NeedsNewDecl = false;
5039   unsigned i = 0;
5040   SmallVector<QualType, 8> OverloadParams;
5041 
5042   for (QualType ParamType : FT->param_types()) {
5043 
5044     // Convert array arguments to pointer to simplify type lookup.
5045     ExprResult ArgRes =
5046         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5047     if (ArgRes.isInvalid())
5048       return nullptr;
5049     Expr *Arg = ArgRes.get();
5050     QualType ArgType = Arg->getType();
5051     if (!ParamType->isPointerType() ||
5052         ParamType.getQualifiers().hasAddressSpace() ||
5053         !ArgType->isPointerType() ||
5054         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5055       OverloadParams.push_back(ParamType);
5056       continue;
5057     }
5058 
5059     NeedsNewDecl = true;
5060     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5061 
5062     QualType PointeeType = ParamType->getPointeeType();
5063     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5064     OverloadParams.push_back(Context.getPointerType(PointeeType));
5065   }
5066 
5067   if (!NeedsNewDecl)
5068     return nullptr;
5069 
5070   FunctionProtoType::ExtProtoInfo EPI;
5071   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5072                                                 OverloadParams, EPI);
5073   DeclContext *Parent = Context.getTranslationUnitDecl();
5074   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5075                                                     FDecl->getLocation(),
5076                                                     FDecl->getLocation(),
5077                                                     FDecl->getIdentifier(),
5078                                                     OverloadTy,
5079                                                     /*TInfo=*/nullptr,
5080                                                     SC_Extern, false,
5081                                                     /*hasPrototype=*/true);
5082   SmallVector<ParmVarDecl*, 16> Params;
5083   FT = cast<FunctionProtoType>(OverloadTy);
5084   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5085     QualType ParamType = FT->getParamType(i);
5086     ParmVarDecl *Parm =
5087         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5088                                 SourceLocation(), nullptr, ParamType,
5089                                 /*TInfo=*/nullptr, SC_None, nullptr);
5090     Parm->setScopeInfo(0, i);
5091     Params.push_back(Parm);
5092   }
5093   OverloadDecl->setParams(Params);
5094   return OverloadDecl;
5095 }
5096 
5097 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5098                                     FunctionDecl *Callee,
5099                                     MultiExprArg ArgExprs) {
5100   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5101   // similar attributes) really don't like it when functions are called with an
5102   // invalid number of args.
5103   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5104                          /*PartialOverloading=*/false) &&
5105       !Callee->isVariadic())
5106     return;
5107   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5108     return;
5109 
5110   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5111     S.Diag(Fn->getLocStart(),
5112            isa<CXXMethodDecl>(Callee)
5113                ? diag::err_ovl_no_viable_member_function_in_call
5114                : diag::err_ovl_no_viable_function_in_call)
5115         << Callee << Callee->getSourceRange();
5116     S.Diag(Callee->getLocation(),
5117            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5118         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5119     return;
5120   }
5121 }
5122 
5123 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5124 /// This provides the location of the left/right parens and a list of comma
5125 /// locations.
5126 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5127                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5128                                Expr *ExecConfig, bool IsExecConfig) {
5129   // Since this might be a postfix expression, get rid of ParenListExprs.
5130   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5131   if (Result.isInvalid()) return ExprError();
5132   Fn = Result.get();
5133 
5134   if (checkArgsForPlaceholders(*this, ArgExprs))
5135     return ExprError();
5136 
5137   if (getLangOpts().CPlusPlus) {
5138     // If this is a pseudo-destructor expression, build the call immediately.
5139     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5140       if (!ArgExprs.empty()) {
5141         // Pseudo-destructor calls should not have any arguments.
5142         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5143             << FixItHint::CreateRemoval(
5144                    SourceRange(ArgExprs.front()->getLocStart(),
5145                                ArgExprs.back()->getLocEnd()));
5146       }
5147 
5148       return new (Context)
5149           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5150     }
5151     if (Fn->getType() == Context.PseudoObjectTy) {
5152       ExprResult result = CheckPlaceholderExpr(Fn);
5153       if (result.isInvalid()) return ExprError();
5154       Fn = result.get();
5155     }
5156 
5157     // Determine whether this is a dependent call inside a C++ template,
5158     // in which case we won't do any semantic analysis now.
5159     bool Dependent = false;
5160     if (Fn->isTypeDependent())
5161       Dependent = true;
5162     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5163       Dependent = true;
5164 
5165     if (Dependent) {
5166       if (ExecConfig) {
5167         return new (Context) CUDAKernelCallExpr(
5168             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5169             Context.DependentTy, VK_RValue, RParenLoc);
5170       } else {
5171         return new (Context) CallExpr(
5172             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5173       }
5174     }
5175 
5176     // Determine whether this is a call to an object (C++ [over.call.object]).
5177     if (Fn->getType()->isRecordType())
5178       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5179                                           RParenLoc);
5180 
5181     if (Fn->getType() == Context.UnknownAnyTy) {
5182       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5183       if (result.isInvalid()) return ExprError();
5184       Fn = result.get();
5185     }
5186 
5187     if (Fn->getType() == Context.BoundMemberTy) {
5188       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5189                                        RParenLoc);
5190     }
5191   }
5192 
5193   // Check for overloaded calls.  This can happen even in C due to extensions.
5194   if (Fn->getType() == Context.OverloadTy) {
5195     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5196 
5197     // We aren't supposed to apply this logic if there's an '&' involved.
5198     if (!find.HasFormOfMemberPointer) {
5199       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5200         return new (Context) CallExpr(
5201             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5202       OverloadExpr *ovl = find.Expression;
5203       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5204         return BuildOverloadedCallExpr(
5205             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5206             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5207       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5208                                        RParenLoc);
5209     }
5210   }
5211 
5212   // If we're directly calling a function, get the appropriate declaration.
5213   if (Fn->getType() == Context.UnknownAnyTy) {
5214     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5215     if (result.isInvalid()) return ExprError();
5216     Fn = result.get();
5217   }
5218 
5219   Expr *NakedFn = Fn->IgnoreParens();
5220 
5221   bool CallingNDeclIndirectly = false;
5222   NamedDecl *NDecl = nullptr;
5223   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5224     if (UnOp->getOpcode() == UO_AddrOf) {
5225       CallingNDeclIndirectly = true;
5226       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5227     }
5228   }
5229 
5230   if (isa<DeclRefExpr>(NakedFn)) {
5231     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5232 
5233     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5234     if (FDecl && FDecl->getBuiltinID()) {
5235       // Rewrite the function decl for this builtin by replacing parameters
5236       // with no explicit address space with the address space of the arguments
5237       // in ArgExprs.
5238       if ((FDecl =
5239                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5240         NDecl = FDecl;
5241         Fn = DeclRefExpr::Create(
5242             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5243             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5244       }
5245     }
5246   } else if (isa<MemberExpr>(NakedFn))
5247     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5248 
5249   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5250     if (CallingNDeclIndirectly &&
5251         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5252                                            Fn->getLocStart()))
5253       return ExprError();
5254 
5255     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5256       return ExprError();
5257 
5258     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5259   }
5260 
5261   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5262                                ExecConfig, IsExecConfig);
5263 }
5264 
5265 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5266 ///
5267 /// __builtin_astype( value, dst type )
5268 ///
5269 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5270                                  SourceLocation BuiltinLoc,
5271                                  SourceLocation RParenLoc) {
5272   ExprValueKind VK = VK_RValue;
5273   ExprObjectKind OK = OK_Ordinary;
5274   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5275   QualType SrcTy = E->getType();
5276   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5277     return ExprError(Diag(BuiltinLoc,
5278                           diag::err_invalid_astype_of_different_size)
5279                      << DstTy
5280                      << SrcTy
5281                      << E->getSourceRange());
5282   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5283 }
5284 
5285 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5286 /// provided arguments.
5287 ///
5288 /// __builtin_convertvector( value, dst type )
5289 ///
5290 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5291                                         SourceLocation BuiltinLoc,
5292                                         SourceLocation RParenLoc) {
5293   TypeSourceInfo *TInfo;
5294   GetTypeFromParser(ParsedDestTy, &TInfo);
5295   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5296 }
5297 
5298 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5299 /// i.e. an expression not of \p OverloadTy.  The expression should
5300 /// unary-convert to an expression of function-pointer or
5301 /// block-pointer type.
5302 ///
5303 /// \param NDecl the declaration being called, if available
5304 ExprResult
5305 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5306                             SourceLocation LParenLoc,
5307                             ArrayRef<Expr *> Args,
5308                             SourceLocation RParenLoc,
5309                             Expr *Config, bool IsExecConfig) {
5310   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5311   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5312 
5313   // Functions with 'interrupt' attribute cannot be called directly.
5314   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5315     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5316     return ExprError();
5317   }
5318 
5319   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5320   // so there's some risk when calling out to non-interrupt handler functions
5321   // that the callee might not preserve them. This is easy to diagnose here,
5322   // but can be very challenging to debug.
5323   if (auto *Caller = getCurFunctionDecl())
5324     if (Caller->hasAttr<ARMInterruptAttr>()) {
5325       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5326       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5327         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5328     }
5329 
5330   // Promote the function operand.
5331   // We special-case function promotion here because we only allow promoting
5332   // builtin functions to function pointers in the callee of a call.
5333   ExprResult Result;
5334   if (BuiltinID &&
5335       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5336     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5337                                CK_BuiltinFnToFnPtr).get();
5338   } else {
5339     Result = CallExprUnaryConversions(Fn);
5340   }
5341   if (Result.isInvalid())
5342     return ExprError();
5343   Fn = Result.get();
5344 
5345   // Make the call expr early, before semantic checks.  This guarantees cleanup
5346   // of arguments and function on error.
5347   CallExpr *TheCall;
5348   if (Config)
5349     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5350                                                cast<CallExpr>(Config), Args,
5351                                                Context.BoolTy, VK_RValue,
5352                                                RParenLoc);
5353   else
5354     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5355                                      VK_RValue, RParenLoc);
5356 
5357   if (!getLangOpts().CPlusPlus) {
5358     // C cannot always handle TypoExpr nodes in builtin calls and direct
5359     // function calls as their argument checking don't necessarily handle
5360     // dependent types properly, so make sure any TypoExprs have been
5361     // dealt with.
5362     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5363     if (!Result.isUsable()) return ExprError();
5364     TheCall = dyn_cast<CallExpr>(Result.get());
5365     if (!TheCall) return Result;
5366     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5367   }
5368 
5369   // Bail out early if calling a builtin with custom typechecking.
5370   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5371     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5372 
5373  retry:
5374   const FunctionType *FuncT;
5375   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5376     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5377     // have type pointer to function".
5378     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5379     if (!FuncT)
5380       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5381                          << Fn->getType() << Fn->getSourceRange());
5382   } else if (const BlockPointerType *BPT =
5383                Fn->getType()->getAs<BlockPointerType>()) {
5384     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5385   } else {
5386     // Handle calls to expressions of unknown-any type.
5387     if (Fn->getType() == Context.UnknownAnyTy) {
5388       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5389       if (rewrite.isInvalid()) return ExprError();
5390       Fn = rewrite.get();
5391       TheCall->setCallee(Fn);
5392       goto retry;
5393     }
5394 
5395     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5396       << Fn->getType() << Fn->getSourceRange());
5397   }
5398 
5399   if (getLangOpts().CUDA) {
5400     if (Config) {
5401       // CUDA: Kernel calls must be to global functions
5402       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5403         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5404             << FDecl->getName() << Fn->getSourceRange());
5405 
5406       // CUDA: Kernel function must have 'void' return type
5407       if (!FuncT->getReturnType()->isVoidType())
5408         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5409             << Fn->getType() << Fn->getSourceRange());
5410     } else {
5411       // CUDA: Calls to global functions must be configured
5412       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5413         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5414             << FDecl->getName() << Fn->getSourceRange());
5415     }
5416   }
5417 
5418   // Check for a valid return type
5419   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5420                           FDecl))
5421     return ExprError();
5422 
5423   // We know the result type of the call, set it.
5424   TheCall->setType(FuncT->getCallResultType(Context));
5425   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5426 
5427   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5428   if (Proto) {
5429     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5430                                 IsExecConfig))
5431       return ExprError();
5432   } else {
5433     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5434 
5435     if (FDecl) {
5436       // Check if we have too few/too many template arguments, based
5437       // on our knowledge of the function definition.
5438       const FunctionDecl *Def = nullptr;
5439       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5440         Proto = Def->getType()->getAs<FunctionProtoType>();
5441        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5442           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5443           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5444       }
5445 
5446       // If the function we're calling isn't a function prototype, but we have
5447       // a function prototype from a prior declaratiom, use that prototype.
5448       if (!FDecl->hasPrototype())
5449         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5450     }
5451 
5452     // Promote the arguments (C99 6.5.2.2p6).
5453     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5454       Expr *Arg = Args[i];
5455 
5456       if (Proto && i < Proto->getNumParams()) {
5457         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5458             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5459         ExprResult ArgE =
5460             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5461         if (ArgE.isInvalid())
5462           return true;
5463 
5464         Arg = ArgE.getAs<Expr>();
5465 
5466       } else {
5467         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5468 
5469         if (ArgE.isInvalid())
5470           return true;
5471 
5472         Arg = ArgE.getAs<Expr>();
5473       }
5474 
5475       if (RequireCompleteType(Arg->getLocStart(),
5476                               Arg->getType(),
5477                               diag::err_call_incomplete_argument, Arg))
5478         return ExprError();
5479 
5480       TheCall->setArg(i, Arg);
5481     }
5482   }
5483 
5484   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5485     if (!Method->isStatic())
5486       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5487         << Fn->getSourceRange());
5488 
5489   // Check for sentinels
5490   if (NDecl)
5491     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5492 
5493   // Do special checking on direct calls to functions.
5494   if (FDecl) {
5495     if (CheckFunctionCall(FDecl, TheCall, Proto))
5496       return ExprError();
5497 
5498     if (BuiltinID)
5499       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5500   } else if (NDecl) {
5501     if (CheckPointerCall(NDecl, TheCall, Proto))
5502       return ExprError();
5503   } else {
5504     if (CheckOtherCall(TheCall, Proto))
5505       return ExprError();
5506   }
5507 
5508   return MaybeBindToTemporary(TheCall);
5509 }
5510 
5511 ExprResult
5512 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5513                            SourceLocation RParenLoc, Expr *InitExpr) {
5514   assert(Ty && "ActOnCompoundLiteral(): missing type");
5515   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5516 
5517   TypeSourceInfo *TInfo;
5518   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5519   if (!TInfo)
5520     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5521 
5522   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5523 }
5524 
5525 ExprResult
5526 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5527                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5528   QualType literalType = TInfo->getType();
5529 
5530   if (literalType->isArrayType()) {
5531     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5532           diag::err_illegal_decl_array_incomplete_type,
5533           SourceRange(LParenLoc,
5534                       LiteralExpr->getSourceRange().getEnd())))
5535       return ExprError();
5536     if (literalType->isVariableArrayType())
5537       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5538         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5539   } else if (!literalType->isDependentType() &&
5540              RequireCompleteType(LParenLoc, literalType,
5541                diag::err_typecheck_decl_incomplete_type,
5542                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5543     return ExprError();
5544 
5545   InitializedEntity Entity
5546     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5547   InitializationKind Kind
5548     = InitializationKind::CreateCStyleCast(LParenLoc,
5549                                            SourceRange(LParenLoc, RParenLoc),
5550                                            /*InitList=*/true);
5551   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5552   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5553                                       &literalType);
5554   if (Result.isInvalid())
5555     return ExprError();
5556   LiteralExpr = Result.get();
5557 
5558   bool isFileScope = !CurContext->isFunctionOrMethod();
5559   if (isFileScope &&
5560       !LiteralExpr->isTypeDependent() &&
5561       !LiteralExpr->isValueDependent() &&
5562       !literalType->isDependentType()) { // 6.5.2.5p3
5563     if (CheckForConstantInitializer(LiteralExpr, literalType))
5564       return ExprError();
5565   }
5566 
5567   // In C, compound literals are l-values for some reason.
5568   // For GCC compatibility, in C++, file-scope array compound literals with
5569   // constant initializers are also l-values, and compound literals are
5570   // otherwise prvalues.
5571   //
5572   // (GCC also treats C++ list-initialized file-scope array prvalues with
5573   // constant initializers as l-values, but that's non-conforming, so we don't
5574   // follow it there.)
5575   //
5576   // FIXME: It would be better to handle the lvalue cases as materializing and
5577   // lifetime-extending a temporary object, but our materialized temporaries
5578   // representation only supports lifetime extension from a variable, not "out
5579   // of thin air".
5580   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5581   // is bound to the result of applying array-to-pointer decay to the compound
5582   // literal.
5583   // FIXME: GCC supports compound literals of reference type, which should
5584   // obviously have a value kind derived from the kind of reference involved.
5585   ExprValueKind VK =
5586       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5587           ? VK_RValue
5588           : VK_LValue;
5589 
5590   return MaybeBindToTemporary(
5591       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5592                                         VK, LiteralExpr, isFileScope));
5593 }
5594 
5595 ExprResult
5596 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5597                     SourceLocation RBraceLoc) {
5598   // Immediately handle non-overload placeholders.  Overloads can be
5599   // resolved contextually, but everything else here can't.
5600   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5601     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5602       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5603 
5604       // Ignore failures; dropping the entire initializer list because
5605       // of one failure would be terrible for indexing/etc.
5606       if (result.isInvalid()) continue;
5607 
5608       InitArgList[I] = result.get();
5609     }
5610   }
5611 
5612   // Semantic analysis for initializers is done by ActOnDeclarator() and
5613   // CheckInitializer() - it requires knowledge of the object being intialized.
5614 
5615   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5616                                                RBraceLoc);
5617   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5618   return E;
5619 }
5620 
5621 /// Do an explicit extend of the given block pointer if we're in ARC.
5622 void Sema::maybeExtendBlockObject(ExprResult &E) {
5623   assert(E.get()->getType()->isBlockPointerType());
5624   assert(E.get()->isRValue());
5625 
5626   // Only do this in an r-value context.
5627   if (!getLangOpts().ObjCAutoRefCount) return;
5628 
5629   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5630                                CK_ARCExtendBlockObject, E.get(),
5631                                /*base path*/ nullptr, VK_RValue);
5632   Cleanup.setExprNeedsCleanups(true);
5633 }
5634 
5635 /// Prepare a conversion of the given expression to an ObjC object
5636 /// pointer type.
5637 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5638   QualType type = E.get()->getType();
5639   if (type->isObjCObjectPointerType()) {
5640     return CK_BitCast;
5641   } else if (type->isBlockPointerType()) {
5642     maybeExtendBlockObject(E);
5643     return CK_BlockPointerToObjCPointerCast;
5644   } else {
5645     assert(type->isPointerType());
5646     return CK_CPointerToObjCPointerCast;
5647   }
5648 }
5649 
5650 /// Prepares for a scalar cast, performing all the necessary stages
5651 /// except the final cast and returning the kind required.
5652 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5653   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5654   // Also, callers should have filtered out the invalid cases with
5655   // pointers.  Everything else should be possible.
5656 
5657   QualType SrcTy = Src.get()->getType();
5658   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5659     return CK_NoOp;
5660 
5661   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5662   case Type::STK_MemberPointer:
5663     llvm_unreachable("member pointer type in C");
5664 
5665   case Type::STK_CPointer:
5666   case Type::STK_BlockPointer:
5667   case Type::STK_ObjCObjectPointer:
5668     switch (DestTy->getScalarTypeKind()) {
5669     case Type::STK_CPointer: {
5670       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5671       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5672       if (SrcAS != DestAS)
5673         return CK_AddressSpaceConversion;
5674       return CK_BitCast;
5675     }
5676     case Type::STK_BlockPointer:
5677       return (SrcKind == Type::STK_BlockPointer
5678                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5679     case Type::STK_ObjCObjectPointer:
5680       if (SrcKind == Type::STK_ObjCObjectPointer)
5681         return CK_BitCast;
5682       if (SrcKind == Type::STK_CPointer)
5683         return CK_CPointerToObjCPointerCast;
5684       maybeExtendBlockObject(Src);
5685       return CK_BlockPointerToObjCPointerCast;
5686     case Type::STK_Bool:
5687       return CK_PointerToBoolean;
5688     case Type::STK_Integral:
5689       return CK_PointerToIntegral;
5690     case Type::STK_Floating:
5691     case Type::STK_FloatingComplex:
5692     case Type::STK_IntegralComplex:
5693     case Type::STK_MemberPointer:
5694       llvm_unreachable("illegal cast from pointer");
5695     }
5696     llvm_unreachable("Should have returned before this");
5697 
5698   case Type::STK_Bool: // casting from bool is like casting from an integer
5699   case Type::STK_Integral:
5700     switch (DestTy->getScalarTypeKind()) {
5701     case Type::STK_CPointer:
5702     case Type::STK_ObjCObjectPointer:
5703     case Type::STK_BlockPointer:
5704       if (Src.get()->isNullPointerConstant(Context,
5705                                            Expr::NPC_ValueDependentIsNull))
5706         return CK_NullToPointer;
5707       return CK_IntegralToPointer;
5708     case Type::STK_Bool:
5709       return CK_IntegralToBoolean;
5710     case Type::STK_Integral:
5711       return CK_IntegralCast;
5712     case Type::STK_Floating:
5713       return CK_IntegralToFloating;
5714     case Type::STK_IntegralComplex:
5715       Src = ImpCastExprToType(Src.get(),
5716                       DestTy->castAs<ComplexType>()->getElementType(),
5717                       CK_IntegralCast);
5718       return CK_IntegralRealToComplex;
5719     case Type::STK_FloatingComplex:
5720       Src = ImpCastExprToType(Src.get(),
5721                       DestTy->castAs<ComplexType>()->getElementType(),
5722                       CK_IntegralToFloating);
5723       return CK_FloatingRealToComplex;
5724     case Type::STK_MemberPointer:
5725       llvm_unreachable("member pointer type in C");
5726     }
5727     llvm_unreachable("Should have returned before this");
5728 
5729   case Type::STK_Floating:
5730     switch (DestTy->getScalarTypeKind()) {
5731     case Type::STK_Floating:
5732       return CK_FloatingCast;
5733     case Type::STK_Bool:
5734       return CK_FloatingToBoolean;
5735     case Type::STK_Integral:
5736       return CK_FloatingToIntegral;
5737     case Type::STK_FloatingComplex:
5738       Src = ImpCastExprToType(Src.get(),
5739                               DestTy->castAs<ComplexType>()->getElementType(),
5740                               CK_FloatingCast);
5741       return CK_FloatingRealToComplex;
5742     case Type::STK_IntegralComplex:
5743       Src = ImpCastExprToType(Src.get(),
5744                               DestTy->castAs<ComplexType>()->getElementType(),
5745                               CK_FloatingToIntegral);
5746       return CK_IntegralRealToComplex;
5747     case Type::STK_CPointer:
5748     case Type::STK_ObjCObjectPointer:
5749     case Type::STK_BlockPointer:
5750       llvm_unreachable("valid float->pointer cast?");
5751     case Type::STK_MemberPointer:
5752       llvm_unreachable("member pointer type in C");
5753     }
5754     llvm_unreachable("Should have returned before this");
5755 
5756   case Type::STK_FloatingComplex:
5757     switch (DestTy->getScalarTypeKind()) {
5758     case Type::STK_FloatingComplex:
5759       return CK_FloatingComplexCast;
5760     case Type::STK_IntegralComplex:
5761       return CK_FloatingComplexToIntegralComplex;
5762     case Type::STK_Floating: {
5763       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5764       if (Context.hasSameType(ET, DestTy))
5765         return CK_FloatingComplexToReal;
5766       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5767       return CK_FloatingCast;
5768     }
5769     case Type::STK_Bool:
5770       return CK_FloatingComplexToBoolean;
5771     case Type::STK_Integral:
5772       Src = ImpCastExprToType(Src.get(),
5773                               SrcTy->castAs<ComplexType>()->getElementType(),
5774                               CK_FloatingComplexToReal);
5775       return CK_FloatingToIntegral;
5776     case Type::STK_CPointer:
5777     case Type::STK_ObjCObjectPointer:
5778     case Type::STK_BlockPointer:
5779       llvm_unreachable("valid complex float->pointer cast?");
5780     case Type::STK_MemberPointer:
5781       llvm_unreachable("member pointer type in C");
5782     }
5783     llvm_unreachable("Should have returned before this");
5784 
5785   case Type::STK_IntegralComplex:
5786     switch (DestTy->getScalarTypeKind()) {
5787     case Type::STK_FloatingComplex:
5788       return CK_IntegralComplexToFloatingComplex;
5789     case Type::STK_IntegralComplex:
5790       return CK_IntegralComplexCast;
5791     case Type::STK_Integral: {
5792       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5793       if (Context.hasSameType(ET, DestTy))
5794         return CK_IntegralComplexToReal;
5795       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5796       return CK_IntegralCast;
5797     }
5798     case Type::STK_Bool:
5799       return CK_IntegralComplexToBoolean;
5800     case Type::STK_Floating:
5801       Src = ImpCastExprToType(Src.get(),
5802                               SrcTy->castAs<ComplexType>()->getElementType(),
5803                               CK_IntegralComplexToReal);
5804       return CK_IntegralToFloating;
5805     case Type::STK_CPointer:
5806     case Type::STK_ObjCObjectPointer:
5807     case Type::STK_BlockPointer:
5808       llvm_unreachable("valid complex int->pointer cast?");
5809     case Type::STK_MemberPointer:
5810       llvm_unreachable("member pointer type in C");
5811     }
5812     llvm_unreachable("Should have returned before this");
5813   }
5814 
5815   llvm_unreachable("Unhandled scalar cast");
5816 }
5817 
5818 static bool breakDownVectorType(QualType type, uint64_t &len,
5819                                 QualType &eltType) {
5820   // Vectors are simple.
5821   if (const VectorType *vecType = type->getAs<VectorType>()) {
5822     len = vecType->getNumElements();
5823     eltType = vecType->getElementType();
5824     assert(eltType->isScalarType());
5825     return true;
5826   }
5827 
5828   // We allow lax conversion to and from non-vector types, but only if
5829   // they're real types (i.e. non-complex, non-pointer scalar types).
5830   if (!type->isRealType()) return false;
5831 
5832   len = 1;
5833   eltType = type;
5834   return true;
5835 }
5836 
5837 /// Are the two types lax-compatible vector types?  That is, given
5838 /// that one of them is a vector, do they have equal storage sizes,
5839 /// where the storage size is the number of elements times the element
5840 /// size?
5841 ///
5842 /// This will also return false if either of the types is neither a
5843 /// vector nor a real type.
5844 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5845   assert(destTy->isVectorType() || srcTy->isVectorType());
5846 
5847   // Disallow lax conversions between scalars and ExtVectors (these
5848   // conversions are allowed for other vector types because common headers
5849   // depend on them).  Most scalar OP ExtVector cases are handled by the
5850   // splat path anyway, which does what we want (convert, not bitcast).
5851   // What this rules out for ExtVectors is crazy things like char4*float.
5852   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5853   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5854 
5855   uint64_t srcLen, destLen;
5856   QualType srcEltTy, destEltTy;
5857   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5858   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5859 
5860   // ASTContext::getTypeSize will return the size rounded up to a
5861   // power of 2, so instead of using that, we need to use the raw
5862   // element size multiplied by the element count.
5863   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5864   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5865 
5866   return (srcLen * srcEltSize == destLen * destEltSize);
5867 }
5868 
5869 /// Is this a legal conversion between two types, one of which is
5870 /// known to be a vector type?
5871 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5872   assert(destTy->isVectorType() || srcTy->isVectorType());
5873 
5874   if (!Context.getLangOpts().LaxVectorConversions)
5875     return false;
5876   return areLaxCompatibleVectorTypes(srcTy, destTy);
5877 }
5878 
5879 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5880                            CastKind &Kind) {
5881   assert(VectorTy->isVectorType() && "Not a vector type!");
5882 
5883   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5884     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5885       return Diag(R.getBegin(),
5886                   Ty->isVectorType() ?
5887                   diag::err_invalid_conversion_between_vectors :
5888                   diag::err_invalid_conversion_between_vector_and_integer)
5889         << VectorTy << Ty << R;
5890   } else
5891     return Diag(R.getBegin(),
5892                 diag::err_invalid_conversion_between_vector_and_scalar)
5893       << VectorTy << Ty << R;
5894 
5895   Kind = CK_BitCast;
5896   return false;
5897 }
5898 
5899 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5900   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5901 
5902   if (DestElemTy == SplattedExpr->getType())
5903     return SplattedExpr;
5904 
5905   assert(DestElemTy->isFloatingType() ||
5906          DestElemTy->isIntegralOrEnumerationType());
5907 
5908   CastKind CK;
5909   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5910     // OpenCL requires that we convert `true` boolean expressions to -1, but
5911     // only when splatting vectors.
5912     if (DestElemTy->isFloatingType()) {
5913       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5914       // in two steps: boolean to signed integral, then to floating.
5915       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5916                                                  CK_BooleanToSignedIntegral);
5917       SplattedExpr = CastExprRes.get();
5918       CK = CK_IntegralToFloating;
5919     } else {
5920       CK = CK_BooleanToSignedIntegral;
5921     }
5922   } else {
5923     ExprResult CastExprRes = SplattedExpr;
5924     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5925     if (CastExprRes.isInvalid())
5926       return ExprError();
5927     SplattedExpr = CastExprRes.get();
5928   }
5929   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5930 }
5931 
5932 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5933                                     Expr *CastExpr, CastKind &Kind) {
5934   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5935 
5936   QualType SrcTy = CastExpr->getType();
5937 
5938   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5939   // an ExtVectorType.
5940   // In OpenCL, casts between vectors of different types are not allowed.
5941   // (See OpenCL 6.2).
5942   if (SrcTy->isVectorType()) {
5943     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5944         || (getLangOpts().OpenCL &&
5945             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5946       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5947         << DestTy << SrcTy << R;
5948       return ExprError();
5949     }
5950     Kind = CK_BitCast;
5951     return CastExpr;
5952   }
5953 
5954   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5955   // conversion will take place first from scalar to elt type, and then
5956   // splat from elt type to vector.
5957   if (SrcTy->isPointerType())
5958     return Diag(R.getBegin(),
5959                 diag::err_invalid_conversion_between_vector_and_scalar)
5960       << DestTy << SrcTy << R;
5961 
5962   Kind = CK_VectorSplat;
5963   return prepareVectorSplat(DestTy, CastExpr);
5964 }
5965 
5966 ExprResult
5967 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5968                     Declarator &D, ParsedType &Ty,
5969                     SourceLocation RParenLoc, Expr *CastExpr) {
5970   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5971          "ActOnCastExpr(): missing type or expr");
5972 
5973   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5974   if (D.isInvalidType())
5975     return ExprError();
5976 
5977   if (getLangOpts().CPlusPlus) {
5978     // Check that there are no default arguments (C++ only).
5979     CheckExtraCXXDefaultArguments(D);
5980   } else {
5981     // Make sure any TypoExprs have been dealt with.
5982     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5983     if (!Res.isUsable())
5984       return ExprError();
5985     CastExpr = Res.get();
5986   }
5987 
5988   checkUnusedDeclAttributes(D);
5989 
5990   QualType castType = castTInfo->getType();
5991   Ty = CreateParsedType(castType, castTInfo);
5992 
5993   bool isVectorLiteral = false;
5994 
5995   // Check for an altivec or OpenCL literal,
5996   // i.e. all the elements are integer constants.
5997   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5998   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5999   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6000        && castType->isVectorType() && (PE || PLE)) {
6001     if (PLE && PLE->getNumExprs() == 0) {
6002       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6003       return ExprError();
6004     }
6005     if (PE || PLE->getNumExprs() == 1) {
6006       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6007       if (!E->getType()->isVectorType())
6008         isVectorLiteral = true;
6009     }
6010     else
6011       isVectorLiteral = true;
6012   }
6013 
6014   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6015   // then handle it as such.
6016   if (isVectorLiteral)
6017     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6018 
6019   // If the Expr being casted is a ParenListExpr, handle it specially.
6020   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6021   // sequence of BinOp comma operators.
6022   if (isa<ParenListExpr>(CastExpr)) {
6023     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6024     if (Result.isInvalid()) return ExprError();
6025     CastExpr = Result.get();
6026   }
6027 
6028   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6029       !getSourceManager().isInSystemMacro(LParenLoc))
6030     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6031 
6032   CheckTollFreeBridgeCast(castType, CastExpr);
6033 
6034   CheckObjCBridgeRelatedCast(castType, CastExpr);
6035 
6036   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6037 
6038   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6039 }
6040 
6041 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6042                                     SourceLocation RParenLoc, Expr *E,
6043                                     TypeSourceInfo *TInfo) {
6044   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6045          "Expected paren or paren list expression");
6046 
6047   Expr **exprs;
6048   unsigned numExprs;
6049   Expr *subExpr;
6050   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6051   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6052     LiteralLParenLoc = PE->getLParenLoc();
6053     LiteralRParenLoc = PE->getRParenLoc();
6054     exprs = PE->getExprs();
6055     numExprs = PE->getNumExprs();
6056   } else { // isa<ParenExpr> by assertion at function entrance
6057     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6058     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6059     subExpr = cast<ParenExpr>(E)->getSubExpr();
6060     exprs = &subExpr;
6061     numExprs = 1;
6062   }
6063 
6064   QualType Ty = TInfo->getType();
6065   assert(Ty->isVectorType() && "Expected vector type");
6066 
6067   SmallVector<Expr *, 8> initExprs;
6068   const VectorType *VTy = Ty->getAs<VectorType>();
6069   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6070 
6071   // '(...)' form of vector initialization in AltiVec: the number of
6072   // initializers must be one or must match the size of the vector.
6073   // If a single value is specified in the initializer then it will be
6074   // replicated to all the components of the vector
6075   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6076     // The number of initializers must be one or must match the size of the
6077     // vector. If a single value is specified in the initializer then it will
6078     // be replicated to all the components of the vector
6079     if (numExprs == 1) {
6080       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6081       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6082       if (Literal.isInvalid())
6083         return ExprError();
6084       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6085                                   PrepareScalarCast(Literal, ElemTy));
6086       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6087     }
6088     else if (numExprs < numElems) {
6089       Diag(E->getExprLoc(),
6090            diag::err_incorrect_number_of_vector_initializers);
6091       return ExprError();
6092     }
6093     else
6094       initExprs.append(exprs, exprs + numExprs);
6095   }
6096   else {
6097     // For OpenCL, when the number of initializers is a single value,
6098     // it will be replicated to all components of the vector.
6099     if (getLangOpts().OpenCL &&
6100         VTy->getVectorKind() == VectorType::GenericVector &&
6101         numExprs == 1) {
6102         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6103         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6104         if (Literal.isInvalid())
6105           return ExprError();
6106         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6107                                     PrepareScalarCast(Literal, ElemTy));
6108         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6109     }
6110 
6111     initExprs.append(exprs, exprs + numExprs);
6112   }
6113   // FIXME: This means that pretty-printing the final AST will produce curly
6114   // braces instead of the original commas.
6115   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6116                                                    initExprs, LiteralRParenLoc);
6117   initE->setType(Ty);
6118   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6119 }
6120 
6121 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6122 /// the ParenListExpr into a sequence of comma binary operators.
6123 ExprResult
6124 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6125   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6126   if (!E)
6127     return OrigExpr;
6128 
6129   ExprResult Result(E->getExpr(0));
6130 
6131   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6132     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6133                         E->getExpr(i));
6134 
6135   if (Result.isInvalid()) return ExprError();
6136 
6137   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6138 }
6139 
6140 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6141                                     SourceLocation R,
6142                                     MultiExprArg Val) {
6143   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6144   return expr;
6145 }
6146 
6147 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6148 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6149 /// emitted.
6150 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6151                                       SourceLocation QuestionLoc) {
6152   Expr *NullExpr = LHSExpr;
6153   Expr *NonPointerExpr = RHSExpr;
6154   Expr::NullPointerConstantKind NullKind =
6155       NullExpr->isNullPointerConstant(Context,
6156                                       Expr::NPC_ValueDependentIsNotNull);
6157 
6158   if (NullKind == Expr::NPCK_NotNull) {
6159     NullExpr = RHSExpr;
6160     NonPointerExpr = LHSExpr;
6161     NullKind =
6162         NullExpr->isNullPointerConstant(Context,
6163                                         Expr::NPC_ValueDependentIsNotNull);
6164   }
6165 
6166   if (NullKind == Expr::NPCK_NotNull)
6167     return false;
6168 
6169   if (NullKind == Expr::NPCK_ZeroExpression)
6170     return false;
6171 
6172   if (NullKind == Expr::NPCK_ZeroLiteral) {
6173     // In this case, check to make sure that we got here from a "NULL"
6174     // string in the source code.
6175     NullExpr = NullExpr->IgnoreParenImpCasts();
6176     SourceLocation loc = NullExpr->getExprLoc();
6177     if (!findMacroSpelling(loc, "NULL"))
6178       return false;
6179   }
6180 
6181   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6182   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6183       << NonPointerExpr->getType() << DiagType
6184       << NonPointerExpr->getSourceRange();
6185   return true;
6186 }
6187 
6188 /// \brief Return false if the condition expression is valid, true otherwise.
6189 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6190   QualType CondTy = Cond->getType();
6191 
6192   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6193   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6194     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6195       << CondTy << Cond->getSourceRange();
6196     return true;
6197   }
6198 
6199   // C99 6.5.15p2
6200   if (CondTy->isScalarType()) return false;
6201 
6202   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6203     << CondTy << Cond->getSourceRange();
6204   return true;
6205 }
6206 
6207 /// \brief Handle when one or both operands are void type.
6208 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6209                                          ExprResult &RHS) {
6210     Expr *LHSExpr = LHS.get();
6211     Expr *RHSExpr = RHS.get();
6212 
6213     if (!LHSExpr->getType()->isVoidType())
6214       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6215         << RHSExpr->getSourceRange();
6216     if (!RHSExpr->getType()->isVoidType())
6217       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6218         << LHSExpr->getSourceRange();
6219     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6220     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6221     return S.Context.VoidTy;
6222 }
6223 
6224 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6225 /// true otherwise.
6226 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6227                                         QualType PointerTy) {
6228   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6229       !NullExpr.get()->isNullPointerConstant(S.Context,
6230                                             Expr::NPC_ValueDependentIsNull))
6231     return true;
6232 
6233   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6234   return false;
6235 }
6236 
6237 /// \brief Checks compatibility between two pointers and return the resulting
6238 /// type.
6239 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6240                                                      ExprResult &RHS,
6241                                                      SourceLocation Loc) {
6242   QualType LHSTy = LHS.get()->getType();
6243   QualType RHSTy = RHS.get()->getType();
6244 
6245   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6246     // Two identical pointers types are always compatible.
6247     return LHSTy;
6248   }
6249 
6250   QualType lhptee, rhptee;
6251 
6252   // Get the pointee types.
6253   bool IsBlockPointer = false;
6254   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6255     lhptee = LHSBTy->getPointeeType();
6256     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6257     IsBlockPointer = true;
6258   } else {
6259     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6260     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6261   }
6262 
6263   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6264   // differently qualified versions of compatible types, the result type is
6265   // a pointer to an appropriately qualified version of the composite
6266   // type.
6267 
6268   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6269   // clause doesn't make sense for our extensions. E.g. address space 2 should
6270   // be incompatible with address space 3: they may live on different devices or
6271   // anything.
6272   Qualifiers lhQual = lhptee.getQualifiers();
6273   Qualifiers rhQual = rhptee.getQualifiers();
6274 
6275   unsigned ResultAddrSpace = 0;
6276   unsigned LAddrSpace = lhQual.getAddressSpace();
6277   unsigned RAddrSpace = rhQual.getAddressSpace();
6278   if (S.getLangOpts().OpenCL) {
6279     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6280     // spaces is disallowed.
6281     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6282       ResultAddrSpace = LAddrSpace;
6283     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6284       ResultAddrSpace = RAddrSpace;
6285     else {
6286       S.Diag(Loc,
6287              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6288           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6289           << RHS.get()->getSourceRange();
6290       return QualType();
6291     }
6292   }
6293 
6294   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6295   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6296   lhQual.removeCVRQualifiers();
6297   rhQual.removeCVRQualifiers();
6298 
6299   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6300   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6301   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6302   // qual types are compatible iff
6303   //  * corresponded types are compatible
6304   //  * CVR qualifiers are equal
6305   //  * address spaces are equal
6306   // Thus for conditional operator we merge CVR and address space unqualified
6307   // pointees and if there is a composite type we return a pointer to it with
6308   // merged qualifiers.
6309   if (S.getLangOpts().OpenCL) {
6310     LHSCastKind = LAddrSpace == ResultAddrSpace
6311                       ? CK_BitCast
6312                       : CK_AddressSpaceConversion;
6313     RHSCastKind = RAddrSpace == ResultAddrSpace
6314                       ? CK_BitCast
6315                       : CK_AddressSpaceConversion;
6316     lhQual.removeAddressSpace();
6317     rhQual.removeAddressSpace();
6318   }
6319 
6320   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6321   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6322 
6323   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6324 
6325   if (CompositeTy.isNull()) {
6326     // In this situation, we assume void* type. No especially good
6327     // reason, but this is what gcc does, and we do have to pick
6328     // to get a consistent AST.
6329     QualType incompatTy;
6330     incompatTy = S.Context.getPointerType(
6331         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6332     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6333     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6334     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6335     // for casts between types with incompatible address space qualifiers.
6336     // For the following code the compiler produces casts between global and
6337     // local address spaces of the corresponded innermost pointees:
6338     // local int *global *a;
6339     // global int *global *b;
6340     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6341     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6342         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6343         << RHS.get()->getSourceRange();
6344     return incompatTy;
6345   }
6346 
6347   // The pointer types are compatible.
6348   // In case of OpenCL ResultTy should have the address space qualifier
6349   // which is a superset of address spaces of both the 2nd and the 3rd
6350   // operands of the conditional operator.
6351   QualType ResultTy = [&, ResultAddrSpace]() {
6352     if (S.getLangOpts().OpenCL) {
6353       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6354       CompositeQuals.setAddressSpace(ResultAddrSpace);
6355       return S.Context
6356           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6357           .withCVRQualifiers(MergedCVRQual);
6358     }
6359     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6360   }();
6361   if (IsBlockPointer)
6362     ResultTy = S.Context.getBlockPointerType(ResultTy);
6363   else
6364     ResultTy = S.Context.getPointerType(ResultTy);
6365 
6366   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6367   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6368   return ResultTy;
6369 }
6370 
6371 /// \brief Return the resulting type when the operands are both block pointers.
6372 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6373                                                           ExprResult &LHS,
6374                                                           ExprResult &RHS,
6375                                                           SourceLocation Loc) {
6376   QualType LHSTy = LHS.get()->getType();
6377   QualType RHSTy = RHS.get()->getType();
6378 
6379   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6380     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6381       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6382       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6383       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6384       return destType;
6385     }
6386     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6387       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6388       << RHS.get()->getSourceRange();
6389     return QualType();
6390   }
6391 
6392   // We have 2 block pointer types.
6393   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6394 }
6395 
6396 /// \brief Return the resulting type when the operands are both pointers.
6397 static QualType
6398 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6399                                             ExprResult &RHS,
6400                                             SourceLocation Loc) {
6401   // get the pointer types
6402   QualType LHSTy = LHS.get()->getType();
6403   QualType RHSTy = RHS.get()->getType();
6404 
6405   // get the "pointed to" types
6406   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6407   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6408 
6409   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6410   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6411     // Figure out necessary qualifiers (C99 6.5.15p6)
6412     QualType destPointee
6413       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6414     QualType destType = S.Context.getPointerType(destPointee);
6415     // Add qualifiers if necessary.
6416     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6417     // Promote to void*.
6418     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6419     return destType;
6420   }
6421   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6422     QualType destPointee
6423       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6424     QualType destType = S.Context.getPointerType(destPointee);
6425     // Add qualifiers if necessary.
6426     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6427     // Promote to void*.
6428     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6429     return destType;
6430   }
6431 
6432   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6433 }
6434 
6435 /// \brief Return false if the first expression is not an integer and the second
6436 /// expression is not a pointer, true otherwise.
6437 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6438                                         Expr* PointerExpr, SourceLocation Loc,
6439                                         bool IsIntFirstExpr) {
6440   if (!PointerExpr->getType()->isPointerType() ||
6441       !Int.get()->getType()->isIntegerType())
6442     return false;
6443 
6444   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6445   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6446 
6447   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6448     << Expr1->getType() << Expr2->getType()
6449     << Expr1->getSourceRange() << Expr2->getSourceRange();
6450   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6451                             CK_IntegralToPointer);
6452   return true;
6453 }
6454 
6455 /// \brief Simple conversion between integer and floating point types.
6456 ///
6457 /// Used when handling the OpenCL conditional operator where the
6458 /// condition is a vector while the other operands are scalar.
6459 ///
6460 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6461 /// types are either integer or floating type. Between the two
6462 /// operands, the type with the higher rank is defined as the "result
6463 /// type". The other operand needs to be promoted to the same type. No
6464 /// other type promotion is allowed. We cannot use
6465 /// UsualArithmeticConversions() for this purpose, since it always
6466 /// promotes promotable types.
6467 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6468                                             ExprResult &RHS,
6469                                             SourceLocation QuestionLoc) {
6470   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6471   if (LHS.isInvalid())
6472     return QualType();
6473   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6474   if (RHS.isInvalid())
6475     return QualType();
6476 
6477   // For conversion purposes, we ignore any qualifiers.
6478   // For example, "const float" and "float" are equivalent.
6479   QualType LHSType =
6480     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6481   QualType RHSType =
6482     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6483 
6484   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6485     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6486       << LHSType << LHS.get()->getSourceRange();
6487     return QualType();
6488   }
6489 
6490   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6491     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6492       << RHSType << RHS.get()->getSourceRange();
6493     return QualType();
6494   }
6495 
6496   // If both types are identical, no conversion is needed.
6497   if (LHSType == RHSType)
6498     return LHSType;
6499 
6500   // Now handle "real" floating types (i.e. float, double, long double).
6501   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6502     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6503                                  /*IsCompAssign = */ false);
6504 
6505   // Finally, we have two differing integer types.
6506   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6507   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6508 }
6509 
6510 /// \brief Convert scalar operands to a vector that matches the
6511 ///        condition in length.
6512 ///
6513 /// Used when handling the OpenCL conditional operator where the
6514 /// condition is a vector while the other operands are scalar.
6515 ///
6516 /// We first compute the "result type" for the scalar operands
6517 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6518 /// into a vector of that type where the length matches the condition
6519 /// vector type. s6.11.6 requires that the element types of the result
6520 /// and the condition must have the same number of bits.
6521 static QualType
6522 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6523                               QualType CondTy, SourceLocation QuestionLoc) {
6524   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6525   if (ResTy.isNull()) return QualType();
6526 
6527   const VectorType *CV = CondTy->getAs<VectorType>();
6528   assert(CV);
6529 
6530   // Determine the vector result type
6531   unsigned NumElements = CV->getNumElements();
6532   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6533 
6534   // Ensure that all types have the same number of bits
6535   if (S.Context.getTypeSize(CV->getElementType())
6536       != S.Context.getTypeSize(ResTy)) {
6537     // Since VectorTy is created internally, it does not pretty print
6538     // with an OpenCL name. Instead, we just print a description.
6539     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6540     SmallString<64> Str;
6541     llvm::raw_svector_ostream OS(Str);
6542     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6543     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6544       << CondTy << OS.str();
6545     return QualType();
6546   }
6547 
6548   // Convert operands to the vector result type
6549   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6550   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6551 
6552   return VectorTy;
6553 }
6554 
6555 /// \brief Return false if this is a valid OpenCL condition vector
6556 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6557                                        SourceLocation QuestionLoc) {
6558   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6559   // integral type.
6560   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6561   assert(CondTy);
6562   QualType EleTy = CondTy->getElementType();
6563   if (EleTy->isIntegerType()) return false;
6564 
6565   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6566     << Cond->getType() << Cond->getSourceRange();
6567   return true;
6568 }
6569 
6570 /// \brief Return false if the vector condition type and the vector
6571 ///        result type are compatible.
6572 ///
6573 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6574 /// number of elements, and their element types have the same number
6575 /// of bits.
6576 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6577                               SourceLocation QuestionLoc) {
6578   const VectorType *CV = CondTy->getAs<VectorType>();
6579   const VectorType *RV = VecResTy->getAs<VectorType>();
6580   assert(CV && RV);
6581 
6582   if (CV->getNumElements() != RV->getNumElements()) {
6583     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6584       << CondTy << VecResTy;
6585     return true;
6586   }
6587 
6588   QualType CVE = CV->getElementType();
6589   QualType RVE = RV->getElementType();
6590 
6591   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6592     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6593       << CondTy << VecResTy;
6594     return true;
6595   }
6596 
6597   return false;
6598 }
6599 
6600 /// \brief Return the resulting type for the conditional operator in
6601 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6602 ///        s6.3.i) when the condition is a vector type.
6603 static QualType
6604 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6605                              ExprResult &LHS, ExprResult &RHS,
6606                              SourceLocation QuestionLoc) {
6607   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6608   if (Cond.isInvalid())
6609     return QualType();
6610   QualType CondTy = Cond.get()->getType();
6611 
6612   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6613     return QualType();
6614 
6615   // If either operand is a vector then find the vector type of the
6616   // result as specified in OpenCL v1.1 s6.3.i.
6617   if (LHS.get()->getType()->isVectorType() ||
6618       RHS.get()->getType()->isVectorType()) {
6619     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6620                                               /*isCompAssign*/false,
6621                                               /*AllowBothBool*/true,
6622                                               /*AllowBoolConversions*/false);
6623     if (VecResTy.isNull()) return QualType();
6624     // The result type must match the condition type as specified in
6625     // OpenCL v1.1 s6.11.6.
6626     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6627       return QualType();
6628     return VecResTy;
6629   }
6630 
6631   // Both operands are scalar.
6632   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6633 }
6634 
6635 /// \brief Return true if the Expr is block type
6636 static bool checkBlockType(Sema &S, const Expr *E) {
6637   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6638     QualType Ty = CE->getCallee()->getType();
6639     if (Ty->isBlockPointerType()) {
6640       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6641       return true;
6642     }
6643   }
6644   return false;
6645 }
6646 
6647 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6648 /// In that case, LHS = cond.
6649 /// C99 6.5.15
6650 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6651                                         ExprResult &RHS, ExprValueKind &VK,
6652                                         ExprObjectKind &OK,
6653                                         SourceLocation QuestionLoc) {
6654 
6655   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6656   if (!LHSResult.isUsable()) return QualType();
6657   LHS = LHSResult;
6658 
6659   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6660   if (!RHSResult.isUsable()) return QualType();
6661   RHS = RHSResult;
6662 
6663   // C++ is sufficiently different to merit its own checker.
6664   if (getLangOpts().CPlusPlus)
6665     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6666 
6667   VK = VK_RValue;
6668   OK = OK_Ordinary;
6669 
6670   // The OpenCL operator with a vector condition is sufficiently
6671   // different to merit its own checker.
6672   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6673     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6674 
6675   // First, check the condition.
6676   Cond = UsualUnaryConversions(Cond.get());
6677   if (Cond.isInvalid())
6678     return QualType();
6679   if (checkCondition(*this, Cond.get(), QuestionLoc))
6680     return QualType();
6681 
6682   // Now check the two expressions.
6683   if (LHS.get()->getType()->isVectorType() ||
6684       RHS.get()->getType()->isVectorType())
6685     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6686                                /*AllowBothBool*/true,
6687                                /*AllowBoolConversions*/false);
6688 
6689   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6690   if (LHS.isInvalid() || RHS.isInvalid())
6691     return QualType();
6692 
6693   QualType LHSTy = LHS.get()->getType();
6694   QualType RHSTy = RHS.get()->getType();
6695 
6696   // Diagnose attempts to convert between __float128 and long double where
6697   // such conversions currently can't be handled.
6698   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6699     Diag(QuestionLoc,
6700          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6701       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6702     return QualType();
6703   }
6704 
6705   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6706   // selection operator (?:).
6707   if (getLangOpts().OpenCL &&
6708       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6709     return QualType();
6710   }
6711 
6712   // If both operands have arithmetic type, do the usual arithmetic conversions
6713   // to find a common type: C99 6.5.15p3,5.
6714   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6715     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6716     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6717 
6718     return ResTy;
6719   }
6720 
6721   // If both operands are the same structure or union type, the result is that
6722   // type.
6723   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6724     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6725       if (LHSRT->getDecl() == RHSRT->getDecl())
6726         // "If both the operands have structure or union type, the result has
6727         // that type."  This implies that CV qualifiers are dropped.
6728         return LHSTy.getUnqualifiedType();
6729     // FIXME: Type of conditional expression must be complete in C mode.
6730   }
6731 
6732   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6733   // The following || allows only one side to be void (a GCC-ism).
6734   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6735     return checkConditionalVoidType(*this, LHS, RHS);
6736   }
6737 
6738   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6739   // the type of the other operand."
6740   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6741   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6742 
6743   // All objective-c pointer type analysis is done here.
6744   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6745                                                         QuestionLoc);
6746   if (LHS.isInvalid() || RHS.isInvalid())
6747     return QualType();
6748   if (!compositeType.isNull())
6749     return compositeType;
6750 
6751 
6752   // Handle block pointer types.
6753   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6754     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6755                                                      QuestionLoc);
6756 
6757   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6758   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6759     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6760                                                        QuestionLoc);
6761 
6762   // GCC compatibility: soften pointer/integer mismatch.  Note that
6763   // null pointers have been filtered out by this point.
6764   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6765       /*isIntFirstExpr=*/true))
6766     return RHSTy;
6767   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6768       /*isIntFirstExpr=*/false))
6769     return LHSTy;
6770 
6771   // Emit a better diagnostic if one of the expressions is a null pointer
6772   // constant and the other is not a pointer type. In this case, the user most
6773   // likely forgot to take the address of the other expression.
6774   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6775     return QualType();
6776 
6777   // Otherwise, the operands are not compatible.
6778   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6779     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6780     << RHS.get()->getSourceRange();
6781   return QualType();
6782 }
6783 
6784 /// FindCompositeObjCPointerType - Helper method to find composite type of
6785 /// two objective-c pointer types of the two input expressions.
6786 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6787                                             SourceLocation QuestionLoc) {
6788   QualType LHSTy = LHS.get()->getType();
6789   QualType RHSTy = RHS.get()->getType();
6790 
6791   // Handle things like Class and struct objc_class*.  Here we case the result
6792   // to the pseudo-builtin, because that will be implicitly cast back to the
6793   // redefinition type if an attempt is made to access its fields.
6794   if (LHSTy->isObjCClassType() &&
6795       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6796     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6797     return LHSTy;
6798   }
6799   if (RHSTy->isObjCClassType() &&
6800       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6801     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6802     return RHSTy;
6803   }
6804   // And the same for struct objc_object* / id
6805   if (LHSTy->isObjCIdType() &&
6806       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6807     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6808     return LHSTy;
6809   }
6810   if (RHSTy->isObjCIdType() &&
6811       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6812     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6813     return RHSTy;
6814   }
6815   // And the same for struct objc_selector* / SEL
6816   if (Context.isObjCSelType(LHSTy) &&
6817       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6818     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6819     return LHSTy;
6820   }
6821   if (Context.isObjCSelType(RHSTy) &&
6822       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6823     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6824     return RHSTy;
6825   }
6826   // Check constraints for Objective-C object pointers types.
6827   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6828 
6829     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6830       // Two identical object pointer types are always compatible.
6831       return LHSTy;
6832     }
6833     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6834     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6835     QualType compositeType = LHSTy;
6836 
6837     // If both operands are interfaces and either operand can be
6838     // assigned to the other, use that type as the composite
6839     // type. This allows
6840     //   xxx ? (A*) a : (B*) b
6841     // where B is a subclass of A.
6842     //
6843     // Additionally, as for assignment, if either type is 'id'
6844     // allow silent coercion. Finally, if the types are
6845     // incompatible then make sure to use 'id' as the composite
6846     // type so the result is acceptable for sending messages to.
6847 
6848     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6849     // It could return the composite type.
6850     if (!(compositeType =
6851           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6852       // Nothing more to do.
6853     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6854       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6855     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6856       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6857     } else if ((LHSTy->isObjCQualifiedIdType() ||
6858                 RHSTy->isObjCQualifiedIdType()) &&
6859                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6860       // Need to handle "id<xx>" explicitly.
6861       // GCC allows qualified id and any Objective-C type to devolve to
6862       // id. Currently localizing to here until clear this should be
6863       // part of ObjCQualifiedIdTypesAreCompatible.
6864       compositeType = Context.getObjCIdType();
6865     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6866       compositeType = Context.getObjCIdType();
6867     } else {
6868       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6869       << LHSTy << RHSTy
6870       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6871       QualType incompatTy = Context.getObjCIdType();
6872       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6873       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6874       return incompatTy;
6875     }
6876     // The object pointer types are compatible.
6877     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6878     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6879     return compositeType;
6880   }
6881   // Check Objective-C object pointer types and 'void *'
6882   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6883     if (getLangOpts().ObjCAutoRefCount) {
6884       // ARC forbids the implicit conversion of object pointers to 'void *',
6885       // so these types are not compatible.
6886       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6887           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6888       LHS = RHS = true;
6889       return QualType();
6890     }
6891     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6892     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6893     QualType destPointee
6894     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6895     QualType destType = Context.getPointerType(destPointee);
6896     // Add qualifiers if necessary.
6897     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6898     // Promote to void*.
6899     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6900     return destType;
6901   }
6902   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6903     if (getLangOpts().ObjCAutoRefCount) {
6904       // ARC forbids the implicit conversion of object pointers to 'void *',
6905       // so these types are not compatible.
6906       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6907           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6908       LHS = RHS = true;
6909       return QualType();
6910     }
6911     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6912     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6913     QualType destPointee
6914     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6915     QualType destType = Context.getPointerType(destPointee);
6916     // Add qualifiers if necessary.
6917     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6918     // Promote to void*.
6919     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6920     return destType;
6921   }
6922   return QualType();
6923 }
6924 
6925 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6926 /// ParenRange in parentheses.
6927 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6928                                const PartialDiagnostic &Note,
6929                                SourceRange ParenRange) {
6930   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6931   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6932       EndLoc.isValid()) {
6933     Self.Diag(Loc, Note)
6934       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6935       << FixItHint::CreateInsertion(EndLoc, ")");
6936   } else {
6937     // We can't display the parentheses, so just show the bare note.
6938     Self.Diag(Loc, Note) << ParenRange;
6939   }
6940 }
6941 
6942 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6943   return BinaryOperator::isAdditiveOp(Opc) ||
6944          BinaryOperator::isMultiplicativeOp(Opc) ||
6945          BinaryOperator::isShiftOp(Opc);
6946 }
6947 
6948 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6949 /// expression, either using a built-in or overloaded operator,
6950 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6951 /// expression.
6952 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6953                                    Expr **RHSExprs) {
6954   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6955   E = E->IgnoreImpCasts();
6956   E = E->IgnoreConversionOperator();
6957   E = E->IgnoreImpCasts();
6958 
6959   // Built-in binary operator.
6960   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6961     if (IsArithmeticOp(OP->getOpcode())) {
6962       *Opcode = OP->getOpcode();
6963       *RHSExprs = OP->getRHS();
6964       return true;
6965     }
6966   }
6967 
6968   // Overloaded operator.
6969   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6970     if (Call->getNumArgs() != 2)
6971       return false;
6972 
6973     // Make sure this is really a binary operator that is safe to pass into
6974     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6975     OverloadedOperatorKind OO = Call->getOperator();
6976     if (OO < OO_Plus || OO > OO_Arrow ||
6977         OO == OO_PlusPlus || OO == OO_MinusMinus)
6978       return false;
6979 
6980     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6981     if (IsArithmeticOp(OpKind)) {
6982       *Opcode = OpKind;
6983       *RHSExprs = Call->getArg(1);
6984       return true;
6985     }
6986   }
6987 
6988   return false;
6989 }
6990 
6991 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6992 /// or is a logical expression such as (x==y) which has int type, but is
6993 /// commonly interpreted as boolean.
6994 static bool ExprLooksBoolean(Expr *E) {
6995   E = E->IgnoreParenImpCasts();
6996 
6997   if (E->getType()->isBooleanType())
6998     return true;
6999   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7000     return OP->isComparisonOp() || OP->isLogicalOp();
7001   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7002     return OP->getOpcode() == UO_LNot;
7003   if (E->getType()->isPointerType())
7004     return true;
7005 
7006   return false;
7007 }
7008 
7009 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7010 /// and binary operator are mixed in a way that suggests the programmer assumed
7011 /// the conditional operator has higher precedence, for example:
7012 /// "int x = a + someBinaryCondition ? 1 : 2".
7013 static void DiagnoseConditionalPrecedence(Sema &Self,
7014                                           SourceLocation OpLoc,
7015                                           Expr *Condition,
7016                                           Expr *LHSExpr,
7017                                           Expr *RHSExpr) {
7018   BinaryOperatorKind CondOpcode;
7019   Expr *CondRHS;
7020 
7021   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7022     return;
7023   if (!ExprLooksBoolean(CondRHS))
7024     return;
7025 
7026   // The condition is an arithmetic binary expression, with a right-
7027   // hand side that looks boolean, so warn.
7028 
7029   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7030       << Condition->getSourceRange()
7031       << BinaryOperator::getOpcodeStr(CondOpcode);
7032 
7033   SuggestParentheses(Self, OpLoc,
7034     Self.PDiag(diag::note_precedence_silence)
7035       << BinaryOperator::getOpcodeStr(CondOpcode),
7036     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7037 
7038   SuggestParentheses(Self, OpLoc,
7039     Self.PDiag(diag::note_precedence_conditional_first),
7040     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7041 }
7042 
7043 /// Compute the nullability of a conditional expression.
7044 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7045                                               QualType LHSTy, QualType RHSTy,
7046                                               ASTContext &Ctx) {
7047   if (!ResTy->isAnyPointerType())
7048     return ResTy;
7049 
7050   auto GetNullability = [&Ctx](QualType Ty) {
7051     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7052     if (Kind)
7053       return *Kind;
7054     return NullabilityKind::Unspecified;
7055   };
7056 
7057   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7058   NullabilityKind MergedKind;
7059 
7060   // Compute nullability of a binary conditional expression.
7061   if (IsBin) {
7062     if (LHSKind == NullabilityKind::NonNull)
7063       MergedKind = NullabilityKind::NonNull;
7064     else
7065       MergedKind = RHSKind;
7066   // Compute nullability of a normal conditional expression.
7067   } else {
7068     if (LHSKind == NullabilityKind::Nullable ||
7069         RHSKind == NullabilityKind::Nullable)
7070       MergedKind = NullabilityKind::Nullable;
7071     else if (LHSKind == NullabilityKind::NonNull)
7072       MergedKind = RHSKind;
7073     else if (RHSKind == NullabilityKind::NonNull)
7074       MergedKind = LHSKind;
7075     else
7076       MergedKind = NullabilityKind::Unspecified;
7077   }
7078 
7079   // Return if ResTy already has the correct nullability.
7080   if (GetNullability(ResTy) == MergedKind)
7081     return ResTy;
7082 
7083   // Strip all nullability from ResTy.
7084   while (ResTy->getNullability(Ctx))
7085     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7086 
7087   // Create a new AttributedType with the new nullability kind.
7088   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7089   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7090 }
7091 
7092 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7093 /// in the case of a the GNU conditional expr extension.
7094 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7095                                     SourceLocation ColonLoc,
7096                                     Expr *CondExpr, Expr *LHSExpr,
7097                                     Expr *RHSExpr) {
7098   if (!getLangOpts().CPlusPlus) {
7099     // C cannot handle TypoExpr nodes in the condition because it
7100     // doesn't handle dependent types properly, so make sure any TypoExprs have
7101     // been dealt with before checking the operands.
7102     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7103     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7104     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7105 
7106     if (!CondResult.isUsable())
7107       return ExprError();
7108 
7109     if (LHSExpr) {
7110       if (!LHSResult.isUsable())
7111         return ExprError();
7112     }
7113 
7114     if (!RHSResult.isUsable())
7115       return ExprError();
7116 
7117     CondExpr = CondResult.get();
7118     LHSExpr = LHSResult.get();
7119     RHSExpr = RHSResult.get();
7120   }
7121 
7122   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7123   // was the condition.
7124   OpaqueValueExpr *opaqueValue = nullptr;
7125   Expr *commonExpr = nullptr;
7126   if (!LHSExpr) {
7127     commonExpr = CondExpr;
7128     // Lower out placeholder types first.  This is important so that we don't
7129     // try to capture a placeholder. This happens in few cases in C++; such
7130     // as Objective-C++'s dictionary subscripting syntax.
7131     if (commonExpr->hasPlaceholderType()) {
7132       ExprResult result = CheckPlaceholderExpr(commonExpr);
7133       if (!result.isUsable()) return ExprError();
7134       commonExpr = result.get();
7135     }
7136     // We usually want to apply unary conversions *before* saving, except
7137     // in the special case of a C++ l-value conditional.
7138     if (!(getLangOpts().CPlusPlus
7139           && !commonExpr->isTypeDependent()
7140           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7141           && commonExpr->isGLValue()
7142           && commonExpr->isOrdinaryOrBitFieldObject()
7143           && RHSExpr->isOrdinaryOrBitFieldObject()
7144           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7145       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7146       if (commonRes.isInvalid())
7147         return ExprError();
7148       commonExpr = commonRes.get();
7149     }
7150 
7151     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7152                                                 commonExpr->getType(),
7153                                                 commonExpr->getValueKind(),
7154                                                 commonExpr->getObjectKind(),
7155                                                 commonExpr);
7156     LHSExpr = CondExpr = opaqueValue;
7157   }
7158 
7159   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7160   ExprValueKind VK = VK_RValue;
7161   ExprObjectKind OK = OK_Ordinary;
7162   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7163   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7164                                              VK, OK, QuestionLoc);
7165   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7166       RHS.isInvalid())
7167     return ExprError();
7168 
7169   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7170                                 RHS.get());
7171 
7172   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7173 
7174   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7175                                          Context);
7176 
7177   if (!commonExpr)
7178     return new (Context)
7179         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7180                             RHS.get(), result, VK, OK);
7181 
7182   return new (Context) BinaryConditionalOperator(
7183       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7184       ColonLoc, result, VK, OK);
7185 }
7186 
7187 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7188 // being closely modeled after the C99 spec:-). The odd characteristic of this
7189 // routine is it effectively iqnores the qualifiers on the top level pointee.
7190 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7191 // FIXME: add a couple examples in this comment.
7192 static Sema::AssignConvertType
7193 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7194   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7195   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7196 
7197   // get the "pointed to" type (ignoring qualifiers at the top level)
7198   const Type *lhptee, *rhptee;
7199   Qualifiers lhq, rhq;
7200   std::tie(lhptee, lhq) =
7201       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7202   std::tie(rhptee, rhq) =
7203       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7204 
7205   Sema::AssignConvertType ConvTy = Sema::Compatible;
7206 
7207   // C99 6.5.16.1p1: This following citation is common to constraints
7208   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7209   // qualifiers of the type *pointed to* by the right;
7210 
7211   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7212   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7213       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7214     // Ignore lifetime for further calculation.
7215     lhq.removeObjCLifetime();
7216     rhq.removeObjCLifetime();
7217   }
7218 
7219   if (!lhq.compatiblyIncludes(rhq)) {
7220     // Treat address-space mismatches as fatal.  TODO: address subspaces
7221     if (!lhq.isAddressSpaceSupersetOf(rhq))
7222       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7223 
7224     // It's okay to add or remove GC or lifetime qualifiers when converting to
7225     // and from void*.
7226     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7227                         .compatiblyIncludes(
7228                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7229              && (lhptee->isVoidType() || rhptee->isVoidType()))
7230       ; // keep old
7231 
7232     // Treat lifetime mismatches as fatal.
7233     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7234       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7235 
7236     // For GCC/MS compatibility, other qualifier mismatches are treated
7237     // as still compatible in C.
7238     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7239   }
7240 
7241   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7242   // incomplete type and the other is a pointer to a qualified or unqualified
7243   // version of void...
7244   if (lhptee->isVoidType()) {
7245     if (rhptee->isIncompleteOrObjectType())
7246       return ConvTy;
7247 
7248     // As an extension, we allow cast to/from void* to function pointer.
7249     assert(rhptee->isFunctionType());
7250     return Sema::FunctionVoidPointer;
7251   }
7252 
7253   if (rhptee->isVoidType()) {
7254     if (lhptee->isIncompleteOrObjectType())
7255       return ConvTy;
7256 
7257     // As an extension, we allow cast to/from void* to function pointer.
7258     assert(lhptee->isFunctionType());
7259     return Sema::FunctionVoidPointer;
7260   }
7261 
7262   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7263   // unqualified versions of compatible types, ...
7264   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7265   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7266     // Check if the pointee types are compatible ignoring the sign.
7267     // We explicitly check for char so that we catch "char" vs
7268     // "unsigned char" on systems where "char" is unsigned.
7269     if (lhptee->isCharType())
7270       ltrans = S.Context.UnsignedCharTy;
7271     else if (lhptee->hasSignedIntegerRepresentation())
7272       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7273 
7274     if (rhptee->isCharType())
7275       rtrans = S.Context.UnsignedCharTy;
7276     else if (rhptee->hasSignedIntegerRepresentation())
7277       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7278 
7279     if (ltrans == rtrans) {
7280       // Types are compatible ignoring the sign. Qualifier incompatibility
7281       // takes priority over sign incompatibility because the sign
7282       // warning can be disabled.
7283       if (ConvTy != Sema::Compatible)
7284         return ConvTy;
7285 
7286       return Sema::IncompatiblePointerSign;
7287     }
7288 
7289     // If we are a multi-level pointer, it's possible that our issue is simply
7290     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7291     // the eventual target type is the same and the pointers have the same
7292     // level of indirection, this must be the issue.
7293     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7294       do {
7295         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7296         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7297       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7298 
7299       if (lhptee == rhptee)
7300         return Sema::IncompatibleNestedPointerQualifiers;
7301     }
7302 
7303     // General pointer incompatibility takes priority over qualifiers.
7304     return Sema::IncompatiblePointer;
7305   }
7306   if (!S.getLangOpts().CPlusPlus &&
7307       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7308     return Sema::IncompatiblePointer;
7309   return ConvTy;
7310 }
7311 
7312 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7313 /// block pointer types are compatible or whether a block and normal pointer
7314 /// are compatible. It is more restrict than comparing two function pointer
7315 // types.
7316 static Sema::AssignConvertType
7317 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7318                                     QualType RHSType) {
7319   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7320   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7321 
7322   QualType lhptee, rhptee;
7323 
7324   // get the "pointed to" type (ignoring qualifiers at the top level)
7325   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7326   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7327 
7328   // In C++, the types have to match exactly.
7329   if (S.getLangOpts().CPlusPlus)
7330     return Sema::IncompatibleBlockPointer;
7331 
7332   Sema::AssignConvertType ConvTy = Sema::Compatible;
7333 
7334   // For blocks we enforce that qualifiers are identical.
7335   Qualifiers LQuals = lhptee.getLocalQualifiers();
7336   Qualifiers RQuals = rhptee.getLocalQualifiers();
7337   if (S.getLangOpts().OpenCL) {
7338     LQuals.removeAddressSpace();
7339     RQuals.removeAddressSpace();
7340   }
7341   if (LQuals != RQuals)
7342     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7343 
7344   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7345   // assignment.
7346   // The current behavior is similar to C++ lambdas. A block might be
7347   // assigned to a variable iff its return type and parameters are compatible
7348   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7349   // an assignment. Presumably it should behave in way that a function pointer
7350   // assignment does in C, so for each parameter and return type:
7351   //  * CVR and address space of LHS should be a superset of CVR and address
7352   //  space of RHS.
7353   //  * unqualified types should be compatible.
7354   if (S.getLangOpts().OpenCL) {
7355     if (!S.Context.typesAreBlockPointerCompatible(
7356             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7357             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7358       return Sema::IncompatibleBlockPointer;
7359   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7360     return Sema::IncompatibleBlockPointer;
7361 
7362   return ConvTy;
7363 }
7364 
7365 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7366 /// for assignment compatibility.
7367 static Sema::AssignConvertType
7368 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7369                                    QualType RHSType) {
7370   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7371   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7372 
7373   if (LHSType->isObjCBuiltinType()) {
7374     // Class is not compatible with ObjC object pointers.
7375     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7376         !RHSType->isObjCQualifiedClassType())
7377       return Sema::IncompatiblePointer;
7378     return Sema::Compatible;
7379   }
7380   if (RHSType->isObjCBuiltinType()) {
7381     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7382         !LHSType->isObjCQualifiedClassType())
7383       return Sema::IncompatiblePointer;
7384     return Sema::Compatible;
7385   }
7386   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7387   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7388 
7389   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7390       // make an exception for id<P>
7391       !LHSType->isObjCQualifiedIdType())
7392     return Sema::CompatiblePointerDiscardsQualifiers;
7393 
7394   if (S.Context.typesAreCompatible(LHSType, RHSType))
7395     return Sema::Compatible;
7396   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7397     return Sema::IncompatibleObjCQualifiedId;
7398   return Sema::IncompatiblePointer;
7399 }
7400 
7401 Sema::AssignConvertType
7402 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7403                                  QualType LHSType, QualType RHSType) {
7404   // Fake up an opaque expression.  We don't actually care about what
7405   // cast operations are required, so if CheckAssignmentConstraints
7406   // adds casts to this they'll be wasted, but fortunately that doesn't
7407   // usually happen on valid code.
7408   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7409   ExprResult RHSPtr = &RHSExpr;
7410   CastKind K = CK_Invalid;
7411 
7412   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7413 }
7414 
7415 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7416 /// has code to accommodate several GCC extensions when type checking
7417 /// pointers. Here are some objectionable examples that GCC considers warnings:
7418 ///
7419 ///  int a, *pint;
7420 ///  short *pshort;
7421 ///  struct foo *pfoo;
7422 ///
7423 ///  pint = pshort; // warning: assignment from incompatible pointer type
7424 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7425 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7426 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7427 ///
7428 /// As a result, the code for dealing with pointers is more complex than the
7429 /// C99 spec dictates.
7430 ///
7431 /// Sets 'Kind' for any result kind except Incompatible.
7432 Sema::AssignConvertType
7433 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7434                                  CastKind &Kind, bool ConvertRHS) {
7435   QualType RHSType = RHS.get()->getType();
7436   QualType OrigLHSType = LHSType;
7437 
7438   // Get canonical types.  We're not formatting these types, just comparing
7439   // them.
7440   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7441   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7442 
7443   // Common case: no conversion required.
7444   if (LHSType == RHSType) {
7445     Kind = CK_NoOp;
7446     return Compatible;
7447   }
7448 
7449   // If we have an atomic type, try a non-atomic assignment, then just add an
7450   // atomic qualification step.
7451   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7452     Sema::AssignConvertType result =
7453       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7454     if (result != Compatible)
7455       return result;
7456     if (Kind != CK_NoOp && ConvertRHS)
7457       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7458     Kind = CK_NonAtomicToAtomic;
7459     return Compatible;
7460   }
7461 
7462   // If the left-hand side is a reference type, then we are in a
7463   // (rare!) case where we've allowed the use of references in C,
7464   // e.g., as a parameter type in a built-in function. In this case,
7465   // just make sure that the type referenced is compatible with the
7466   // right-hand side type. The caller is responsible for adjusting
7467   // LHSType so that the resulting expression does not have reference
7468   // type.
7469   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7470     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7471       Kind = CK_LValueBitCast;
7472       return Compatible;
7473     }
7474     return Incompatible;
7475   }
7476 
7477   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7478   // to the same ExtVector type.
7479   if (LHSType->isExtVectorType()) {
7480     if (RHSType->isExtVectorType())
7481       return Incompatible;
7482     if (RHSType->isArithmeticType()) {
7483       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7484       if (ConvertRHS)
7485         RHS = prepareVectorSplat(LHSType, RHS.get());
7486       Kind = CK_VectorSplat;
7487       return Compatible;
7488     }
7489   }
7490 
7491   // Conversions to or from vector type.
7492   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7493     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7494       // Allow assignments of an AltiVec vector type to an equivalent GCC
7495       // vector type and vice versa
7496       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7497         Kind = CK_BitCast;
7498         return Compatible;
7499       }
7500 
7501       // If we are allowing lax vector conversions, and LHS and RHS are both
7502       // vectors, the total size only needs to be the same. This is a bitcast;
7503       // no bits are changed but the result type is different.
7504       if (isLaxVectorConversion(RHSType, LHSType)) {
7505         Kind = CK_BitCast;
7506         return IncompatibleVectors;
7507       }
7508     }
7509 
7510     // When the RHS comes from another lax conversion (e.g. binops between
7511     // scalars and vectors) the result is canonicalized as a vector. When the
7512     // LHS is also a vector, the lax is allowed by the condition above. Handle
7513     // the case where LHS is a scalar.
7514     if (LHSType->isScalarType()) {
7515       const VectorType *VecType = RHSType->getAs<VectorType>();
7516       if (VecType && VecType->getNumElements() == 1 &&
7517           isLaxVectorConversion(RHSType, LHSType)) {
7518         ExprResult *VecExpr = &RHS;
7519         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7520         Kind = CK_BitCast;
7521         return Compatible;
7522       }
7523     }
7524 
7525     return Incompatible;
7526   }
7527 
7528   // Diagnose attempts to convert between __float128 and long double where
7529   // such conversions currently can't be handled.
7530   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7531     return Incompatible;
7532 
7533   // Arithmetic conversions.
7534   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7535       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7536     if (ConvertRHS)
7537       Kind = PrepareScalarCast(RHS, LHSType);
7538     return Compatible;
7539   }
7540 
7541   // Conversions to normal pointers.
7542   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7543     // U* -> T*
7544     if (isa<PointerType>(RHSType)) {
7545       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7546       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7547       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7548       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7549     }
7550 
7551     // int -> T*
7552     if (RHSType->isIntegerType()) {
7553       Kind = CK_IntegralToPointer; // FIXME: null?
7554       return IntToPointer;
7555     }
7556 
7557     // C pointers are not compatible with ObjC object pointers,
7558     // with two exceptions:
7559     if (isa<ObjCObjectPointerType>(RHSType)) {
7560       //  - conversions to void*
7561       if (LHSPointer->getPointeeType()->isVoidType()) {
7562         Kind = CK_BitCast;
7563         return Compatible;
7564       }
7565 
7566       //  - conversions from 'Class' to the redefinition type
7567       if (RHSType->isObjCClassType() &&
7568           Context.hasSameType(LHSType,
7569                               Context.getObjCClassRedefinitionType())) {
7570         Kind = CK_BitCast;
7571         return Compatible;
7572       }
7573 
7574       Kind = CK_BitCast;
7575       return IncompatiblePointer;
7576     }
7577 
7578     // U^ -> void*
7579     if (RHSType->getAs<BlockPointerType>()) {
7580       if (LHSPointer->getPointeeType()->isVoidType()) {
7581         unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7582         unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7583                                   ->getPointeeType()
7584                                   .getAddressSpace();
7585         Kind =
7586             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7587         return Compatible;
7588       }
7589     }
7590 
7591     return Incompatible;
7592   }
7593 
7594   // Conversions to block pointers.
7595   if (isa<BlockPointerType>(LHSType)) {
7596     // U^ -> T^
7597     if (RHSType->isBlockPointerType()) {
7598       unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7599                                 ->getPointeeType()
7600                                 .getAddressSpace();
7601       unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7602                                 ->getPointeeType()
7603                                 .getAddressSpace();
7604       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7605       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7606     }
7607 
7608     // int or null -> T^
7609     if (RHSType->isIntegerType()) {
7610       Kind = CK_IntegralToPointer; // FIXME: null
7611       return IntToBlockPointer;
7612     }
7613 
7614     // id -> T^
7615     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7616       Kind = CK_AnyPointerToBlockPointerCast;
7617       return Compatible;
7618     }
7619 
7620     // void* -> T^
7621     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7622       if (RHSPT->getPointeeType()->isVoidType()) {
7623         Kind = CK_AnyPointerToBlockPointerCast;
7624         return Compatible;
7625       }
7626 
7627     return Incompatible;
7628   }
7629 
7630   // Conversions to Objective-C pointers.
7631   if (isa<ObjCObjectPointerType>(LHSType)) {
7632     // A* -> B*
7633     if (RHSType->isObjCObjectPointerType()) {
7634       Kind = CK_BitCast;
7635       Sema::AssignConvertType result =
7636         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7637       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7638           result == Compatible &&
7639           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7640         result = IncompatibleObjCWeakRef;
7641       return result;
7642     }
7643 
7644     // int or null -> A*
7645     if (RHSType->isIntegerType()) {
7646       Kind = CK_IntegralToPointer; // FIXME: null
7647       return IntToPointer;
7648     }
7649 
7650     // In general, C pointers are not compatible with ObjC object pointers,
7651     // with two exceptions:
7652     if (isa<PointerType>(RHSType)) {
7653       Kind = CK_CPointerToObjCPointerCast;
7654 
7655       //  - conversions from 'void*'
7656       if (RHSType->isVoidPointerType()) {
7657         return Compatible;
7658       }
7659 
7660       //  - conversions to 'Class' from its redefinition type
7661       if (LHSType->isObjCClassType() &&
7662           Context.hasSameType(RHSType,
7663                               Context.getObjCClassRedefinitionType())) {
7664         return Compatible;
7665       }
7666 
7667       return IncompatiblePointer;
7668     }
7669 
7670     // Only under strict condition T^ is compatible with an Objective-C pointer.
7671     if (RHSType->isBlockPointerType() &&
7672         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7673       if (ConvertRHS)
7674         maybeExtendBlockObject(RHS);
7675       Kind = CK_BlockPointerToObjCPointerCast;
7676       return Compatible;
7677     }
7678 
7679     return Incompatible;
7680   }
7681 
7682   // Conversions from pointers that are not covered by the above.
7683   if (isa<PointerType>(RHSType)) {
7684     // T* -> _Bool
7685     if (LHSType == Context.BoolTy) {
7686       Kind = CK_PointerToBoolean;
7687       return Compatible;
7688     }
7689 
7690     // T* -> int
7691     if (LHSType->isIntegerType()) {
7692       Kind = CK_PointerToIntegral;
7693       return PointerToInt;
7694     }
7695 
7696     return Incompatible;
7697   }
7698 
7699   // Conversions from Objective-C pointers that are not covered by the above.
7700   if (isa<ObjCObjectPointerType>(RHSType)) {
7701     // T* -> _Bool
7702     if (LHSType == Context.BoolTy) {
7703       Kind = CK_PointerToBoolean;
7704       return Compatible;
7705     }
7706 
7707     // T* -> int
7708     if (LHSType->isIntegerType()) {
7709       Kind = CK_PointerToIntegral;
7710       return PointerToInt;
7711     }
7712 
7713     return Incompatible;
7714   }
7715 
7716   // struct A -> struct B
7717   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7718     if (Context.typesAreCompatible(LHSType, RHSType)) {
7719       Kind = CK_NoOp;
7720       return Compatible;
7721     }
7722   }
7723 
7724   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7725     Kind = CK_IntToOCLSampler;
7726     return Compatible;
7727   }
7728 
7729   return Incompatible;
7730 }
7731 
7732 /// \brief Constructs a transparent union from an expression that is
7733 /// used to initialize the transparent union.
7734 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7735                                       ExprResult &EResult, QualType UnionType,
7736                                       FieldDecl *Field) {
7737   // Build an initializer list that designates the appropriate member
7738   // of the transparent union.
7739   Expr *E = EResult.get();
7740   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7741                                                    E, SourceLocation());
7742   Initializer->setType(UnionType);
7743   Initializer->setInitializedFieldInUnion(Field);
7744 
7745   // Build a compound literal constructing a value of the transparent
7746   // union type from this initializer list.
7747   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7748   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7749                                         VK_RValue, Initializer, false);
7750 }
7751 
7752 Sema::AssignConvertType
7753 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7754                                                ExprResult &RHS) {
7755   QualType RHSType = RHS.get()->getType();
7756 
7757   // If the ArgType is a Union type, we want to handle a potential
7758   // transparent_union GCC extension.
7759   const RecordType *UT = ArgType->getAsUnionType();
7760   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7761     return Incompatible;
7762 
7763   // The field to initialize within the transparent union.
7764   RecordDecl *UD = UT->getDecl();
7765   FieldDecl *InitField = nullptr;
7766   // It's compatible if the expression matches any of the fields.
7767   for (auto *it : UD->fields()) {
7768     if (it->getType()->isPointerType()) {
7769       // If the transparent union contains a pointer type, we allow:
7770       // 1) void pointer
7771       // 2) null pointer constant
7772       if (RHSType->isPointerType())
7773         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7774           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7775           InitField = it;
7776           break;
7777         }
7778 
7779       if (RHS.get()->isNullPointerConstant(Context,
7780                                            Expr::NPC_ValueDependentIsNull)) {
7781         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7782                                 CK_NullToPointer);
7783         InitField = it;
7784         break;
7785       }
7786     }
7787 
7788     CastKind Kind = CK_Invalid;
7789     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7790           == Compatible) {
7791       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7792       InitField = it;
7793       break;
7794     }
7795   }
7796 
7797   if (!InitField)
7798     return Incompatible;
7799 
7800   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7801   return Compatible;
7802 }
7803 
7804 Sema::AssignConvertType
7805 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7806                                        bool Diagnose,
7807                                        bool DiagnoseCFAudited,
7808                                        bool ConvertRHS) {
7809   // We need to be able to tell the caller whether we diagnosed a problem, if
7810   // they ask us to issue diagnostics.
7811   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7812 
7813   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7814   // we can't avoid *all* modifications at the moment, so we need some somewhere
7815   // to put the updated value.
7816   ExprResult LocalRHS = CallerRHS;
7817   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7818 
7819   if (getLangOpts().CPlusPlus) {
7820     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7821       // C++ 5.17p3: If the left operand is not of class type, the
7822       // expression is implicitly converted (C++ 4) to the
7823       // cv-unqualified type of the left operand.
7824       QualType RHSType = RHS.get()->getType();
7825       if (Diagnose) {
7826         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7827                                         AA_Assigning);
7828       } else {
7829         ImplicitConversionSequence ICS =
7830             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7831                                   /*SuppressUserConversions=*/false,
7832                                   /*AllowExplicit=*/false,
7833                                   /*InOverloadResolution=*/false,
7834                                   /*CStyle=*/false,
7835                                   /*AllowObjCWritebackConversion=*/false);
7836         if (ICS.isFailure())
7837           return Incompatible;
7838         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7839                                         ICS, AA_Assigning);
7840       }
7841       if (RHS.isInvalid())
7842         return Incompatible;
7843       Sema::AssignConvertType result = Compatible;
7844       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7845           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7846         result = IncompatibleObjCWeakRef;
7847       return result;
7848     }
7849 
7850     // FIXME: Currently, we fall through and treat C++ classes like C
7851     // structures.
7852     // FIXME: We also fall through for atomics; not sure what should
7853     // happen there, though.
7854   } else if (RHS.get()->getType() == Context.OverloadTy) {
7855     // As a set of extensions to C, we support overloading on functions. These
7856     // functions need to be resolved here.
7857     DeclAccessPair DAP;
7858     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7859             RHS.get(), LHSType, /*Complain=*/false, DAP))
7860       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7861     else
7862       return Incompatible;
7863   }
7864 
7865   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7866   // a null pointer constant.
7867   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7868        LHSType->isBlockPointerType()) &&
7869       RHS.get()->isNullPointerConstant(Context,
7870                                        Expr::NPC_ValueDependentIsNull)) {
7871     if (Diagnose || ConvertRHS) {
7872       CastKind Kind;
7873       CXXCastPath Path;
7874       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7875                              /*IgnoreBaseAccess=*/false, Diagnose);
7876       if (ConvertRHS)
7877         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7878     }
7879     return Compatible;
7880   }
7881 
7882   // This check seems unnatural, however it is necessary to ensure the proper
7883   // conversion of functions/arrays. If the conversion were done for all
7884   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7885   // expressions that suppress this implicit conversion (&, sizeof).
7886   //
7887   // Suppress this for references: C++ 8.5.3p5.
7888   if (!LHSType->isReferenceType()) {
7889     // FIXME: We potentially allocate here even if ConvertRHS is false.
7890     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7891     if (RHS.isInvalid())
7892       return Incompatible;
7893   }
7894 
7895   Expr *PRE = RHS.get()->IgnoreParenCasts();
7896   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7897     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7898     if (PDecl && !PDecl->hasDefinition()) {
7899       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7900       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7901     }
7902   }
7903 
7904   CastKind Kind = CK_Invalid;
7905   Sema::AssignConvertType result =
7906     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7907 
7908   // C99 6.5.16.1p2: The value of the right operand is converted to the
7909   // type of the assignment expression.
7910   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7911   // so that we can use references in built-in functions even in C.
7912   // The getNonReferenceType() call makes sure that the resulting expression
7913   // does not have reference type.
7914   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7915     QualType Ty = LHSType.getNonLValueExprType(Context);
7916     Expr *E = RHS.get();
7917 
7918     // Check for various Objective-C errors. If we are not reporting
7919     // diagnostics and just checking for errors, e.g., during overload
7920     // resolution, return Incompatible to indicate the failure.
7921     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7922         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7923                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
7924       if (!Diagnose)
7925         return Incompatible;
7926     }
7927     if (getLangOpts().ObjC1 &&
7928         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7929                                            E->getType(), E, Diagnose) ||
7930          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7931       if (!Diagnose)
7932         return Incompatible;
7933       // Replace the expression with a corrected version and continue so we
7934       // can find further errors.
7935       RHS = E;
7936       return Compatible;
7937     }
7938 
7939     if (ConvertRHS)
7940       RHS = ImpCastExprToType(E, Ty, Kind);
7941   }
7942   return result;
7943 }
7944 
7945 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7946                                ExprResult &RHS) {
7947   Diag(Loc, diag::err_typecheck_invalid_operands)
7948     << LHS.get()->getType() << RHS.get()->getType()
7949     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7950   return QualType();
7951 }
7952 
7953 // Diagnose cases where a scalar was implicitly converted to a vector and
7954 // diagnose the underlying types. Otherwise, diagnose the error
7955 // as invalid vector logical operands for non-C++ cases.
7956 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
7957                                             ExprResult &RHS) {
7958   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
7959   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
7960 
7961   bool LHSNatVec = LHSType->isVectorType();
7962   bool RHSNatVec = RHSType->isVectorType();
7963 
7964   if (!(LHSNatVec && RHSNatVec)) {
7965     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
7966     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
7967     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
7968         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
7969         << Vector->getSourceRange();
7970     return QualType();
7971   }
7972 
7973   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
7974       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
7975       << RHS.get()->getSourceRange();
7976 
7977   return QualType();
7978 }
7979 
7980 /// Try to convert a value of non-vector type to a vector type by converting
7981 /// the type to the element type of the vector and then performing a splat.
7982 /// If the language is OpenCL, we only use conversions that promote scalar
7983 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7984 /// for float->int.
7985 ///
7986 /// OpenCL V2.0 6.2.6.p2:
7987 /// An error shall occur if any scalar operand type has greater rank
7988 /// than the type of the vector element.
7989 ///
7990 /// \param scalar - if non-null, actually perform the conversions
7991 /// \return true if the operation fails (but without diagnosing the failure)
7992 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7993                                      QualType scalarTy,
7994                                      QualType vectorEltTy,
7995                                      QualType vectorTy,
7996                                      unsigned &DiagID) {
7997   // The conversion to apply to the scalar before splatting it,
7998   // if necessary.
7999   CastKind scalarCast = CK_Invalid;
8000 
8001   if (vectorEltTy->isIntegralType(S.Context)) {
8002     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8003         (scalarTy->isIntegerType() &&
8004          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8005       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8006       return true;
8007     }
8008     if (!scalarTy->isIntegralType(S.Context))
8009       return true;
8010     scalarCast = CK_IntegralCast;
8011   } else if (vectorEltTy->isRealFloatingType()) {
8012     if (scalarTy->isRealFloatingType()) {
8013       if (S.getLangOpts().OpenCL &&
8014           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8015         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8016         return true;
8017       }
8018       scalarCast = CK_FloatingCast;
8019     }
8020     else if (scalarTy->isIntegralType(S.Context))
8021       scalarCast = CK_IntegralToFloating;
8022     else
8023       return true;
8024   } else {
8025     return true;
8026   }
8027 
8028   // Adjust scalar if desired.
8029   if (scalar) {
8030     if (scalarCast != CK_Invalid)
8031       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8032     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8033   }
8034   return false;
8035 }
8036 
8037 /// Test if a (constant) integer Int can be casted to another integer type
8038 /// IntTy without losing precision.
8039 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8040                                       QualType OtherIntTy) {
8041   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8042 
8043   // Reject cases where the value of the Int is unknown as that would
8044   // possibly cause truncation, but accept cases where the scalar can be
8045   // demoted without loss of precision.
8046   llvm::APSInt Result;
8047   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8048   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8049   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8050   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8051 
8052   if (CstInt) {
8053     // If the scalar is constant and is of a higher order and has more active
8054     // bits that the vector element type, reject it.
8055     unsigned NumBits = IntSigned
8056                            ? (Result.isNegative() ? Result.getMinSignedBits()
8057                                                   : Result.getActiveBits())
8058                            : Result.getActiveBits();
8059     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8060       return true;
8061 
8062     // If the signedness of the scalar type and the vector element type
8063     // differs and the number of bits is greater than that of the vector
8064     // element reject it.
8065     return (IntSigned != OtherIntSigned &&
8066             NumBits > S.Context.getIntWidth(OtherIntTy));
8067   }
8068 
8069   // Reject cases where the value of the scalar is not constant and it's
8070   // order is greater than that of the vector element type.
8071   return (Order < 0);
8072 }
8073 
8074 /// Test if a (constant) integer Int can be casted to floating point type
8075 /// FloatTy without losing precision.
8076 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8077                                      QualType FloatTy) {
8078   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8079 
8080   // Determine if the integer constant can be expressed as a floating point
8081   // number of the appropiate type.
8082   llvm::APSInt Result;
8083   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8084   uint64_t Bits = 0;
8085   if (CstInt) {
8086     // Reject constants that would be truncated if they were converted to
8087     // the floating point type. Test by simple to/from conversion.
8088     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8089     //        could be avoided if there was a convertFromAPInt method
8090     //        which could signal back if implicit truncation occurred.
8091     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8092     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8093                            llvm::APFloat::rmTowardZero);
8094     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8095                              !IntTy->hasSignedIntegerRepresentation());
8096     bool Ignored = false;
8097     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8098                            &Ignored);
8099     if (Result != ConvertBack)
8100       return true;
8101   } else {
8102     // Reject types that cannot be fully encoded into the mantissa of
8103     // the float.
8104     Bits = S.Context.getTypeSize(IntTy);
8105     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8106         S.Context.getFloatTypeSemantics(FloatTy));
8107     if (Bits > FloatPrec)
8108       return true;
8109   }
8110 
8111   return false;
8112 }
8113 
8114 /// Attempt to convert and splat Scalar into a vector whose types matches
8115 /// Vector following GCC conversion rules. The rule is that implicit
8116 /// conversion can occur when Scalar can be casted to match Vector's element
8117 /// type without causing truncation of Scalar.
8118 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8119                                         ExprResult *Vector) {
8120   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8121   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8122   const VectorType *VT = VectorTy->getAs<VectorType>();
8123 
8124   assert(!isa<ExtVectorType>(VT) &&
8125          "ExtVectorTypes should not be handled here!");
8126 
8127   QualType VectorEltTy = VT->getElementType();
8128 
8129   // Reject cases where the vector element type or the scalar element type are
8130   // not integral or floating point types.
8131   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8132     return true;
8133 
8134   // The conversion to apply to the scalar before splatting it,
8135   // if necessary.
8136   CastKind ScalarCast = CK_NoOp;
8137 
8138   // Accept cases where the vector elements are integers and the scalar is
8139   // an integer.
8140   // FIXME: Notionally if the scalar was a floating point value with a precise
8141   //        integral representation, we could cast it to an appropriate integer
8142   //        type and then perform the rest of the checks here. GCC will perform
8143   //        this conversion in some cases as determined by the input language.
8144   //        We should accept it on a language independent basis.
8145   if (VectorEltTy->isIntegralType(S.Context) &&
8146       ScalarTy->isIntegralType(S.Context) &&
8147       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8148 
8149     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8150       return true;
8151 
8152     ScalarCast = CK_IntegralCast;
8153   } else if (VectorEltTy->isRealFloatingType()) {
8154     if (ScalarTy->isRealFloatingType()) {
8155 
8156       // Reject cases where the scalar type is not a constant and has a higher
8157       // Order than the vector element type.
8158       llvm::APFloat Result(0.0);
8159       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8160       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8161       if (!CstScalar && Order < 0)
8162         return true;
8163 
8164       // If the scalar cannot be safely casted to the vector element type,
8165       // reject it.
8166       if (CstScalar) {
8167         bool Truncated = false;
8168         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8169                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8170         if (Truncated)
8171           return true;
8172       }
8173 
8174       ScalarCast = CK_FloatingCast;
8175     } else if (ScalarTy->isIntegralType(S.Context)) {
8176       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8177         return true;
8178 
8179       ScalarCast = CK_IntegralToFloating;
8180     } else
8181       return true;
8182   }
8183 
8184   // Adjust scalar if desired.
8185   if (Scalar) {
8186     if (ScalarCast != CK_NoOp)
8187       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8188     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8189   }
8190   return false;
8191 }
8192 
8193 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8194                                    SourceLocation Loc, bool IsCompAssign,
8195                                    bool AllowBothBool,
8196                                    bool AllowBoolConversions) {
8197   if (!IsCompAssign) {
8198     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8199     if (LHS.isInvalid())
8200       return QualType();
8201   }
8202   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8203   if (RHS.isInvalid())
8204     return QualType();
8205 
8206   // For conversion purposes, we ignore any qualifiers.
8207   // For example, "const float" and "float" are equivalent.
8208   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8209   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8210 
8211   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8212   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8213   assert(LHSVecType || RHSVecType);
8214 
8215   // AltiVec-style "vector bool op vector bool" combinations are allowed
8216   // for some operators but not others.
8217   if (!AllowBothBool &&
8218       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8219       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8220     return InvalidOperands(Loc, LHS, RHS);
8221 
8222   // If the vector types are identical, return.
8223   if (Context.hasSameType(LHSType, RHSType))
8224     return LHSType;
8225 
8226   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8227   if (LHSVecType && RHSVecType &&
8228       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8229     if (isa<ExtVectorType>(LHSVecType)) {
8230       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8231       return LHSType;
8232     }
8233 
8234     if (!IsCompAssign)
8235       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8236     return RHSType;
8237   }
8238 
8239   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8240   // can be mixed, with the result being the non-bool type.  The non-bool
8241   // operand must have integer element type.
8242   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8243       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8244       (Context.getTypeSize(LHSVecType->getElementType()) ==
8245        Context.getTypeSize(RHSVecType->getElementType()))) {
8246     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8247         LHSVecType->getElementType()->isIntegerType() &&
8248         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8249       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8250       return LHSType;
8251     }
8252     if (!IsCompAssign &&
8253         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8254         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8255         RHSVecType->getElementType()->isIntegerType()) {
8256       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8257       return RHSType;
8258     }
8259   }
8260 
8261   // If there's a vector type and a scalar, try to convert the scalar to
8262   // the vector element type and splat.
8263   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8264   if (!RHSVecType) {
8265     if (isa<ExtVectorType>(LHSVecType)) {
8266       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8267                                     LHSVecType->getElementType(), LHSType,
8268                                     DiagID))
8269         return LHSType;
8270     } else {
8271       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8272         return LHSType;
8273     }
8274   }
8275   if (!LHSVecType) {
8276     if (isa<ExtVectorType>(RHSVecType)) {
8277       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8278                                     LHSType, RHSVecType->getElementType(),
8279                                     RHSType, DiagID))
8280         return RHSType;
8281     } else {
8282       if (LHS.get()->getValueKind() == VK_LValue ||
8283           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8284         return RHSType;
8285     }
8286   }
8287 
8288   // FIXME: The code below also handles conversion between vectors and
8289   // non-scalars, we should break this down into fine grained specific checks
8290   // and emit proper diagnostics.
8291   QualType VecType = LHSVecType ? LHSType : RHSType;
8292   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8293   QualType OtherType = LHSVecType ? RHSType : LHSType;
8294   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8295   if (isLaxVectorConversion(OtherType, VecType)) {
8296     // If we're allowing lax vector conversions, only the total (data) size
8297     // needs to be the same. For non compound assignment, if one of the types is
8298     // scalar, the result is always the vector type.
8299     if (!IsCompAssign) {
8300       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8301       return VecType;
8302     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8303     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8304     // type. Note that this is already done by non-compound assignments in
8305     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8306     // <1 x T> -> T. The result is also a vector type.
8307     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8308                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8309       ExprResult *RHSExpr = &RHS;
8310       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8311       return VecType;
8312     }
8313   }
8314 
8315   // Okay, the expression is invalid.
8316 
8317   // If there's a non-vector, non-real operand, diagnose that.
8318   if ((!RHSVecType && !RHSType->isRealType()) ||
8319       (!LHSVecType && !LHSType->isRealType())) {
8320     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8321       << LHSType << RHSType
8322       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8323     return QualType();
8324   }
8325 
8326   // OpenCL V1.1 6.2.6.p1:
8327   // If the operands are of more than one vector type, then an error shall
8328   // occur. Implicit conversions between vector types are not permitted, per
8329   // section 6.2.1.
8330   if (getLangOpts().OpenCL &&
8331       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8332       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8333     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8334                                                            << RHSType;
8335     return QualType();
8336   }
8337 
8338 
8339   // If there is a vector type that is not a ExtVector and a scalar, we reach
8340   // this point if scalar could not be converted to the vector's element type
8341   // without truncation.
8342   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8343       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8344     QualType Scalar = LHSVecType ? RHSType : LHSType;
8345     QualType Vector = LHSVecType ? LHSType : RHSType;
8346     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8347     Diag(Loc,
8348          diag::err_typecheck_vector_not_convertable_implict_truncation)
8349         << ScalarOrVector << Scalar << Vector;
8350 
8351     return QualType();
8352   }
8353 
8354   // Otherwise, use the generic diagnostic.
8355   Diag(Loc, DiagID)
8356     << LHSType << RHSType
8357     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8358   return QualType();
8359 }
8360 
8361 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8362 // expression.  These are mainly cases where the null pointer is used as an
8363 // integer instead of a pointer.
8364 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8365                                 SourceLocation Loc, bool IsCompare) {
8366   // The canonical way to check for a GNU null is with isNullPointerConstant,
8367   // but we use a bit of a hack here for speed; this is a relatively
8368   // hot path, and isNullPointerConstant is slow.
8369   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8370   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8371 
8372   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8373 
8374   // Avoid analyzing cases where the result will either be invalid (and
8375   // diagnosed as such) or entirely valid and not something to warn about.
8376   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8377       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8378     return;
8379 
8380   // Comparison operations would not make sense with a null pointer no matter
8381   // what the other expression is.
8382   if (!IsCompare) {
8383     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8384         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8385         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8386     return;
8387   }
8388 
8389   // The rest of the operations only make sense with a null pointer
8390   // if the other expression is a pointer.
8391   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8392       NonNullType->canDecayToPointerType())
8393     return;
8394 
8395   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8396       << LHSNull /* LHS is NULL */ << NonNullType
8397       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8398 }
8399 
8400 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8401                                                ExprResult &RHS,
8402                                                SourceLocation Loc, bool IsDiv) {
8403   // Check for division/remainder by zero.
8404   llvm::APSInt RHSValue;
8405   if (!RHS.get()->isValueDependent() &&
8406       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8407     S.DiagRuntimeBehavior(Loc, RHS.get(),
8408                           S.PDiag(diag::warn_remainder_division_by_zero)
8409                             << IsDiv << RHS.get()->getSourceRange());
8410 }
8411 
8412 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8413                                            SourceLocation Loc,
8414                                            bool IsCompAssign, bool IsDiv) {
8415   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8416 
8417   if (LHS.get()->getType()->isVectorType() ||
8418       RHS.get()->getType()->isVectorType())
8419     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8420                                /*AllowBothBool*/getLangOpts().AltiVec,
8421                                /*AllowBoolConversions*/false);
8422 
8423   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8424   if (LHS.isInvalid() || RHS.isInvalid())
8425     return QualType();
8426 
8427 
8428   if (compType.isNull() || !compType->isArithmeticType())
8429     return InvalidOperands(Loc, LHS, RHS);
8430   if (IsDiv)
8431     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8432   return compType;
8433 }
8434 
8435 QualType Sema::CheckRemainderOperands(
8436   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8437   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8438 
8439   if (LHS.get()->getType()->isVectorType() ||
8440       RHS.get()->getType()->isVectorType()) {
8441     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8442         RHS.get()->getType()->hasIntegerRepresentation())
8443       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8444                                  /*AllowBothBool*/getLangOpts().AltiVec,
8445                                  /*AllowBoolConversions*/false);
8446     return InvalidOperands(Loc, LHS, RHS);
8447   }
8448 
8449   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8450   if (LHS.isInvalid() || RHS.isInvalid())
8451     return QualType();
8452 
8453   if (compType.isNull() || !compType->isIntegerType())
8454     return InvalidOperands(Loc, LHS, RHS);
8455   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8456   return compType;
8457 }
8458 
8459 /// \brief Diagnose invalid arithmetic on two void pointers.
8460 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8461                                                 Expr *LHSExpr, Expr *RHSExpr) {
8462   S.Diag(Loc, S.getLangOpts().CPlusPlus
8463                 ? diag::err_typecheck_pointer_arith_void_type
8464                 : diag::ext_gnu_void_ptr)
8465     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8466                             << RHSExpr->getSourceRange();
8467 }
8468 
8469 /// \brief Diagnose invalid arithmetic on a void pointer.
8470 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8471                                             Expr *Pointer) {
8472   S.Diag(Loc, S.getLangOpts().CPlusPlus
8473                 ? diag::err_typecheck_pointer_arith_void_type
8474                 : diag::ext_gnu_void_ptr)
8475     << 0 /* one pointer */ << Pointer->getSourceRange();
8476 }
8477 
8478 /// \brief Diagnose invalid arithmetic on two function pointers.
8479 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8480                                                     Expr *LHS, Expr *RHS) {
8481   assert(LHS->getType()->isAnyPointerType());
8482   assert(RHS->getType()->isAnyPointerType());
8483   S.Diag(Loc, S.getLangOpts().CPlusPlus
8484                 ? diag::err_typecheck_pointer_arith_function_type
8485                 : diag::ext_gnu_ptr_func_arith)
8486     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8487     // We only show the second type if it differs from the first.
8488     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8489                                                    RHS->getType())
8490     << RHS->getType()->getPointeeType()
8491     << LHS->getSourceRange() << RHS->getSourceRange();
8492 }
8493 
8494 /// \brief Diagnose invalid arithmetic on a function pointer.
8495 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8496                                                 Expr *Pointer) {
8497   assert(Pointer->getType()->isAnyPointerType());
8498   S.Diag(Loc, S.getLangOpts().CPlusPlus
8499                 ? diag::err_typecheck_pointer_arith_function_type
8500                 : diag::ext_gnu_ptr_func_arith)
8501     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8502     << 0 /* one pointer, so only one type */
8503     << Pointer->getSourceRange();
8504 }
8505 
8506 /// \brief Emit error if Operand is incomplete pointer type
8507 ///
8508 /// \returns True if pointer has incomplete type
8509 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8510                                                  Expr *Operand) {
8511   QualType ResType = Operand->getType();
8512   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8513     ResType = ResAtomicType->getValueType();
8514 
8515   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8516   QualType PointeeTy = ResType->getPointeeType();
8517   return S.RequireCompleteType(Loc, PointeeTy,
8518                                diag::err_typecheck_arithmetic_incomplete_type,
8519                                PointeeTy, Operand->getSourceRange());
8520 }
8521 
8522 /// \brief Check the validity of an arithmetic pointer operand.
8523 ///
8524 /// If the operand has pointer type, this code will check for pointer types
8525 /// which are invalid in arithmetic operations. These will be diagnosed
8526 /// appropriately, including whether or not the use is supported as an
8527 /// extension.
8528 ///
8529 /// \returns True when the operand is valid to use (even if as an extension).
8530 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8531                                             Expr *Operand) {
8532   QualType ResType = Operand->getType();
8533   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8534     ResType = ResAtomicType->getValueType();
8535 
8536   if (!ResType->isAnyPointerType()) return true;
8537 
8538   QualType PointeeTy = ResType->getPointeeType();
8539   if (PointeeTy->isVoidType()) {
8540     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8541     return !S.getLangOpts().CPlusPlus;
8542   }
8543   if (PointeeTy->isFunctionType()) {
8544     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8545     return !S.getLangOpts().CPlusPlus;
8546   }
8547 
8548   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8549 
8550   return true;
8551 }
8552 
8553 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8554 /// operands.
8555 ///
8556 /// This routine will diagnose any invalid arithmetic on pointer operands much
8557 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8558 /// for emitting a single diagnostic even for operations where both LHS and RHS
8559 /// are (potentially problematic) pointers.
8560 ///
8561 /// \returns True when the operand is valid to use (even if as an extension).
8562 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8563                                                 Expr *LHSExpr, Expr *RHSExpr) {
8564   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8565   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8566   if (!isLHSPointer && !isRHSPointer) return true;
8567 
8568   QualType LHSPointeeTy, RHSPointeeTy;
8569   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8570   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8571 
8572   // if both are pointers check if operation is valid wrt address spaces
8573   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8574     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8575     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8576     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8577       S.Diag(Loc,
8578              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8579           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8580           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8581       return false;
8582     }
8583   }
8584 
8585   // Check for arithmetic on pointers to incomplete types.
8586   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8587   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8588   if (isLHSVoidPtr || isRHSVoidPtr) {
8589     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8590     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8591     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8592 
8593     return !S.getLangOpts().CPlusPlus;
8594   }
8595 
8596   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8597   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8598   if (isLHSFuncPtr || isRHSFuncPtr) {
8599     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8600     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8601                                                                 RHSExpr);
8602     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8603 
8604     return !S.getLangOpts().CPlusPlus;
8605   }
8606 
8607   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8608     return false;
8609   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8610     return false;
8611 
8612   return true;
8613 }
8614 
8615 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8616 /// literal.
8617 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8618                                   Expr *LHSExpr, Expr *RHSExpr) {
8619   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8620   Expr* IndexExpr = RHSExpr;
8621   if (!StrExpr) {
8622     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8623     IndexExpr = LHSExpr;
8624   }
8625 
8626   bool IsStringPlusInt = StrExpr &&
8627       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8628   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8629     return;
8630 
8631   llvm::APSInt index;
8632   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8633     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8634     if (index.isNonNegative() &&
8635         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8636                               index.isUnsigned()))
8637       return;
8638   }
8639 
8640   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8641   Self.Diag(OpLoc, diag::warn_string_plus_int)
8642       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8643 
8644   // Only print a fixit for "str" + int, not for int + "str".
8645   if (IndexExpr == RHSExpr) {
8646     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8647     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8648         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8649         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8650         << FixItHint::CreateInsertion(EndLoc, "]");
8651   } else
8652     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8653 }
8654 
8655 /// \brief Emit a warning when adding a char literal to a string.
8656 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8657                                    Expr *LHSExpr, Expr *RHSExpr) {
8658   const Expr *StringRefExpr = LHSExpr;
8659   const CharacterLiteral *CharExpr =
8660       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8661 
8662   if (!CharExpr) {
8663     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8664     StringRefExpr = RHSExpr;
8665   }
8666 
8667   if (!CharExpr || !StringRefExpr)
8668     return;
8669 
8670   const QualType StringType = StringRefExpr->getType();
8671 
8672   // Return if not a PointerType.
8673   if (!StringType->isAnyPointerType())
8674     return;
8675 
8676   // Return if not a CharacterType.
8677   if (!StringType->getPointeeType()->isAnyCharacterType())
8678     return;
8679 
8680   ASTContext &Ctx = Self.getASTContext();
8681   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8682 
8683   const QualType CharType = CharExpr->getType();
8684   if (!CharType->isAnyCharacterType() &&
8685       CharType->isIntegerType() &&
8686       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8687     Self.Diag(OpLoc, diag::warn_string_plus_char)
8688         << DiagRange << Ctx.CharTy;
8689   } else {
8690     Self.Diag(OpLoc, diag::warn_string_plus_char)
8691         << DiagRange << CharExpr->getType();
8692   }
8693 
8694   // Only print a fixit for str + char, not for char + str.
8695   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8696     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8697     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8698         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8699         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8700         << FixItHint::CreateInsertion(EndLoc, "]");
8701   } else {
8702     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8703   }
8704 }
8705 
8706 /// \brief Emit error when two pointers are incompatible.
8707 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8708                                            Expr *LHSExpr, Expr *RHSExpr) {
8709   assert(LHSExpr->getType()->isAnyPointerType());
8710   assert(RHSExpr->getType()->isAnyPointerType());
8711   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8712     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8713     << RHSExpr->getSourceRange();
8714 }
8715 
8716 // C99 6.5.6
8717 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8718                                      SourceLocation Loc, BinaryOperatorKind Opc,
8719                                      QualType* CompLHSTy) {
8720   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8721 
8722   if (LHS.get()->getType()->isVectorType() ||
8723       RHS.get()->getType()->isVectorType()) {
8724     QualType compType = CheckVectorOperands(
8725         LHS, RHS, Loc, CompLHSTy,
8726         /*AllowBothBool*/getLangOpts().AltiVec,
8727         /*AllowBoolConversions*/getLangOpts().ZVector);
8728     if (CompLHSTy) *CompLHSTy = compType;
8729     return compType;
8730   }
8731 
8732   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8733   if (LHS.isInvalid() || RHS.isInvalid())
8734     return QualType();
8735 
8736   // Diagnose "string literal" '+' int and string '+' "char literal".
8737   if (Opc == BO_Add) {
8738     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8739     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8740   }
8741 
8742   // handle the common case first (both operands are arithmetic).
8743   if (!compType.isNull() && compType->isArithmeticType()) {
8744     if (CompLHSTy) *CompLHSTy = compType;
8745     return compType;
8746   }
8747 
8748   // Type-checking.  Ultimately the pointer's going to be in PExp;
8749   // note that we bias towards the LHS being the pointer.
8750   Expr *PExp = LHS.get(), *IExp = RHS.get();
8751 
8752   bool isObjCPointer;
8753   if (PExp->getType()->isPointerType()) {
8754     isObjCPointer = false;
8755   } else if (PExp->getType()->isObjCObjectPointerType()) {
8756     isObjCPointer = true;
8757   } else {
8758     std::swap(PExp, IExp);
8759     if (PExp->getType()->isPointerType()) {
8760       isObjCPointer = false;
8761     } else if (PExp->getType()->isObjCObjectPointerType()) {
8762       isObjCPointer = true;
8763     } else {
8764       return InvalidOperands(Loc, LHS, RHS);
8765     }
8766   }
8767   assert(PExp->getType()->isAnyPointerType());
8768 
8769   if (!IExp->getType()->isIntegerType())
8770     return InvalidOperands(Loc, LHS, RHS);
8771 
8772   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8773     return QualType();
8774 
8775   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8776     return QualType();
8777 
8778   // Check array bounds for pointer arithemtic
8779   CheckArrayAccess(PExp, IExp);
8780 
8781   if (CompLHSTy) {
8782     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8783     if (LHSTy.isNull()) {
8784       LHSTy = LHS.get()->getType();
8785       if (LHSTy->isPromotableIntegerType())
8786         LHSTy = Context.getPromotedIntegerType(LHSTy);
8787     }
8788     *CompLHSTy = LHSTy;
8789   }
8790 
8791   return PExp->getType();
8792 }
8793 
8794 // C99 6.5.6
8795 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8796                                         SourceLocation Loc,
8797                                         QualType* CompLHSTy) {
8798   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8799 
8800   if (LHS.get()->getType()->isVectorType() ||
8801       RHS.get()->getType()->isVectorType()) {
8802     QualType compType = CheckVectorOperands(
8803         LHS, RHS, Loc, CompLHSTy,
8804         /*AllowBothBool*/getLangOpts().AltiVec,
8805         /*AllowBoolConversions*/getLangOpts().ZVector);
8806     if (CompLHSTy) *CompLHSTy = compType;
8807     return compType;
8808   }
8809 
8810   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8811   if (LHS.isInvalid() || RHS.isInvalid())
8812     return QualType();
8813 
8814   // Enforce type constraints: C99 6.5.6p3.
8815 
8816   // Handle the common case first (both operands are arithmetic).
8817   if (!compType.isNull() && compType->isArithmeticType()) {
8818     if (CompLHSTy) *CompLHSTy = compType;
8819     return compType;
8820   }
8821 
8822   // Either ptr - int   or   ptr - ptr.
8823   if (LHS.get()->getType()->isAnyPointerType()) {
8824     QualType lpointee = LHS.get()->getType()->getPointeeType();
8825 
8826     // Diagnose bad cases where we step over interface counts.
8827     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8828         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8829       return QualType();
8830 
8831     // The result type of a pointer-int computation is the pointer type.
8832     if (RHS.get()->getType()->isIntegerType()) {
8833       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8834         return QualType();
8835 
8836       // Check array bounds for pointer arithemtic
8837       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8838                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8839 
8840       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8841       return LHS.get()->getType();
8842     }
8843 
8844     // Handle pointer-pointer subtractions.
8845     if (const PointerType *RHSPTy
8846           = RHS.get()->getType()->getAs<PointerType>()) {
8847       QualType rpointee = RHSPTy->getPointeeType();
8848 
8849       if (getLangOpts().CPlusPlus) {
8850         // Pointee types must be the same: C++ [expr.add]
8851         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8852           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8853         }
8854       } else {
8855         // Pointee types must be compatible C99 6.5.6p3
8856         if (!Context.typesAreCompatible(
8857                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8858                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8859           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8860           return QualType();
8861         }
8862       }
8863 
8864       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8865                                                LHS.get(), RHS.get()))
8866         return QualType();
8867 
8868       // The pointee type may have zero size.  As an extension, a structure or
8869       // union may have zero size or an array may have zero length.  In this
8870       // case subtraction does not make sense.
8871       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8872         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8873         if (ElementSize.isZero()) {
8874           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8875             << rpointee.getUnqualifiedType()
8876             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8877         }
8878       }
8879 
8880       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8881       return Context.getPointerDiffType();
8882     }
8883   }
8884 
8885   return InvalidOperands(Loc, LHS, RHS);
8886 }
8887 
8888 static bool isScopedEnumerationType(QualType T) {
8889   if (const EnumType *ET = T->getAs<EnumType>())
8890     return ET->getDecl()->isScoped();
8891   return false;
8892 }
8893 
8894 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8895                                    SourceLocation Loc, BinaryOperatorKind Opc,
8896                                    QualType LHSType) {
8897   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8898   // so skip remaining warnings as we don't want to modify values within Sema.
8899   if (S.getLangOpts().OpenCL)
8900     return;
8901 
8902   llvm::APSInt Right;
8903   // Check right/shifter operand
8904   if (RHS.get()->isValueDependent() ||
8905       !RHS.get()->EvaluateAsInt(Right, S.Context))
8906     return;
8907 
8908   if (Right.isNegative()) {
8909     S.DiagRuntimeBehavior(Loc, RHS.get(),
8910                           S.PDiag(diag::warn_shift_negative)
8911                             << RHS.get()->getSourceRange());
8912     return;
8913   }
8914   llvm::APInt LeftBits(Right.getBitWidth(),
8915                        S.Context.getTypeSize(LHS.get()->getType()));
8916   if (Right.uge(LeftBits)) {
8917     S.DiagRuntimeBehavior(Loc, RHS.get(),
8918                           S.PDiag(diag::warn_shift_gt_typewidth)
8919                             << RHS.get()->getSourceRange());
8920     return;
8921   }
8922   if (Opc != BO_Shl)
8923     return;
8924 
8925   // When left shifting an ICE which is signed, we can check for overflow which
8926   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8927   // integers have defined behavior modulo one more than the maximum value
8928   // representable in the result type, so never warn for those.
8929   llvm::APSInt Left;
8930   if (LHS.get()->isValueDependent() ||
8931       LHSType->hasUnsignedIntegerRepresentation() ||
8932       !LHS.get()->EvaluateAsInt(Left, S.Context))
8933     return;
8934 
8935   // If LHS does not have a signed type and non-negative value
8936   // then, the behavior is undefined. Warn about it.
8937   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8938     S.DiagRuntimeBehavior(Loc, LHS.get(),
8939                           S.PDiag(diag::warn_shift_lhs_negative)
8940                             << LHS.get()->getSourceRange());
8941     return;
8942   }
8943 
8944   llvm::APInt ResultBits =
8945       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8946   if (LeftBits.uge(ResultBits))
8947     return;
8948   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8949   Result = Result.shl(Right);
8950 
8951   // Print the bit representation of the signed integer as an unsigned
8952   // hexadecimal number.
8953   SmallString<40> HexResult;
8954   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8955 
8956   // If we are only missing a sign bit, this is less likely to result in actual
8957   // bugs -- if the result is cast back to an unsigned type, it will have the
8958   // expected value. Thus we place this behind a different warning that can be
8959   // turned off separately if needed.
8960   if (LeftBits == ResultBits - 1) {
8961     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8962         << HexResult << LHSType
8963         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8964     return;
8965   }
8966 
8967   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8968     << HexResult.str() << Result.getMinSignedBits() << LHSType
8969     << Left.getBitWidth() << LHS.get()->getSourceRange()
8970     << RHS.get()->getSourceRange();
8971 }
8972 
8973 /// \brief Return the resulting type when a vector is shifted
8974 ///        by a scalar or vector shift amount.
8975 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8976                                  SourceLocation Loc, bool IsCompAssign) {
8977   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8978   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8979       !LHS.get()->getType()->isVectorType()) {
8980     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8981       << RHS.get()->getType() << LHS.get()->getType()
8982       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8983     return QualType();
8984   }
8985 
8986   if (!IsCompAssign) {
8987     LHS = S.UsualUnaryConversions(LHS.get());
8988     if (LHS.isInvalid()) return QualType();
8989   }
8990 
8991   RHS = S.UsualUnaryConversions(RHS.get());
8992   if (RHS.isInvalid()) return QualType();
8993 
8994   QualType LHSType = LHS.get()->getType();
8995   // Note that LHS might be a scalar because the routine calls not only in
8996   // OpenCL case.
8997   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8998   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8999 
9000   // Note that RHS might not be a vector.
9001   QualType RHSType = RHS.get()->getType();
9002   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9003   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9004 
9005   // The operands need to be integers.
9006   if (!LHSEleType->isIntegerType()) {
9007     S.Diag(Loc, diag::err_typecheck_expect_int)
9008       << LHS.get()->getType() << LHS.get()->getSourceRange();
9009     return QualType();
9010   }
9011 
9012   if (!RHSEleType->isIntegerType()) {
9013     S.Diag(Loc, diag::err_typecheck_expect_int)
9014       << RHS.get()->getType() << RHS.get()->getSourceRange();
9015     return QualType();
9016   }
9017 
9018   if (!LHSVecTy) {
9019     assert(RHSVecTy);
9020     if (IsCompAssign)
9021       return RHSType;
9022     if (LHSEleType != RHSEleType) {
9023       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9024       LHSEleType = RHSEleType;
9025     }
9026     QualType VecTy =
9027         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9028     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9029     LHSType = VecTy;
9030   } else if (RHSVecTy) {
9031     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9032     // are applied component-wise. So if RHS is a vector, then ensure
9033     // that the number of elements is the same as LHS...
9034     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9035       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9036         << LHS.get()->getType() << RHS.get()->getType()
9037         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9038       return QualType();
9039     }
9040     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9041       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9042       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9043       if (LHSBT != RHSBT &&
9044           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9045         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9046             << LHS.get()->getType() << RHS.get()->getType()
9047             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9048       }
9049     }
9050   } else {
9051     // ...else expand RHS to match the number of elements in LHS.
9052     QualType VecTy =
9053       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9054     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9055   }
9056 
9057   return LHSType;
9058 }
9059 
9060 // C99 6.5.7
9061 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9062                                   SourceLocation Loc, BinaryOperatorKind Opc,
9063                                   bool IsCompAssign) {
9064   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9065 
9066   // Vector shifts promote their scalar inputs to vector type.
9067   if (LHS.get()->getType()->isVectorType() ||
9068       RHS.get()->getType()->isVectorType()) {
9069     if (LangOpts.ZVector) {
9070       // The shift operators for the z vector extensions work basically
9071       // like general shifts, except that neither the LHS nor the RHS is
9072       // allowed to be a "vector bool".
9073       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9074         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9075           return InvalidOperands(Loc, LHS, RHS);
9076       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9077         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9078           return InvalidOperands(Loc, LHS, RHS);
9079     }
9080     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9081   }
9082 
9083   // Shifts don't perform usual arithmetic conversions, they just do integer
9084   // promotions on each operand. C99 6.5.7p3
9085 
9086   // For the LHS, do usual unary conversions, but then reset them away
9087   // if this is a compound assignment.
9088   ExprResult OldLHS = LHS;
9089   LHS = UsualUnaryConversions(LHS.get());
9090   if (LHS.isInvalid())
9091     return QualType();
9092   QualType LHSType = LHS.get()->getType();
9093   if (IsCompAssign) LHS = OldLHS;
9094 
9095   // The RHS is simpler.
9096   RHS = UsualUnaryConversions(RHS.get());
9097   if (RHS.isInvalid())
9098     return QualType();
9099   QualType RHSType = RHS.get()->getType();
9100 
9101   // C99 6.5.7p2: Each of the operands shall have integer type.
9102   if (!LHSType->hasIntegerRepresentation() ||
9103       !RHSType->hasIntegerRepresentation())
9104     return InvalidOperands(Loc, LHS, RHS);
9105 
9106   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9107   // hasIntegerRepresentation() above instead of this.
9108   if (isScopedEnumerationType(LHSType) ||
9109       isScopedEnumerationType(RHSType)) {
9110     return InvalidOperands(Loc, LHS, RHS);
9111   }
9112   // Sanity-check shift operands
9113   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9114 
9115   // "The type of the result is that of the promoted left operand."
9116   return LHSType;
9117 }
9118 
9119 static bool IsWithinTemplateSpecialization(Decl *D) {
9120   if (DeclContext *DC = D->getDeclContext()) {
9121     if (isa<ClassTemplateSpecializationDecl>(DC))
9122       return true;
9123     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
9124       return FD->isFunctionTemplateSpecialization();
9125   }
9126   return false;
9127 }
9128 
9129 /// If two different enums are compared, raise a warning.
9130 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9131                                 Expr *RHS) {
9132   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9133   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9134 
9135   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9136   if (!LHSEnumType)
9137     return;
9138   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9139   if (!RHSEnumType)
9140     return;
9141 
9142   // Ignore anonymous enums.
9143   if (!LHSEnumType->getDecl()->getIdentifier())
9144     return;
9145   if (!RHSEnumType->getDecl()->getIdentifier())
9146     return;
9147 
9148   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9149     return;
9150 
9151   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9152       << LHSStrippedType << RHSStrippedType
9153       << LHS->getSourceRange() << RHS->getSourceRange();
9154 }
9155 
9156 /// \brief Diagnose bad pointer comparisons.
9157 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9158                                               ExprResult &LHS, ExprResult &RHS,
9159                                               bool IsError) {
9160   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9161                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9162     << LHS.get()->getType() << RHS.get()->getType()
9163     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9164 }
9165 
9166 /// \brief Returns false if the pointers are converted to a composite type,
9167 /// true otherwise.
9168 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9169                                            ExprResult &LHS, ExprResult &RHS) {
9170   // C++ [expr.rel]p2:
9171   //   [...] Pointer conversions (4.10) and qualification
9172   //   conversions (4.4) are performed on pointer operands (or on
9173   //   a pointer operand and a null pointer constant) to bring
9174   //   them to their composite pointer type. [...]
9175   //
9176   // C++ [expr.eq]p1 uses the same notion for (in)equality
9177   // comparisons of pointers.
9178 
9179   QualType LHSType = LHS.get()->getType();
9180   QualType RHSType = RHS.get()->getType();
9181   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9182          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9183 
9184   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9185   if (T.isNull()) {
9186     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9187         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9188       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9189     else
9190       S.InvalidOperands(Loc, LHS, RHS);
9191     return true;
9192   }
9193 
9194   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9195   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9196   return false;
9197 }
9198 
9199 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9200                                                     ExprResult &LHS,
9201                                                     ExprResult &RHS,
9202                                                     bool IsError) {
9203   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9204                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9205     << LHS.get()->getType() << RHS.get()->getType()
9206     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9207 }
9208 
9209 static bool isObjCObjectLiteral(ExprResult &E) {
9210   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9211   case Stmt::ObjCArrayLiteralClass:
9212   case Stmt::ObjCDictionaryLiteralClass:
9213   case Stmt::ObjCStringLiteralClass:
9214   case Stmt::ObjCBoxedExprClass:
9215     return true;
9216   default:
9217     // Note that ObjCBoolLiteral is NOT an object literal!
9218     return false;
9219   }
9220 }
9221 
9222 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9223   const ObjCObjectPointerType *Type =
9224     LHS->getType()->getAs<ObjCObjectPointerType>();
9225 
9226   // If this is not actually an Objective-C object, bail out.
9227   if (!Type)
9228     return false;
9229 
9230   // Get the LHS object's interface type.
9231   QualType InterfaceType = Type->getPointeeType();
9232 
9233   // If the RHS isn't an Objective-C object, bail out.
9234   if (!RHS->getType()->isObjCObjectPointerType())
9235     return false;
9236 
9237   // Try to find the -isEqual: method.
9238   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9239   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9240                                                       InterfaceType,
9241                                                       /*instance=*/true);
9242   if (!Method) {
9243     if (Type->isObjCIdType()) {
9244       // For 'id', just check the global pool.
9245       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9246                                                   /*receiverId=*/true);
9247     } else {
9248       // Check protocols.
9249       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9250                                              /*instance=*/true);
9251     }
9252   }
9253 
9254   if (!Method)
9255     return false;
9256 
9257   QualType T = Method->parameters()[0]->getType();
9258   if (!T->isObjCObjectPointerType())
9259     return false;
9260 
9261   QualType R = Method->getReturnType();
9262   if (!R->isScalarType())
9263     return false;
9264 
9265   return true;
9266 }
9267 
9268 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9269   FromE = FromE->IgnoreParenImpCasts();
9270   switch (FromE->getStmtClass()) {
9271     default:
9272       break;
9273     case Stmt::ObjCStringLiteralClass:
9274       // "string literal"
9275       return LK_String;
9276     case Stmt::ObjCArrayLiteralClass:
9277       // "array literal"
9278       return LK_Array;
9279     case Stmt::ObjCDictionaryLiteralClass:
9280       // "dictionary literal"
9281       return LK_Dictionary;
9282     case Stmt::BlockExprClass:
9283       return LK_Block;
9284     case Stmt::ObjCBoxedExprClass: {
9285       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9286       switch (Inner->getStmtClass()) {
9287         case Stmt::IntegerLiteralClass:
9288         case Stmt::FloatingLiteralClass:
9289         case Stmt::CharacterLiteralClass:
9290         case Stmt::ObjCBoolLiteralExprClass:
9291         case Stmt::CXXBoolLiteralExprClass:
9292           // "numeric literal"
9293           return LK_Numeric;
9294         case Stmt::ImplicitCastExprClass: {
9295           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9296           // Boolean literals can be represented by implicit casts.
9297           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9298             return LK_Numeric;
9299           break;
9300         }
9301         default:
9302           break;
9303       }
9304       return LK_Boxed;
9305     }
9306   }
9307   return LK_None;
9308 }
9309 
9310 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9311                                           ExprResult &LHS, ExprResult &RHS,
9312                                           BinaryOperator::Opcode Opc){
9313   Expr *Literal;
9314   Expr *Other;
9315   if (isObjCObjectLiteral(LHS)) {
9316     Literal = LHS.get();
9317     Other = RHS.get();
9318   } else {
9319     Literal = RHS.get();
9320     Other = LHS.get();
9321   }
9322 
9323   // Don't warn on comparisons against nil.
9324   Other = Other->IgnoreParenCasts();
9325   if (Other->isNullPointerConstant(S.getASTContext(),
9326                                    Expr::NPC_ValueDependentIsNotNull))
9327     return;
9328 
9329   // This should be kept in sync with warn_objc_literal_comparison.
9330   // LK_String should always be after the other literals, since it has its own
9331   // warning flag.
9332   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9333   assert(LiteralKind != Sema::LK_Block);
9334   if (LiteralKind == Sema::LK_None) {
9335     llvm_unreachable("Unknown Objective-C object literal kind");
9336   }
9337 
9338   if (LiteralKind == Sema::LK_String)
9339     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9340       << Literal->getSourceRange();
9341   else
9342     S.Diag(Loc, diag::warn_objc_literal_comparison)
9343       << LiteralKind << Literal->getSourceRange();
9344 
9345   if (BinaryOperator::isEqualityOp(Opc) &&
9346       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9347     SourceLocation Start = LHS.get()->getLocStart();
9348     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9349     CharSourceRange OpRange =
9350       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9351 
9352     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9353       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9354       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9355       << FixItHint::CreateInsertion(End, "]");
9356   }
9357 }
9358 
9359 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9360 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9361                                            ExprResult &RHS, SourceLocation Loc,
9362                                            BinaryOperatorKind Opc) {
9363   // Check that left hand side is !something.
9364   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9365   if (!UO || UO->getOpcode() != UO_LNot) return;
9366 
9367   // Only check if the right hand side is non-bool arithmetic type.
9368   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9369 
9370   // Make sure that the something in !something is not bool.
9371   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9372   if (SubExpr->isKnownToHaveBooleanValue()) return;
9373 
9374   // Emit warning.
9375   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9376   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9377       << Loc << IsBitwiseOp;
9378 
9379   // First note suggest !(x < y)
9380   SourceLocation FirstOpen = SubExpr->getLocStart();
9381   SourceLocation FirstClose = RHS.get()->getLocEnd();
9382   FirstClose = S.getLocForEndOfToken(FirstClose);
9383   if (FirstClose.isInvalid())
9384     FirstOpen = SourceLocation();
9385   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9386       << IsBitwiseOp
9387       << FixItHint::CreateInsertion(FirstOpen, "(")
9388       << FixItHint::CreateInsertion(FirstClose, ")");
9389 
9390   // Second note suggests (!x) < y
9391   SourceLocation SecondOpen = LHS.get()->getLocStart();
9392   SourceLocation SecondClose = LHS.get()->getLocEnd();
9393   SecondClose = S.getLocForEndOfToken(SecondClose);
9394   if (SecondClose.isInvalid())
9395     SecondOpen = SourceLocation();
9396   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9397       << FixItHint::CreateInsertion(SecondOpen, "(")
9398       << FixItHint::CreateInsertion(SecondClose, ")");
9399 }
9400 
9401 // Get the decl for a simple expression: a reference to a variable,
9402 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9403 static ValueDecl *getCompareDecl(Expr *E) {
9404   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9405     return DR->getDecl();
9406   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9407     if (Ivar->isFreeIvar())
9408       return Ivar->getDecl();
9409   }
9410   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9411     if (Mem->isImplicitAccess())
9412       return Mem->getMemberDecl();
9413   }
9414   return nullptr;
9415 }
9416 
9417 // C99 6.5.8, C++ [expr.rel]
9418 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9419                                     SourceLocation Loc, BinaryOperatorKind Opc,
9420                                     bool IsRelational) {
9421   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9422 
9423   // Handle vector comparisons separately.
9424   if (LHS.get()->getType()->isVectorType() ||
9425       RHS.get()->getType()->isVectorType())
9426     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9427 
9428   QualType LHSType = LHS.get()->getType();
9429   QualType RHSType = RHS.get()->getType();
9430 
9431   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9432   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9433 
9434   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9435   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9436 
9437   if (!LHSType->hasFloatingRepresentation() &&
9438       !(LHSType->isBlockPointerType() && IsRelational) &&
9439       !LHS.get()->getLocStart().isMacroID() &&
9440       !RHS.get()->getLocStart().isMacroID() &&
9441       !inTemplateInstantiation()) {
9442     // For non-floating point types, check for self-comparisons of the form
9443     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9444     // often indicate logic errors in the program.
9445     //
9446     // NOTE: Don't warn about comparison expressions resulting from macro
9447     // expansion. Also don't warn about comparisons which are only self
9448     // comparisons within a template specialization. The warnings should catch
9449     // obvious cases in the definition of the template anyways. The idea is to
9450     // warn when the typed comparison operator will always evaluate to the same
9451     // result.
9452     ValueDecl *DL = getCompareDecl(LHSStripped);
9453     ValueDecl *DR = getCompareDecl(RHSStripped);
9454     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9455       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9456                           << 0 // self-
9457                           << (Opc == BO_EQ
9458                               || Opc == BO_LE
9459                               || Opc == BO_GE));
9460     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9461                !DL->getType()->isReferenceType() &&
9462                !DR->getType()->isReferenceType()) {
9463         // what is it always going to eval to?
9464         char always_evals_to;
9465         switch(Opc) {
9466         case BO_EQ: // e.g. array1 == array2
9467           always_evals_to = 0; // false
9468           break;
9469         case BO_NE: // e.g. array1 != array2
9470           always_evals_to = 1; // true
9471           break;
9472         default:
9473           // best we can say is 'a constant'
9474           always_evals_to = 2; // e.g. array1 <= array2
9475           break;
9476         }
9477         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9478                             << 1 // array
9479                             << always_evals_to);
9480     }
9481 
9482     if (isa<CastExpr>(LHSStripped))
9483       LHSStripped = LHSStripped->IgnoreParenCasts();
9484     if (isa<CastExpr>(RHSStripped))
9485       RHSStripped = RHSStripped->IgnoreParenCasts();
9486 
9487     // Warn about comparisons against a string constant (unless the other
9488     // operand is null), the user probably wants strcmp.
9489     Expr *literalString = nullptr;
9490     Expr *literalStringStripped = nullptr;
9491     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9492         !RHSStripped->isNullPointerConstant(Context,
9493                                             Expr::NPC_ValueDependentIsNull)) {
9494       literalString = LHS.get();
9495       literalStringStripped = LHSStripped;
9496     } else if ((isa<StringLiteral>(RHSStripped) ||
9497                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9498                !LHSStripped->isNullPointerConstant(Context,
9499                                             Expr::NPC_ValueDependentIsNull)) {
9500       literalString = RHS.get();
9501       literalStringStripped = RHSStripped;
9502     }
9503 
9504     if (literalString) {
9505       DiagRuntimeBehavior(Loc, nullptr,
9506         PDiag(diag::warn_stringcompare)
9507           << isa<ObjCEncodeExpr>(literalStringStripped)
9508           << literalString->getSourceRange());
9509     }
9510   }
9511 
9512   // C99 6.5.8p3 / C99 6.5.9p4
9513   UsualArithmeticConversions(LHS, RHS);
9514   if (LHS.isInvalid() || RHS.isInvalid())
9515     return QualType();
9516 
9517   LHSType = LHS.get()->getType();
9518   RHSType = RHS.get()->getType();
9519 
9520   // The result of comparisons is 'bool' in C++, 'int' in C.
9521   QualType ResultTy = Context.getLogicalOperationType();
9522 
9523   if (IsRelational) {
9524     if (LHSType->isRealType() && RHSType->isRealType())
9525       return ResultTy;
9526   } else {
9527     // Check for comparisons of floating point operands using != and ==.
9528     if (LHSType->hasFloatingRepresentation())
9529       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9530 
9531     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9532       return ResultTy;
9533   }
9534 
9535   const Expr::NullPointerConstantKind LHSNullKind =
9536       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9537   const Expr::NullPointerConstantKind RHSNullKind =
9538       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9539   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9540   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9541 
9542   if (!IsRelational && LHSIsNull != RHSIsNull) {
9543     bool IsEquality = Opc == BO_EQ;
9544     if (RHSIsNull)
9545       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9546                                    RHS.get()->getSourceRange());
9547     else
9548       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9549                                    LHS.get()->getSourceRange());
9550   }
9551 
9552   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9553       (RHSType->isIntegerType() && !RHSIsNull)) {
9554     // Skip normal pointer conversion checks in this case; we have better
9555     // diagnostics for this below.
9556   } else if (getLangOpts().CPlusPlus) {
9557     // Equality comparison of a function pointer to a void pointer is invalid,
9558     // but we allow it as an extension.
9559     // FIXME: If we really want to allow this, should it be part of composite
9560     // pointer type computation so it works in conditionals too?
9561     if (!IsRelational &&
9562         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9563          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9564       // This is a gcc extension compatibility comparison.
9565       // In a SFINAE context, we treat this as a hard error to maintain
9566       // conformance with the C++ standard.
9567       diagnoseFunctionPointerToVoidComparison(
9568           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9569 
9570       if (isSFINAEContext())
9571         return QualType();
9572 
9573       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9574       return ResultTy;
9575     }
9576 
9577     // C++ [expr.eq]p2:
9578     //   If at least one operand is a pointer [...] bring them to their
9579     //   composite pointer type.
9580     // C++ [expr.rel]p2:
9581     //   If both operands are pointers, [...] bring them to their composite
9582     //   pointer type.
9583     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9584             (IsRelational ? 2 : 1) &&
9585         (!LangOpts.ObjCAutoRefCount ||
9586          !(LHSType->isObjCObjectPointerType() ||
9587            RHSType->isObjCObjectPointerType()))) {
9588       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9589         return QualType();
9590       else
9591         return ResultTy;
9592     }
9593   } else if (LHSType->isPointerType() &&
9594              RHSType->isPointerType()) { // C99 6.5.8p2
9595     // All of the following pointer-related warnings are GCC extensions, except
9596     // when handling null pointer constants.
9597     QualType LCanPointeeTy =
9598       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9599     QualType RCanPointeeTy =
9600       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9601 
9602     // C99 6.5.9p2 and C99 6.5.8p2
9603     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9604                                    RCanPointeeTy.getUnqualifiedType())) {
9605       // Valid unless a relational comparison of function pointers
9606       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9607         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9608           << LHSType << RHSType << LHS.get()->getSourceRange()
9609           << RHS.get()->getSourceRange();
9610       }
9611     } else if (!IsRelational &&
9612                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9613       // Valid unless comparison between non-null pointer and function pointer
9614       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9615           && !LHSIsNull && !RHSIsNull)
9616         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9617                                                 /*isError*/false);
9618     } else {
9619       // Invalid
9620       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9621     }
9622     if (LCanPointeeTy != RCanPointeeTy) {
9623       // Treat NULL constant as a special case in OpenCL.
9624       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9625         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9626         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9627           Diag(Loc,
9628                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9629               << LHSType << RHSType << 0 /* comparison */
9630               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9631         }
9632       }
9633       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9634       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9635       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9636                                                : CK_BitCast;
9637       if (LHSIsNull && !RHSIsNull)
9638         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9639       else
9640         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9641     }
9642     return ResultTy;
9643   }
9644 
9645   if (getLangOpts().CPlusPlus) {
9646     // C++ [expr.eq]p4:
9647     //   Two operands of type std::nullptr_t or one operand of type
9648     //   std::nullptr_t and the other a null pointer constant compare equal.
9649     if (!IsRelational && LHSIsNull && RHSIsNull) {
9650       if (LHSType->isNullPtrType()) {
9651         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9652         return ResultTy;
9653       }
9654       if (RHSType->isNullPtrType()) {
9655         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9656         return ResultTy;
9657       }
9658     }
9659 
9660     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9661     // These aren't covered by the composite pointer type rules.
9662     if (!IsRelational && RHSType->isNullPtrType() &&
9663         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9664       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9665       return ResultTy;
9666     }
9667     if (!IsRelational && LHSType->isNullPtrType() &&
9668         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9669       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9670       return ResultTy;
9671     }
9672 
9673     if (IsRelational &&
9674         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9675          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9676       // HACK: Relational comparison of nullptr_t against a pointer type is
9677       // invalid per DR583, but we allow it within std::less<> and friends,
9678       // since otherwise common uses of it break.
9679       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9680       // friends to have std::nullptr_t overload candidates.
9681       DeclContext *DC = CurContext;
9682       if (isa<FunctionDecl>(DC))
9683         DC = DC->getParent();
9684       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9685         if (CTSD->isInStdNamespace() &&
9686             llvm::StringSwitch<bool>(CTSD->getName())
9687                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9688                 .Default(false)) {
9689           if (RHSType->isNullPtrType())
9690             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9691           else
9692             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9693           return ResultTy;
9694         }
9695       }
9696     }
9697 
9698     // C++ [expr.eq]p2:
9699     //   If at least one operand is a pointer to member, [...] bring them to
9700     //   their composite pointer type.
9701     if (!IsRelational &&
9702         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9703       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9704         return QualType();
9705       else
9706         return ResultTy;
9707     }
9708 
9709     // Handle scoped enumeration types specifically, since they don't promote
9710     // to integers.
9711     if (LHS.get()->getType()->isEnumeralType() &&
9712         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9713                                        RHS.get()->getType()))
9714       return ResultTy;
9715   }
9716 
9717   // Handle block pointer types.
9718   if (!IsRelational && LHSType->isBlockPointerType() &&
9719       RHSType->isBlockPointerType()) {
9720     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9721     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9722 
9723     if (!LHSIsNull && !RHSIsNull &&
9724         !Context.typesAreCompatible(lpointee, rpointee)) {
9725       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9726         << LHSType << RHSType << LHS.get()->getSourceRange()
9727         << RHS.get()->getSourceRange();
9728     }
9729     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9730     return ResultTy;
9731   }
9732 
9733   // Allow block pointers to be compared with null pointer constants.
9734   if (!IsRelational
9735       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9736           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9737     if (!LHSIsNull && !RHSIsNull) {
9738       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9739              ->getPointeeType()->isVoidType())
9740             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9741                 ->getPointeeType()->isVoidType())))
9742         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9743           << LHSType << RHSType << LHS.get()->getSourceRange()
9744           << RHS.get()->getSourceRange();
9745     }
9746     if (LHSIsNull && !RHSIsNull)
9747       LHS = ImpCastExprToType(LHS.get(), RHSType,
9748                               RHSType->isPointerType() ? CK_BitCast
9749                                 : CK_AnyPointerToBlockPointerCast);
9750     else
9751       RHS = ImpCastExprToType(RHS.get(), LHSType,
9752                               LHSType->isPointerType() ? CK_BitCast
9753                                 : CK_AnyPointerToBlockPointerCast);
9754     return ResultTy;
9755   }
9756 
9757   if (LHSType->isObjCObjectPointerType() ||
9758       RHSType->isObjCObjectPointerType()) {
9759     const PointerType *LPT = LHSType->getAs<PointerType>();
9760     const PointerType *RPT = RHSType->getAs<PointerType>();
9761     if (LPT || RPT) {
9762       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9763       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9764 
9765       if (!LPtrToVoid && !RPtrToVoid &&
9766           !Context.typesAreCompatible(LHSType, RHSType)) {
9767         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9768                                           /*isError*/false);
9769       }
9770       if (LHSIsNull && !RHSIsNull) {
9771         Expr *E = LHS.get();
9772         if (getLangOpts().ObjCAutoRefCount)
9773           CheckObjCConversion(SourceRange(), RHSType, E,
9774                               CCK_ImplicitConversion);
9775         LHS = ImpCastExprToType(E, RHSType,
9776                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9777       }
9778       else {
9779         Expr *E = RHS.get();
9780         if (getLangOpts().ObjCAutoRefCount)
9781           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
9782                               /*Diagnose=*/true,
9783                               /*DiagnoseCFAudited=*/false, Opc);
9784         RHS = ImpCastExprToType(E, LHSType,
9785                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9786       }
9787       return ResultTy;
9788     }
9789     if (LHSType->isObjCObjectPointerType() &&
9790         RHSType->isObjCObjectPointerType()) {
9791       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9792         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9793                                           /*isError*/false);
9794       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9795         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9796 
9797       if (LHSIsNull && !RHSIsNull)
9798         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9799       else
9800         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9801       return ResultTy;
9802     }
9803   }
9804   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9805       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9806     unsigned DiagID = 0;
9807     bool isError = false;
9808     if (LangOpts.DebuggerSupport) {
9809       // Under a debugger, allow the comparison of pointers to integers,
9810       // since users tend to want to compare addresses.
9811     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9812                (RHSIsNull && RHSType->isIntegerType())) {
9813       if (IsRelational) {
9814         isError = getLangOpts().CPlusPlus;
9815         DiagID =
9816           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9817                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9818       }
9819     } else if (getLangOpts().CPlusPlus) {
9820       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9821       isError = true;
9822     } else if (IsRelational)
9823       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9824     else
9825       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9826 
9827     if (DiagID) {
9828       Diag(Loc, DiagID)
9829         << LHSType << RHSType << LHS.get()->getSourceRange()
9830         << RHS.get()->getSourceRange();
9831       if (isError)
9832         return QualType();
9833     }
9834 
9835     if (LHSType->isIntegerType())
9836       LHS = ImpCastExprToType(LHS.get(), RHSType,
9837                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9838     else
9839       RHS = ImpCastExprToType(RHS.get(), LHSType,
9840                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9841     return ResultTy;
9842   }
9843 
9844   // Handle block pointers.
9845   if (!IsRelational && RHSIsNull
9846       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9847     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9848     return ResultTy;
9849   }
9850   if (!IsRelational && LHSIsNull
9851       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9852     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9853     return ResultTy;
9854   }
9855 
9856   if (getLangOpts().OpenCLVersion >= 200) {
9857     if (LHSIsNull && RHSType->isQueueT()) {
9858       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9859       return ResultTy;
9860     }
9861 
9862     if (LHSType->isQueueT() && RHSIsNull) {
9863       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9864       return ResultTy;
9865     }
9866   }
9867 
9868   return InvalidOperands(Loc, LHS, RHS);
9869 }
9870 
9871 // Return a signed ext_vector_type that is of identical size and number of
9872 // elements. For floating point vectors, return an integer type of identical
9873 // size and number of elements. In the non ext_vector_type case, search from
9874 // the largest type to the smallest type to avoid cases where long long == long,
9875 // where long gets picked over long long.
9876 QualType Sema::GetSignedVectorType(QualType V) {
9877   const VectorType *VTy = V->getAs<VectorType>();
9878   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9879 
9880   if (isa<ExtVectorType>(VTy)) {
9881     if (TypeSize == Context.getTypeSize(Context.CharTy))
9882       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9883     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9884       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9885     else if (TypeSize == Context.getTypeSize(Context.IntTy))
9886       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9887     else if (TypeSize == Context.getTypeSize(Context.LongTy))
9888       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9889     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9890            "Unhandled vector element size in vector compare");
9891     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9892   }
9893 
9894   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
9895     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
9896                                  VectorType::GenericVector);
9897   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9898     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
9899                                  VectorType::GenericVector);
9900   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9901     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
9902                                  VectorType::GenericVector);
9903   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9904     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
9905                                  VectorType::GenericVector);
9906   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
9907          "Unhandled vector element size in vector compare");
9908   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
9909                                VectorType::GenericVector);
9910 }
9911 
9912 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9913 /// operates on extended vector types.  Instead of producing an IntTy result,
9914 /// like a scalar comparison, a vector comparison produces a vector of integer
9915 /// types.
9916 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9917                                           SourceLocation Loc,
9918                                           bool IsRelational) {
9919   // Check to make sure we're operating on vectors of the same type and width,
9920   // Allowing one side to be a scalar of element type.
9921   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9922                               /*AllowBothBool*/true,
9923                               /*AllowBoolConversions*/getLangOpts().ZVector);
9924   if (vType.isNull())
9925     return vType;
9926 
9927   QualType LHSType = LHS.get()->getType();
9928 
9929   // If AltiVec, the comparison results in a numeric type, i.e.
9930   // bool for C++, int for C
9931   if (getLangOpts().AltiVec &&
9932       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9933     return Context.getLogicalOperationType();
9934 
9935   // For non-floating point types, check for self-comparisons of the form
9936   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9937   // often indicate logic errors in the program.
9938   if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
9939     if (DeclRefExpr* DRL
9940           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9941       if (DeclRefExpr* DRR
9942             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9943         if (DRL->getDecl() == DRR->getDecl())
9944           DiagRuntimeBehavior(Loc, nullptr,
9945                               PDiag(diag::warn_comparison_always)
9946                                 << 0 // self-
9947                                 << 2 // "a constant"
9948                               );
9949   }
9950 
9951   // Check for comparisons of floating point operands using != and ==.
9952   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9953     assert (RHS.get()->getType()->hasFloatingRepresentation());
9954     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9955   }
9956 
9957   // Return a signed type for the vector.
9958   return GetSignedVectorType(vType);
9959 }
9960 
9961 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9962                                           SourceLocation Loc) {
9963   // Ensure that either both operands are of the same vector type, or
9964   // one operand is of a vector type and the other is of its element type.
9965   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9966                                        /*AllowBothBool*/true,
9967                                        /*AllowBoolConversions*/false);
9968   if (vType.isNull())
9969     return InvalidOperands(Loc, LHS, RHS);
9970   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9971       vType->hasFloatingRepresentation())
9972     return InvalidOperands(Loc, LHS, RHS);
9973   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
9974   //        usage of the logical operators && and || with vectors in C. This
9975   //        check could be notionally dropped.
9976   if (!getLangOpts().CPlusPlus &&
9977       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
9978     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
9979 
9980   return GetSignedVectorType(LHS.get()->getType());
9981 }
9982 
9983 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9984                                            SourceLocation Loc,
9985                                            BinaryOperatorKind Opc) {
9986   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9987 
9988   bool IsCompAssign =
9989       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9990 
9991   if (LHS.get()->getType()->isVectorType() ||
9992       RHS.get()->getType()->isVectorType()) {
9993     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9994         RHS.get()->getType()->hasIntegerRepresentation())
9995       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9996                         /*AllowBothBool*/true,
9997                         /*AllowBoolConversions*/getLangOpts().ZVector);
9998     return InvalidOperands(Loc, LHS, RHS);
9999   }
10000 
10001   if (Opc == BO_And)
10002     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10003 
10004   ExprResult LHSResult = LHS, RHSResult = RHS;
10005   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10006                                                  IsCompAssign);
10007   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10008     return QualType();
10009   LHS = LHSResult.get();
10010   RHS = RHSResult.get();
10011 
10012   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10013     return compType;
10014   return InvalidOperands(Loc, LHS, RHS);
10015 }
10016 
10017 // C99 6.5.[13,14]
10018 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10019                                            SourceLocation Loc,
10020                                            BinaryOperatorKind Opc) {
10021   // Check vector operands differently.
10022   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10023     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10024 
10025   // Diagnose cases where the user write a logical and/or but probably meant a
10026   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10027   // is a constant.
10028   if (LHS.get()->getType()->isIntegerType() &&
10029       !LHS.get()->getType()->isBooleanType() &&
10030       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10031       // Don't warn in macros or template instantiations.
10032       !Loc.isMacroID() && !inTemplateInstantiation()) {
10033     // If the RHS can be constant folded, and if it constant folds to something
10034     // that isn't 0 or 1 (which indicate a potential logical operation that
10035     // happened to fold to true/false) then warn.
10036     // Parens on the RHS are ignored.
10037     llvm::APSInt Result;
10038     if (RHS.get()->EvaluateAsInt(Result, Context))
10039       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10040            !RHS.get()->getExprLoc().isMacroID()) ||
10041           (Result != 0 && Result != 1)) {
10042         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10043           << RHS.get()->getSourceRange()
10044           << (Opc == BO_LAnd ? "&&" : "||");
10045         // Suggest replacing the logical operator with the bitwise version
10046         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10047             << (Opc == BO_LAnd ? "&" : "|")
10048             << FixItHint::CreateReplacement(SourceRange(
10049                                                  Loc, getLocForEndOfToken(Loc)),
10050                                             Opc == BO_LAnd ? "&" : "|");
10051         if (Opc == BO_LAnd)
10052           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10053           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10054               << FixItHint::CreateRemoval(
10055                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10056                               RHS.get()->getLocEnd()));
10057       }
10058   }
10059 
10060   if (!Context.getLangOpts().CPlusPlus) {
10061     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10062     // not operate on the built-in scalar and vector float types.
10063     if (Context.getLangOpts().OpenCL &&
10064         Context.getLangOpts().OpenCLVersion < 120) {
10065       if (LHS.get()->getType()->isFloatingType() ||
10066           RHS.get()->getType()->isFloatingType())
10067         return InvalidOperands(Loc, LHS, RHS);
10068     }
10069 
10070     LHS = UsualUnaryConversions(LHS.get());
10071     if (LHS.isInvalid())
10072       return QualType();
10073 
10074     RHS = UsualUnaryConversions(RHS.get());
10075     if (RHS.isInvalid())
10076       return QualType();
10077 
10078     if (!LHS.get()->getType()->isScalarType() ||
10079         !RHS.get()->getType()->isScalarType())
10080       return InvalidOperands(Loc, LHS, RHS);
10081 
10082     return Context.IntTy;
10083   }
10084 
10085   // The following is safe because we only use this method for
10086   // non-overloadable operands.
10087 
10088   // C++ [expr.log.and]p1
10089   // C++ [expr.log.or]p1
10090   // The operands are both contextually converted to type bool.
10091   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10092   if (LHSRes.isInvalid())
10093     return InvalidOperands(Loc, LHS, RHS);
10094   LHS = LHSRes;
10095 
10096   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10097   if (RHSRes.isInvalid())
10098     return InvalidOperands(Loc, LHS, RHS);
10099   RHS = RHSRes;
10100 
10101   // C++ [expr.log.and]p2
10102   // C++ [expr.log.or]p2
10103   // The result is a bool.
10104   return Context.BoolTy;
10105 }
10106 
10107 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10108   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10109   if (!ME) return false;
10110   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10111   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10112       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10113   if (!Base) return false;
10114   return Base->getMethodDecl() != nullptr;
10115 }
10116 
10117 /// Is the given expression (which must be 'const') a reference to a
10118 /// variable which was originally non-const, but which has become
10119 /// 'const' due to being captured within a block?
10120 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10121 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10122   assert(E->isLValue() && E->getType().isConstQualified());
10123   E = E->IgnoreParens();
10124 
10125   // Must be a reference to a declaration from an enclosing scope.
10126   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10127   if (!DRE) return NCCK_None;
10128   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10129 
10130   // The declaration must be a variable which is not declared 'const'.
10131   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10132   if (!var) return NCCK_None;
10133   if (var->getType().isConstQualified()) return NCCK_None;
10134   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10135 
10136   // Decide whether the first capture was for a block or a lambda.
10137   DeclContext *DC = S.CurContext, *Prev = nullptr;
10138   // Decide whether the first capture was for a block or a lambda.
10139   while (DC) {
10140     // For init-capture, it is possible that the variable belongs to the
10141     // template pattern of the current context.
10142     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10143       if (var->isInitCapture() &&
10144           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10145         break;
10146     if (DC == var->getDeclContext())
10147       break;
10148     Prev = DC;
10149     DC = DC->getParent();
10150   }
10151   // Unless we have an init-capture, we've gone one step too far.
10152   if (!var->isInitCapture())
10153     DC = Prev;
10154   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10155 }
10156 
10157 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10158   Ty = Ty.getNonReferenceType();
10159   if (IsDereference && Ty->isPointerType())
10160     Ty = Ty->getPointeeType();
10161   return !Ty.isConstQualified();
10162 }
10163 
10164 /// Emit the "read-only variable not assignable" error and print notes to give
10165 /// more information about why the variable is not assignable, such as pointing
10166 /// to the declaration of a const variable, showing that a method is const, or
10167 /// that the function is returning a const reference.
10168 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10169                                     SourceLocation Loc) {
10170   // Update err_typecheck_assign_const and note_typecheck_assign_const
10171   // when this enum is changed.
10172   enum {
10173     ConstFunction,
10174     ConstVariable,
10175     ConstMember,
10176     ConstMethod,
10177     ConstUnknown,  // Keep as last element
10178   };
10179 
10180   SourceRange ExprRange = E->getSourceRange();
10181 
10182   // Only emit one error on the first const found.  All other consts will emit
10183   // a note to the error.
10184   bool DiagnosticEmitted = false;
10185 
10186   // Track if the current expression is the result of a dereference, and if the
10187   // next checked expression is the result of a dereference.
10188   bool IsDereference = false;
10189   bool NextIsDereference = false;
10190 
10191   // Loop to process MemberExpr chains.
10192   while (true) {
10193     IsDereference = NextIsDereference;
10194 
10195     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10196     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10197       NextIsDereference = ME->isArrow();
10198       const ValueDecl *VD = ME->getMemberDecl();
10199       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10200         // Mutable fields can be modified even if the class is const.
10201         if (Field->isMutable()) {
10202           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10203           break;
10204         }
10205 
10206         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10207           if (!DiagnosticEmitted) {
10208             S.Diag(Loc, diag::err_typecheck_assign_const)
10209                 << ExprRange << ConstMember << false /*static*/ << Field
10210                 << Field->getType();
10211             DiagnosticEmitted = true;
10212           }
10213           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10214               << ConstMember << false /*static*/ << Field << Field->getType()
10215               << Field->getSourceRange();
10216         }
10217         E = ME->getBase();
10218         continue;
10219       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10220         if (VDecl->getType().isConstQualified()) {
10221           if (!DiagnosticEmitted) {
10222             S.Diag(Loc, diag::err_typecheck_assign_const)
10223                 << ExprRange << ConstMember << true /*static*/ << VDecl
10224                 << VDecl->getType();
10225             DiagnosticEmitted = true;
10226           }
10227           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10228               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10229               << VDecl->getSourceRange();
10230         }
10231         // Static fields do not inherit constness from parents.
10232         break;
10233       }
10234       break;
10235     } // End MemberExpr
10236     break;
10237   }
10238 
10239   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10240     // Function calls
10241     const FunctionDecl *FD = CE->getDirectCallee();
10242     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10243       if (!DiagnosticEmitted) {
10244         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10245                                                       << ConstFunction << FD;
10246         DiagnosticEmitted = true;
10247       }
10248       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10249              diag::note_typecheck_assign_const)
10250           << ConstFunction << FD << FD->getReturnType()
10251           << FD->getReturnTypeSourceRange();
10252     }
10253   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10254     // Point to variable declaration.
10255     if (const ValueDecl *VD = DRE->getDecl()) {
10256       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10257         if (!DiagnosticEmitted) {
10258           S.Diag(Loc, diag::err_typecheck_assign_const)
10259               << ExprRange << ConstVariable << VD << VD->getType();
10260           DiagnosticEmitted = true;
10261         }
10262         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10263             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10264       }
10265     }
10266   } else if (isa<CXXThisExpr>(E)) {
10267     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10268       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10269         if (MD->isConst()) {
10270           if (!DiagnosticEmitted) {
10271             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10272                                                           << ConstMethod << MD;
10273             DiagnosticEmitted = true;
10274           }
10275           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10276               << ConstMethod << MD << MD->getSourceRange();
10277         }
10278       }
10279     }
10280   }
10281 
10282   if (DiagnosticEmitted)
10283     return;
10284 
10285   // Can't determine a more specific message, so display the generic error.
10286   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10287 }
10288 
10289 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10290 /// emit an error and return true.  If so, return false.
10291 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10292   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10293 
10294   S.CheckShadowingDeclModification(E, Loc);
10295 
10296   SourceLocation OrigLoc = Loc;
10297   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10298                                                               &Loc);
10299   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10300     IsLV = Expr::MLV_InvalidMessageExpression;
10301   if (IsLV == Expr::MLV_Valid)
10302     return false;
10303 
10304   unsigned DiagID = 0;
10305   bool NeedType = false;
10306   switch (IsLV) { // C99 6.5.16p2
10307   case Expr::MLV_ConstQualified:
10308     // Use a specialized diagnostic when we're assigning to an object
10309     // from an enclosing function or block.
10310     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10311       if (NCCK == NCCK_Block)
10312         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10313       else
10314         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10315       break;
10316     }
10317 
10318     // In ARC, use some specialized diagnostics for occasions where we
10319     // infer 'const'.  These are always pseudo-strong variables.
10320     if (S.getLangOpts().ObjCAutoRefCount) {
10321       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10322       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10323         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10324 
10325         // Use the normal diagnostic if it's pseudo-__strong but the
10326         // user actually wrote 'const'.
10327         if (var->isARCPseudoStrong() &&
10328             (!var->getTypeSourceInfo() ||
10329              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10330           // There are two pseudo-strong cases:
10331           //  - self
10332           ObjCMethodDecl *method = S.getCurMethodDecl();
10333           if (method && var == method->getSelfDecl())
10334             DiagID = method->isClassMethod()
10335               ? diag::err_typecheck_arc_assign_self_class_method
10336               : diag::err_typecheck_arc_assign_self;
10337 
10338           //  - fast enumeration variables
10339           else
10340             DiagID = diag::err_typecheck_arr_assign_enumeration;
10341 
10342           SourceRange Assign;
10343           if (Loc != OrigLoc)
10344             Assign = SourceRange(OrigLoc, OrigLoc);
10345           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10346           // We need to preserve the AST regardless, so migration tool
10347           // can do its job.
10348           return false;
10349         }
10350       }
10351     }
10352 
10353     // If none of the special cases above are triggered, then this is a
10354     // simple const assignment.
10355     if (DiagID == 0) {
10356       DiagnoseConstAssignment(S, E, Loc);
10357       return true;
10358     }
10359 
10360     break;
10361   case Expr::MLV_ConstAddrSpace:
10362     DiagnoseConstAssignment(S, E, Loc);
10363     return true;
10364   case Expr::MLV_ArrayType:
10365   case Expr::MLV_ArrayTemporary:
10366     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10367     NeedType = true;
10368     break;
10369   case Expr::MLV_NotObjectType:
10370     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10371     NeedType = true;
10372     break;
10373   case Expr::MLV_LValueCast:
10374     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10375     break;
10376   case Expr::MLV_Valid:
10377     llvm_unreachable("did not take early return for MLV_Valid");
10378   case Expr::MLV_InvalidExpression:
10379   case Expr::MLV_MemberFunction:
10380   case Expr::MLV_ClassTemporary:
10381     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10382     break;
10383   case Expr::MLV_IncompleteType:
10384   case Expr::MLV_IncompleteVoidType:
10385     return S.RequireCompleteType(Loc, E->getType(),
10386              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10387   case Expr::MLV_DuplicateVectorComponents:
10388     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10389     break;
10390   case Expr::MLV_NoSetterProperty:
10391     llvm_unreachable("readonly properties should be processed differently");
10392   case Expr::MLV_InvalidMessageExpression:
10393     DiagID = diag::err_readonly_message_assignment;
10394     break;
10395   case Expr::MLV_SubObjCPropertySetting:
10396     DiagID = diag::err_no_subobject_property_setting;
10397     break;
10398   }
10399 
10400   SourceRange Assign;
10401   if (Loc != OrigLoc)
10402     Assign = SourceRange(OrigLoc, OrigLoc);
10403   if (NeedType)
10404     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10405   else
10406     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10407   return true;
10408 }
10409 
10410 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10411                                          SourceLocation Loc,
10412                                          Sema &Sema) {
10413   // C / C++ fields
10414   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10415   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10416   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10417     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10418       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10419   }
10420 
10421   // Objective-C instance variables
10422   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10423   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10424   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10425     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10426     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10427     if (RL && RR && RL->getDecl() == RR->getDecl())
10428       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10429   }
10430 }
10431 
10432 // C99 6.5.16.1
10433 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10434                                        SourceLocation Loc,
10435                                        QualType CompoundType) {
10436   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10437 
10438   // Verify that LHS is a modifiable lvalue, and emit error if not.
10439   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10440     return QualType();
10441 
10442   QualType LHSType = LHSExpr->getType();
10443   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10444                                              CompoundType;
10445   // OpenCL v1.2 s6.1.1.1 p2:
10446   // The half data type can only be used to declare a pointer to a buffer that
10447   // contains half values
10448   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10449     LHSType->isHalfType()) {
10450     Diag(Loc, diag::err_opencl_half_load_store) << 1
10451         << LHSType.getUnqualifiedType();
10452     return QualType();
10453   }
10454 
10455   AssignConvertType ConvTy;
10456   if (CompoundType.isNull()) {
10457     Expr *RHSCheck = RHS.get();
10458 
10459     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10460 
10461     QualType LHSTy(LHSType);
10462     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10463     if (RHS.isInvalid())
10464       return QualType();
10465     // Special case of NSObject attributes on c-style pointer types.
10466     if (ConvTy == IncompatiblePointer &&
10467         ((Context.isObjCNSObjectType(LHSType) &&
10468           RHSType->isObjCObjectPointerType()) ||
10469          (Context.isObjCNSObjectType(RHSType) &&
10470           LHSType->isObjCObjectPointerType())))
10471       ConvTy = Compatible;
10472 
10473     if (ConvTy == Compatible &&
10474         LHSType->isObjCObjectType())
10475         Diag(Loc, diag::err_objc_object_assignment)
10476           << LHSType;
10477 
10478     // If the RHS is a unary plus or minus, check to see if they = and + are
10479     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10480     // instead of "x += 4".
10481     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10482       RHSCheck = ICE->getSubExpr();
10483     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10484       if ((UO->getOpcode() == UO_Plus ||
10485            UO->getOpcode() == UO_Minus) &&
10486           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10487           // Only if the two operators are exactly adjacent.
10488           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10489           // And there is a space or other character before the subexpr of the
10490           // unary +/-.  We don't want to warn on "x=-1".
10491           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10492           UO->getSubExpr()->getLocStart().isFileID()) {
10493         Diag(Loc, diag::warn_not_compound_assign)
10494           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10495           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10496       }
10497     }
10498 
10499     if (ConvTy == Compatible) {
10500       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10501         // Warn about retain cycles where a block captures the LHS, but
10502         // not if the LHS is a simple variable into which the block is
10503         // being stored...unless that variable can be captured by reference!
10504         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10505         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10506         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10507           checkRetainCycles(LHSExpr, RHS.get());
10508       }
10509 
10510       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10511           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10512         // It is safe to assign a weak reference into a strong variable.
10513         // Although this code can still have problems:
10514         //   id x = self.weakProp;
10515         //   id y = self.weakProp;
10516         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10517         // paths through the function. This should be revisited if
10518         // -Wrepeated-use-of-weak is made flow-sensitive.
10519         // For ObjCWeak only, we do not warn if the assign is to a non-weak
10520         // variable, which will be valid for the current autorelease scope.
10521         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10522                              RHS.get()->getLocStart()))
10523           getCurFunction()->markSafeWeakUse(RHS.get());
10524 
10525       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10526         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10527       }
10528     }
10529   } else {
10530     // Compound assignment "x += y"
10531     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10532   }
10533 
10534   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10535                                RHS.get(), AA_Assigning))
10536     return QualType();
10537 
10538   CheckForNullPointerDereference(*this, LHSExpr);
10539 
10540   // C99 6.5.16p3: The type of an assignment expression is the type of the
10541   // left operand unless the left operand has qualified type, in which case
10542   // it is the unqualified version of the type of the left operand.
10543   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10544   // is converted to the type of the assignment expression (above).
10545   // C++ 5.17p1: the type of the assignment expression is that of its left
10546   // operand.
10547   return (getLangOpts().CPlusPlus
10548           ? LHSType : LHSType.getUnqualifiedType());
10549 }
10550 
10551 // Only ignore explicit casts to void.
10552 static bool IgnoreCommaOperand(const Expr *E) {
10553   E = E->IgnoreParens();
10554 
10555   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10556     if (CE->getCastKind() == CK_ToVoid) {
10557       return true;
10558     }
10559   }
10560 
10561   return false;
10562 }
10563 
10564 // Look for instances where it is likely the comma operator is confused with
10565 // another operator.  There is a whitelist of acceptable expressions for the
10566 // left hand side of the comma operator, otherwise emit a warning.
10567 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10568   // No warnings in macros
10569   if (Loc.isMacroID())
10570     return;
10571 
10572   // Don't warn in template instantiations.
10573   if (inTemplateInstantiation())
10574     return;
10575 
10576   // Scope isn't fine-grained enough to whitelist the specific cases, so
10577   // instead, skip more than needed, then call back into here with the
10578   // CommaVisitor in SemaStmt.cpp.
10579   // The whitelisted locations are the initialization and increment portions
10580   // of a for loop.  The additional checks are on the condition of
10581   // if statements, do/while loops, and for loops.
10582   const unsigned ForIncrementFlags =
10583       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10584   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10585   const unsigned ScopeFlags = getCurScope()->getFlags();
10586   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10587       (ScopeFlags & ForInitFlags) == ForInitFlags)
10588     return;
10589 
10590   // If there are multiple comma operators used together, get the RHS of the
10591   // of the comma operator as the LHS.
10592   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10593     if (BO->getOpcode() != BO_Comma)
10594       break;
10595     LHS = BO->getRHS();
10596   }
10597 
10598   // Only allow some expressions on LHS to not warn.
10599   if (IgnoreCommaOperand(LHS))
10600     return;
10601 
10602   Diag(Loc, diag::warn_comma_operator);
10603   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10604       << LHS->getSourceRange()
10605       << FixItHint::CreateInsertion(LHS->getLocStart(),
10606                                     LangOpts.CPlusPlus ? "static_cast<void>("
10607                                                        : "(void)(")
10608       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10609                                     ")");
10610 }
10611 
10612 // C99 6.5.17
10613 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10614                                    SourceLocation Loc) {
10615   LHS = S.CheckPlaceholderExpr(LHS.get());
10616   RHS = S.CheckPlaceholderExpr(RHS.get());
10617   if (LHS.isInvalid() || RHS.isInvalid())
10618     return QualType();
10619 
10620   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10621   // operands, but not unary promotions.
10622   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10623 
10624   // So we treat the LHS as a ignored value, and in C++ we allow the
10625   // containing site to determine what should be done with the RHS.
10626   LHS = S.IgnoredValueConversions(LHS.get());
10627   if (LHS.isInvalid())
10628     return QualType();
10629 
10630   S.DiagnoseUnusedExprResult(LHS.get());
10631 
10632   if (!S.getLangOpts().CPlusPlus) {
10633     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10634     if (RHS.isInvalid())
10635       return QualType();
10636     if (!RHS.get()->getType()->isVoidType())
10637       S.RequireCompleteType(Loc, RHS.get()->getType(),
10638                             diag::err_incomplete_type);
10639   }
10640 
10641   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10642     S.DiagnoseCommaOperator(LHS.get(), Loc);
10643 
10644   return RHS.get()->getType();
10645 }
10646 
10647 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10648 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10649 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10650                                                ExprValueKind &VK,
10651                                                ExprObjectKind &OK,
10652                                                SourceLocation OpLoc,
10653                                                bool IsInc, bool IsPrefix) {
10654   if (Op->isTypeDependent())
10655     return S.Context.DependentTy;
10656 
10657   QualType ResType = Op->getType();
10658   // Atomic types can be used for increment / decrement where the non-atomic
10659   // versions can, so ignore the _Atomic() specifier for the purpose of
10660   // checking.
10661   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10662     ResType = ResAtomicType->getValueType();
10663 
10664   assert(!ResType.isNull() && "no type for increment/decrement expression");
10665 
10666   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10667     // Decrement of bool is not allowed.
10668     if (!IsInc) {
10669       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10670       return QualType();
10671     }
10672     // Increment of bool sets it to true, but is deprecated.
10673     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10674                                               : diag::warn_increment_bool)
10675       << Op->getSourceRange();
10676   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10677     // Error on enum increments and decrements in C++ mode
10678     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10679     return QualType();
10680   } else if (ResType->isRealType()) {
10681     // OK!
10682   } else if (ResType->isPointerType()) {
10683     // C99 6.5.2.4p2, 6.5.6p2
10684     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10685       return QualType();
10686   } else if (ResType->isObjCObjectPointerType()) {
10687     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10688     // Otherwise, we just need a complete type.
10689     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10690         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10691       return QualType();
10692   } else if (ResType->isAnyComplexType()) {
10693     // C99 does not support ++/-- on complex types, we allow as an extension.
10694     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10695       << ResType << Op->getSourceRange();
10696   } else if (ResType->isPlaceholderType()) {
10697     ExprResult PR = S.CheckPlaceholderExpr(Op);
10698     if (PR.isInvalid()) return QualType();
10699     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10700                                           IsInc, IsPrefix);
10701   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10702     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10703   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10704              (ResType->getAs<VectorType>()->getVectorKind() !=
10705               VectorType::AltiVecBool)) {
10706     // The z vector extensions allow ++ and -- for non-bool vectors.
10707   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10708             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10709     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10710   } else {
10711     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10712       << ResType << int(IsInc) << Op->getSourceRange();
10713     return QualType();
10714   }
10715   // At this point, we know we have a real, complex or pointer type.
10716   // Now make sure the operand is a modifiable lvalue.
10717   if (CheckForModifiableLvalue(Op, OpLoc, S))
10718     return QualType();
10719   // In C++, a prefix increment is the same type as the operand. Otherwise
10720   // (in C or with postfix), the increment is the unqualified type of the
10721   // operand.
10722   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10723     VK = VK_LValue;
10724     OK = Op->getObjectKind();
10725     return ResType;
10726   } else {
10727     VK = VK_RValue;
10728     return ResType.getUnqualifiedType();
10729   }
10730 }
10731 
10732 
10733 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10734 /// This routine allows us to typecheck complex/recursive expressions
10735 /// where the declaration is needed for type checking. We only need to
10736 /// handle cases when the expression references a function designator
10737 /// or is an lvalue. Here are some examples:
10738 ///  - &(x) => x
10739 ///  - &*****f => f for f a function designator.
10740 ///  - &s.xx => s
10741 ///  - &s.zz[1].yy -> s, if zz is an array
10742 ///  - *(x + 1) -> x, if x is an array
10743 ///  - &"123"[2] -> 0
10744 ///  - & __real__ x -> x
10745 static ValueDecl *getPrimaryDecl(Expr *E) {
10746   switch (E->getStmtClass()) {
10747   case Stmt::DeclRefExprClass:
10748     return cast<DeclRefExpr>(E)->getDecl();
10749   case Stmt::MemberExprClass:
10750     // If this is an arrow operator, the address is an offset from
10751     // the base's value, so the object the base refers to is
10752     // irrelevant.
10753     if (cast<MemberExpr>(E)->isArrow())
10754       return nullptr;
10755     // Otherwise, the expression refers to a part of the base
10756     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10757   case Stmt::ArraySubscriptExprClass: {
10758     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10759     // promotion of register arrays earlier.
10760     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10761     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10762       if (ICE->getSubExpr()->getType()->isArrayType())
10763         return getPrimaryDecl(ICE->getSubExpr());
10764     }
10765     return nullptr;
10766   }
10767   case Stmt::UnaryOperatorClass: {
10768     UnaryOperator *UO = cast<UnaryOperator>(E);
10769 
10770     switch(UO->getOpcode()) {
10771     case UO_Real:
10772     case UO_Imag:
10773     case UO_Extension:
10774       return getPrimaryDecl(UO->getSubExpr());
10775     default:
10776       return nullptr;
10777     }
10778   }
10779   case Stmt::ParenExprClass:
10780     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10781   case Stmt::ImplicitCastExprClass:
10782     // If the result of an implicit cast is an l-value, we care about
10783     // the sub-expression; otherwise, the result here doesn't matter.
10784     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10785   default:
10786     return nullptr;
10787   }
10788 }
10789 
10790 namespace {
10791   enum {
10792     AO_Bit_Field = 0,
10793     AO_Vector_Element = 1,
10794     AO_Property_Expansion = 2,
10795     AO_Register_Variable = 3,
10796     AO_No_Error = 4
10797   };
10798 }
10799 /// \brief Diagnose invalid operand for address of operations.
10800 ///
10801 /// \param Type The type of operand which cannot have its address taken.
10802 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10803                                          Expr *E, unsigned Type) {
10804   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10805 }
10806 
10807 /// CheckAddressOfOperand - The operand of & must be either a function
10808 /// designator or an lvalue designating an object. If it is an lvalue, the
10809 /// object cannot be declared with storage class register or be a bit field.
10810 /// Note: The usual conversions are *not* applied to the operand of the &
10811 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10812 /// In C++, the operand might be an overloaded function name, in which case
10813 /// we allow the '&' but retain the overloaded-function type.
10814 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10815   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10816     if (PTy->getKind() == BuiltinType::Overload) {
10817       Expr *E = OrigOp.get()->IgnoreParens();
10818       if (!isa<OverloadExpr>(E)) {
10819         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10820         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10821           << OrigOp.get()->getSourceRange();
10822         return QualType();
10823       }
10824 
10825       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10826       if (isa<UnresolvedMemberExpr>(Ovl))
10827         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10828           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10829             << OrigOp.get()->getSourceRange();
10830           return QualType();
10831         }
10832 
10833       return Context.OverloadTy;
10834     }
10835 
10836     if (PTy->getKind() == BuiltinType::UnknownAny)
10837       return Context.UnknownAnyTy;
10838 
10839     if (PTy->getKind() == BuiltinType::BoundMember) {
10840       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10841         << OrigOp.get()->getSourceRange();
10842       return QualType();
10843     }
10844 
10845     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10846     if (OrigOp.isInvalid()) return QualType();
10847   }
10848 
10849   if (OrigOp.get()->isTypeDependent())
10850     return Context.DependentTy;
10851 
10852   assert(!OrigOp.get()->getType()->isPlaceholderType());
10853 
10854   // Make sure to ignore parentheses in subsequent checks
10855   Expr *op = OrigOp.get()->IgnoreParens();
10856 
10857   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10858   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10859     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10860     return QualType();
10861   }
10862 
10863   if (getLangOpts().C99) {
10864     // Implement C99-only parts of addressof rules.
10865     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10866       if (uOp->getOpcode() == UO_Deref)
10867         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10868         // (assuming the deref expression is valid).
10869         return uOp->getSubExpr()->getType();
10870     }
10871     // Technically, there should be a check for array subscript
10872     // expressions here, but the result of one is always an lvalue anyway.
10873   }
10874   ValueDecl *dcl = getPrimaryDecl(op);
10875 
10876   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10877     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10878                                            op->getLocStart()))
10879       return QualType();
10880 
10881   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10882   unsigned AddressOfError = AO_No_Error;
10883 
10884   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10885     bool sfinae = (bool)isSFINAEContext();
10886     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10887                                   : diag::ext_typecheck_addrof_temporary)
10888       << op->getType() << op->getSourceRange();
10889     if (sfinae)
10890       return QualType();
10891     // Materialize the temporary as an lvalue so that we can take its address.
10892     OrigOp = op =
10893         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10894   } else if (isa<ObjCSelectorExpr>(op)) {
10895     return Context.getPointerType(op->getType());
10896   } else if (lval == Expr::LV_MemberFunction) {
10897     // If it's an instance method, make a member pointer.
10898     // The expression must have exactly the form &A::foo.
10899 
10900     // If the underlying expression isn't a decl ref, give up.
10901     if (!isa<DeclRefExpr>(op)) {
10902       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10903         << OrigOp.get()->getSourceRange();
10904       return QualType();
10905     }
10906     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10907     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10908 
10909     // The id-expression was parenthesized.
10910     if (OrigOp.get() != DRE) {
10911       Diag(OpLoc, diag::err_parens_pointer_member_function)
10912         << OrigOp.get()->getSourceRange();
10913 
10914     // The method was named without a qualifier.
10915     } else if (!DRE->getQualifier()) {
10916       if (MD->getParent()->getName().empty())
10917         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10918           << op->getSourceRange();
10919       else {
10920         SmallString<32> Str;
10921         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10922         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10923           << op->getSourceRange()
10924           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10925       }
10926     }
10927 
10928     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10929     if (isa<CXXDestructorDecl>(MD))
10930       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10931 
10932     QualType MPTy = Context.getMemberPointerType(
10933         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10934     // Under the MS ABI, lock down the inheritance model now.
10935     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10936       (void)isCompleteType(OpLoc, MPTy);
10937     return MPTy;
10938   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10939     // C99 6.5.3.2p1
10940     // The operand must be either an l-value or a function designator
10941     if (!op->getType()->isFunctionType()) {
10942       // Use a special diagnostic for loads from property references.
10943       if (isa<PseudoObjectExpr>(op)) {
10944         AddressOfError = AO_Property_Expansion;
10945       } else {
10946         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10947           << op->getType() << op->getSourceRange();
10948         return QualType();
10949       }
10950     }
10951   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10952     // The operand cannot be a bit-field
10953     AddressOfError = AO_Bit_Field;
10954   } else if (op->getObjectKind() == OK_VectorComponent) {
10955     // The operand cannot be an element of a vector
10956     AddressOfError = AO_Vector_Element;
10957   } else if (dcl) { // C99 6.5.3.2p1
10958     // We have an lvalue with a decl. Make sure the decl is not declared
10959     // with the register storage-class specifier.
10960     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10961       // in C++ it is not error to take address of a register
10962       // variable (c++03 7.1.1P3)
10963       if (vd->getStorageClass() == SC_Register &&
10964           !getLangOpts().CPlusPlus) {
10965         AddressOfError = AO_Register_Variable;
10966       }
10967     } else if (isa<MSPropertyDecl>(dcl)) {
10968       AddressOfError = AO_Property_Expansion;
10969     } else if (isa<FunctionTemplateDecl>(dcl)) {
10970       return Context.OverloadTy;
10971     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10972       // Okay: we can take the address of a field.
10973       // Could be a pointer to member, though, if there is an explicit
10974       // scope qualifier for the class.
10975       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10976         DeclContext *Ctx = dcl->getDeclContext();
10977         if (Ctx && Ctx->isRecord()) {
10978           if (dcl->getType()->isReferenceType()) {
10979             Diag(OpLoc,
10980                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10981               << dcl->getDeclName() << dcl->getType();
10982             return QualType();
10983           }
10984 
10985           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10986             Ctx = Ctx->getParent();
10987 
10988           QualType MPTy = Context.getMemberPointerType(
10989               op->getType(),
10990               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10991           // Under the MS ABI, lock down the inheritance model now.
10992           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10993             (void)isCompleteType(OpLoc, MPTy);
10994           return MPTy;
10995         }
10996       }
10997     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10998                !isa<BindingDecl>(dcl))
10999       llvm_unreachable("Unknown/unexpected decl type");
11000   }
11001 
11002   if (AddressOfError != AO_No_Error) {
11003     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11004     return QualType();
11005   }
11006 
11007   if (lval == Expr::LV_IncompleteVoidType) {
11008     // Taking the address of a void variable is technically illegal, but we
11009     // allow it in cases which are otherwise valid.
11010     // Example: "extern void x; void* y = &x;".
11011     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11012   }
11013 
11014   // If the operand has type "type", the result has type "pointer to type".
11015   if (op->getType()->isObjCObjectType())
11016     return Context.getObjCObjectPointerType(op->getType());
11017 
11018   CheckAddressOfPackedMember(op);
11019 
11020   return Context.getPointerType(op->getType());
11021 }
11022 
11023 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11024   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11025   if (!DRE)
11026     return;
11027   const Decl *D = DRE->getDecl();
11028   if (!D)
11029     return;
11030   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11031   if (!Param)
11032     return;
11033   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11034     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11035       return;
11036   if (FunctionScopeInfo *FD = S.getCurFunction())
11037     if (!FD->ModifiedNonNullParams.count(Param))
11038       FD->ModifiedNonNullParams.insert(Param);
11039 }
11040 
11041 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11042 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11043                                         SourceLocation OpLoc) {
11044   if (Op->isTypeDependent())
11045     return S.Context.DependentTy;
11046 
11047   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11048   if (ConvResult.isInvalid())
11049     return QualType();
11050   Op = ConvResult.get();
11051   QualType OpTy = Op->getType();
11052   QualType Result;
11053 
11054   if (isa<CXXReinterpretCastExpr>(Op)) {
11055     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11056     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11057                                      Op->getSourceRange());
11058   }
11059 
11060   if (const PointerType *PT = OpTy->getAs<PointerType>())
11061   {
11062     Result = PT->getPointeeType();
11063   }
11064   else if (const ObjCObjectPointerType *OPT =
11065              OpTy->getAs<ObjCObjectPointerType>())
11066     Result = OPT->getPointeeType();
11067   else {
11068     ExprResult PR = S.CheckPlaceholderExpr(Op);
11069     if (PR.isInvalid()) return QualType();
11070     if (PR.get() != Op)
11071       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11072   }
11073 
11074   if (Result.isNull()) {
11075     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11076       << OpTy << Op->getSourceRange();
11077     return QualType();
11078   }
11079 
11080   // Note that per both C89 and C99, indirection is always legal, even if Result
11081   // is an incomplete type or void.  It would be possible to warn about
11082   // dereferencing a void pointer, but it's completely well-defined, and such a
11083   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11084   // for pointers to 'void' but is fine for any other pointer type:
11085   //
11086   // C++ [expr.unary.op]p1:
11087   //   [...] the expression to which [the unary * operator] is applied shall
11088   //   be a pointer to an object type, or a pointer to a function type
11089   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11090     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11091       << OpTy << Op->getSourceRange();
11092 
11093   // Dereferences are usually l-values...
11094   VK = VK_LValue;
11095 
11096   // ...except that certain expressions are never l-values in C.
11097   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11098     VK = VK_RValue;
11099 
11100   return Result;
11101 }
11102 
11103 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11104   BinaryOperatorKind Opc;
11105   switch (Kind) {
11106   default: llvm_unreachable("Unknown binop!");
11107   case tok::periodstar:           Opc = BO_PtrMemD; break;
11108   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11109   case tok::star:                 Opc = BO_Mul; break;
11110   case tok::slash:                Opc = BO_Div; break;
11111   case tok::percent:              Opc = BO_Rem; break;
11112   case tok::plus:                 Opc = BO_Add; break;
11113   case tok::minus:                Opc = BO_Sub; break;
11114   case tok::lessless:             Opc = BO_Shl; break;
11115   case tok::greatergreater:       Opc = BO_Shr; break;
11116   case tok::lessequal:            Opc = BO_LE; break;
11117   case tok::less:                 Opc = BO_LT; break;
11118   case tok::greaterequal:         Opc = BO_GE; break;
11119   case tok::greater:              Opc = BO_GT; break;
11120   case tok::exclaimequal:         Opc = BO_NE; break;
11121   case tok::equalequal:           Opc = BO_EQ; break;
11122   case tok::amp:                  Opc = BO_And; break;
11123   case tok::caret:                Opc = BO_Xor; break;
11124   case tok::pipe:                 Opc = BO_Or; break;
11125   case tok::ampamp:               Opc = BO_LAnd; break;
11126   case tok::pipepipe:             Opc = BO_LOr; break;
11127   case tok::equal:                Opc = BO_Assign; break;
11128   case tok::starequal:            Opc = BO_MulAssign; break;
11129   case tok::slashequal:           Opc = BO_DivAssign; break;
11130   case tok::percentequal:         Opc = BO_RemAssign; break;
11131   case tok::plusequal:            Opc = BO_AddAssign; break;
11132   case tok::minusequal:           Opc = BO_SubAssign; break;
11133   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11134   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11135   case tok::ampequal:             Opc = BO_AndAssign; break;
11136   case tok::caretequal:           Opc = BO_XorAssign; break;
11137   case tok::pipeequal:            Opc = BO_OrAssign; break;
11138   case tok::comma:                Opc = BO_Comma; break;
11139   }
11140   return Opc;
11141 }
11142 
11143 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11144   tok::TokenKind Kind) {
11145   UnaryOperatorKind Opc;
11146   switch (Kind) {
11147   default: llvm_unreachable("Unknown unary op!");
11148   case tok::plusplus:     Opc = UO_PreInc; break;
11149   case tok::minusminus:   Opc = UO_PreDec; break;
11150   case tok::amp:          Opc = UO_AddrOf; break;
11151   case tok::star:         Opc = UO_Deref; break;
11152   case tok::plus:         Opc = UO_Plus; break;
11153   case tok::minus:        Opc = UO_Minus; break;
11154   case tok::tilde:        Opc = UO_Not; break;
11155   case tok::exclaim:      Opc = UO_LNot; break;
11156   case tok::kw___real:    Opc = UO_Real; break;
11157   case tok::kw___imag:    Opc = UO_Imag; break;
11158   case tok::kw___extension__: Opc = UO_Extension; break;
11159   }
11160   return Opc;
11161 }
11162 
11163 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11164 /// This warning is only emitted for builtin assignment operations. It is also
11165 /// suppressed in the event of macro expansions.
11166 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11167                                    SourceLocation OpLoc) {
11168   if (S.inTemplateInstantiation())
11169     return;
11170   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11171     return;
11172   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11173   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11174   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11175   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11176   if (!LHSDeclRef || !RHSDeclRef ||
11177       LHSDeclRef->getLocation().isMacroID() ||
11178       RHSDeclRef->getLocation().isMacroID())
11179     return;
11180   const ValueDecl *LHSDecl =
11181     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11182   const ValueDecl *RHSDecl =
11183     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11184   if (LHSDecl != RHSDecl)
11185     return;
11186   if (LHSDecl->getType().isVolatileQualified())
11187     return;
11188   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11189     if (RefTy->getPointeeType().isVolatileQualified())
11190       return;
11191 
11192   S.Diag(OpLoc, diag::warn_self_assignment)
11193       << LHSDeclRef->getType()
11194       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11195 }
11196 
11197 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11198 /// is usually indicative of introspection within the Objective-C pointer.
11199 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11200                                           SourceLocation OpLoc) {
11201   if (!S.getLangOpts().ObjC1)
11202     return;
11203 
11204   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11205   const Expr *LHS = L.get();
11206   const Expr *RHS = R.get();
11207 
11208   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11209     ObjCPointerExpr = LHS;
11210     OtherExpr = RHS;
11211   }
11212   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11213     ObjCPointerExpr = RHS;
11214     OtherExpr = LHS;
11215   }
11216 
11217   // This warning is deliberately made very specific to reduce false
11218   // positives with logic that uses '&' for hashing.  This logic mainly
11219   // looks for code trying to introspect into tagged pointers, which
11220   // code should generally never do.
11221   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11222     unsigned Diag = diag::warn_objc_pointer_masking;
11223     // Determine if we are introspecting the result of performSelectorXXX.
11224     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11225     // Special case messages to -performSelector and friends, which
11226     // can return non-pointer values boxed in a pointer value.
11227     // Some clients may wish to silence warnings in this subcase.
11228     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11229       Selector S = ME->getSelector();
11230       StringRef SelArg0 = S.getNameForSlot(0);
11231       if (SelArg0.startswith("performSelector"))
11232         Diag = diag::warn_objc_pointer_masking_performSelector;
11233     }
11234 
11235     S.Diag(OpLoc, Diag)
11236       << ObjCPointerExpr->getSourceRange();
11237   }
11238 }
11239 
11240 static NamedDecl *getDeclFromExpr(Expr *E) {
11241   if (!E)
11242     return nullptr;
11243   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11244     return DRE->getDecl();
11245   if (auto *ME = dyn_cast<MemberExpr>(E))
11246     return ME->getMemberDecl();
11247   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11248     return IRE->getDecl();
11249   return nullptr;
11250 }
11251 
11252 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11253 /// operator @p Opc at location @c TokLoc. This routine only supports
11254 /// built-in operations; ActOnBinOp handles overloaded operators.
11255 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11256                                     BinaryOperatorKind Opc,
11257                                     Expr *LHSExpr, Expr *RHSExpr) {
11258   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11259     // The syntax only allows initializer lists on the RHS of assignment,
11260     // so we don't need to worry about accepting invalid code for
11261     // non-assignment operators.
11262     // C++11 5.17p9:
11263     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11264     //   of x = {} is x = T().
11265     InitializationKind Kind =
11266         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11267     InitializedEntity Entity =
11268         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11269     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11270     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11271     if (Init.isInvalid())
11272       return Init;
11273     RHSExpr = Init.get();
11274   }
11275 
11276   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11277   QualType ResultTy;     // Result type of the binary operator.
11278   // The following two variables are used for compound assignment operators
11279   QualType CompLHSTy;    // Type of LHS after promotions for computation
11280   QualType CompResultTy; // Type of computation result
11281   ExprValueKind VK = VK_RValue;
11282   ExprObjectKind OK = OK_Ordinary;
11283 
11284   if (!getLangOpts().CPlusPlus) {
11285     // C cannot handle TypoExpr nodes on either side of a binop because it
11286     // doesn't handle dependent types properly, so make sure any TypoExprs have
11287     // been dealt with before checking the operands.
11288     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11289     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11290       if (Opc != BO_Assign)
11291         return ExprResult(E);
11292       // Avoid correcting the RHS to the same Expr as the LHS.
11293       Decl *D = getDeclFromExpr(E);
11294       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11295     });
11296     if (!LHS.isUsable() || !RHS.isUsable())
11297       return ExprError();
11298   }
11299 
11300   if (getLangOpts().OpenCL) {
11301     QualType LHSTy = LHSExpr->getType();
11302     QualType RHSTy = RHSExpr->getType();
11303     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11304     // the ATOMIC_VAR_INIT macro.
11305     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11306       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11307       if (BO_Assign == Opc)
11308         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11309       else
11310         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11311       return ExprError();
11312     }
11313 
11314     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11315     // only with a builtin functions and therefore should be disallowed here.
11316     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11317         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11318         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11319         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11320       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11321       return ExprError();
11322     }
11323   }
11324 
11325   switch (Opc) {
11326   case BO_Assign:
11327     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11328     if (getLangOpts().CPlusPlus &&
11329         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11330       VK = LHS.get()->getValueKind();
11331       OK = LHS.get()->getObjectKind();
11332     }
11333     if (!ResultTy.isNull()) {
11334       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11335       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11336     }
11337     RecordModifiableNonNullParam(*this, LHS.get());
11338     break;
11339   case BO_PtrMemD:
11340   case BO_PtrMemI:
11341     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11342                                             Opc == BO_PtrMemI);
11343     break;
11344   case BO_Mul:
11345   case BO_Div:
11346     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11347                                            Opc == BO_Div);
11348     break;
11349   case BO_Rem:
11350     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11351     break;
11352   case BO_Add:
11353     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11354     break;
11355   case BO_Sub:
11356     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11357     break;
11358   case BO_Shl:
11359   case BO_Shr:
11360     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11361     break;
11362   case BO_LE:
11363   case BO_LT:
11364   case BO_GE:
11365   case BO_GT:
11366     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11367     break;
11368   case BO_EQ:
11369   case BO_NE:
11370     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11371     break;
11372   case BO_And:
11373     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11374     LLVM_FALLTHROUGH;
11375   case BO_Xor:
11376   case BO_Or:
11377     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11378     break;
11379   case BO_LAnd:
11380   case BO_LOr:
11381     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11382     break;
11383   case BO_MulAssign:
11384   case BO_DivAssign:
11385     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11386                                                Opc == BO_DivAssign);
11387     CompLHSTy = CompResultTy;
11388     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11389       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11390     break;
11391   case BO_RemAssign:
11392     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11393     CompLHSTy = CompResultTy;
11394     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11395       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11396     break;
11397   case BO_AddAssign:
11398     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11399     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11400       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11401     break;
11402   case BO_SubAssign:
11403     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11404     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11405       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11406     break;
11407   case BO_ShlAssign:
11408   case BO_ShrAssign:
11409     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11410     CompLHSTy = CompResultTy;
11411     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11412       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11413     break;
11414   case BO_AndAssign:
11415   case BO_OrAssign: // fallthrough
11416     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11417     LLVM_FALLTHROUGH;
11418   case BO_XorAssign:
11419     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11420     CompLHSTy = CompResultTy;
11421     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11422       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11423     break;
11424   case BO_Comma:
11425     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11426     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11427       VK = RHS.get()->getValueKind();
11428       OK = RHS.get()->getObjectKind();
11429     }
11430     break;
11431   }
11432   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11433     return ExprError();
11434 
11435   // Check for array bounds violations for both sides of the BinaryOperator
11436   CheckArrayAccess(LHS.get());
11437   CheckArrayAccess(RHS.get());
11438 
11439   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11440     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11441                                                  &Context.Idents.get("object_setClass"),
11442                                                  SourceLocation(), LookupOrdinaryName);
11443     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11444       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11445       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11446       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11447       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11448       FixItHint::CreateInsertion(RHSLocEnd, ")");
11449     }
11450     else
11451       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11452   }
11453   else if (const ObjCIvarRefExpr *OIRE =
11454            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11455     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11456 
11457   if (CompResultTy.isNull())
11458     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11459                                         OK, OpLoc, FPFeatures);
11460   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11461       OK_ObjCProperty) {
11462     VK = VK_LValue;
11463     OK = LHS.get()->getObjectKind();
11464   }
11465   return new (Context) CompoundAssignOperator(
11466       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11467       OpLoc, FPFeatures);
11468 }
11469 
11470 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11471 /// operators are mixed in a way that suggests that the programmer forgot that
11472 /// comparison operators have higher precedence. The most typical example of
11473 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11474 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11475                                       SourceLocation OpLoc, Expr *LHSExpr,
11476                                       Expr *RHSExpr) {
11477   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11478   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11479 
11480   // Check that one of the sides is a comparison operator and the other isn't.
11481   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11482   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11483   if (isLeftComp == isRightComp)
11484     return;
11485 
11486   // Bitwise operations are sometimes used as eager logical ops.
11487   // Don't diagnose this.
11488   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11489   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11490   if (isLeftBitwise || isRightBitwise)
11491     return;
11492 
11493   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11494                                                    OpLoc)
11495                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11496   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11497   SourceRange ParensRange = isLeftComp ?
11498       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11499     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11500 
11501   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11502     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11503   SuggestParentheses(Self, OpLoc,
11504     Self.PDiag(diag::note_precedence_silence) << OpStr,
11505     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11506   SuggestParentheses(Self, OpLoc,
11507     Self.PDiag(diag::note_precedence_bitwise_first)
11508       << BinaryOperator::getOpcodeStr(Opc),
11509     ParensRange);
11510 }
11511 
11512 /// \brief It accepts a '&&' expr that is inside a '||' one.
11513 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11514 /// in parentheses.
11515 static void
11516 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11517                                        BinaryOperator *Bop) {
11518   assert(Bop->getOpcode() == BO_LAnd);
11519   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11520       << Bop->getSourceRange() << OpLoc;
11521   SuggestParentheses(Self, Bop->getOperatorLoc(),
11522     Self.PDiag(diag::note_precedence_silence)
11523       << Bop->getOpcodeStr(),
11524     Bop->getSourceRange());
11525 }
11526 
11527 /// \brief Returns true if the given expression can be evaluated as a constant
11528 /// 'true'.
11529 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11530   bool Res;
11531   return !E->isValueDependent() &&
11532          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11533 }
11534 
11535 /// \brief Returns true if the given expression can be evaluated as a constant
11536 /// 'false'.
11537 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11538   bool Res;
11539   return !E->isValueDependent() &&
11540          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11541 }
11542 
11543 /// \brief Look for '&&' in the left hand of a '||' expr.
11544 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11545                                              Expr *LHSExpr, Expr *RHSExpr) {
11546   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11547     if (Bop->getOpcode() == BO_LAnd) {
11548       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11549       if (EvaluatesAsFalse(S, RHSExpr))
11550         return;
11551       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11552       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11553         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11554     } else if (Bop->getOpcode() == BO_LOr) {
11555       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11556         // If it's "a || b && 1 || c" we didn't warn earlier for
11557         // "a || b && 1", but warn now.
11558         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11559           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11560       }
11561     }
11562   }
11563 }
11564 
11565 /// \brief Look for '&&' in the right hand of a '||' expr.
11566 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11567                                              Expr *LHSExpr, Expr *RHSExpr) {
11568   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11569     if (Bop->getOpcode() == BO_LAnd) {
11570       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11571       if (EvaluatesAsFalse(S, LHSExpr))
11572         return;
11573       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11574       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11575         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11576     }
11577   }
11578 }
11579 
11580 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11581 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11582 /// the '&' expression in parentheses.
11583 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11584                                          SourceLocation OpLoc, Expr *SubExpr) {
11585   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11586     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11587       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11588         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11589         << Bop->getSourceRange() << OpLoc;
11590       SuggestParentheses(S, Bop->getOperatorLoc(),
11591         S.PDiag(diag::note_precedence_silence)
11592           << Bop->getOpcodeStr(),
11593         Bop->getSourceRange());
11594     }
11595   }
11596 }
11597 
11598 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11599                                     Expr *SubExpr, StringRef Shift) {
11600   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11601     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11602       StringRef Op = Bop->getOpcodeStr();
11603       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11604           << Bop->getSourceRange() << OpLoc << Shift << Op;
11605       SuggestParentheses(S, Bop->getOperatorLoc(),
11606           S.PDiag(diag::note_precedence_silence) << Op,
11607           Bop->getSourceRange());
11608     }
11609   }
11610 }
11611 
11612 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11613                                  Expr *LHSExpr, Expr *RHSExpr) {
11614   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11615   if (!OCE)
11616     return;
11617 
11618   FunctionDecl *FD = OCE->getDirectCallee();
11619   if (!FD || !FD->isOverloadedOperator())
11620     return;
11621 
11622   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11623   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11624     return;
11625 
11626   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11627       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11628       << (Kind == OO_LessLess);
11629   SuggestParentheses(S, OCE->getOperatorLoc(),
11630                      S.PDiag(diag::note_precedence_silence)
11631                          << (Kind == OO_LessLess ? "<<" : ">>"),
11632                      OCE->getSourceRange());
11633   SuggestParentheses(S, OpLoc,
11634                      S.PDiag(diag::note_evaluate_comparison_first),
11635                      SourceRange(OCE->getArg(1)->getLocStart(),
11636                                  RHSExpr->getLocEnd()));
11637 }
11638 
11639 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11640 /// precedence.
11641 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11642                                     SourceLocation OpLoc, Expr *LHSExpr,
11643                                     Expr *RHSExpr){
11644   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11645   if (BinaryOperator::isBitwiseOp(Opc))
11646     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11647 
11648   // Diagnose "arg1 & arg2 | arg3"
11649   if ((Opc == BO_Or || Opc == BO_Xor) &&
11650       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11651     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11652     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11653   }
11654 
11655   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11656   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11657   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11658     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11659     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11660   }
11661 
11662   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11663       || Opc == BO_Shr) {
11664     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11665     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11666     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11667   }
11668 
11669   // Warn on overloaded shift operators and comparisons, such as:
11670   // cout << 5 == 4;
11671   if (BinaryOperator::isComparisonOp(Opc))
11672     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11673 }
11674 
11675 // Binary Operators.  'Tok' is the token for the operator.
11676 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11677                             tok::TokenKind Kind,
11678                             Expr *LHSExpr, Expr *RHSExpr) {
11679   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11680   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11681   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11682 
11683   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11684   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11685 
11686   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11687 }
11688 
11689 /// Build an overloaded binary operator expression in the given scope.
11690 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11691                                        BinaryOperatorKind Opc,
11692                                        Expr *LHS, Expr *RHS) {
11693   // Find all of the overloaded operators visible from this
11694   // point. We perform both an operator-name lookup from the local
11695   // scope and an argument-dependent lookup based on the types of
11696   // the arguments.
11697   UnresolvedSet<16> Functions;
11698   OverloadedOperatorKind OverOp
11699     = BinaryOperator::getOverloadedOperator(Opc);
11700   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11701     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11702                                    RHS->getType(), Functions);
11703 
11704   // Build the (potentially-overloaded, potentially-dependent)
11705   // binary operation.
11706   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11707 }
11708 
11709 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11710                             BinaryOperatorKind Opc,
11711                             Expr *LHSExpr, Expr *RHSExpr) {
11712   // We want to end up calling one of checkPseudoObjectAssignment
11713   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11714   // both expressions are overloadable or either is type-dependent),
11715   // or CreateBuiltinBinOp (in any other case).  We also want to get
11716   // any placeholder types out of the way.
11717 
11718   // Handle pseudo-objects in the LHS.
11719   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11720     // Assignments with a pseudo-object l-value need special analysis.
11721     if (pty->getKind() == BuiltinType::PseudoObject &&
11722         BinaryOperator::isAssignmentOp(Opc))
11723       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11724 
11725     // Don't resolve overloads if the other type is overloadable.
11726     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11727       // We can't actually test that if we still have a placeholder,
11728       // though.  Fortunately, none of the exceptions we see in that
11729       // code below are valid when the LHS is an overload set.  Note
11730       // that an overload set can be dependently-typed, but it never
11731       // instantiates to having an overloadable type.
11732       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11733       if (resolvedRHS.isInvalid()) return ExprError();
11734       RHSExpr = resolvedRHS.get();
11735 
11736       if (RHSExpr->isTypeDependent() ||
11737           RHSExpr->getType()->isOverloadableType())
11738         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11739     }
11740 
11741     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
11742     // template, diagnose the missing 'template' keyword instead of diagnosing
11743     // an invalid use of a bound member function.
11744     //
11745     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
11746     // to C++1z [over.over]/1.4, but we already checked for that case above.
11747     if (Opc == BO_LT && inTemplateInstantiation() &&
11748         (pty->getKind() == BuiltinType::BoundMember ||
11749          pty->getKind() == BuiltinType::Overload)) {
11750       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
11751       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
11752           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
11753             return isa<FunctionTemplateDecl>(ND);
11754           })) {
11755         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
11756                                 : OE->getNameLoc(),
11757              diag::err_template_kw_missing)
11758           << OE->getName().getAsString() << "";
11759         return ExprError();
11760       }
11761     }
11762 
11763     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11764     if (LHS.isInvalid()) return ExprError();
11765     LHSExpr = LHS.get();
11766   }
11767 
11768   // Handle pseudo-objects in the RHS.
11769   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11770     // An overload in the RHS can potentially be resolved by the type
11771     // being assigned to.
11772     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11773       if (getLangOpts().CPlusPlus &&
11774           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11775            LHSExpr->getType()->isOverloadableType()))
11776         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11777 
11778       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11779     }
11780 
11781     // Don't resolve overloads if the other type is overloadable.
11782     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11783         LHSExpr->getType()->isOverloadableType())
11784       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11785 
11786     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11787     if (!resolvedRHS.isUsable()) return ExprError();
11788     RHSExpr = resolvedRHS.get();
11789   }
11790 
11791   if (getLangOpts().CPlusPlus) {
11792     // If either expression is type-dependent, always build an
11793     // overloaded op.
11794     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11795       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11796 
11797     // Otherwise, build an overloaded op if either expression has an
11798     // overloadable type.
11799     if (LHSExpr->getType()->isOverloadableType() ||
11800         RHSExpr->getType()->isOverloadableType())
11801       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11802   }
11803 
11804   // Build a built-in binary operation.
11805   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11806 }
11807 
11808 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11809                                       UnaryOperatorKind Opc,
11810                                       Expr *InputExpr) {
11811   ExprResult Input = InputExpr;
11812   ExprValueKind VK = VK_RValue;
11813   ExprObjectKind OK = OK_Ordinary;
11814   QualType resultType;
11815   if (getLangOpts().OpenCL) {
11816     QualType Ty = InputExpr->getType();
11817     // The only legal unary operation for atomics is '&'.
11818     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11819     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11820     // only with a builtin functions and therefore should be disallowed here.
11821         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11822         || Ty->isBlockPointerType())) {
11823       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11824                        << InputExpr->getType()
11825                        << Input.get()->getSourceRange());
11826     }
11827   }
11828   switch (Opc) {
11829   case UO_PreInc:
11830   case UO_PreDec:
11831   case UO_PostInc:
11832   case UO_PostDec:
11833     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11834                                                 OpLoc,
11835                                                 Opc == UO_PreInc ||
11836                                                 Opc == UO_PostInc,
11837                                                 Opc == UO_PreInc ||
11838                                                 Opc == UO_PreDec);
11839     break;
11840   case UO_AddrOf:
11841     resultType = CheckAddressOfOperand(Input, OpLoc);
11842     RecordModifiableNonNullParam(*this, InputExpr);
11843     break;
11844   case UO_Deref: {
11845     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11846     if (Input.isInvalid()) return ExprError();
11847     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11848     break;
11849   }
11850   case UO_Plus:
11851   case UO_Minus:
11852     Input = UsualUnaryConversions(Input.get());
11853     if (Input.isInvalid()) return ExprError();
11854     resultType = Input.get()->getType();
11855     if (resultType->isDependentType())
11856       break;
11857     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11858       break;
11859     else if (resultType->isVectorType() &&
11860              // The z vector extensions don't allow + or - with bool vectors.
11861              (!Context.getLangOpts().ZVector ||
11862               resultType->getAs<VectorType>()->getVectorKind() !=
11863               VectorType::AltiVecBool))
11864       break;
11865     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11866              Opc == UO_Plus &&
11867              resultType->isPointerType())
11868       break;
11869 
11870     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11871       << resultType << Input.get()->getSourceRange());
11872 
11873   case UO_Not: // bitwise complement
11874     Input = UsualUnaryConversions(Input.get());
11875     if (Input.isInvalid())
11876       return ExprError();
11877     resultType = Input.get()->getType();
11878     if (resultType->isDependentType())
11879       break;
11880     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11881     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11882       // C99 does not support '~' for complex conjugation.
11883       Diag(OpLoc, diag::ext_integer_complement_complex)
11884           << resultType << Input.get()->getSourceRange();
11885     else if (resultType->hasIntegerRepresentation())
11886       break;
11887     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
11888       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11889       // on vector float types.
11890       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11891       if (!T->isIntegerType())
11892         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11893                           << resultType << Input.get()->getSourceRange());
11894     } else {
11895       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11896                        << resultType << Input.get()->getSourceRange());
11897     }
11898     break;
11899 
11900   case UO_LNot: // logical negation
11901     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11902     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11903     if (Input.isInvalid()) return ExprError();
11904     resultType = Input.get()->getType();
11905 
11906     // Though we still have to promote half FP to float...
11907     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11908       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11909       resultType = Context.FloatTy;
11910     }
11911 
11912     if (resultType->isDependentType())
11913       break;
11914     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11915       // C99 6.5.3.3p1: ok, fallthrough;
11916       if (Context.getLangOpts().CPlusPlus) {
11917         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11918         // operand contextually converted to bool.
11919         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11920                                   ScalarTypeToBooleanCastKind(resultType));
11921       } else if (Context.getLangOpts().OpenCL &&
11922                  Context.getLangOpts().OpenCLVersion < 120) {
11923         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11924         // operate on scalar float types.
11925         if (!resultType->isIntegerType() && !resultType->isPointerType())
11926           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11927                            << resultType << Input.get()->getSourceRange());
11928       }
11929     } else if (resultType->isExtVectorType()) {
11930       if (Context.getLangOpts().OpenCL &&
11931           Context.getLangOpts().OpenCLVersion < 120) {
11932         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11933         // operate on vector float types.
11934         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11935         if (!T->isIntegerType())
11936           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11937                            << resultType << Input.get()->getSourceRange());
11938       }
11939       // Vector logical not returns the signed variant of the operand type.
11940       resultType = GetSignedVectorType(resultType);
11941       break;
11942     } else {
11943       // FIXME: GCC's vector extension permits the usage of '!' with a vector
11944       //        type in C++. We should allow that here too.
11945       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11946         << resultType << Input.get()->getSourceRange());
11947     }
11948 
11949     // LNot always has type int. C99 6.5.3.3p5.
11950     // In C++, it's bool. C++ 5.3.1p8
11951     resultType = Context.getLogicalOperationType();
11952     break;
11953   case UO_Real:
11954   case UO_Imag:
11955     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11956     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11957     // complex l-values to ordinary l-values and all other values to r-values.
11958     if (Input.isInvalid()) return ExprError();
11959     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11960       if (Input.get()->getValueKind() != VK_RValue &&
11961           Input.get()->getObjectKind() == OK_Ordinary)
11962         VK = Input.get()->getValueKind();
11963     } else if (!getLangOpts().CPlusPlus) {
11964       // In C, a volatile scalar is read by __imag. In C++, it is not.
11965       Input = DefaultLvalueConversion(Input.get());
11966     }
11967     break;
11968   case UO_Extension:
11969     resultType = Input.get()->getType();
11970     VK = Input.get()->getValueKind();
11971     OK = Input.get()->getObjectKind();
11972     break;
11973   case UO_Coawait:
11974     // It's unnessesary to represent the pass-through operator co_await in the
11975     // AST; just return the input expression instead.
11976     assert(!Input.get()->getType()->isDependentType() &&
11977                    "the co_await expression must be non-dependant before "
11978                    "building operator co_await");
11979     return Input;
11980   }
11981   if (resultType.isNull() || Input.isInvalid())
11982     return ExprError();
11983 
11984   // Check for array bounds violations in the operand of the UnaryOperator,
11985   // except for the '*' and '&' operators that have to be handled specially
11986   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11987   // that are explicitly defined as valid by the standard).
11988   if (Opc != UO_AddrOf && Opc != UO_Deref)
11989     CheckArrayAccess(Input.get());
11990 
11991   return new (Context)
11992       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11993 }
11994 
11995 /// \brief Determine whether the given expression is a qualified member
11996 /// access expression, of a form that could be turned into a pointer to member
11997 /// with the address-of operator.
11998 static bool isQualifiedMemberAccess(Expr *E) {
11999   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12000     if (!DRE->getQualifier())
12001       return false;
12002 
12003     ValueDecl *VD = DRE->getDecl();
12004     if (!VD->isCXXClassMember())
12005       return false;
12006 
12007     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12008       return true;
12009     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12010       return Method->isInstance();
12011 
12012     return false;
12013   }
12014 
12015   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12016     if (!ULE->getQualifier())
12017       return false;
12018 
12019     for (NamedDecl *D : ULE->decls()) {
12020       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12021         if (Method->isInstance())
12022           return true;
12023       } else {
12024         // Overload set does not contain methods.
12025         break;
12026       }
12027     }
12028 
12029     return false;
12030   }
12031 
12032   return false;
12033 }
12034 
12035 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12036                               UnaryOperatorKind Opc, Expr *Input) {
12037   // First things first: handle placeholders so that the
12038   // overloaded-operator check considers the right type.
12039   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12040     // Increment and decrement of pseudo-object references.
12041     if (pty->getKind() == BuiltinType::PseudoObject &&
12042         UnaryOperator::isIncrementDecrementOp(Opc))
12043       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12044 
12045     // extension is always a builtin operator.
12046     if (Opc == UO_Extension)
12047       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12048 
12049     // & gets special logic for several kinds of placeholder.
12050     // The builtin code knows what to do.
12051     if (Opc == UO_AddrOf &&
12052         (pty->getKind() == BuiltinType::Overload ||
12053          pty->getKind() == BuiltinType::UnknownAny ||
12054          pty->getKind() == BuiltinType::BoundMember))
12055       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12056 
12057     // Anything else needs to be handled now.
12058     ExprResult Result = CheckPlaceholderExpr(Input);
12059     if (Result.isInvalid()) return ExprError();
12060     Input = Result.get();
12061   }
12062 
12063   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12064       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12065       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12066     // Find all of the overloaded operators visible from this
12067     // point. We perform both an operator-name lookup from the local
12068     // scope and an argument-dependent lookup based on the types of
12069     // the arguments.
12070     UnresolvedSet<16> Functions;
12071     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12072     if (S && OverOp != OO_None)
12073       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12074                                    Functions);
12075 
12076     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12077   }
12078 
12079   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12080 }
12081 
12082 // Unary Operators.  'Tok' is the token for the operator.
12083 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12084                               tok::TokenKind Op, Expr *Input) {
12085   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12086 }
12087 
12088 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12089 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12090                                 LabelDecl *TheDecl) {
12091   TheDecl->markUsed(Context);
12092   // Create the AST node.  The address of a label always has type 'void*'.
12093   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12094                                      Context.getPointerType(Context.VoidTy));
12095 }
12096 
12097 /// Given the last statement in a statement-expression, check whether
12098 /// the result is a producing expression (like a call to an
12099 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12100 /// release out of the full-expression.  Otherwise, return null.
12101 /// Cannot fail.
12102 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12103   // Should always be wrapped with one of these.
12104   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12105   if (!cleanups) return nullptr;
12106 
12107   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12108   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12109     return nullptr;
12110 
12111   // Splice out the cast.  This shouldn't modify any interesting
12112   // features of the statement.
12113   Expr *producer = cast->getSubExpr();
12114   assert(producer->getType() == cast->getType());
12115   assert(producer->getValueKind() == cast->getValueKind());
12116   cleanups->setSubExpr(producer);
12117   return cleanups;
12118 }
12119 
12120 void Sema::ActOnStartStmtExpr() {
12121   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12122 }
12123 
12124 void Sema::ActOnStmtExprError() {
12125   // Note that function is also called by TreeTransform when leaving a
12126   // StmtExpr scope without rebuilding anything.
12127 
12128   DiscardCleanupsInEvaluationContext();
12129   PopExpressionEvaluationContext();
12130 }
12131 
12132 ExprResult
12133 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12134                     SourceLocation RPLoc) { // "({..})"
12135   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12136   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12137 
12138   if (hasAnyUnrecoverableErrorsInThisFunction())
12139     DiscardCleanupsInEvaluationContext();
12140   assert(!Cleanup.exprNeedsCleanups() &&
12141          "cleanups within StmtExpr not correctly bound!");
12142   PopExpressionEvaluationContext();
12143 
12144   // FIXME: there are a variety of strange constraints to enforce here, for
12145   // example, it is not possible to goto into a stmt expression apparently.
12146   // More semantic analysis is needed.
12147 
12148   // If there are sub-stmts in the compound stmt, take the type of the last one
12149   // as the type of the stmtexpr.
12150   QualType Ty = Context.VoidTy;
12151   bool StmtExprMayBindToTemp = false;
12152   if (!Compound->body_empty()) {
12153     Stmt *LastStmt = Compound->body_back();
12154     LabelStmt *LastLabelStmt = nullptr;
12155     // If LastStmt is a label, skip down through into the body.
12156     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12157       LastLabelStmt = Label;
12158       LastStmt = Label->getSubStmt();
12159     }
12160 
12161     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12162       // Do function/array conversion on the last expression, but not
12163       // lvalue-to-rvalue.  However, initialize an unqualified type.
12164       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12165       if (LastExpr.isInvalid())
12166         return ExprError();
12167       Ty = LastExpr.get()->getType().getUnqualifiedType();
12168 
12169       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12170         // In ARC, if the final expression ends in a consume, splice
12171         // the consume out and bind it later.  In the alternate case
12172         // (when dealing with a retainable type), the result
12173         // initialization will create a produce.  In both cases the
12174         // result will be +1, and we'll need to balance that out with
12175         // a bind.
12176         if (Expr *rebuiltLastStmt
12177               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12178           LastExpr = rebuiltLastStmt;
12179         } else {
12180           LastExpr = PerformCopyInitialization(
12181                             InitializedEntity::InitializeResult(LPLoc,
12182                                                                 Ty,
12183                                                                 false),
12184                                                    SourceLocation(),
12185                                                LastExpr);
12186         }
12187 
12188         if (LastExpr.isInvalid())
12189           return ExprError();
12190         if (LastExpr.get() != nullptr) {
12191           if (!LastLabelStmt)
12192             Compound->setLastStmt(LastExpr.get());
12193           else
12194             LastLabelStmt->setSubStmt(LastExpr.get());
12195           StmtExprMayBindToTemp = true;
12196         }
12197       }
12198     }
12199   }
12200 
12201   // FIXME: Check that expression type is complete/non-abstract; statement
12202   // expressions are not lvalues.
12203   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12204   if (StmtExprMayBindToTemp)
12205     return MaybeBindToTemporary(ResStmtExpr);
12206   return ResStmtExpr;
12207 }
12208 
12209 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12210                                       TypeSourceInfo *TInfo,
12211                                       ArrayRef<OffsetOfComponent> Components,
12212                                       SourceLocation RParenLoc) {
12213   QualType ArgTy = TInfo->getType();
12214   bool Dependent = ArgTy->isDependentType();
12215   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12216 
12217   // We must have at least one component that refers to the type, and the first
12218   // one is known to be a field designator.  Verify that the ArgTy represents
12219   // a struct/union/class.
12220   if (!Dependent && !ArgTy->isRecordType())
12221     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12222                        << ArgTy << TypeRange);
12223 
12224   // Type must be complete per C99 7.17p3 because a declaring a variable
12225   // with an incomplete type would be ill-formed.
12226   if (!Dependent
12227       && RequireCompleteType(BuiltinLoc, ArgTy,
12228                              diag::err_offsetof_incomplete_type, TypeRange))
12229     return ExprError();
12230 
12231   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
12232   // GCC extension, diagnose them.
12233   // FIXME: This diagnostic isn't actually visible because the location is in
12234   // a system header!
12235   if (Components.size() != 1)
12236     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
12237       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
12238 
12239   bool DidWarnAboutNonPOD = false;
12240   QualType CurrentType = ArgTy;
12241   SmallVector<OffsetOfNode, 4> Comps;
12242   SmallVector<Expr*, 4> Exprs;
12243   for (const OffsetOfComponent &OC : Components) {
12244     if (OC.isBrackets) {
12245       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12246       if (!CurrentType->isDependentType()) {
12247         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12248         if(!AT)
12249           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12250                            << CurrentType);
12251         CurrentType = AT->getElementType();
12252       } else
12253         CurrentType = Context.DependentTy;
12254 
12255       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12256       if (IdxRval.isInvalid())
12257         return ExprError();
12258       Expr *Idx = IdxRval.get();
12259 
12260       // The expression must be an integral expression.
12261       // FIXME: An integral constant expression?
12262       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12263           !Idx->getType()->isIntegerType())
12264         return ExprError(Diag(Idx->getLocStart(),
12265                               diag::err_typecheck_subscript_not_integer)
12266                          << Idx->getSourceRange());
12267 
12268       // Record this array index.
12269       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12270       Exprs.push_back(Idx);
12271       continue;
12272     }
12273 
12274     // Offset of a field.
12275     if (CurrentType->isDependentType()) {
12276       // We have the offset of a field, but we can't look into the dependent
12277       // type. Just record the identifier of the field.
12278       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12279       CurrentType = Context.DependentTy;
12280       continue;
12281     }
12282 
12283     // We need to have a complete type to look into.
12284     if (RequireCompleteType(OC.LocStart, CurrentType,
12285                             diag::err_offsetof_incomplete_type))
12286       return ExprError();
12287 
12288     // Look for the designated field.
12289     const RecordType *RC = CurrentType->getAs<RecordType>();
12290     if (!RC)
12291       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12292                        << CurrentType);
12293     RecordDecl *RD = RC->getDecl();
12294 
12295     // C++ [lib.support.types]p5:
12296     //   The macro offsetof accepts a restricted set of type arguments in this
12297     //   International Standard. type shall be a POD structure or a POD union
12298     //   (clause 9).
12299     // C++11 [support.types]p4:
12300     //   If type is not a standard-layout class (Clause 9), the results are
12301     //   undefined.
12302     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12303       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12304       unsigned DiagID =
12305         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12306                             : diag::ext_offsetof_non_pod_type;
12307 
12308       if (!IsSafe && !DidWarnAboutNonPOD &&
12309           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12310                               PDiag(DiagID)
12311                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12312                               << CurrentType))
12313         DidWarnAboutNonPOD = true;
12314     }
12315 
12316     // Look for the field.
12317     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12318     LookupQualifiedName(R, RD);
12319     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12320     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12321     if (!MemberDecl) {
12322       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12323         MemberDecl = IndirectMemberDecl->getAnonField();
12324     }
12325 
12326     if (!MemberDecl)
12327       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12328                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12329                                                               OC.LocEnd));
12330 
12331     // C99 7.17p3:
12332     //   (If the specified member is a bit-field, the behavior is undefined.)
12333     //
12334     // We diagnose this as an error.
12335     if (MemberDecl->isBitField()) {
12336       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12337         << MemberDecl->getDeclName()
12338         << SourceRange(BuiltinLoc, RParenLoc);
12339       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12340       return ExprError();
12341     }
12342 
12343     RecordDecl *Parent = MemberDecl->getParent();
12344     if (IndirectMemberDecl)
12345       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12346 
12347     // If the member was found in a base class, introduce OffsetOfNodes for
12348     // the base class indirections.
12349     CXXBasePaths Paths;
12350     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12351                       Paths)) {
12352       if (Paths.getDetectedVirtual()) {
12353         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12354           << MemberDecl->getDeclName()
12355           << SourceRange(BuiltinLoc, RParenLoc);
12356         return ExprError();
12357       }
12358 
12359       CXXBasePath &Path = Paths.front();
12360       for (const CXXBasePathElement &B : Path)
12361         Comps.push_back(OffsetOfNode(B.Base));
12362     }
12363 
12364     if (IndirectMemberDecl) {
12365       for (auto *FI : IndirectMemberDecl->chain()) {
12366         assert(isa<FieldDecl>(FI));
12367         Comps.push_back(OffsetOfNode(OC.LocStart,
12368                                      cast<FieldDecl>(FI), OC.LocEnd));
12369       }
12370     } else
12371       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12372 
12373     CurrentType = MemberDecl->getType().getNonReferenceType();
12374   }
12375 
12376   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12377                               Comps, Exprs, RParenLoc);
12378 }
12379 
12380 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12381                                       SourceLocation BuiltinLoc,
12382                                       SourceLocation TypeLoc,
12383                                       ParsedType ParsedArgTy,
12384                                       ArrayRef<OffsetOfComponent> Components,
12385                                       SourceLocation RParenLoc) {
12386 
12387   TypeSourceInfo *ArgTInfo;
12388   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12389   if (ArgTy.isNull())
12390     return ExprError();
12391 
12392   if (!ArgTInfo)
12393     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12394 
12395   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12396 }
12397 
12398 
12399 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12400                                  Expr *CondExpr,
12401                                  Expr *LHSExpr, Expr *RHSExpr,
12402                                  SourceLocation RPLoc) {
12403   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12404 
12405   ExprValueKind VK = VK_RValue;
12406   ExprObjectKind OK = OK_Ordinary;
12407   QualType resType;
12408   bool ValueDependent = false;
12409   bool CondIsTrue = false;
12410   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12411     resType = Context.DependentTy;
12412     ValueDependent = true;
12413   } else {
12414     // The conditional expression is required to be a constant expression.
12415     llvm::APSInt condEval(32);
12416     ExprResult CondICE
12417       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12418           diag::err_typecheck_choose_expr_requires_constant, false);
12419     if (CondICE.isInvalid())
12420       return ExprError();
12421     CondExpr = CondICE.get();
12422     CondIsTrue = condEval.getZExtValue();
12423 
12424     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12425     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12426 
12427     resType = ActiveExpr->getType();
12428     ValueDependent = ActiveExpr->isValueDependent();
12429     VK = ActiveExpr->getValueKind();
12430     OK = ActiveExpr->getObjectKind();
12431   }
12432 
12433   return new (Context)
12434       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12435                  CondIsTrue, resType->isDependentType(), ValueDependent);
12436 }
12437 
12438 //===----------------------------------------------------------------------===//
12439 // Clang Extensions.
12440 //===----------------------------------------------------------------------===//
12441 
12442 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12443 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12444   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12445 
12446   if (LangOpts.CPlusPlus) {
12447     Decl *ManglingContextDecl;
12448     if (MangleNumberingContext *MCtx =
12449             getCurrentMangleNumberContext(Block->getDeclContext(),
12450                                           ManglingContextDecl)) {
12451       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12452       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12453     }
12454   }
12455 
12456   PushBlockScope(CurScope, Block);
12457   CurContext->addDecl(Block);
12458   if (CurScope)
12459     PushDeclContext(CurScope, Block);
12460   else
12461     CurContext = Block;
12462 
12463   getCurBlock()->HasImplicitReturnType = true;
12464 
12465   // Enter a new evaluation context to insulate the block from any
12466   // cleanups from the enclosing full-expression.
12467   PushExpressionEvaluationContext(
12468       ExpressionEvaluationContext::PotentiallyEvaluated);
12469 }
12470 
12471 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12472                                Scope *CurScope) {
12473   assert(ParamInfo.getIdentifier() == nullptr &&
12474          "block-id should have no identifier!");
12475   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12476   BlockScopeInfo *CurBlock = getCurBlock();
12477 
12478   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12479   QualType T = Sig->getType();
12480 
12481   // FIXME: We should allow unexpanded parameter packs here, but that would,
12482   // in turn, make the block expression contain unexpanded parameter packs.
12483   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12484     // Drop the parameters.
12485     FunctionProtoType::ExtProtoInfo EPI;
12486     EPI.HasTrailingReturn = false;
12487     EPI.TypeQuals |= DeclSpec::TQ_const;
12488     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12489     Sig = Context.getTrivialTypeSourceInfo(T);
12490   }
12491 
12492   // GetTypeForDeclarator always produces a function type for a block
12493   // literal signature.  Furthermore, it is always a FunctionProtoType
12494   // unless the function was written with a typedef.
12495   assert(T->isFunctionType() &&
12496          "GetTypeForDeclarator made a non-function block signature");
12497 
12498   // Look for an explicit signature in that function type.
12499   FunctionProtoTypeLoc ExplicitSignature;
12500 
12501   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12502   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12503 
12504     // Check whether that explicit signature was synthesized by
12505     // GetTypeForDeclarator.  If so, don't save that as part of the
12506     // written signature.
12507     if (ExplicitSignature.getLocalRangeBegin() ==
12508         ExplicitSignature.getLocalRangeEnd()) {
12509       // This would be much cheaper if we stored TypeLocs instead of
12510       // TypeSourceInfos.
12511       TypeLoc Result = ExplicitSignature.getReturnLoc();
12512       unsigned Size = Result.getFullDataSize();
12513       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12514       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12515 
12516       ExplicitSignature = FunctionProtoTypeLoc();
12517     }
12518   }
12519 
12520   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12521   CurBlock->FunctionType = T;
12522 
12523   const FunctionType *Fn = T->getAs<FunctionType>();
12524   QualType RetTy = Fn->getReturnType();
12525   bool isVariadic =
12526     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12527 
12528   CurBlock->TheDecl->setIsVariadic(isVariadic);
12529 
12530   // Context.DependentTy is used as a placeholder for a missing block
12531   // return type.  TODO:  what should we do with declarators like:
12532   //   ^ * { ... }
12533   // If the answer is "apply template argument deduction"....
12534   if (RetTy != Context.DependentTy) {
12535     CurBlock->ReturnType = RetTy;
12536     CurBlock->TheDecl->setBlockMissingReturnType(false);
12537     CurBlock->HasImplicitReturnType = false;
12538   }
12539 
12540   // Push block parameters from the declarator if we had them.
12541   SmallVector<ParmVarDecl*, 8> Params;
12542   if (ExplicitSignature) {
12543     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12544       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12545       if (Param->getIdentifier() == nullptr &&
12546           !Param->isImplicit() &&
12547           !Param->isInvalidDecl() &&
12548           !getLangOpts().CPlusPlus)
12549         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12550       Params.push_back(Param);
12551     }
12552 
12553   // Fake up parameter variables if we have a typedef, like
12554   //   ^ fntype { ... }
12555   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12556     for (const auto &I : Fn->param_types()) {
12557       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12558           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12559       Params.push_back(Param);
12560     }
12561   }
12562 
12563   // Set the parameters on the block decl.
12564   if (!Params.empty()) {
12565     CurBlock->TheDecl->setParams(Params);
12566     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12567                              /*CheckParameterNames=*/false);
12568   }
12569 
12570   // Finally we can process decl attributes.
12571   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12572 
12573   // Put the parameter variables in scope.
12574   for (auto AI : CurBlock->TheDecl->parameters()) {
12575     AI->setOwningFunction(CurBlock->TheDecl);
12576 
12577     // If this has an identifier, add it to the scope stack.
12578     if (AI->getIdentifier()) {
12579       CheckShadow(CurBlock->TheScope, AI);
12580 
12581       PushOnScopeChains(AI, CurBlock->TheScope);
12582     }
12583   }
12584 }
12585 
12586 /// ActOnBlockError - If there is an error parsing a block, this callback
12587 /// is invoked to pop the information about the block from the action impl.
12588 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12589   // Leave the expression-evaluation context.
12590   DiscardCleanupsInEvaluationContext();
12591   PopExpressionEvaluationContext();
12592 
12593   // Pop off CurBlock, handle nested blocks.
12594   PopDeclContext();
12595   PopFunctionScopeInfo();
12596 }
12597 
12598 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12599 /// literal was successfully completed.  ^(int x){...}
12600 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12601                                     Stmt *Body, Scope *CurScope) {
12602   // If blocks are disabled, emit an error.
12603   if (!LangOpts.Blocks)
12604     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12605 
12606   // Leave the expression-evaluation context.
12607   if (hasAnyUnrecoverableErrorsInThisFunction())
12608     DiscardCleanupsInEvaluationContext();
12609   assert(!Cleanup.exprNeedsCleanups() &&
12610          "cleanups within block not correctly bound!");
12611   PopExpressionEvaluationContext();
12612 
12613   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12614 
12615   if (BSI->HasImplicitReturnType)
12616     deduceClosureReturnType(*BSI);
12617 
12618   PopDeclContext();
12619 
12620   QualType RetTy = Context.VoidTy;
12621   if (!BSI->ReturnType.isNull())
12622     RetTy = BSI->ReturnType;
12623 
12624   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12625   QualType BlockTy;
12626 
12627   // Set the captured variables on the block.
12628   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12629   SmallVector<BlockDecl::Capture, 4> Captures;
12630   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12631     if (Cap.isThisCapture())
12632       continue;
12633     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12634                               Cap.isNested(), Cap.getInitExpr());
12635     Captures.push_back(NewCap);
12636   }
12637   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12638 
12639   // If the user wrote a function type in some form, try to use that.
12640   if (!BSI->FunctionType.isNull()) {
12641     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12642 
12643     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12644     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12645 
12646     // Turn protoless block types into nullary block types.
12647     if (isa<FunctionNoProtoType>(FTy)) {
12648       FunctionProtoType::ExtProtoInfo EPI;
12649       EPI.ExtInfo = Ext;
12650       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12651 
12652     // Otherwise, if we don't need to change anything about the function type,
12653     // preserve its sugar structure.
12654     } else if (FTy->getReturnType() == RetTy &&
12655                (!NoReturn || FTy->getNoReturnAttr())) {
12656       BlockTy = BSI->FunctionType;
12657 
12658     // Otherwise, make the minimal modifications to the function type.
12659     } else {
12660       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12661       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12662       EPI.TypeQuals = 0; // FIXME: silently?
12663       EPI.ExtInfo = Ext;
12664       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12665     }
12666 
12667   // If we don't have a function type, just build one from nothing.
12668   } else {
12669     FunctionProtoType::ExtProtoInfo EPI;
12670     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12671     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12672   }
12673 
12674   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12675   BlockTy = Context.getBlockPointerType(BlockTy);
12676 
12677   // If needed, diagnose invalid gotos and switches in the block.
12678   if (getCurFunction()->NeedsScopeChecking() &&
12679       !PP.isCodeCompletionEnabled())
12680     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12681 
12682   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12683 
12684   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12685     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
12686 
12687   // Try to apply the named return value optimization. We have to check again
12688   // if we can do this, though, because blocks keep return statements around
12689   // to deduce an implicit return type.
12690   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12691       !BSI->TheDecl->isDependentContext())
12692     computeNRVO(Body, BSI);
12693 
12694   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12695   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12696   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12697 
12698   // If the block isn't obviously global, i.e. it captures anything at
12699   // all, then we need to do a few things in the surrounding context:
12700   if (Result->getBlockDecl()->hasCaptures()) {
12701     // First, this expression has a new cleanup object.
12702     ExprCleanupObjects.push_back(Result->getBlockDecl());
12703     Cleanup.setExprNeedsCleanups(true);
12704 
12705     // It also gets a branch-protected scope if any of the captured
12706     // variables needs destruction.
12707     for (const auto &CI : Result->getBlockDecl()->captures()) {
12708       const VarDecl *var = CI.getVariable();
12709       if (var->getType().isDestructedType() != QualType::DK_none) {
12710         getCurFunction()->setHasBranchProtectedScope();
12711         break;
12712       }
12713     }
12714   }
12715 
12716   return Result;
12717 }
12718 
12719 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12720                             SourceLocation RPLoc) {
12721   TypeSourceInfo *TInfo;
12722   GetTypeFromParser(Ty, &TInfo);
12723   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12724 }
12725 
12726 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12727                                 Expr *E, TypeSourceInfo *TInfo,
12728                                 SourceLocation RPLoc) {
12729   Expr *OrigExpr = E;
12730   bool IsMS = false;
12731 
12732   // CUDA device code does not support varargs.
12733   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12734     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12735       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12736       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12737         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12738     }
12739   }
12740 
12741   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12742   // as Microsoft ABI on an actual Microsoft platform, where
12743   // __builtin_ms_va_list and __builtin_va_list are the same.)
12744   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12745       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12746     QualType MSVaListType = Context.getBuiltinMSVaListType();
12747     if (Context.hasSameType(MSVaListType, E->getType())) {
12748       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12749         return ExprError();
12750       IsMS = true;
12751     }
12752   }
12753 
12754   // Get the va_list type
12755   QualType VaListType = Context.getBuiltinVaListType();
12756   if (!IsMS) {
12757     if (VaListType->isArrayType()) {
12758       // Deal with implicit array decay; for example, on x86-64,
12759       // va_list is an array, but it's supposed to decay to
12760       // a pointer for va_arg.
12761       VaListType = Context.getArrayDecayedType(VaListType);
12762       // Make sure the input expression also decays appropriately.
12763       ExprResult Result = UsualUnaryConversions(E);
12764       if (Result.isInvalid())
12765         return ExprError();
12766       E = Result.get();
12767     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12768       // If va_list is a record type and we are compiling in C++ mode,
12769       // check the argument using reference binding.
12770       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12771           Context, Context.getLValueReferenceType(VaListType), false);
12772       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12773       if (Init.isInvalid())
12774         return ExprError();
12775       E = Init.getAs<Expr>();
12776     } else {
12777       // Otherwise, the va_list argument must be an l-value because
12778       // it is modified by va_arg.
12779       if (!E->isTypeDependent() &&
12780           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12781         return ExprError();
12782     }
12783   }
12784 
12785   if (!IsMS && !E->isTypeDependent() &&
12786       !Context.hasSameType(VaListType, E->getType()))
12787     return ExprError(Diag(E->getLocStart(),
12788                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12789       << OrigExpr->getType() << E->getSourceRange());
12790 
12791   if (!TInfo->getType()->isDependentType()) {
12792     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12793                             diag::err_second_parameter_to_va_arg_incomplete,
12794                             TInfo->getTypeLoc()))
12795       return ExprError();
12796 
12797     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12798                                TInfo->getType(),
12799                                diag::err_second_parameter_to_va_arg_abstract,
12800                                TInfo->getTypeLoc()))
12801       return ExprError();
12802 
12803     if (!TInfo->getType().isPODType(Context)) {
12804       Diag(TInfo->getTypeLoc().getBeginLoc(),
12805            TInfo->getType()->isObjCLifetimeType()
12806              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12807              : diag::warn_second_parameter_to_va_arg_not_pod)
12808         << TInfo->getType()
12809         << TInfo->getTypeLoc().getSourceRange();
12810     }
12811 
12812     // Check for va_arg where arguments of the given type will be promoted
12813     // (i.e. this va_arg is guaranteed to have undefined behavior).
12814     QualType PromoteType;
12815     if (TInfo->getType()->isPromotableIntegerType()) {
12816       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12817       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12818         PromoteType = QualType();
12819     }
12820     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12821       PromoteType = Context.DoubleTy;
12822     if (!PromoteType.isNull())
12823       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12824                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12825                           << TInfo->getType()
12826                           << PromoteType
12827                           << TInfo->getTypeLoc().getSourceRange());
12828   }
12829 
12830   QualType T = TInfo->getType().getNonLValueExprType(Context);
12831   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12832 }
12833 
12834 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12835   // The type of __null will be int or long, depending on the size of
12836   // pointers on the target.
12837   QualType Ty;
12838   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12839   if (pw == Context.getTargetInfo().getIntWidth())
12840     Ty = Context.IntTy;
12841   else if (pw == Context.getTargetInfo().getLongWidth())
12842     Ty = Context.LongTy;
12843   else if (pw == Context.getTargetInfo().getLongLongWidth())
12844     Ty = Context.LongLongTy;
12845   else {
12846     llvm_unreachable("I don't know size of pointer!");
12847   }
12848 
12849   return new (Context) GNUNullExpr(Ty, TokenLoc);
12850 }
12851 
12852 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12853                                               bool Diagnose) {
12854   if (!getLangOpts().ObjC1)
12855     return false;
12856 
12857   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12858   if (!PT)
12859     return false;
12860 
12861   if (!PT->isObjCIdType()) {
12862     // Check if the destination is the 'NSString' interface.
12863     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12864     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12865       return false;
12866   }
12867 
12868   // Ignore any parens, implicit casts (should only be
12869   // array-to-pointer decays), and not-so-opaque values.  The last is
12870   // important for making this trigger for property assignments.
12871   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12872   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12873     if (OV->getSourceExpr())
12874       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12875 
12876   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12877   if (!SL || !SL->isAscii())
12878     return false;
12879   if (Diagnose) {
12880     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12881       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12882     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12883   }
12884   return true;
12885 }
12886 
12887 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12888                                               const Expr *SrcExpr) {
12889   if (!DstType->isFunctionPointerType() ||
12890       !SrcExpr->getType()->isFunctionType())
12891     return false;
12892 
12893   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12894   if (!DRE)
12895     return false;
12896 
12897   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12898   if (!FD)
12899     return false;
12900 
12901   return !S.checkAddressOfFunctionIsAvailable(FD,
12902                                               /*Complain=*/true,
12903                                               SrcExpr->getLocStart());
12904 }
12905 
12906 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12907                                     SourceLocation Loc,
12908                                     QualType DstType, QualType SrcType,
12909                                     Expr *SrcExpr, AssignmentAction Action,
12910                                     bool *Complained) {
12911   if (Complained)
12912     *Complained = false;
12913 
12914   // Decode the result (notice that AST's are still created for extensions).
12915   bool CheckInferredResultType = false;
12916   bool isInvalid = false;
12917   unsigned DiagKind = 0;
12918   FixItHint Hint;
12919   ConversionFixItGenerator ConvHints;
12920   bool MayHaveConvFixit = false;
12921   bool MayHaveFunctionDiff = false;
12922   const ObjCInterfaceDecl *IFace = nullptr;
12923   const ObjCProtocolDecl *PDecl = nullptr;
12924 
12925   switch (ConvTy) {
12926   case Compatible:
12927       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12928       return false;
12929 
12930   case PointerToInt:
12931     DiagKind = diag::ext_typecheck_convert_pointer_int;
12932     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12933     MayHaveConvFixit = true;
12934     break;
12935   case IntToPointer:
12936     DiagKind = diag::ext_typecheck_convert_int_pointer;
12937     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12938     MayHaveConvFixit = true;
12939     break;
12940   case IncompatiblePointer:
12941     if (Action == AA_Passing_CFAudited)
12942       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12943     else if (SrcType->isFunctionPointerType() &&
12944              DstType->isFunctionPointerType())
12945       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12946     else
12947       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12948 
12949     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12950       SrcType->isObjCObjectPointerType();
12951     if (Hint.isNull() && !CheckInferredResultType) {
12952       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12953     }
12954     else if (CheckInferredResultType) {
12955       SrcType = SrcType.getUnqualifiedType();
12956       DstType = DstType.getUnqualifiedType();
12957     }
12958     MayHaveConvFixit = true;
12959     break;
12960   case IncompatiblePointerSign:
12961     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12962     break;
12963   case FunctionVoidPointer:
12964     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12965     break;
12966   case IncompatiblePointerDiscardsQualifiers: {
12967     // Perform array-to-pointer decay if necessary.
12968     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12969 
12970     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12971     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12972     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12973       DiagKind = diag::err_typecheck_incompatible_address_space;
12974       break;
12975 
12976 
12977     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12978       DiagKind = diag::err_typecheck_incompatible_ownership;
12979       break;
12980     }
12981 
12982     llvm_unreachable("unknown error case for discarding qualifiers!");
12983     // fallthrough
12984   }
12985   case CompatiblePointerDiscardsQualifiers:
12986     // If the qualifiers lost were because we were applying the
12987     // (deprecated) C++ conversion from a string literal to a char*
12988     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12989     // Ideally, this check would be performed in
12990     // checkPointerTypesForAssignment. However, that would require a
12991     // bit of refactoring (so that the second argument is an
12992     // expression, rather than a type), which should be done as part
12993     // of a larger effort to fix checkPointerTypesForAssignment for
12994     // C++ semantics.
12995     if (getLangOpts().CPlusPlus &&
12996         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12997       return false;
12998     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12999     break;
13000   case IncompatibleNestedPointerQualifiers:
13001     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13002     break;
13003   case IntToBlockPointer:
13004     DiagKind = diag::err_int_to_block_pointer;
13005     break;
13006   case IncompatibleBlockPointer:
13007     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13008     break;
13009   case IncompatibleObjCQualifiedId: {
13010     if (SrcType->isObjCQualifiedIdType()) {
13011       const ObjCObjectPointerType *srcOPT =
13012                 SrcType->getAs<ObjCObjectPointerType>();
13013       for (auto *srcProto : srcOPT->quals()) {
13014         PDecl = srcProto;
13015         break;
13016       }
13017       if (const ObjCInterfaceType *IFaceT =
13018             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13019         IFace = IFaceT->getDecl();
13020     }
13021     else if (DstType->isObjCQualifiedIdType()) {
13022       const ObjCObjectPointerType *dstOPT =
13023         DstType->getAs<ObjCObjectPointerType>();
13024       for (auto *dstProto : dstOPT->quals()) {
13025         PDecl = dstProto;
13026         break;
13027       }
13028       if (const ObjCInterfaceType *IFaceT =
13029             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13030         IFace = IFaceT->getDecl();
13031     }
13032     DiagKind = diag::warn_incompatible_qualified_id;
13033     break;
13034   }
13035   case IncompatibleVectors:
13036     DiagKind = diag::warn_incompatible_vectors;
13037     break;
13038   case IncompatibleObjCWeakRef:
13039     DiagKind = diag::err_arc_weak_unavailable_assign;
13040     break;
13041   case Incompatible:
13042     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13043       if (Complained)
13044         *Complained = true;
13045       return true;
13046     }
13047 
13048     DiagKind = diag::err_typecheck_convert_incompatible;
13049     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13050     MayHaveConvFixit = true;
13051     isInvalid = true;
13052     MayHaveFunctionDiff = true;
13053     break;
13054   }
13055 
13056   QualType FirstType, SecondType;
13057   switch (Action) {
13058   case AA_Assigning:
13059   case AA_Initializing:
13060     // The destination type comes first.
13061     FirstType = DstType;
13062     SecondType = SrcType;
13063     break;
13064 
13065   case AA_Returning:
13066   case AA_Passing:
13067   case AA_Passing_CFAudited:
13068   case AA_Converting:
13069   case AA_Sending:
13070   case AA_Casting:
13071     // The source type comes first.
13072     FirstType = SrcType;
13073     SecondType = DstType;
13074     break;
13075   }
13076 
13077   PartialDiagnostic FDiag = PDiag(DiagKind);
13078   if (Action == AA_Passing_CFAudited)
13079     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13080   else
13081     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13082 
13083   // If we can fix the conversion, suggest the FixIts.
13084   assert(ConvHints.isNull() || Hint.isNull());
13085   if (!ConvHints.isNull()) {
13086     for (FixItHint &H : ConvHints.Hints)
13087       FDiag << H;
13088   } else {
13089     FDiag << Hint;
13090   }
13091   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13092 
13093   if (MayHaveFunctionDiff)
13094     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13095 
13096   Diag(Loc, FDiag);
13097   if (DiagKind == diag::warn_incompatible_qualified_id &&
13098       PDecl && IFace && !IFace->hasDefinition())
13099       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13100         << IFace->getName() << PDecl->getName();
13101 
13102   if (SecondType == Context.OverloadTy)
13103     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13104                               FirstType, /*TakingAddress=*/true);
13105 
13106   if (CheckInferredResultType)
13107     EmitRelatedResultTypeNote(SrcExpr);
13108 
13109   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13110     EmitRelatedResultTypeNoteForReturn(DstType);
13111 
13112   if (Complained)
13113     *Complained = true;
13114   return isInvalid;
13115 }
13116 
13117 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13118                                                  llvm::APSInt *Result) {
13119   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13120   public:
13121     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13122       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13123     }
13124   } Diagnoser;
13125 
13126   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13127 }
13128 
13129 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13130                                                  llvm::APSInt *Result,
13131                                                  unsigned DiagID,
13132                                                  bool AllowFold) {
13133   class IDDiagnoser : public VerifyICEDiagnoser {
13134     unsigned DiagID;
13135 
13136   public:
13137     IDDiagnoser(unsigned DiagID)
13138       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13139 
13140     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13141       S.Diag(Loc, DiagID) << SR;
13142     }
13143   } Diagnoser(DiagID);
13144 
13145   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13146 }
13147 
13148 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13149                                             SourceRange SR) {
13150   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13151 }
13152 
13153 ExprResult
13154 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13155                                       VerifyICEDiagnoser &Diagnoser,
13156                                       bool AllowFold) {
13157   SourceLocation DiagLoc = E->getLocStart();
13158 
13159   if (getLangOpts().CPlusPlus11) {
13160     // C++11 [expr.const]p5:
13161     //   If an expression of literal class type is used in a context where an
13162     //   integral constant expression is required, then that class type shall
13163     //   have a single non-explicit conversion function to an integral or
13164     //   unscoped enumeration type
13165     ExprResult Converted;
13166     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13167     public:
13168       CXX11ConvertDiagnoser(bool Silent)
13169           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13170                                 Silent, true) {}
13171 
13172       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13173                                            QualType T) override {
13174         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13175       }
13176 
13177       SemaDiagnosticBuilder diagnoseIncomplete(
13178           Sema &S, SourceLocation Loc, QualType T) override {
13179         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13180       }
13181 
13182       SemaDiagnosticBuilder diagnoseExplicitConv(
13183           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13184         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13185       }
13186 
13187       SemaDiagnosticBuilder noteExplicitConv(
13188           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13189         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13190                  << ConvTy->isEnumeralType() << ConvTy;
13191       }
13192 
13193       SemaDiagnosticBuilder diagnoseAmbiguous(
13194           Sema &S, SourceLocation Loc, QualType T) override {
13195         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13196       }
13197 
13198       SemaDiagnosticBuilder noteAmbiguous(
13199           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13200         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13201                  << ConvTy->isEnumeralType() << ConvTy;
13202       }
13203 
13204       SemaDiagnosticBuilder diagnoseConversion(
13205           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13206         llvm_unreachable("conversion functions are permitted");
13207       }
13208     } ConvertDiagnoser(Diagnoser.Suppress);
13209 
13210     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13211                                                     ConvertDiagnoser);
13212     if (Converted.isInvalid())
13213       return Converted;
13214     E = Converted.get();
13215     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13216       return ExprError();
13217   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13218     // An ICE must be of integral or unscoped enumeration type.
13219     if (!Diagnoser.Suppress)
13220       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13221     return ExprError();
13222   }
13223 
13224   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13225   // in the non-ICE case.
13226   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13227     if (Result)
13228       *Result = E->EvaluateKnownConstInt(Context);
13229     return E;
13230   }
13231 
13232   Expr::EvalResult EvalResult;
13233   SmallVector<PartialDiagnosticAt, 8> Notes;
13234   EvalResult.Diag = &Notes;
13235 
13236   // Try to evaluate the expression, and produce diagnostics explaining why it's
13237   // not a constant expression as a side-effect.
13238   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13239                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13240 
13241   // In C++11, we can rely on diagnostics being produced for any expression
13242   // which is not a constant expression. If no diagnostics were produced, then
13243   // this is a constant expression.
13244   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13245     if (Result)
13246       *Result = EvalResult.Val.getInt();
13247     return E;
13248   }
13249 
13250   // If our only note is the usual "invalid subexpression" note, just point
13251   // the caret at its location rather than producing an essentially
13252   // redundant note.
13253   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13254         diag::note_invalid_subexpr_in_const_expr) {
13255     DiagLoc = Notes[0].first;
13256     Notes.clear();
13257   }
13258 
13259   if (!Folded || !AllowFold) {
13260     if (!Diagnoser.Suppress) {
13261       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13262       for (const PartialDiagnosticAt &Note : Notes)
13263         Diag(Note.first, Note.second);
13264     }
13265 
13266     return ExprError();
13267   }
13268 
13269   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13270   for (const PartialDiagnosticAt &Note : Notes)
13271     Diag(Note.first, Note.second);
13272 
13273   if (Result)
13274     *Result = EvalResult.Val.getInt();
13275   return E;
13276 }
13277 
13278 namespace {
13279   // Handle the case where we conclude a expression which we speculatively
13280   // considered to be unevaluated is actually evaluated.
13281   class TransformToPE : public TreeTransform<TransformToPE> {
13282     typedef TreeTransform<TransformToPE> BaseTransform;
13283 
13284   public:
13285     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13286 
13287     // Make sure we redo semantic analysis
13288     bool AlwaysRebuild() { return true; }
13289 
13290     // Make sure we handle LabelStmts correctly.
13291     // FIXME: This does the right thing, but maybe we need a more general
13292     // fix to TreeTransform?
13293     StmtResult TransformLabelStmt(LabelStmt *S) {
13294       S->getDecl()->setStmt(nullptr);
13295       return BaseTransform::TransformLabelStmt(S);
13296     }
13297 
13298     // We need to special-case DeclRefExprs referring to FieldDecls which
13299     // are not part of a member pointer formation; normal TreeTransforming
13300     // doesn't catch this case because of the way we represent them in the AST.
13301     // FIXME: This is a bit ugly; is it really the best way to handle this
13302     // case?
13303     //
13304     // Error on DeclRefExprs referring to FieldDecls.
13305     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13306       if (isa<FieldDecl>(E->getDecl()) &&
13307           !SemaRef.isUnevaluatedContext())
13308         return SemaRef.Diag(E->getLocation(),
13309                             diag::err_invalid_non_static_member_use)
13310             << E->getDecl() << E->getSourceRange();
13311 
13312       return BaseTransform::TransformDeclRefExpr(E);
13313     }
13314 
13315     // Exception: filter out member pointer formation
13316     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13317       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13318         return E;
13319 
13320       return BaseTransform::TransformUnaryOperator(E);
13321     }
13322 
13323     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13324       // Lambdas never need to be transformed.
13325       return E;
13326     }
13327   };
13328 }
13329 
13330 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13331   assert(isUnevaluatedContext() &&
13332          "Should only transform unevaluated expressions");
13333   ExprEvalContexts.back().Context =
13334       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13335   if (isUnevaluatedContext())
13336     return E;
13337   return TransformToPE(*this).TransformExpr(E);
13338 }
13339 
13340 void
13341 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13342                                       Decl *LambdaContextDecl,
13343                                       bool IsDecltype) {
13344   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13345                                 LambdaContextDecl, IsDecltype);
13346   Cleanup.reset();
13347   if (!MaybeODRUseExprs.empty())
13348     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13349 }
13350 
13351 void
13352 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13353                                       ReuseLambdaContextDecl_t,
13354                                       bool IsDecltype) {
13355   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13356   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13357 }
13358 
13359 void Sema::PopExpressionEvaluationContext() {
13360   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13361   unsigned NumTypos = Rec.NumTypos;
13362 
13363   if (!Rec.Lambdas.empty()) {
13364     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13365       unsigned D;
13366       if (Rec.isUnevaluated()) {
13367         // C++11 [expr.prim.lambda]p2:
13368         //   A lambda-expression shall not appear in an unevaluated operand
13369         //   (Clause 5).
13370         D = diag::err_lambda_unevaluated_operand;
13371       } else {
13372         // C++1y [expr.const]p2:
13373         //   A conditional-expression e is a core constant expression unless the
13374         //   evaluation of e, following the rules of the abstract machine, would
13375         //   evaluate [...] a lambda-expression.
13376         D = diag::err_lambda_in_constant_expression;
13377       }
13378 
13379       // C++1z allows lambda expressions as core constant expressions.
13380       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13381       // 1607) from appearing within template-arguments and array-bounds that
13382       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13383       // unevaluated contexts) might lift some of these restrictions in a
13384       // future version.
13385       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z)
13386         for (const auto *L : Rec.Lambdas)
13387           Diag(L->getLocStart(), D);
13388     } else {
13389       // Mark the capture expressions odr-used. This was deferred
13390       // during lambda expression creation.
13391       for (auto *Lambda : Rec.Lambdas) {
13392         for (auto *C : Lambda->capture_inits())
13393           MarkDeclarationsReferencedInExpr(C);
13394       }
13395     }
13396   }
13397 
13398   // When are coming out of an unevaluated context, clear out any
13399   // temporaries that we may have created as part of the evaluation of
13400   // the expression in that context: they aren't relevant because they
13401   // will never be constructed.
13402   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13403     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13404                              ExprCleanupObjects.end());
13405     Cleanup = Rec.ParentCleanup;
13406     CleanupVarDeclMarking();
13407     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13408   // Otherwise, merge the contexts together.
13409   } else {
13410     Cleanup.mergeFrom(Rec.ParentCleanup);
13411     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13412                             Rec.SavedMaybeODRUseExprs.end());
13413   }
13414 
13415   // Pop the current expression evaluation context off the stack.
13416   ExprEvalContexts.pop_back();
13417 
13418   if (!ExprEvalContexts.empty())
13419     ExprEvalContexts.back().NumTypos += NumTypos;
13420   else
13421     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13422                             "last ExpressionEvaluationContextRecord");
13423 }
13424 
13425 void Sema::DiscardCleanupsInEvaluationContext() {
13426   ExprCleanupObjects.erase(
13427          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13428          ExprCleanupObjects.end());
13429   Cleanup.reset();
13430   MaybeODRUseExprs.clear();
13431 }
13432 
13433 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13434   if (!E->getType()->isVariablyModifiedType())
13435     return E;
13436   return TransformToPotentiallyEvaluated(E);
13437 }
13438 
13439 /// Are we within a context in which some evaluation could be performed (be it
13440 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13441 /// captured by C++'s idea of an "unevaluated context".
13442 static bool isEvaluatableContext(Sema &SemaRef) {
13443   switch (SemaRef.ExprEvalContexts.back().Context) {
13444     case Sema::ExpressionEvaluationContext::Unevaluated:
13445     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13446     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13447       // Expressions in this context are never evaluated.
13448       return false;
13449 
13450     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13451     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13452     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13453       // Expressions in this context could be evaluated.
13454       return true;
13455 
13456     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13457       // Referenced declarations will only be used if the construct in the
13458       // containing expression is used, at which point we'll be given another
13459       // turn to mark them.
13460       return false;
13461   }
13462   llvm_unreachable("Invalid context");
13463 }
13464 
13465 /// Are we within a context in which references to resolved functions or to
13466 /// variables result in odr-use?
13467 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13468   // An expression in a template is not really an expression until it's been
13469   // instantiated, so it doesn't trigger odr-use.
13470   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13471     return false;
13472 
13473   switch (SemaRef.ExprEvalContexts.back().Context) {
13474     case Sema::ExpressionEvaluationContext::Unevaluated:
13475     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13476     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13477     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13478       return false;
13479 
13480     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13481     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13482       return true;
13483 
13484     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13485       return false;
13486   }
13487   llvm_unreachable("Invalid context");
13488 }
13489 
13490 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13491   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13492   return Func->isConstexpr() &&
13493          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13494 }
13495 
13496 /// \brief Mark a function referenced, and check whether it is odr-used
13497 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13498 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13499                                   bool MightBeOdrUse) {
13500   assert(Func && "No function?");
13501 
13502   Func->setReferenced();
13503 
13504   // C++11 [basic.def.odr]p3:
13505   //   A function whose name appears as a potentially-evaluated expression is
13506   //   odr-used if it is the unique lookup result or the selected member of a
13507   //   set of overloaded functions [...].
13508   //
13509   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13510   // can just check that here.
13511   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13512 
13513   // Determine whether we require a function definition to exist, per
13514   // C++11 [temp.inst]p3:
13515   //   Unless a function template specialization has been explicitly
13516   //   instantiated or explicitly specialized, the function template
13517   //   specialization is implicitly instantiated when the specialization is
13518   //   referenced in a context that requires a function definition to exist.
13519   //
13520   // That is either when this is an odr-use, or when a usage of a constexpr
13521   // function occurs within an evaluatable context.
13522   bool NeedDefinition =
13523       OdrUse || (isEvaluatableContext(*this) &&
13524                  isImplicitlyDefinableConstexprFunction(Func));
13525 
13526   // C++14 [temp.expl.spec]p6:
13527   //   If a template [...] is explicitly specialized then that specialization
13528   //   shall be declared before the first use of that specialization that would
13529   //   cause an implicit instantiation to take place, in every translation unit
13530   //   in which such a use occurs
13531   if (NeedDefinition &&
13532       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13533        Func->getMemberSpecializationInfo()))
13534     checkSpecializationVisibility(Loc, Func);
13535 
13536   // C++14 [except.spec]p17:
13537   //   An exception-specification is considered to be needed when:
13538   //   - the function is odr-used or, if it appears in an unevaluated operand,
13539   //     would be odr-used if the expression were potentially-evaluated;
13540   //
13541   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13542   // function is a pure virtual function we're calling, and in that case the
13543   // function was selected by overload resolution and we need to resolve its
13544   // exception specification for a different reason.
13545   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13546   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13547     ResolveExceptionSpec(Loc, FPT);
13548 
13549   // If we don't need to mark the function as used, and we don't need to
13550   // try to provide a definition, there's nothing more to do.
13551   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13552       (!NeedDefinition || Func->getBody()))
13553     return;
13554 
13555   // Note that this declaration has been used.
13556   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13557     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13558     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13559       if (Constructor->isDefaultConstructor()) {
13560         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13561           return;
13562         DefineImplicitDefaultConstructor(Loc, Constructor);
13563       } else if (Constructor->isCopyConstructor()) {
13564         DefineImplicitCopyConstructor(Loc, Constructor);
13565       } else if (Constructor->isMoveConstructor()) {
13566         DefineImplicitMoveConstructor(Loc, Constructor);
13567       }
13568     } else if (Constructor->getInheritedConstructor()) {
13569       DefineInheritingConstructor(Loc, Constructor);
13570     }
13571   } else if (CXXDestructorDecl *Destructor =
13572                  dyn_cast<CXXDestructorDecl>(Func)) {
13573     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13574     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13575       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13576         return;
13577       DefineImplicitDestructor(Loc, Destructor);
13578     }
13579     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13580       MarkVTableUsed(Loc, Destructor->getParent());
13581   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13582     if (MethodDecl->isOverloadedOperator() &&
13583         MethodDecl->getOverloadedOperator() == OO_Equal) {
13584       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13585       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13586         if (MethodDecl->isCopyAssignmentOperator())
13587           DefineImplicitCopyAssignment(Loc, MethodDecl);
13588         else if (MethodDecl->isMoveAssignmentOperator())
13589           DefineImplicitMoveAssignment(Loc, MethodDecl);
13590       }
13591     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13592                MethodDecl->getParent()->isLambda()) {
13593       CXXConversionDecl *Conversion =
13594           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13595       if (Conversion->isLambdaToBlockPointerConversion())
13596         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13597       else
13598         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13599     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13600       MarkVTableUsed(Loc, MethodDecl->getParent());
13601   }
13602 
13603   // Recursive functions should be marked when used from another function.
13604   // FIXME: Is this really right?
13605   if (CurContext == Func) return;
13606 
13607   // Implicit instantiation of function templates and member functions of
13608   // class templates.
13609   if (Func->isImplicitlyInstantiable()) {
13610     bool AlreadyInstantiated = false;
13611     SourceLocation PointOfInstantiation = Loc;
13612     if (FunctionTemplateSpecializationInfo *SpecInfo
13613                               = Func->getTemplateSpecializationInfo()) {
13614       if (SpecInfo->getPointOfInstantiation().isInvalid())
13615         SpecInfo->setPointOfInstantiation(Loc);
13616       else if (SpecInfo->getTemplateSpecializationKind()
13617                  == TSK_ImplicitInstantiation) {
13618         AlreadyInstantiated = true;
13619         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13620       }
13621     } else if (MemberSpecializationInfo *MSInfo
13622                                 = Func->getMemberSpecializationInfo()) {
13623       if (MSInfo->getPointOfInstantiation().isInvalid())
13624         MSInfo->setPointOfInstantiation(Loc);
13625       else if (MSInfo->getTemplateSpecializationKind()
13626                  == TSK_ImplicitInstantiation) {
13627         AlreadyInstantiated = true;
13628         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13629       }
13630     }
13631 
13632     if (!AlreadyInstantiated || Func->isConstexpr()) {
13633       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13634           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13635           CodeSynthesisContexts.size())
13636         PendingLocalImplicitInstantiations.push_back(
13637             std::make_pair(Func, PointOfInstantiation));
13638       else if (Func->isConstexpr())
13639         // Do not defer instantiations of constexpr functions, to avoid the
13640         // expression evaluator needing to call back into Sema if it sees a
13641         // call to such a function.
13642         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13643       else {
13644         Func->setInstantiationIsPending(true);
13645         PendingInstantiations.push_back(std::make_pair(Func,
13646                                                        PointOfInstantiation));
13647         // Notify the consumer that a function was implicitly instantiated.
13648         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13649       }
13650     }
13651   } else {
13652     // Walk redefinitions, as some of them may be instantiable.
13653     for (auto i : Func->redecls()) {
13654       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13655         MarkFunctionReferenced(Loc, i, OdrUse);
13656     }
13657   }
13658 
13659   if (!OdrUse) return;
13660 
13661   // Keep track of used but undefined functions.
13662   if (!Func->isDefined()) {
13663     if (mightHaveNonExternalLinkage(Func))
13664       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13665     else if (Func->getMostRecentDecl()->isInlined() &&
13666              !LangOpts.GNUInline &&
13667              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13668       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13669   }
13670 
13671   Func->markUsed(Context);
13672 }
13673 
13674 static void
13675 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13676                                    ValueDecl *var, DeclContext *DC) {
13677   DeclContext *VarDC = var->getDeclContext();
13678 
13679   //  If the parameter still belongs to the translation unit, then
13680   //  we're actually just using one parameter in the declaration of
13681   //  the next.
13682   if (isa<ParmVarDecl>(var) &&
13683       isa<TranslationUnitDecl>(VarDC))
13684     return;
13685 
13686   // For C code, don't diagnose about capture if we're not actually in code
13687   // right now; it's impossible to write a non-constant expression outside of
13688   // function context, so we'll get other (more useful) diagnostics later.
13689   //
13690   // For C++, things get a bit more nasty... it would be nice to suppress this
13691   // diagnostic for certain cases like using a local variable in an array bound
13692   // for a member of a local class, but the correct predicate is not obvious.
13693   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13694     return;
13695 
13696   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13697   unsigned ContextKind = 3; // unknown
13698   if (isa<CXXMethodDecl>(VarDC) &&
13699       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13700     ContextKind = 2;
13701   } else if (isa<FunctionDecl>(VarDC)) {
13702     ContextKind = 0;
13703   } else if (isa<BlockDecl>(VarDC)) {
13704     ContextKind = 1;
13705   }
13706 
13707   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13708     << var << ValueKind << ContextKind << VarDC;
13709   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13710       << var;
13711 
13712   // FIXME: Add additional diagnostic info about class etc. which prevents
13713   // capture.
13714 }
13715 
13716 
13717 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13718                                       bool &SubCapturesAreNested,
13719                                       QualType &CaptureType,
13720                                       QualType &DeclRefType) {
13721    // Check whether we've already captured it.
13722   if (CSI->CaptureMap.count(Var)) {
13723     // If we found a capture, any subcaptures are nested.
13724     SubCapturesAreNested = true;
13725 
13726     // Retrieve the capture type for this variable.
13727     CaptureType = CSI->getCapture(Var).getCaptureType();
13728 
13729     // Compute the type of an expression that refers to this variable.
13730     DeclRefType = CaptureType.getNonReferenceType();
13731 
13732     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13733     // are mutable in the sense that user can change their value - they are
13734     // private instances of the captured declarations.
13735     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13736     if (Cap.isCopyCapture() &&
13737         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13738         !(isa<CapturedRegionScopeInfo>(CSI) &&
13739           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13740       DeclRefType.addConst();
13741     return true;
13742   }
13743   return false;
13744 }
13745 
13746 // Only block literals, captured statements, and lambda expressions can
13747 // capture; other scopes don't work.
13748 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13749                                  SourceLocation Loc,
13750                                  const bool Diagnose, Sema &S) {
13751   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13752     return getLambdaAwareParentOfDeclContext(DC);
13753   else if (Var->hasLocalStorage()) {
13754     if (Diagnose)
13755        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13756   }
13757   return nullptr;
13758 }
13759 
13760 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13761 // certain types of variables (unnamed, variably modified types etc.)
13762 // so check for eligibility.
13763 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13764                                  SourceLocation Loc,
13765                                  const bool Diagnose, Sema &S) {
13766 
13767   bool IsBlock = isa<BlockScopeInfo>(CSI);
13768   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13769 
13770   // Lambdas are not allowed to capture unnamed variables
13771   // (e.g. anonymous unions).
13772   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13773   // assuming that's the intent.
13774   if (IsLambda && !Var->getDeclName()) {
13775     if (Diagnose) {
13776       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13777       S.Diag(Var->getLocation(), diag::note_declared_at);
13778     }
13779     return false;
13780   }
13781 
13782   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13783   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13784     if (Diagnose) {
13785       S.Diag(Loc, diag::err_ref_vm_type);
13786       S.Diag(Var->getLocation(), diag::note_previous_decl)
13787         << Var->getDeclName();
13788     }
13789     return false;
13790   }
13791   // Prohibit structs with flexible array members too.
13792   // We cannot capture what is in the tail end of the struct.
13793   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13794     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13795       if (Diagnose) {
13796         if (IsBlock)
13797           S.Diag(Loc, diag::err_ref_flexarray_type);
13798         else
13799           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13800             << Var->getDeclName();
13801         S.Diag(Var->getLocation(), diag::note_previous_decl)
13802           << Var->getDeclName();
13803       }
13804       return false;
13805     }
13806   }
13807   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13808   // Lambdas and captured statements are not allowed to capture __block
13809   // variables; they don't support the expected semantics.
13810   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13811     if (Diagnose) {
13812       S.Diag(Loc, diag::err_capture_block_variable)
13813         << Var->getDeclName() << !IsLambda;
13814       S.Diag(Var->getLocation(), diag::note_previous_decl)
13815         << Var->getDeclName();
13816     }
13817     return false;
13818   }
13819   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
13820   if (S.getLangOpts().OpenCL && IsBlock &&
13821       Var->getType()->isBlockPointerType()) {
13822     if (Diagnose)
13823       S.Diag(Loc, diag::err_opencl_block_ref_block);
13824     return false;
13825   }
13826 
13827   return true;
13828 }
13829 
13830 // Returns true if the capture by block was successful.
13831 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13832                                  SourceLocation Loc,
13833                                  const bool BuildAndDiagnose,
13834                                  QualType &CaptureType,
13835                                  QualType &DeclRefType,
13836                                  const bool Nested,
13837                                  Sema &S) {
13838   Expr *CopyExpr = nullptr;
13839   bool ByRef = false;
13840 
13841   // Blocks are not allowed to capture arrays.
13842   if (CaptureType->isArrayType()) {
13843     if (BuildAndDiagnose) {
13844       S.Diag(Loc, diag::err_ref_array_type);
13845       S.Diag(Var->getLocation(), diag::note_previous_decl)
13846       << Var->getDeclName();
13847     }
13848     return false;
13849   }
13850 
13851   // Forbid the block-capture of autoreleasing variables.
13852   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13853     if (BuildAndDiagnose) {
13854       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13855         << /*block*/ 0;
13856       S.Diag(Var->getLocation(), diag::note_previous_decl)
13857         << Var->getDeclName();
13858     }
13859     return false;
13860   }
13861 
13862   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13863   if (const auto *PT = CaptureType->getAs<PointerType>()) {
13864     // This function finds out whether there is an AttributedType of kind
13865     // attr_objc_ownership in Ty. The existence of AttributedType of kind
13866     // attr_objc_ownership implies __autoreleasing was explicitly specified
13867     // rather than being added implicitly by the compiler.
13868     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13869       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13870         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13871           return true;
13872 
13873         // Peel off AttributedTypes that are not of kind objc_ownership.
13874         Ty = AttrTy->getModifiedType();
13875       }
13876 
13877       return false;
13878     };
13879 
13880     QualType PointeeTy = PT->getPointeeType();
13881 
13882     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13883         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13884         !IsObjCOwnershipAttributedType(PointeeTy)) {
13885       if (BuildAndDiagnose) {
13886         SourceLocation VarLoc = Var->getLocation();
13887         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13888         {
13889           auto AddAutoreleaseNote =
13890               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
13891           // Provide a fix-it for the '__autoreleasing' keyword at the
13892           // appropriate location in the variable's type.
13893           if (const auto *TSI = Var->getTypeSourceInfo()) {
13894             PointerTypeLoc PTL =
13895                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
13896             if (PTL) {
13897               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
13898               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
13899                                                S.getLangOpts());
13900               if (Loc.isValid()) {
13901                 StringRef CharAtLoc = Lexer::getSourceText(
13902                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
13903                     S.getSourceManager(), S.getLangOpts());
13904                 AddAutoreleaseNote << FixItHint::CreateInsertion(
13905                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
13906                              ? " __autoreleasing "
13907                              : " __autoreleasing");
13908               }
13909             }
13910           }
13911         }
13912         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13913       }
13914     }
13915   }
13916 
13917   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13918   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13919       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13920     // Block capture by reference does not change the capture or
13921     // declaration reference types.
13922     ByRef = true;
13923   } else {
13924     // Block capture by copy introduces 'const'.
13925     CaptureType = CaptureType.getNonReferenceType().withConst();
13926     DeclRefType = CaptureType;
13927 
13928     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13929       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13930         // The capture logic needs the destructor, so make sure we mark it.
13931         // Usually this is unnecessary because most local variables have
13932         // their destructors marked at declaration time, but parameters are
13933         // an exception because it's technically only the call site that
13934         // actually requires the destructor.
13935         if (isa<ParmVarDecl>(Var))
13936           S.FinalizeVarWithDestructor(Var, Record);
13937 
13938         // Enter a new evaluation context to insulate the copy
13939         // full-expression.
13940         EnterExpressionEvaluationContext scope(
13941             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13942 
13943         // According to the blocks spec, the capture of a variable from
13944         // the stack requires a const copy constructor.  This is not true
13945         // of the copy/move done to move a __block variable to the heap.
13946         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13947                                                   DeclRefType.withConst(),
13948                                                   VK_LValue, Loc);
13949 
13950         ExprResult Result
13951           = S.PerformCopyInitialization(
13952               InitializedEntity::InitializeBlock(Var->getLocation(),
13953                                                   CaptureType, false),
13954               Loc, DeclRef);
13955 
13956         // Build a full-expression copy expression if initialization
13957         // succeeded and used a non-trivial constructor.  Recover from
13958         // errors by pretending that the copy isn't necessary.
13959         if (!Result.isInvalid() &&
13960             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13961                 ->isTrivial()) {
13962           Result = S.MaybeCreateExprWithCleanups(Result);
13963           CopyExpr = Result.get();
13964         }
13965       }
13966     }
13967   }
13968 
13969   // Actually capture the variable.
13970   if (BuildAndDiagnose)
13971     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13972                     SourceLocation(), CaptureType, CopyExpr);
13973 
13974   return true;
13975 
13976 }
13977 
13978 
13979 /// \brief Capture the given variable in the captured region.
13980 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13981                                     VarDecl *Var,
13982                                     SourceLocation Loc,
13983                                     const bool BuildAndDiagnose,
13984                                     QualType &CaptureType,
13985                                     QualType &DeclRefType,
13986                                     const bool RefersToCapturedVariable,
13987                                     Sema &S) {
13988   // By default, capture variables by reference.
13989   bool ByRef = true;
13990   // Using an LValue reference type is consistent with Lambdas (see below).
13991   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13992     if (S.IsOpenMPCapturedDecl(Var))
13993       DeclRefType = DeclRefType.getUnqualifiedType();
13994     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13995   }
13996 
13997   if (ByRef)
13998     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13999   else
14000     CaptureType = DeclRefType;
14001 
14002   Expr *CopyExpr = nullptr;
14003   if (BuildAndDiagnose) {
14004     // The current implementation assumes that all variables are captured
14005     // by references. Since there is no capture by copy, no expression
14006     // evaluation will be needed.
14007     RecordDecl *RD = RSI->TheRecordDecl;
14008 
14009     FieldDecl *Field
14010       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14011                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14012                           nullptr, false, ICIS_NoInit);
14013     Field->setImplicit(true);
14014     Field->setAccess(AS_private);
14015     RD->addDecl(Field);
14016 
14017     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14018                                             DeclRefType, VK_LValue, Loc);
14019     Var->setReferenced(true);
14020     Var->markUsed(S.Context);
14021   }
14022 
14023   // Actually capture the variable.
14024   if (BuildAndDiagnose)
14025     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14026                     SourceLocation(), CaptureType, CopyExpr);
14027 
14028 
14029   return true;
14030 }
14031 
14032 /// \brief Create a field within the lambda class for the variable
14033 /// being captured.
14034 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14035                                     QualType FieldType, QualType DeclRefType,
14036                                     SourceLocation Loc,
14037                                     bool RefersToCapturedVariable) {
14038   CXXRecordDecl *Lambda = LSI->Lambda;
14039 
14040   // Build the non-static data member.
14041   FieldDecl *Field
14042     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14043                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14044                         nullptr, false, ICIS_NoInit);
14045   Field->setImplicit(true);
14046   Field->setAccess(AS_private);
14047   Lambda->addDecl(Field);
14048 }
14049 
14050 /// \brief Capture the given variable in the lambda.
14051 static bool captureInLambda(LambdaScopeInfo *LSI,
14052                             VarDecl *Var,
14053                             SourceLocation Loc,
14054                             const bool BuildAndDiagnose,
14055                             QualType &CaptureType,
14056                             QualType &DeclRefType,
14057                             const bool RefersToCapturedVariable,
14058                             const Sema::TryCaptureKind Kind,
14059                             SourceLocation EllipsisLoc,
14060                             const bool IsTopScope,
14061                             Sema &S) {
14062 
14063   // Determine whether we are capturing by reference or by value.
14064   bool ByRef = false;
14065   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14066     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14067   } else {
14068     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14069   }
14070 
14071   // Compute the type of the field that will capture this variable.
14072   if (ByRef) {
14073     // C++11 [expr.prim.lambda]p15:
14074     //   An entity is captured by reference if it is implicitly or
14075     //   explicitly captured but not captured by copy. It is
14076     //   unspecified whether additional unnamed non-static data
14077     //   members are declared in the closure type for entities
14078     //   captured by reference.
14079     //
14080     // FIXME: It is not clear whether we want to build an lvalue reference
14081     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14082     // to do the former, while EDG does the latter. Core issue 1249 will
14083     // clarify, but for now we follow GCC because it's a more permissive and
14084     // easily defensible position.
14085     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14086   } else {
14087     // C++11 [expr.prim.lambda]p14:
14088     //   For each entity captured by copy, an unnamed non-static
14089     //   data member is declared in the closure type. The
14090     //   declaration order of these members is unspecified. The type
14091     //   of such a data member is the type of the corresponding
14092     //   captured entity if the entity is not a reference to an
14093     //   object, or the referenced type otherwise. [Note: If the
14094     //   captured entity is a reference to a function, the
14095     //   corresponding data member is also a reference to a
14096     //   function. - end note ]
14097     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14098       if (!RefType->getPointeeType()->isFunctionType())
14099         CaptureType = RefType->getPointeeType();
14100     }
14101 
14102     // Forbid the lambda copy-capture of autoreleasing variables.
14103     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14104       if (BuildAndDiagnose) {
14105         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14106         S.Diag(Var->getLocation(), diag::note_previous_decl)
14107           << Var->getDeclName();
14108       }
14109       return false;
14110     }
14111 
14112     // Make sure that by-copy captures are of a complete and non-abstract type.
14113     if (BuildAndDiagnose) {
14114       if (!CaptureType->isDependentType() &&
14115           S.RequireCompleteType(Loc, CaptureType,
14116                                 diag::err_capture_of_incomplete_type,
14117                                 Var->getDeclName()))
14118         return false;
14119 
14120       if (S.RequireNonAbstractType(Loc, CaptureType,
14121                                    diag::err_capture_of_abstract_type))
14122         return false;
14123     }
14124   }
14125 
14126   // Capture this variable in the lambda.
14127   if (BuildAndDiagnose)
14128     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14129                             RefersToCapturedVariable);
14130 
14131   // Compute the type of a reference to this captured variable.
14132   if (ByRef)
14133     DeclRefType = CaptureType.getNonReferenceType();
14134   else {
14135     // C++ [expr.prim.lambda]p5:
14136     //   The closure type for a lambda-expression has a public inline
14137     //   function call operator [...]. This function call operator is
14138     //   declared const (9.3.1) if and only if the lambda-expression's
14139     //   parameter-declaration-clause is not followed by mutable.
14140     DeclRefType = CaptureType.getNonReferenceType();
14141     if (!LSI->Mutable && !CaptureType->isReferenceType())
14142       DeclRefType.addConst();
14143   }
14144 
14145   // Add the capture.
14146   if (BuildAndDiagnose)
14147     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14148                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14149 
14150   return true;
14151 }
14152 
14153 bool Sema::tryCaptureVariable(
14154     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14155     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14156     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14157   // An init-capture is notionally from the context surrounding its
14158   // declaration, but its parent DC is the lambda class.
14159   DeclContext *VarDC = Var->getDeclContext();
14160   if (Var->isInitCapture())
14161     VarDC = VarDC->getParent();
14162 
14163   DeclContext *DC = CurContext;
14164   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
14165       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
14166   // We need to sync up the Declaration Context with the
14167   // FunctionScopeIndexToStopAt
14168   if (FunctionScopeIndexToStopAt) {
14169     unsigned FSIndex = FunctionScopes.size() - 1;
14170     while (FSIndex != MaxFunctionScopesIndex) {
14171       DC = getLambdaAwareParentOfDeclContext(DC);
14172       --FSIndex;
14173     }
14174   }
14175 
14176 
14177   // If the variable is declared in the current context, there is no need to
14178   // capture it.
14179   if (VarDC == DC) return true;
14180 
14181   // Capture global variables if it is required to use private copy of this
14182   // variable.
14183   bool IsGlobal = !Var->hasLocalStorage();
14184   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
14185     return true;
14186 
14187   // Walk up the stack to determine whether we can capture the variable,
14188   // performing the "simple" checks that don't depend on type. We stop when
14189   // we've either hit the declared scope of the variable or find an existing
14190   // capture of that variable.  We start from the innermost capturing-entity
14191   // (the DC) and ensure that all intervening capturing-entities
14192   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14193   // declcontext can either capture the variable or have already captured
14194   // the variable.
14195   CaptureType = Var->getType();
14196   DeclRefType = CaptureType.getNonReferenceType();
14197   bool Nested = false;
14198   bool Explicit = (Kind != TryCapture_Implicit);
14199   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14200   do {
14201     // Only block literals, captured statements, and lambda expressions can
14202     // capture; other scopes don't work.
14203     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14204                                                               ExprLoc,
14205                                                               BuildAndDiagnose,
14206                                                               *this);
14207     // We need to check for the parent *first* because, if we *have*
14208     // private-captured a global variable, we need to recursively capture it in
14209     // intermediate blocks, lambdas, etc.
14210     if (!ParentDC) {
14211       if (IsGlobal) {
14212         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14213         break;
14214       }
14215       return true;
14216     }
14217 
14218     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14219     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14220 
14221 
14222     // Check whether we've already captured it.
14223     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14224                                              DeclRefType)) {
14225       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14226       break;
14227     }
14228     // If we are instantiating a generic lambda call operator body,
14229     // we do not want to capture new variables.  What was captured
14230     // during either a lambdas transformation or initial parsing
14231     // should be used.
14232     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14233       if (BuildAndDiagnose) {
14234         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14235         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14236           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14237           Diag(Var->getLocation(), diag::note_previous_decl)
14238              << Var->getDeclName();
14239           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14240         } else
14241           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14242       }
14243       return true;
14244     }
14245     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14246     // certain types of variables (unnamed, variably modified types etc.)
14247     // so check for eligibility.
14248     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14249        return true;
14250 
14251     // Try to capture variable-length arrays types.
14252     if (Var->getType()->isVariablyModifiedType()) {
14253       // We're going to walk down into the type and look for VLA
14254       // expressions.
14255       QualType QTy = Var->getType();
14256       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14257         QTy = PVD->getOriginalType();
14258       captureVariablyModifiedType(Context, QTy, CSI);
14259     }
14260 
14261     if (getLangOpts().OpenMP) {
14262       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14263         // OpenMP private variables should not be captured in outer scope, so
14264         // just break here. Similarly, global variables that are captured in a
14265         // target region should not be captured outside the scope of the region.
14266         if (RSI->CapRegionKind == CR_OpenMP) {
14267           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14268           // When we detect target captures we are looking from inside the
14269           // target region, therefore we need to propagate the capture from the
14270           // enclosing region. Therefore, the capture is not initially nested.
14271           if (IsTargetCap)
14272             FunctionScopesIndex--;
14273 
14274           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
14275             Nested = !IsTargetCap;
14276             DeclRefType = DeclRefType.getUnqualifiedType();
14277             CaptureType = Context.getLValueReferenceType(DeclRefType);
14278             break;
14279           }
14280         }
14281       }
14282     }
14283     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14284       // No capture-default, and this is not an explicit capture
14285       // so cannot capture this variable.
14286       if (BuildAndDiagnose) {
14287         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14288         Diag(Var->getLocation(), diag::note_previous_decl)
14289           << Var->getDeclName();
14290         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14291           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14292                diag::note_lambda_decl);
14293         // FIXME: If we error out because an outer lambda can not implicitly
14294         // capture a variable that an inner lambda explicitly captures, we
14295         // should have the inner lambda do the explicit capture - because
14296         // it makes for cleaner diagnostics later.  This would purely be done
14297         // so that the diagnostic does not misleadingly claim that a variable
14298         // can not be captured by a lambda implicitly even though it is captured
14299         // explicitly.  Suggestion:
14300         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14301         //    at the function head
14302         //  - cache the StartingDeclContext - this must be a lambda
14303         //  - captureInLambda in the innermost lambda the variable.
14304       }
14305       return true;
14306     }
14307 
14308     FunctionScopesIndex--;
14309     DC = ParentDC;
14310     Explicit = false;
14311   } while (!VarDC->Equals(DC));
14312 
14313   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14314   // computing the type of the capture at each step, checking type-specific
14315   // requirements, and adding captures if requested.
14316   // If the variable had already been captured previously, we start capturing
14317   // at the lambda nested within that one.
14318   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14319        ++I) {
14320     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14321 
14322     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14323       if (!captureInBlock(BSI, Var, ExprLoc,
14324                           BuildAndDiagnose, CaptureType,
14325                           DeclRefType, Nested, *this))
14326         return true;
14327       Nested = true;
14328     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14329       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14330                                    BuildAndDiagnose, CaptureType,
14331                                    DeclRefType, Nested, *this))
14332         return true;
14333       Nested = true;
14334     } else {
14335       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14336       if (!captureInLambda(LSI, Var, ExprLoc,
14337                            BuildAndDiagnose, CaptureType,
14338                            DeclRefType, Nested, Kind, EllipsisLoc,
14339                             /*IsTopScope*/I == N - 1, *this))
14340         return true;
14341       Nested = true;
14342     }
14343   }
14344   return false;
14345 }
14346 
14347 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14348                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14349   QualType CaptureType;
14350   QualType DeclRefType;
14351   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14352                             /*BuildAndDiagnose=*/true, CaptureType,
14353                             DeclRefType, nullptr);
14354 }
14355 
14356 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14357   QualType CaptureType;
14358   QualType DeclRefType;
14359   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14360                              /*BuildAndDiagnose=*/false, CaptureType,
14361                              DeclRefType, nullptr);
14362 }
14363 
14364 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14365   QualType CaptureType;
14366   QualType DeclRefType;
14367 
14368   // Determine whether we can capture this variable.
14369   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14370                          /*BuildAndDiagnose=*/false, CaptureType,
14371                          DeclRefType, nullptr))
14372     return QualType();
14373 
14374   return DeclRefType;
14375 }
14376 
14377 
14378 
14379 // If either the type of the variable or the initializer is dependent,
14380 // return false. Otherwise, determine whether the variable is a constant
14381 // expression. Use this if you need to know if a variable that might or
14382 // might not be dependent is truly a constant expression.
14383 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14384     ASTContext &Context) {
14385 
14386   if (Var->getType()->isDependentType())
14387     return false;
14388   const VarDecl *DefVD = nullptr;
14389   Var->getAnyInitializer(DefVD);
14390   if (!DefVD)
14391     return false;
14392   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14393   Expr *Init = cast<Expr>(Eval->Value);
14394   if (Init->isValueDependent())
14395     return false;
14396   return IsVariableAConstantExpression(Var, Context);
14397 }
14398 
14399 
14400 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14401   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14402   // an object that satisfies the requirements for appearing in a
14403   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14404   // is immediately applied."  This function handles the lvalue-to-rvalue
14405   // conversion part.
14406   MaybeODRUseExprs.erase(E->IgnoreParens());
14407 
14408   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14409   // to a variable that is a constant expression, and if so, identify it as
14410   // a reference to a variable that does not involve an odr-use of that
14411   // variable.
14412   if (LambdaScopeInfo *LSI = getCurLambda()) {
14413     Expr *SansParensExpr = E->IgnoreParens();
14414     VarDecl *Var = nullptr;
14415     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14416       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14417     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14418       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14419 
14420     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14421       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14422   }
14423 }
14424 
14425 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14426   Res = CorrectDelayedTyposInExpr(Res);
14427 
14428   if (!Res.isUsable())
14429     return Res;
14430 
14431   // If a constant-expression is a reference to a variable where we delay
14432   // deciding whether it is an odr-use, just assume we will apply the
14433   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14434   // (a non-type template argument), we have special handling anyway.
14435   UpdateMarkingForLValueToRValue(Res.get());
14436   return Res;
14437 }
14438 
14439 void Sema::CleanupVarDeclMarking() {
14440   for (Expr *E : MaybeODRUseExprs) {
14441     VarDecl *Var;
14442     SourceLocation Loc;
14443     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14444       Var = cast<VarDecl>(DRE->getDecl());
14445       Loc = DRE->getLocation();
14446     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14447       Var = cast<VarDecl>(ME->getMemberDecl());
14448       Loc = ME->getMemberLoc();
14449     } else {
14450       llvm_unreachable("Unexpected expression");
14451     }
14452 
14453     MarkVarDeclODRUsed(Var, Loc, *this,
14454                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14455   }
14456 
14457   MaybeODRUseExprs.clear();
14458 }
14459 
14460 
14461 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14462                                     VarDecl *Var, Expr *E) {
14463   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14464          "Invalid Expr argument to DoMarkVarDeclReferenced");
14465   Var->setReferenced();
14466 
14467   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14468 
14469   bool OdrUseContext = isOdrUseContext(SemaRef);
14470   bool NeedDefinition =
14471       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14472                         Var->isUsableInConstantExpressions(SemaRef.Context));
14473 
14474   VarTemplateSpecializationDecl *VarSpec =
14475       dyn_cast<VarTemplateSpecializationDecl>(Var);
14476   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14477          "Can't instantiate a partial template specialization.");
14478 
14479   // If this might be a member specialization of a static data member, check
14480   // the specialization is visible. We already did the checks for variable
14481   // template specializations when we created them.
14482   if (NeedDefinition && TSK != TSK_Undeclared &&
14483       !isa<VarTemplateSpecializationDecl>(Var))
14484     SemaRef.checkSpecializationVisibility(Loc, Var);
14485 
14486   // Perform implicit instantiation of static data members, static data member
14487   // templates of class templates, and variable template specializations. Delay
14488   // instantiations of variable templates, except for those that could be used
14489   // in a constant expression.
14490   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14491     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14492 
14493     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14494       if (Var->getPointOfInstantiation().isInvalid()) {
14495         // This is a modification of an existing AST node. Notify listeners.
14496         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14497           L->StaticDataMemberInstantiated(Var);
14498       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14499         // Don't bother trying to instantiate it again, unless we might need
14500         // its initializer before we get to the end of the TU.
14501         TryInstantiating = false;
14502     }
14503 
14504     if (Var->getPointOfInstantiation().isInvalid())
14505       Var->setTemplateSpecializationKind(TSK, Loc);
14506 
14507     if (TryInstantiating) {
14508       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14509       bool InstantiationDependent = false;
14510       bool IsNonDependent =
14511           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14512                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14513                   : true;
14514 
14515       // Do not instantiate specializations that are still type-dependent.
14516       if (IsNonDependent) {
14517         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14518           // Do not defer instantiations of variables which could be used in a
14519           // constant expression.
14520           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14521         } else {
14522           SemaRef.PendingInstantiations
14523               .push_back(std::make_pair(Var, PointOfInstantiation));
14524         }
14525       }
14526     }
14527   }
14528 
14529   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14530   // the requirements for appearing in a constant expression (5.19) and, if
14531   // it is an object, the lvalue-to-rvalue conversion (4.1)
14532   // is immediately applied."  We check the first part here, and
14533   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14534   // Note that we use the C++11 definition everywhere because nothing in
14535   // C++03 depends on whether we get the C++03 version correct. The second
14536   // part does not apply to references, since they are not objects.
14537   if (OdrUseContext && E &&
14538       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14539     // A reference initialized by a constant expression can never be
14540     // odr-used, so simply ignore it.
14541     if (!Var->getType()->isReferenceType())
14542       SemaRef.MaybeODRUseExprs.insert(E);
14543   } else if (OdrUseContext) {
14544     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14545                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14546   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14547     // If this is a dependent context, we don't need to mark variables as
14548     // odr-used, but we may still need to track them for lambda capture.
14549     // FIXME: Do we also need to do this inside dependent typeid expressions
14550     // (which are modeled as unevaluated at this point)?
14551     const bool RefersToEnclosingScope =
14552         (SemaRef.CurContext != Var->getDeclContext() &&
14553          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14554     if (RefersToEnclosingScope) {
14555       LambdaScopeInfo *const LSI =
14556           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14557       if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
14558         // If a variable could potentially be odr-used, defer marking it so
14559         // until we finish analyzing the full expression for any
14560         // lvalue-to-rvalue
14561         // or discarded value conversions that would obviate odr-use.
14562         // Add it to the list of potential captures that will be analyzed
14563         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14564         // unless the variable is a reference that was initialized by a constant
14565         // expression (this will never need to be captured or odr-used).
14566         assert(E && "Capture variable should be used in an expression.");
14567         if (!Var->getType()->isReferenceType() ||
14568             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14569           LSI->addPotentialCapture(E->IgnoreParens());
14570       }
14571     }
14572   }
14573 }
14574 
14575 /// \brief Mark a variable referenced, and check whether it is odr-used
14576 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14577 /// used directly for normal expressions referring to VarDecl.
14578 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14579   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14580 }
14581 
14582 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14583                                Decl *D, Expr *E, bool MightBeOdrUse) {
14584   if (SemaRef.isInOpenMPDeclareTargetContext())
14585     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14586 
14587   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14588     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14589     return;
14590   }
14591 
14592   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14593 
14594   // If this is a call to a method via a cast, also mark the method in the
14595   // derived class used in case codegen can devirtualize the call.
14596   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14597   if (!ME)
14598     return;
14599   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14600   if (!MD)
14601     return;
14602   // Only attempt to devirtualize if this is truly a virtual call.
14603   bool IsVirtualCall = MD->isVirtual() &&
14604                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14605   if (!IsVirtualCall)
14606     return;
14607 
14608   // If it's possible to devirtualize the call, mark the called function
14609   // referenced.
14610   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
14611       ME->getBase(), SemaRef.getLangOpts().AppleKext);
14612   if (DM)
14613     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14614 }
14615 
14616 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14617 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
14618   // TODO: update this with DR# once a defect report is filed.
14619   // C++11 defect. The address of a pure member should not be an ODR use, even
14620   // if it's a qualified reference.
14621   bool OdrUse = true;
14622   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14623     if (Method->isVirtual() &&
14624         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
14625       OdrUse = false;
14626   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14627 }
14628 
14629 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14630 void Sema::MarkMemberReferenced(MemberExpr *E) {
14631   // C++11 [basic.def.odr]p2:
14632   //   A non-overloaded function whose name appears as a potentially-evaluated
14633   //   expression or a member of a set of candidate functions, if selected by
14634   //   overload resolution when referred to from a potentially-evaluated
14635   //   expression, is odr-used, unless it is a pure virtual function and its
14636   //   name is not explicitly qualified.
14637   bool MightBeOdrUse = true;
14638   if (E->performsVirtualDispatch(getLangOpts())) {
14639     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14640       if (Method->isPure())
14641         MightBeOdrUse = false;
14642   }
14643   SourceLocation Loc = E->getMemberLoc().isValid() ?
14644                             E->getMemberLoc() : E->getLocStart();
14645   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14646 }
14647 
14648 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14649 /// marks the declaration referenced, and performs odr-use checking for
14650 /// functions and variables. This method should not be used when building a
14651 /// normal expression which refers to a variable.
14652 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14653                                  bool MightBeOdrUse) {
14654   if (MightBeOdrUse) {
14655     if (auto *VD = dyn_cast<VarDecl>(D)) {
14656       MarkVariableReferenced(Loc, VD);
14657       return;
14658     }
14659   }
14660   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14661     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14662     return;
14663   }
14664   D->setReferenced();
14665 }
14666 
14667 namespace {
14668   // Mark all of the declarations used by a type as referenced.
14669   // FIXME: Not fully implemented yet! We need to have a better understanding
14670   // of when we're entering a context we should not recurse into.
14671   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14672   // TreeTransforms rebuilding the type in a new context. Rather than
14673   // duplicating the TreeTransform logic, we should consider reusing it here.
14674   // Currently that causes problems when rebuilding LambdaExprs.
14675   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14676     Sema &S;
14677     SourceLocation Loc;
14678 
14679   public:
14680     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14681 
14682     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14683 
14684     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14685   };
14686 }
14687 
14688 bool MarkReferencedDecls::TraverseTemplateArgument(
14689     const TemplateArgument &Arg) {
14690   {
14691     // A non-type template argument is a constant-evaluated context.
14692     EnterExpressionEvaluationContext Evaluated(
14693         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
14694     if (Arg.getKind() == TemplateArgument::Declaration) {
14695       if (Decl *D = Arg.getAsDecl())
14696         S.MarkAnyDeclReferenced(Loc, D, true);
14697     } else if (Arg.getKind() == TemplateArgument::Expression) {
14698       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14699     }
14700   }
14701 
14702   return Inherited::TraverseTemplateArgument(Arg);
14703 }
14704 
14705 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14706   MarkReferencedDecls Marker(*this, Loc);
14707   Marker.TraverseType(T);
14708 }
14709 
14710 namespace {
14711   /// \brief Helper class that marks all of the declarations referenced by
14712   /// potentially-evaluated subexpressions as "referenced".
14713   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14714     Sema &S;
14715     bool SkipLocalVariables;
14716 
14717   public:
14718     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14719 
14720     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14721       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14722 
14723     void VisitDeclRefExpr(DeclRefExpr *E) {
14724       // If we were asked not to visit local variables, don't.
14725       if (SkipLocalVariables) {
14726         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14727           if (VD->hasLocalStorage())
14728             return;
14729       }
14730 
14731       S.MarkDeclRefReferenced(E);
14732     }
14733 
14734     void VisitMemberExpr(MemberExpr *E) {
14735       S.MarkMemberReferenced(E);
14736       Inherited::VisitMemberExpr(E);
14737     }
14738 
14739     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14740       S.MarkFunctionReferenced(E->getLocStart(),
14741             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14742       Visit(E->getSubExpr());
14743     }
14744 
14745     void VisitCXXNewExpr(CXXNewExpr *E) {
14746       if (E->getOperatorNew())
14747         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14748       if (E->getOperatorDelete())
14749         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14750       Inherited::VisitCXXNewExpr(E);
14751     }
14752 
14753     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14754       if (E->getOperatorDelete())
14755         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14756       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14757       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14758         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14759         S.MarkFunctionReferenced(E->getLocStart(),
14760                                     S.LookupDestructor(Record));
14761       }
14762 
14763       Inherited::VisitCXXDeleteExpr(E);
14764     }
14765 
14766     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14767       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14768       Inherited::VisitCXXConstructExpr(E);
14769     }
14770 
14771     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14772       Visit(E->getExpr());
14773     }
14774 
14775     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14776       Inherited::VisitImplicitCastExpr(E);
14777 
14778       if (E->getCastKind() == CK_LValueToRValue)
14779         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14780     }
14781   };
14782 }
14783 
14784 /// \brief Mark any declarations that appear within this expression or any
14785 /// potentially-evaluated subexpressions as "referenced".
14786 ///
14787 /// \param SkipLocalVariables If true, don't mark local variables as
14788 /// 'referenced'.
14789 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14790                                             bool SkipLocalVariables) {
14791   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14792 }
14793 
14794 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14795 /// of the program being compiled.
14796 ///
14797 /// This routine emits the given diagnostic when the code currently being
14798 /// type-checked is "potentially evaluated", meaning that there is a
14799 /// possibility that the code will actually be executable. Code in sizeof()
14800 /// expressions, code used only during overload resolution, etc., are not
14801 /// potentially evaluated. This routine will suppress such diagnostics or,
14802 /// in the absolutely nutty case of potentially potentially evaluated
14803 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14804 /// later.
14805 ///
14806 /// This routine should be used for all diagnostics that describe the run-time
14807 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14808 /// Failure to do so will likely result in spurious diagnostics or failures
14809 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14810 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14811                                const PartialDiagnostic &PD) {
14812   switch (ExprEvalContexts.back().Context) {
14813   case ExpressionEvaluationContext::Unevaluated:
14814   case ExpressionEvaluationContext::UnevaluatedList:
14815   case ExpressionEvaluationContext::UnevaluatedAbstract:
14816   case ExpressionEvaluationContext::DiscardedStatement:
14817     // The argument will never be evaluated, so don't complain.
14818     break;
14819 
14820   case ExpressionEvaluationContext::ConstantEvaluated:
14821     // Relevant diagnostics should be produced by constant evaluation.
14822     break;
14823 
14824   case ExpressionEvaluationContext::PotentiallyEvaluated:
14825   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14826     if (Statement && getCurFunctionOrMethodDecl()) {
14827       FunctionScopes.back()->PossiblyUnreachableDiags.
14828         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14829     }
14830     else
14831       Diag(Loc, PD);
14832 
14833     return true;
14834   }
14835 
14836   return false;
14837 }
14838 
14839 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14840                                CallExpr *CE, FunctionDecl *FD) {
14841   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14842     return false;
14843 
14844   // If we're inside a decltype's expression, don't check for a valid return
14845   // type or construct temporaries until we know whether this is the last call.
14846   if (ExprEvalContexts.back().IsDecltype) {
14847     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14848     return false;
14849   }
14850 
14851   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14852     FunctionDecl *FD;
14853     CallExpr *CE;
14854 
14855   public:
14856     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14857       : FD(FD), CE(CE) { }
14858 
14859     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14860       if (!FD) {
14861         S.Diag(Loc, diag::err_call_incomplete_return)
14862           << T << CE->getSourceRange();
14863         return;
14864       }
14865 
14866       S.Diag(Loc, diag::err_call_function_incomplete_return)
14867         << CE->getSourceRange() << FD->getDeclName() << T;
14868       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14869           << FD->getDeclName();
14870     }
14871   } Diagnoser(FD, CE);
14872 
14873   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14874     return true;
14875 
14876   return false;
14877 }
14878 
14879 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14880 // will prevent this condition from triggering, which is what we want.
14881 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14882   SourceLocation Loc;
14883 
14884   unsigned diagnostic = diag::warn_condition_is_assignment;
14885   bool IsOrAssign = false;
14886 
14887   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14888     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14889       return;
14890 
14891     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14892 
14893     // Greylist some idioms by putting them into a warning subcategory.
14894     if (ObjCMessageExpr *ME
14895           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14896       Selector Sel = ME->getSelector();
14897 
14898       // self = [<foo> init...]
14899       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14900         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14901 
14902       // <foo> = [<bar> nextObject]
14903       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14904         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14905     }
14906 
14907     Loc = Op->getOperatorLoc();
14908   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14909     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14910       return;
14911 
14912     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14913     Loc = Op->getOperatorLoc();
14914   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14915     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14916   else {
14917     // Not an assignment.
14918     return;
14919   }
14920 
14921   Diag(Loc, diagnostic) << E->getSourceRange();
14922 
14923   SourceLocation Open = E->getLocStart();
14924   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14925   Diag(Loc, diag::note_condition_assign_silence)
14926         << FixItHint::CreateInsertion(Open, "(")
14927         << FixItHint::CreateInsertion(Close, ")");
14928 
14929   if (IsOrAssign)
14930     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14931       << FixItHint::CreateReplacement(Loc, "!=");
14932   else
14933     Diag(Loc, diag::note_condition_assign_to_comparison)
14934       << FixItHint::CreateReplacement(Loc, "==");
14935 }
14936 
14937 /// \brief Redundant parentheses over an equality comparison can indicate
14938 /// that the user intended an assignment used as condition.
14939 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14940   // Don't warn if the parens came from a macro.
14941   SourceLocation parenLoc = ParenE->getLocStart();
14942   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14943     return;
14944   // Don't warn for dependent expressions.
14945   if (ParenE->isTypeDependent())
14946     return;
14947 
14948   Expr *E = ParenE->IgnoreParens();
14949 
14950   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14951     if (opE->getOpcode() == BO_EQ &&
14952         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14953                                                            == Expr::MLV_Valid) {
14954       SourceLocation Loc = opE->getOperatorLoc();
14955 
14956       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14957       SourceRange ParenERange = ParenE->getSourceRange();
14958       Diag(Loc, diag::note_equality_comparison_silence)
14959         << FixItHint::CreateRemoval(ParenERange.getBegin())
14960         << FixItHint::CreateRemoval(ParenERange.getEnd());
14961       Diag(Loc, diag::note_equality_comparison_to_assign)
14962         << FixItHint::CreateReplacement(Loc, "=");
14963     }
14964 }
14965 
14966 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14967                                        bool IsConstexpr) {
14968   DiagnoseAssignmentAsCondition(E);
14969   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14970     DiagnoseEqualityWithExtraParens(parenE);
14971 
14972   ExprResult result = CheckPlaceholderExpr(E);
14973   if (result.isInvalid()) return ExprError();
14974   E = result.get();
14975 
14976   if (!E->isTypeDependent()) {
14977     if (getLangOpts().CPlusPlus)
14978       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14979 
14980     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14981     if (ERes.isInvalid())
14982       return ExprError();
14983     E = ERes.get();
14984 
14985     QualType T = E->getType();
14986     if (!T->isScalarType()) { // C99 6.8.4.1p1
14987       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14988         << T << E->getSourceRange();
14989       return ExprError();
14990     }
14991     CheckBoolLikeConversion(E, Loc);
14992   }
14993 
14994   return E;
14995 }
14996 
14997 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14998                                            Expr *SubExpr, ConditionKind CK) {
14999   // Empty conditions are valid in for-statements.
15000   if (!SubExpr)
15001     return ConditionResult();
15002 
15003   ExprResult Cond;
15004   switch (CK) {
15005   case ConditionKind::Boolean:
15006     Cond = CheckBooleanCondition(Loc, SubExpr);
15007     break;
15008 
15009   case ConditionKind::ConstexprIf:
15010     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15011     break;
15012 
15013   case ConditionKind::Switch:
15014     Cond = CheckSwitchCondition(Loc, SubExpr);
15015     break;
15016   }
15017   if (Cond.isInvalid())
15018     return ConditionError();
15019 
15020   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15021   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15022   if (!FullExpr.get())
15023     return ConditionError();
15024 
15025   return ConditionResult(*this, nullptr, FullExpr,
15026                          CK == ConditionKind::ConstexprIf);
15027 }
15028 
15029 namespace {
15030   /// A visitor for rebuilding a call to an __unknown_any expression
15031   /// to have an appropriate type.
15032   struct RebuildUnknownAnyFunction
15033     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15034 
15035     Sema &S;
15036 
15037     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15038 
15039     ExprResult VisitStmt(Stmt *S) {
15040       llvm_unreachable("unexpected statement!");
15041     }
15042 
15043     ExprResult VisitExpr(Expr *E) {
15044       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15045         << E->getSourceRange();
15046       return ExprError();
15047     }
15048 
15049     /// Rebuild an expression which simply semantically wraps another
15050     /// expression which it shares the type and value kind of.
15051     template <class T> ExprResult rebuildSugarExpr(T *E) {
15052       ExprResult SubResult = Visit(E->getSubExpr());
15053       if (SubResult.isInvalid()) return ExprError();
15054 
15055       Expr *SubExpr = SubResult.get();
15056       E->setSubExpr(SubExpr);
15057       E->setType(SubExpr->getType());
15058       E->setValueKind(SubExpr->getValueKind());
15059       assert(E->getObjectKind() == OK_Ordinary);
15060       return E;
15061     }
15062 
15063     ExprResult VisitParenExpr(ParenExpr *E) {
15064       return rebuildSugarExpr(E);
15065     }
15066 
15067     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15068       return rebuildSugarExpr(E);
15069     }
15070 
15071     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15072       ExprResult SubResult = Visit(E->getSubExpr());
15073       if (SubResult.isInvalid()) return ExprError();
15074 
15075       Expr *SubExpr = SubResult.get();
15076       E->setSubExpr(SubExpr);
15077       E->setType(S.Context.getPointerType(SubExpr->getType()));
15078       assert(E->getValueKind() == VK_RValue);
15079       assert(E->getObjectKind() == OK_Ordinary);
15080       return E;
15081     }
15082 
15083     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15084       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15085 
15086       E->setType(VD->getType());
15087 
15088       assert(E->getValueKind() == VK_RValue);
15089       if (S.getLangOpts().CPlusPlus &&
15090           !(isa<CXXMethodDecl>(VD) &&
15091             cast<CXXMethodDecl>(VD)->isInstance()))
15092         E->setValueKind(VK_LValue);
15093 
15094       return E;
15095     }
15096 
15097     ExprResult VisitMemberExpr(MemberExpr *E) {
15098       return resolveDecl(E, E->getMemberDecl());
15099     }
15100 
15101     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15102       return resolveDecl(E, E->getDecl());
15103     }
15104   };
15105 }
15106 
15107 /// Given a function expression of unknown-any type, try to rebuild it
15108 /// to have a function type.
15109 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15110   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15111   if (Result.isInvalid()) return ExprError();
15112   return S.DefaultFunctionArrayConversion(Result.get());
15113 }
15114 
15115 namespace {
15116   /// A visitor for rebuilding an expression of type __unknown_anytype
15117   /// into one which resolves the type directly on the referring
15118   /// expression.  Strict preservation of the original source
15119   /// structure is not a goal.
15120   struct RebuildUnknownAnyExpr
15121     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15122 
15123     Sema &S;
15124 
15125     /// The current destination type.
15126     QualType DestType;
15127 
15128     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15129       : S(S), DestType(CastType) {}
15130 
15131     ExprResult VisitStmt(Stmt *S) {
15132       llvm_unreachable("unexpected statement!");
15133     }
15134 
15135     ExprResult VisitExpr(Expr *E) {
15136       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15137         << E->getSourceRange();
15138       return ExprError();
15139     }
15140 
15141     ExprResult VisitCallExpr(CallExpr *E);
15142     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15143 
15144     /// Rebuild an expression which simply semantically wraps another
15145     /// expression which it shares the type and value kind of.
15146     template <class T> ExprResult rebuildSugarExpr(T *E) {
15147       ExprResult SubResult = Visit(E->getSubExpr());
15148       if (SubResult.isInvalid()) return ExprError();
15149       Expr *SubExpr = SubResult.get();
15150       E->setSubExpr(SubExpr);
15151       E->setType(SubExpr->getType());
15152       E->setValueKind(SubExpr->getValueKind());
15153       assert(E->getObjectKind() == OK_Ordinary);
15154       return E;
15155     }
15156 
15157     ExprResult VisitParenExpr(ParenExpr *E) {
15158       return rebuildSugarExpr(E);
15159     }
15160 
15161     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15162       return rebuildSugarExpr(E);
15163     }
15164 
15165     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15166       const PointerType *Ptr = DestType->getAs<PointerType>();
15167       if (!Ptr) {
15168         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15169           << E->getSourceRange();
15170         return ExprError();
15171       }
15172 
15173       if (isa<CallExpr>(E->getSubExpr())) {
15174         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15175           << E->getSourceRange();
15176         return ExprError();
15177       }
15178 
15179       assert(E->getValueKind() == VK_RValue);
15180       assert(E->getObjectKind() == OK_Ordinary);
15181       E->setType(DestType);
15182 
15183       // Build the sub-expression as if it were an object of the pointee type.
15184       DestType = Ptr->getPointeeType();
15185       ExprResult SubResult = Visit(E->getSubExpr());
15186       if (SubResult.isInvalid()) return ExprError();
15187       E->setSubExpr(SubResult.get());
15188       return E;
15189     }
15190 
15191     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15192 
15193     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15194 
15195     ExprResult VisitMemberExpr(MemberExpr *E) {
15196       return resolveDecl(E, E->getMemberDecl());
15197     }
15198 
15199     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15200       return resolveDecl(E, E->getDecl());
15201     }
15202   };
15203 }
15204 
15205 /// Rebuilds a call expression which yielded __unknown_anytype.
15206 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15207   Expr *CalleeExpr = E->getCallee();
15208 
15209   enum FnKind {
15210     FK_MemberFunction,
15211     FK_FunctionPointer,
15212     FK_BlockPointer
15213   };
15214 
15215   FnKind Kind;
15216   QualType CalleeType = CalleeExpr->getType();
15217   if (CalleeType == S.Context.BoundMemberTy) {
15218     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15219     Kind = FK_MemberFunction;
15220     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15221   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15222     CalleeType = Ptr->getPointeeType();
15223     Kind = FK_FunctionPointer;
15224   } else {
15225     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15226     Kind = FK_BlockPointer;
15227   }
15228   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15229 
15230   // Verify that this is a legal result type of a function.
15231   if (DestType->isArrayType() || DestType->isFunctionType()) {
15232     unsigned diagID = diag::err_func_returning_array_function;
15233     if (Kind == FK_BlockPointer)
15234       diagID = diag::err_block_returning_array_function;
15235 
15236     S.Diag(E->getExprLoc(), diagID)
15237       << DestType->isFunctionType() << DestType;
15238     return ExprError();
15239   }
15240 
15241   // Otherwise, go ahead and set DestType as the call's result.
15242   E->setType(DestType.getNonLValueExprType(S.Context));
15243   E->setValueKind(Expr::getValueKindForType(DestType));
15244   assert(E->getObjectKind() == OK_Ordinary);
15245 
15246   // Rebuild the function type, replacing the result type with DestType.
15247   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15248   if (Proto) {
15249     // __unknown_anytype(...) is a special case used by the debugger when
15250     // it has no idea what a function's signature is.
15251     //
15252     // We want to build this call essentially under the K&R
15253     // unprototyped rules, but making a FunctionNoProtoType in C++
15254     // would foul up all sorts of assumptions.  However, we cannot
15255     // simply pass all arguments as variadic arguments, nor can we
15256     // portably just call the function under a non-variadic type; see
15257     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15258     // However, it turns out that in practice it is generally safe to
15259     // call a function declared as "A foo(B,C,D);" under the prototype
15260     // "A foo(B,C,D,...);".  The only known exception is with the
15261     // Windows ABI, where any variadic function is implicitly cdecl
15262     // regardless of its normal CC.  Therefore we change the parameter
15263     // types to match the types of the arguments.
15264     //
15265     // This is a hack, but it is far superior to moving the
15266     // corresponding target-specific code from IR-gen to Sema/AST.
15267 
15268     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15269     SmallVector<QualType, 8> ArgTypes;
15270     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15271       ArgTypes.reserve(E->getNumArgs());
15272       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15273         Expr *Arg = E->getArg(i);
15274         QualType ArgType = Arg->getType();
15275         if (E->isLValue()) {
15276           ArgType = S.Context.getLValueReferenceType(ArgType);
15277         } else if (E->isXValue()) {
15278           ArgType = S.Context.getRValueReferenceType(ArgType);
15279         }
15280         ArgTypes.push_back(ArgType);
15281       }
15282       ParamTypes = ArgTypes;
15283     }
15284     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15285                                          Proto->getExtProtoInfo());
15286   } else {
15287     DestType = S.Context.getFunctionNoProtoType(DestType,
15288                                                 FnType->getExtInfo());
15289   }
15290 
15291   // Rebuild the appropriate pointer-to-function type.
15292   switch (Kind) {
15293   case FK_MemberFunction:
15294     // Nothing to do.
15295     break;
15296 
15297   case FK_FunctionPointer:
15298     DestType = S.Context.getPointerType(DestType);
15299     break;
15300 
15301   case FK_BlockPointer:
15302     DestType = S.Context.getBlockPointerType(DestType);
15303     break;
15304   }
15305 
15306   // Finally, we can recurse.
15307   ExprResult CalleeResult = Visit(CalleeExpr);
15308   if (!CalleeResult.isUsable()) return ExprError();
15309   E->setCallee(CalleeResult.get());
15310 
15311   // Bind a temporary if necessary.
15312   return S.MaybeBindToTemporary(E);
15313 }
15314 
15315 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15316   // Verify that this is a legal result type of a call.
15317   if (DestType->isArrayType() || DestType->isFunctionType()) {
15318     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15319       << DestType->isFunctionType() << DestType;
15320     return ExprError();
15321   }
15322 
15323   // Rewrite the method result type if available.
15324   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15325     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15326     Method->setReturnType(DestType);
15327   }
15328 
15329   // Change the type of the message.
15330   E->setType(DestType.getNonReferenceType());
15331   E->setValueKind(Expr::getValueKindForType(DestType));
15332 
15333   return S.MaybeBindToTemporary(E);
15334 }
15335 
15336 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15337   // The only case we should ever see here is a function-to-pointer decay.
15338   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15339     assert(E->getValueKind() == VK_RValue);
15340     assert(E->getObjectKind() == OK_Ordinary);
15341 
15342     E->setType(DestType);
15343 
15344     // Rebuild the sub-expression as the pointee (function) type.
15345     DestType = DestType->castAs<PointerType>()->getPointeeType();
15346 
15347     ExprResult Result = Visit(E->getSubExpr());
15348     if (!Result.isUsable()) return ExprError();
15349 
15350     E->setSubExpr(Result.get());
15351     return E;
15352   } else if (E->getCastKind() == CK_LValueToRValue) {
15353     assert(E->getValueKind() == VK_RValue);
15354     assert(E->getObjectKind() == OK_Ordinary);
15355 
15356     assert(isa<BlockPointerType>(E->getType()));
15357 
15358     E->setType(DestType);
15359 
15360     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15361     DestType = S.Context.getLValueReferenceType(DestType);
15362 
15363     ExprResult Result = Visit(E->getSubExpr());
15364     if (!Result.isUsable()) return ExprError();
15365 
15366     E->setSubExpr(Result.get());
15367     return E;
15368   } else {
15369     llvm_unreachable("Unhandled cast type!");
15370   }
15371 }
15372 
15373 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15374   ExprValueKind ValueKind = VK_LValue;
15375   QualType Type = DestType;
15376 
15377   // We know how to make this work for certain kinds of decls:
15378 
15379   //  - functions
15380   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15381     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15382       DestType = Ptr->getPointeeType();
15383       ExprResult Result = resolveDecl(E, VD);
15384       if (Result.isInvalid()) return ExprError();
15385       return S.ImpCastExprToType(Result.get(), Type,
15386                                  CK_FunctionToPointerDecay, VK_RValue);
15387     }
15388 
15389     if (!Type->isFunctionType()) {
15390       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15391         << VD << E->getSourceRange();
15392       return ExprError();
15393     }
15394     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15395       // We must match the FunctionDecl's type to the hack introduced in
15396       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15397       // type. See the lengthy commentary in that routine.
15398       QualType FDT = FD->getType();
15399       const FunctionType *FnType = FDT->castAs<FunctionType>();
15400       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15401       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15402       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15403         SourceLocation Loc = FD->getLocation();
15404         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15405                                       FD->getDeclContext(),
15406                                       Loc, Loc, FD->getNameInfo().getName(),
15407                                       DestType, FD->getTypeSourceInfo(),
15408                                       SC_None, false/*isInlineSpecified*/,
15409                                       FD->hasPrototype(),
15410                                       false/*isConstexprSpecified*/);
15411 
15412         if (FD->getQualifier())
15413           NewFD->setQualifierInfo(FD->getQualifierLoc());
15414 
15415         SmallVector<ParmVarDecl*, 16> Params;
15416         for (const auto &AI : FT->param_types()) {
15417           ParmVarDecl *Param =
15418             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15419           Param->setScopeInfo(0, Params.size());
15420           Params.push_back(Param);
15421         }
15422         NewFD->setParams(Params);
15423         DRE->setDecl(NewFD);
15424         VD = DRE->getDecl();
15425       }
15426     }
15427 
15428     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15429       if (MD->isInstance()) {
15430         ValueKind = VK_RValue;
15431         Type = S.Context.BoundMemberTy;
15432       }
15433 
15434     // Function references aren't l-values in C.
15435     if (!S.getLangOpts().CPlusPlus)
15436       ValueKind = VK_RValue;
15437 
15438   //  - variables
15439   } else if (isa<VarDecl>(VD)) {
15440     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15441       Type = RefTy->getPointeeType();
15442     } else if (Type->isFunctionType()) {
15443       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15444         << VD << E->getSourceRange();
15445       return ExprError();
15446     }
15447 
15448   //  - nothing else
15449   } else {
15450     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15451       << VD << E->getSourceRange();
15452     return ExprError();
15453   }
15454 
15455   // Modifying the declaration like this is friendly to IR-gen but
15456   // also really dangerous.
15457   VD->setType(DestType);
15458   E->setType(Type);
15459   E->setValueKind(ValueKind);
15460   return E;
15461 }
15462 
15463 /// Check a cast of an unknown-any type.  We intentionally only
15464 /// trigger this for C-style casts.
15465 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15466                                      Expr *CastExpr, CastKind &CastKind,
15467                                      ExprValueKind &VK, CXXCastPath &Path) {
15468   // The type we're casting to must be either void or complete.
15469   if (!CastType->isVoidType() &&
15470       RequireCompleteType(TypeRange.getBegin(), CastType,
15471                           diag::err_typecheck_cast_to_incomplete))
15472     return ExprError();
15473 
15474   // Rewrite the casted expression from scratch.
15475   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15476   if (!result.isUsable()) return ExprError();
15477 
15478   CastExpr = result.get();
15479   VK = CastExpr->getValueKind();
15480   CastKind = CK_NoOp;
15481 
15482   return CastExpr;
15483 }
15484 
15485 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15486   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15487 }
15488 
15489 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15490                                     Expr *arg, QualType &paramType) {
15491   // If the syntactic form of the argument is not an explicit cast of
15492   // any sort, just do default argument promotion.
15493   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15494   if (!castArg) {
15495     ExprResult result = DefaultArgumentPromotion(arg);
15496     if (result.isInvalid()) return ExprError();
15497     paramType = result.get()->getType();
15498     return result;
15499   }
15500 
15501   // Otherwise, use the type that was written in the explicit cast.
15502   assert(!arg->hasPlaceholderType());
15503   paramType = castArg->getTypeAsWritten();
15504 
15505   // Copy-initialize a parameter of that type.
15506   InitializedEntity entity =
15507     InitializedEntity::InitializeParameter(Context, paramType,
15508                                            /*consumed*/ false);
15509   return PerformCopyInitialization(entity, callLoc, arg);
15510 }
15511 
15512 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15513   Expr *orig = E;
15514   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15515   while (true) {
15516     E = E->IgnoreParenImpCasts();
15517     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15518       E = call->getCallee();
15519       diagID = diag::err_uncasted_call_of_unknown_any;
15520     } else {
15521       break;
15522     }
15523   }
15524 
15525   SourceLocation loc;
15526   NamedDecl *d;
15527   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15528     loc = ref->getLocation();
15529     d = ref->getDecl();
15530   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15531     loc = mem->getMemberLoc();
15532     d = mem->getMemberDecl();
15533   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15534     diagID = diag::err_uncasted_call_of_unknown_any;
15535     loc = msg->getSelectorStartLoc();
15536     d = msg->getMethodDecl();
15537     if (!d) {
15538       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15539         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15540         << orig->getSourceRange();
15541       return ExprError();
15542     }
15543   } else {
15544     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15545       << E->getSourceRange();
15546     return ExprError();
15547   }
15548 
15549   S.Diag(loc, diagID) << d << orig->getSourceRange();
15550 
15551   // Never recoverable.
15552   return ExprError();
15553 }
15554 
15555 /// Check for operands with placeholder types and complain if found.
15556 /// Returns ExprError() if there was an error and no recovery was possible.
15557 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15558   if (!getLangOpts().CPlusPlus) {
15559     // C cannot handle TypoExpr nodes on either side of a binop because it
15560     // doesn't handle dependent types properly, so make sure any TypoExprs have
15561     // been dealt with before checking the operands.
15562     ExprResult Result = CorrectDelayedTyposInExpr(E);
15563     if (!Result.isUsable()) return ExprError();
15564     E = Result.get();
15565   }
15566 
15567   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15568   if (!placeholderType) return E;
15569 
15570   switch (placeholderType->getKind()) {
15571 
15572   // Overloaded expressions.
15573   case BuiltinType::Overload: {
15574     // Try to resolve a single function template specialization.
15575     // This is obligatory.
15576     ExprResult Result = E;
15577     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15578       return Result;
15579 
15580     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15581     // leaves Result unchanged on failure.
15582     Result = E;
15583     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15584       return Result;
15585 
15586     // If that failed, try to recover with a call.
15587     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15588                          /*complain*/ true);
15589     return Result;
15590   }
15591 
15592   // Bound member functions.
15593   case BuiltinType::BoundMember: {
15594     ExprResult result = E;
15595     const Expr *BME = E->IgnoreParens();
15596     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15597     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15598     if (isa<CXXPseudoDestructorExpr>(BME)) {
15599       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15600     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15601       if (ME->getMemberNameInfo().getName().getNameKind() ==
15602           DeclarationName::CXXDestructorName)
15603         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15604     }
15605     tryToRecoverWithCall(result, PD,
15606                          /*complain*/ true);
15607     return result;
15608   }
15609 
15610   // ARC unbridged casts.
15611   case BuiltinType::ARCUnbridgedCast: {
15612     Expr *realCast = stripARCUnbridgedCast(E);
15613     diagnoseARCUnbridgedCast(realCast);
15614     return realCast;
15615   }
15616 
15617   // Expressions of unknown type.
15618   case BuiltinType::UnknownAny:
15619     return diagnoseUnknownAnyExpr(*this, E);
15620 
15621   // Pseudo-objects.
15622   case BuiltinType::PseudoObject:
15623     return checkPseudoObjectRValue(E);
15624 
15625   case BuiltinType::BuiltinFn: {
15626     // Accept __noop without parens by implicitly converting it to a call expr.
15627     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15628     if (DRE) {
15629       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15630       if (FD->getBuiltinID() == Builtin::BI__noop) {
15631         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15632                               CK_BuiltinFnToFnPtr).get();
15633         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15634                                       VK_RValue, SourceLocation());
15635       }
15636     }
15637 
15638     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15639     return ExprError();
15640   }
15641 
15642   // Expressions of unknown type.
15643   case BuiltinType::OMPArraySection:
15644     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15645     return ExprError();
15646 
15647   // Everything else should be impossible.
15648 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15649   case BuiltinType::Id:
15650 #include "clang/Basic/OpenCLImageTypes.def"
15651 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15652 #define PLACEHOLDER_TYPE(Id, SingletonId)
15653 #include "clang/AST/BuiltinTypes.def"
15654     break;
15655   }
15656 
15657   llvm_unreachable("invalid placeholder type!");
15658 }
15659 
15660 bool Sema::CheckCaseExpression(Expr *E) {
15661   if (E->isTypeDependent())
15662     return true;
15663   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15664     return E->getType()->isIntegralOrEnumerationType();
15665   return false;
15666 }
15667 
15668 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15669 ExprResult
15670 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15671   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15672          "Unknown Objective-C Boolean value!");
15673   QualType BoolT = Context.ObjCBuiltinBoolTy;
15674   if (!Context.getBOOLDecl()) {
15675     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15676                         Sema::LookupOrdinaryName);
15677     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15678       NamedDecl *ND = Result.getFoundDecl();
15679       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15680         Context.setBOOLDecl(TD);
15681     }
15682   }
15683   if (Context.getBOOLDecl())
15684     BoolT = Context.getBOOLType();
15685   return new (Context)
15686       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15687 }
15688 
15689 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15690     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15691     SourceLocation RParen) {
15692 
15693   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15694 
15695   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15696                            [&](const AvailabilitySpec &Spec) {
15697                              return Spec.getPlatform() == Platform;
15698                            });
15699 
15700   VersionTuple Version;
15701   if (Spec != AvailSpecs.end())
15702     Version = Spec->getVersion();
15703 
15704   // The use of `@available` in the enclosing function should be analyzed to
15705   // warn when it's used inappropriately (i.e. not if(@available)).
15706   if (getCurFunctionOrMethodDecl())
15707     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
15708   else if (getCurBlock() || getCurLambda())
15709     getCurFunction()->HasPotentialAvailabilityViolations = true;
15710 
15711   return new (Context)
15712       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15713 }
15714