1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
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 extra semantic analysis beyond what is enforced
11 //  by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/ExprOpenMP.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/ConvertUTF.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/Locale.h"
42 #include "llvm/Support/raw_ostream.h"
43 
44 using namespace clang;
45 using namespace sema;
46 
47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48                                                     unsigned ByteNo) const {
49   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50                                Context.getTargetInfo());
51 }
52 
53 /// Checks that a call expression's argument count is the desired number.
54 /// This is useful when doing custom type-checking.  Returns true on error.
55 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56   unsigned argCount = call->getNumArgs();
57   if (argCount == desiredArgCount) return false;
58 
59   if (argCount < desiredArgCount)
60     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61         << 0 /*function call*/ << desiredArgCount << argCount
62         << call->getSourceRange();
63 
64   // Highlight all the excess arguments.
65   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66                     call->getArg(argCount - 1)->getLocEnd());
67 
68   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69     << 0 /*function call*/ << desiredArgCount << argCount
70     << call->getArg(1)->getSourceRange();
71 }
72 
73 /// Check that the first argument to __builtin_annotation is an integer
74 /// and the second argument is a non-wide string literal.
75 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76   if (checkArgCount(S, TheCall, 2))
77     return true;
78 
79   // First argument should be an integer.
80   Expr *ValArg = TheCall->getArg(0);
81   QualType Ty = ValArg->getType();
82   if (!Ty->isIntegerType()) {
83     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84       << ValArg->getSourceRange();
85     return true;
86   }
87 
88   // Second argument should be a constant string.
89   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91   if (!Literal || !Literal->isAscii()) {
92     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93       << StrArg->getSourceRange();
94     return true;
95   }
96 
97   TheCall->setType(Ty);
98   return false;
99 }
100 
101 /// Check that the argument to __builtin_addressof is a glvalue, and set the
102 /// result type to the corresponding pointer type.
103 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104   if (checkArgCount(S, TheCall, 1))
105     return true;
106 
107   ExprResult Arg(TheCall->getArg(0));
108   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109   if (ResultType.isNull())
110     return true;
111 
112   TheCall->setArg(0, Arg.get());
113   TheCall->setType(ResultType);
114   return false;
115 }
116 
117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118   if (checkArgCount(S, TheCall, 3))
119     return true;
120 
121   // First two arguments should be integers.
122   for (unsigned I = 0; I < 2; ++I) {
123     Expr *Arg = TheCall->getArg(I);
124     QualType Ty = Arg->getType();
125     if (!Ty->isIntegerType()) {
126       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127           << Ty << Arg->getSourceRange();
128       return true;
129     }
130   }
131 
132   // Third argument should be a pointer to a non-const integer.
133   // IRGen correctly handles volatile, restrict, and address spaces, and
134   // the other qualifiers aren't possible.
135   {
136     Expr *Arg = TheCall->getArg(2);
137     QualType Ty = Arg->getType();
138     const auto *PtrTy = Ty->getAs<PointerType>();
139     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140           !PtrTy->getPointeeType().isConstQualified())) {
141       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142           << Ty << Arg->getSourceRange();
143       return true;
144     }
145   }
146 
147   return false;
148 }
149 
150 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 		                  CallExpr *TheCall, unsigned SizeIdx,
152                                   unsigned DstSizeIdx) {
153   if (TheCall->getNumArgs() <= SizeIdx ||
154       TheCall->getNumArgs() <= DstSizeIdx)
155     return;
156 
157   const Expr *SizeArg = TheCall->getArg(SizeIdx);
158   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159 
160   llvm::APSInt Size, DstSize;
161 
162   // find out if both sizes are known at compile time
163   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165     return;
166 
167   if (Size.ule(DstSize))
168     return;
169 
170   // confirmed overflow so generate the diagnostic.
171   IdentifierInfo *FnName = FDecl->getIdentifier();
172   SourceLocation SL = TheCall->getLocStart();
173   SourceRange SR = TheCall->getSourceRange();
174 
175   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176 }
177 
178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179   if (checkArgCount(S, BuiltinCall, 2))
180     return true;
181 
182   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184   Expr *Call = BuiltinCall->getArg(0);
185   Expr *Chain = BuiltinCall->getArg(1);
186 
187   if (Call->getStmtClass() != Stmt::CallExprClass) {
188     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189         << Call->getSourceRange();
190     return true;
191   }
192 
193   auto CE = cast<CallExpr>(Call);
194   if (CE->getCallee()->getType()->isBlockPointerType()) {
195     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196         << Call->getSourceRange();
197     return true;
198   }
199 
200   const Decl *TargetDecl = CE->getCalleeDecl();
201   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202     if (FD->getBuiltinID()) {
203       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204           << Call->getSourceRange();
205       return true;
206     }
207 
208   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210         << Call->getSourceRange();
211     return true;
212   }
213 
214   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215   if (ChainResult.isInvalid())
216     return true;
217   if (!ChainResult.get()->getType()->isPointerType()) {
218     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219         << Chain->getSourceRange();
220     return true;
221   }
222 
223   QualType ReturnTy = CE->getCallReturnType(S.Context);
224   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225   QualType BuiltinTy = S.Context.getFunctionType(
226       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228 
229   Builtin =
230       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231 
232   BuiltinCall->setType(CE->getType());
233   BuiltinCall->setValueKind(CE->getValueKind());
234   BuiltinCall->setObjectKind(CE->getObjectKind());
235   BuiltinCall->setCallee(Builtin);
236   BuiltinCall->setArg(1, ChainResult.get());
237 
238   return false;
239 }
240 
241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242                                      Scope::ScopeFlags NeededScopeFlags,
243                                      unsigned DiagID) {
244   // Scopes aren't available during instantiation. Fortunately, builtin
245   // functions cannot be template args so they cannot be formed through template
246   // instantiation. Therefore checking once during the parse is sufficient.
247   if (!SemaRef.ActiveTemplateInstantiations.empty())
248     return false;
249 
250   Scope *S = SemaRef.getCurScope();
251   while (S && !S->isSEHExceptScope())
252     S = S->getParent();
253   if (!S || !(S->getFlags() & NeededScopeFlags)) {
254     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256         << DRE->getDecl()->getIdentifier();
257     return true;
258   }
259 
260   return false;
261 }
262 
263 static inline bool isBlockPointer(Expr *Arg) {
264   return Arg->getType()->isBlockPointerType();
265 }
266 
267 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268 /// void*, which is a requirement of device side enqueue.
269 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270   const BlockPointerType *BPT =
271       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272   ArrayRef<QualType> Params =
273       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274   unsigned ArgCounter = 0;
275   bool IllegalParams = false;
276   // Iterate through the block parameters until either one is found that is not
277   // a local void*, or the block is valid.
278   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279        I != E; ++I, ++ArgCounter) {
280     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282             LangAS::opencl_local) {
283       // Get the location of the error. If a block literal has been passed
284       // (BlockExpr) then we can point straight to the offending argument,
285       // else we just point to the variable reference.
286       SourceLocation ErrorLoc;
287       if (isa<BlockExpr>(BlockArg)) {
288         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290       } else if (isa<DeclRefExpr>(BlockArg)) {
291         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292       }
293       S.Diag(ErrorLoc,
294              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295       IllegalParams = true;
296     }
297   }
298 
299   return IllegalParams;
300 }
301 
302 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303 /// get_kernel_work_group_size
304 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
305 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306   if (checkArgCount(S, TheCall, 1))
307     return true;
308 
309   Expr *BlockArg = TheCall->getArg(0);
310   if (!isBlockPointer(BlockArg)) {
311     S.Diag(BlockArg->getLocStart(),
312            diag::err_opencl_enqueue_kernel_expected_type) << "block";
313     return true;
314   }
315   return checkOpenCLBlockArgs(S, BlockArg);
316 }
317 
318 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
319                                             unsigned Start, unsigned End);
320 
321 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
322 /// 'local void*' parameter of passed block.
323 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
324                                            Expr *BlockArg,
325                                            unsigned NumNonVarArgs) {
326   const BlockPointerType *BPT =
327       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
328   unsigned NumBlockParams =
329       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
330   unsigned TotalNumArgs = TheCall->getNumArgs();
331 
332   // For each argument passed to the block, a corresponding uint needs to
333   // be passed to describe the size of the local memory.
334   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
335     S.Diag(TheCall->getLocStart(),
336            diag::err_opencl_enqueue_kernel_local_size_args);
337     return true;
338   }
339 
340   // Check that the sizes of the local memory are specified by integers.
341   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
342                                          TotalNumArgs - 1);
343 }
344 
345 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
346 /// overload formats specified in Table 6.13.17.1.
347 /// int enqueue_kernel(queue_t queue,
348 ///                    kernel_enqueue_flags_t flags,
349 ///                    const ndrange_t ndrange,
350 ///                    void (^block)(void))
351 /// int enqueue_kernel(queue_t queue,
352 ///                    kernel_enqueue_flags_t flags,
353 ///                    const ndrange_t ndrange,
354 ///                    uint num_events_in_wait_list,
355 ///                    clk_event_t *event_wait_list,
356 ///                    clk_event_t *event_ret,
357 ///                    void (^block)(void))
358 /// int enqueue_kernel(queue_t queue,
359 ///                    kernel_enqueue_flags_t flags,
360 ///                    const ndrange_t ndrange,
361 ///                    void (^block)(local void*, ...),
362 ///                    uint size0, ...)
363 /// int enqueue_kernel(queue_t queue,
364 ///                    kernel_enqueue_flags_t flags,
365 ///                    const ndrange_t ndrange,
366 ///                    uint num_events_in_wait_list,
367 ///                    clk_event_t *event_wait_list,
368 ///                    clk_event_t *event_ret,
369 ///                    void (^block)(local void*, ...),
370 ///                    uint size0, ...)
371 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
372   unsigned NumArgs = TheCall->getNumArgs();
373 
374   if (NumArgs < 4) {
375     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
376     return true;
377   }
378 
379   Expr *Arg0 = TheCall->getArg(0);
380   Expr *Arg1 = TheCall->getArg(1);
381   Expr *Arg2 = TheCall->getArg(2);
382   Expr *Arg3 = TheCall->getArg(3);
383 
384   // First argument always needs to be a queue_t type.
385   if (!Arg0->getType()->isQueueT()) {
386     S.Diag(TheCall->getArg(0)->getLocStart(),
387            diag::err_opencl_enqueue_kernel_expected_type)
388         << S.Context.OCLQueueTy;
389     return true;
390   }
391 
392   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
393   if (!Arg1->getType()->isIntegerType()) {
394     S.Diag(TheCall->getArg(1)->getLocStart(),
395            diag::err_opencl_enqueue_kernel_expected_type)
396         << "'kernel_enqueue_flags_t' (i.e. uint)";
397     return true;
398   }
399 
400   // Third argument is always an ndrange_t type.
401   if (!Arg2->getType()->isNDRangeT()) {
402     S.Diag(TheCall->getArg(2)->getLocStart(),
403            diag::err_opencl_enqueue_kernel_expected_type)
404         << S.Context.OCLNDRangeTy;
405     return true;
406   }
407 
408   // With four arguments, there is only one form that the function could be
409   // called in: no events and no variable arguments.
410   if (NumArgs == 4) {
411     // check that the last argument is the right block type.
412     if (!isBlockPointer(Arg3)) {
413       S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
414           << "block";
415       return true;
416     }
417     // we have a block type, check the prototype
418     const BlockPointerType *BPT =
419         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
420     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
421       S.Diag(Arg3->getLocStart(),
422              diag::err_opencl_enqueue_kernel_blocks_no_args);
423       return true;
424     }
425     return false;
426   }
427   // we can have block + varargs.
428   if (isBlockPointer(Arg3))
429     return (checkOpenCLBlockArgs(S, Arg3) ||
430             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
431   // last two cases with either exactly 7 args or 7 args and varargs.
432   if (NumArgs >= 7) {
433     // check common block argument.
434     Expr *Arg6 = TheCall->getArg(6);
435     if (!isBlockPointer(Arg6)) {
436       S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
437           << "block";
438       return true;
439     }
440     if (checkOpenCLBlockArgs(S, Arg6))
441       return true;
442 
443     // Forth argument has to be any integer type.
444     if (!Arg3->getType()->isIntegerType()) {
445       S.Diag(TheCall->getArg(3)->getLocStart(),
446              diag::err_opencl_enqueue_kernel_expected_type)
447           << "integer";
448       return true;
449     }
450     // check remaining common arguments.
451     Expr *Arg4 = TheCall->getArg(4);
452     Expr *Arg5 = TheCall->getArg(5);
453 
454     // Fith argument is always passed as pointers to clk_event_t.
455     if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
456       S.Diag(TheCall->getArg(4)->getLocStart(),
457              diag::err_opencl_enqueue_kernel_expected_type)
458           << S.Context.getPointerType(S.Context.OCLClkEventTy);
459       return true;
460     }
461 
462     // Sixth argument is always passed as pointers to clk_event_t.
463     if (!(Arg5->getType()->isPointerType() &&
464           Arg5->getType()->getPointeeType()->isClkEventT())) {
465       S.Diag(TheCall->getArg(5)->getLocStart(),
466              diag::err_opencl_enqueue_kernel_expected_type)
467           << S.Context.getPointerType(S.Context.OCLClkEventTy);
468       return true;
469     }
470 
471     if (NumArgs == 7)
472       return false;
473 
474     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
475   }
476 
477   // None of the specific case has been detected, give generic error
478   S.Diag(TheCall->getLocStart(),
479          diag::err_opencl_enqueue_kernel_incorrect_args);
480   return true;
481 }
482 
483 /// Returns OpenCL access qual.
484 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
485     return D->getAttr<OpenCLAccessAttr>();
486 }
487 
488 /// Returns true if pipe element type is different from the pointer.
489 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
490   const Expr *Arg0 = Call->getArg(0);
491   // First argument type should always be pipe.
492   if (!Arg0->getType()->isPipeType()) {
493     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
494         << Call->getDirectCallee() << Arg0->getSourceRange();
495     return true;
496   }
497   OpenCLAccessAttr *AccessQual =
498       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
499   // Validates the access qualifier is compatible with the call.
500   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
501   // read_only and write_only, and assumed to be read_only if no qualifier is
502   // specified.
503   switch (Call->getDirectCallee()->getBuiltinID()) {
504   case Builtin::BIread_pipe:
505   case Builtin::BIreserve_read_pipe:
506   case Builtin::BIcommit_read_pipe:
507   case Builtin::BIwork_group_reserve_read_pipe:
508   case Builtin::BIsub_group_reserve_read_pipe:
509   case Builtin::BIwork_group_commit_read_pipe:
510   case Builtin::BIsub_group_commit_read_pipe:
511     if (!(!AccessQual || AccessQual->isReadOnly())) {
512       S.Diag(Arg0->getLocStart(),
513              diag::err_opencl_builtin_pipe_invalid_access_modifier)
514           << "read_only" << Arg0->getSourceRange();
515       return true;
516     }
517     break;
518   case Builtin::BIwrite_pipe:
519   case Builtin::BIreserve_write_pipe:
520   case Builtin::BIcommit_write_pipe:
521   case Builtin::BIwork_group_reserve_write_pipe:
522   case Builtin::BIsub_group_reserve_write_pipe:
523   case Builtin::BIwork_group_commit_write_pipe:
524   case Builtin::BIsub_group_commit_write_pipe:
525     if (!(AccessQual && AccessQual->isWriteOnly())) {
526       S.Diag(Arg0->getLocStart(),
527              diag::err_opencl_builtin_pipe_invalid_access_modifier)
528           << "write_only" << Arg0->getSourceRange();
529       return true;
530     }
531     break;
532   default:
533     break;
534   }
535   return false;
536 }
537 
538 /// Returns true if pipe element type is different from the pointer.
539 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
540   const Expr *Arg0 = Call->getArg(0);
541   const Expr *ArgIdx = Call->getArg(Idx);
542   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
543   const QualType EltTy = PipeTy->getElementType();
544   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
545   // The Idx argument should be a pointer and the type of the pointer and
546   // the type of pipe element should also be the same.
547   if (!ArgTy ||
548       !S.Context.hasSameType(
549           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
550     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
551         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
552         << ArgIdx->getType() << ArgIdx->getSourceRange();
553     return true;
554   }
555   return false;
556 }
557 
558 // \brief Performs semantic analysis for the read/write_pipe call.
559 // \param S Reference to the semantic analyzer.
560 // \param Call A pointer to the builtin call.
561 // \return True if a semantic error has been found, false otherwise.
562 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
563   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
564   // functions have two forms.
565   switch (Call->getNumArgs()) {
566   case 2: {
567     if (checkOpenCLPipeArg(S, Call))
568       return true;
569     // The call with 2 arguments should be
570     // read/write_pipe(pipe T, T*).
571     // Check packet type T.
572     if (checkOpenCLPipePacketType(S, Call, 1))
573       return true;
574   } break;
575 
576   case 4: {
577     if (checkOpenCLPipeArg(S, Call))
578       return true;
579     // The call with 4 arguments should be
580     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
581     // Check reserve_id_t.
582     if (!Call->getArg(1)->getType()->isReserveIDT()) {
583       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
584           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
585           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
586       return true;
587     }
588 
589     // Check the index.
590     const Expr *Arg2 = Call->getArg(2);
591     if (!Arg2->getType()->isIntegerType() &&
592         !Arg2->getType()->isUnsignedIntegerType()) {
593       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
594           << Call->getDirectCallee() << S.Context.UnsignedIntTy
595           << Arg2->getType() << Arg2->getSourceRange();
596       return true;
597     }
598 
599     // Check packet type T.
600     if (checkOpenCLPipePacketType(S, Call, 3))
601       return true;
602   } break;
603   default:
604     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
605         << Call->getDirectCallee() << Call->getSourceRange();
606     return true;
607   }
608 
609   return false;
610 }
611 
612 // \brief Performs a semantic analysis on the {work_group_/sub_group_
613 //        /_}reserve_{read/write}_pipe
614 // \param S Reference to the semantic analyzer.
615 // \param Call The call to the builtin function to be analyzed.
616 // \return True if a semantic error was found, false otherwise.
617 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
618   if (checkArgCount(S, Call, 2))
619     return true;
620 
621   if (checkOpenCLPipeArg(S, Call))
622     return true;
623 
624   // Check the reserve size.
625   if (!Call->getArg(1)->getType()->isIntegerType() &&
626       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
627     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
628         << Call->getDirectCallee() << S.Context.UnsignedIntTy
629         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
630     return true;
631   }
632 
633   return false;
634 }
635 
636 // \brief Performs a semantic analysis on {work_group_/sub_group_
637 //        /_}commit_{read/write}_pipe
638 // \param S Reference to the semantic analyzer.
639 // \param Call The call to the builtin function to be analyzed.
640 // \return True if a semantic error was found, false otherwise.
641 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
642   if (checkArgCount(S, Call, 2))
643     return true;
644 
645   if (checkOpenCLPipeArg(S, Call))
646     return true;
647 
648   // Check reserve_id_t.
649   if (!Call->getArg(1)->getType()->isReserveIDT()) {
650     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
651         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
652         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
653     return true;
654   }
655 
656   return false;
657 }
658 
659 // \brief Performs a semantic analysis on the call to built-in Pipe
660 //        Query Functions.
661 // \param S Reference to the semantic analyzer.
662 // \param Call The call to the builtin function to be analyzed.
663 // \return True if a semantic error was found, false otherwise.
664 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
665   if (checkArgCount(S, Call, 1))
666     return true;
667 
668   if (!Call->getArg(0)->getType()->isPipeType()) {
669     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
670         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
671     return true;
672   }
673 
674   return false;
675 }
676 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
677 // \brief Performs semantic analysis for the to_global/local/private call.
678 // \param S Reference to the semantic analyzer.
679 // \param BuiltinID ID of the builtin function.
680 // \param Call A pointer to the builtin call.
681 // \return True if a semantic error has been found, false otherwise.
682 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
683                                     CallExpr *Call) {
684   if (Call->getNumArgs() != 1) {
685     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
686         << Call->getDirectCallee() << Call->getSourceRange();
687     return true;
688   }
689 
690   auto RT = Call->getArg(0)->getType();
691   if (!RT->isPointerType() || RT->getPointeeType()
692       .getAddressSpace() == LangAS::opencl_constant) {
693     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
694         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
695     return true;
696   }
697 
698   RT = RT->getPointeeType();
699   auto Qual = RT.getQualifiers();
700   switch (BuiltinID) {
701   case Builtin::BIto_global:
702     Qual.setAddressSpace(LangAS::opencl_global);
703     break;
704   case Builtin::BIto_local:
705     Qual.setAddressSpace(LangAS::opencl_local);
706     break;
707   default:
708     Qual.removeAddressSpace();
709   }
710   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
711       RT.getUnqualifiedType(), Qual)));
712 
713   return false;
714 }
715 
716 ExprResult
717 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
718                                CallExpr *TheCall) {
719   ExprResult TheCallResult(TheCall);
720 
721   // Find out if any arguments are required to be integer constant expressions.
722   unsigned ICEArguments = 0;
723   ASTContext::GetBuiltinTypeError Error;
724   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
725   if (Error != ASTContext::GE_None)
726     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
727 
728   // If any arguments are required to be ICE's, check and diagnose.
729   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
730     // Skip arguments not required to be ICE's.
731     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
732 
733     llvm::APSInt Result;
734     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
735       return true;
736     ICEArguments &= ~(1 << ArgNo);
737   }
738 
739   switch (BuiltinID) {
740   case Builtin::BI__builtin___CFStringMakeConstantString:
741     assert(TheCall->getNumArgs() == 1 &&
742            "Wrong # arguments to builtin CFStringMakeConstantString");
743     if (CheckObjCString(TheCall->getArg(0)))
744       return ExprError();
745     break;
746   case Builtin::BI__builtin_stdarg_start:
747   case Builtin::BI__builtin_va_start:
748     if (SemaBuiltinVAStart(TheCall))
749       return ExprError();
750     break;
751   case Builtin::BI__va_start: {
752     switch (Context.getTargetInfo().getTriple().getArch()) {
753     case llvm::Triple::arm:
754     case llvm::Triple::thumb:
755       if (SemaBuiltinVAStartARM(TheCall))
756         return ExprError();
757       break;
758     default:
759       if (SemaBuiltinVAStart(TheCall))
760         return ExprError();
761       break;
762     }
763     break;
764   }
765   case Builtin::BI__builtin_isgreater:
766   case Builtin::BI__builtin_isgreaterequal:
767   case Builtin::BI__builtin_isless:
768   case Builtin::BI__builtin_islessequal:
769   case Builtin::BI__builtin_islessgreater:
770   case Builtin::BI__builtin_isunordered:
771     if (SemaBuiltinUnorderedCompare(TheCall))
772       return ExprError();
773     break;
774   case Builtin::BI__builtin_fpclassify:
775     if (SemaBuiltinFPClassification(TheCall, 6))
776       return ExprError();
777     break;
778   case Builtin::BI__builtin_isfinite:
779   case Builtin::BI__builtin_isinf:
780   case Builtin::BI__builtin_isinf_sign:
781   case Builtin::BI__builtin_isnan:
782   case Builtin::BI__builtin_isnormal:
783     if (SemaBuiltinFPClassification(TheCall, 1))
784       return ExprError();
785     break;
786   case Builtin::BI__builtin_shufflevector:
787     return SemaBuiltinShuffleVector(TheCall);
788     // TheCall will be freed by the smart pointer here, but that's fine, since
789     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
790   case Builtin::BI__builtin_prefetch:
791     if (SemaBuiltinPrefetch(TheCall))
792       return ExprError();
793     break;
794   case Builtin::BI__assume:
795   case Builtin::BI__builtin_assume:
796     if (SemaBuiltinAssume(TheCall))
797       return ExprError();
798     break;
799   case Builtin::BI__builtin_assume_aligned:
800     if (SemaBuiltinAssumeAligned(TheCall))
801       return ExprError();
802     break;
803   case Builtin::BI__builtin_object_size:
804     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
805       return ExprError();
806     break;
807   case Builtin::BI__builtin_longjmp:
808     if (SemaBuiltinLongjmp(TheCall))
809       return ExprError();
810     break;
811   case Builtin::BI__builtin_setjmp:
812     if (SemaBuiltinSetjmp(TheCall))
813       return ExprError();
814     break;
815   case Builtin::BI_setjmp:
816   case Builtin::BI_setjmpex:
817     if (checkArgCount(*this, TheCall, 1))
818       return true;
819     break;
820 
821   case Builtin::BI__builtin_classify_type:
822     if (checkArgCount(*this, TheCall, 1)) return true;
823     TheCall->setType(Context.IntTy);
824     break;
825   case Builtin::BI__builtin_constant_p:
826     if (checkArgCount(*this, TheCall, 1)) return true;
827     TheCall->setType(Context.IntTy);
828     break;
829   case Builtin::BI__sync_fetch_and_add:
830   case Builtin::BI__sync_fetch_and_add_1:
831   case Builtin::BI__sync_fetch_and_add_2:
832   case Builtin::BI__sync_fetch_and_add_4:
833   case Builtin::BI__sync_fetch_and_add_8:
834   case Builtin::BI__sync_fetch_and_add_16:
835   case Builtin::BI__sync_fetch_and_sub:
836   case Builtin::BI__sync_fetch_and_sub_1:
837   case Builtin::BI__sync_fetch_and_sub_2:
838   case Builtin::BI__sync_fetch_and_sub_4:
839   case Builtin::BI__sync_fetch_and_sub_8:
840   case Builtin::BI__sync_fetch_and_sub_16:
841   case Builtin::BI__sync_fetch_and_or:
842   case Builtin::BI__sync_fetch_and_or_1:
843   case Builtin::BI__sync_fetch_and_or_2:
844   case Builtin::BI__sync_fetch_and_or_4:
845   case Builtin::BI__sync_fetch_and_or_8:
846   case Builtin::BI__sync_fetch_and_or_16:
847   case Builtin::BI__sync_fetch_and_and:
848   case Builtin::BI__sync_fetch_and_and_1:
849   case Builtin::BI__sync_fetch_and_and_2:
850   case Builtin::BI__sync_fetch_and_and_4:
851   case Builtin::BI__sync_fetch_and_and_8:
852   case Builtin::BI__sync_fetch_and_and_16:
853   case Builtin::BI__sync_fetch_and_xor:
854   case Builtin::BI__sync_fetch_and_xor_1:
855   case Builtin::BI__sync_fetch_and_xor_2:
856   case Builtin::BI__sync_fetch_and_xor_4:
857   case Builtin::BI__sync_fetch_and_xor_8:
858   case Builtin::BI__sync_fetch_and_xor_16:
859   case Builtin::BI__sync_fetch_and_nand:
860   case Builtin::BI__sync_fetch_and_nand_1:
861   case Builtin::BI__sync_fetch_and_nand_2:
862   case Builtin::BI__sync_fetch_and_nand_4:
863   case Builtin::BI__sync_fetch_and_nand_8:
864   case Builtin::BI__sync_fetch_and_nand_16:
865   case Builtin::BI__sync_add_and_fetch:
866   case Builtin::BI__sync_add_and_fetch_1:
867   case Builtin::BI__sync_add_and_fetch_2:
868   case Builtin::BI__sync_add_and_fetch_4:
869   case Builtin::BI__sync_add_and_fetch_8:
870   case Builtin::BI__sync_add_and_fetch_16:
871   case Builtin::BI__sync_sub_and_fetch:
872   case Builtin::BI__sync_sub_and_fetch_1:
873   case Builtin::BI__sync_sub_and_fetch_2:
874   case Builtin::BI__sync_sub_and_fetch_4:
875   case Builtin::BI__sync_sub_and_fetch_8:
876   case Builtin::BI__sync_sub_and_fetch_16:
877   case Builtin::BI__sync_and_and_fetch:
878   case Builtin::BI__sync_and_and_fetch_1:
879   case Builtin::BI__sync_and_and_fetch_2:
880   case Builtin::BI__sync_and_and_fetch_4:
881   case Builtin::BI__sync_and_and_fetch_8:
882   case Builtin::BI__sync_and_and_fetch_16:
883   case Builtin::BI__sync_or_and_fetch:
884   case Builtin::BI__sync_or_and_fetch_1:
885   case Builtin::BI__sync_or_and_fetch_2:
886   case Builtin::BI__sync_or_and_fetch_4:
887   case Builtin::BI__sync_or_and_fetch_8:
888   case Builtin::BI__sync_or_and_fetch_16:
889   case Builtin::BI__sync_xor_and_fetch:
890   case Builtin::BI__sync_xor_and_fetch_1:
891   case Builtin::BI__sync_xor_and_fetch_2:
892   case Builtin::BI__sync_xor_and_fetch_4:
893   case Builtin::BI__sync_xor_and_fetch_8:
894   case Builtin::BI__sync_xor_and_fetch_16:
895   case Builtin::BI__sync_nand_and_fetch:
896   case Builtin::BI__sync_nand_and_fetch_1:
897   case Builtin::BI__sync_nand_and_fetch_2:
898   case Builtin::BI__sync_nand_and_fetch_4:
899   case Builtin::BI__sync_nand_and_fetch_8:
900   case Builtin::BI__sync_nand_and_fetch_16:
901   case Builtin::BI__sync_val_compare_and_swap:
902   case Builtin::BI__sync_val_compare_and_swap_1:
903   case Builtin::BI__sync_val_compare_and_swap_2:
904   case Builtin::BI__sync_val_compare_and_swap_4:
905   case Builtin::BI__sync_val_compare_and_swap_8:
906   case Builtin::BI__sync_val_compare_and_swap_16:
907   case Builtin::BI__sync_bool_compare_and_swap:
908   case Builtin::BI__sync_bool_compare_and_swap_1:
909   case Builtin::BI__sync_bool_compare_and_swap_2:
910   case Builtin::BI__sync_bool_compare_and_swap_4:
911   case Builtin::BI__sync_bool_compare_and_swap_8:
912   case Builtin::BI__sync_bool_compare_and_swap_16:
913   case Builtin::BI__sync_lock_test_and_set:
914   case Builtin::BI__sync_lock_test_and_set_1:
915   case Builtin::BI__sync_lock_test_and_set_2:
916   case Builtin::BI__sync_lock_test_and_set_4:
917   case Builtin::BI__sync_lock_test_and_set_8:
918   case Builtin::BI__sync_lock_test_and_set_16:
919   case Builtin::BI__sync_lock_release:
920   case Builtin::BI__sync_lock_release_1:
921   case Builtin::BI__sync_lock_release_2:
922   case Builtin::BI__sync_lock_release_4:
923   case Builtin::BI__sync_lock_release_8:
924   case Builtin::BI__sync_lock_release_16:
925   case Builtin::BI__sync_swap:
926   case Builtin::BI__sync_swap_1:
927   case Builtin::BI__sync_swap_2:
928   case Builtin::BI__sync_swap_4:
929   case Builtin::BI__sync_swap_8:
930   case Builtin::BI__sync_swap_16:
931     return SemaBuiltinAtomicOverloaded(TheCallResult);
932   case Builtin::BI__builtin_nontemporal_load:
933   case Builtin::BI__builtin_nontemporal_store:
934     return SemaBuiltinNontemporalOverloaded(TheCallResult);
935 #define BUILTIN(ID, TYPE, ATTRS)
936 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
937   case Builtin::BI##ID: \
938     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
939 #include "clang/Basic/Builtins.def"
940   case Builtin::BI__builtin_annotation:
941     if (SemaBuiltinAnnotation(*this, TheCall))
942       return ExprError();
943     break;
944   case Builtin::BI__builtin_addressof:
945     if (SemaBuiltinAddressof(*this, TheCall))
946       return ExprError();
947     break;
948   case Builtin::BI__builtin_add_overflow:
949   case Builtin::BI__builtin_sub_overflow:
950   case Builtin::BI__builtin_mul_overflow:
951     if (SemaBuiltinOverflow(*this, TheCall))
952       return ExprError();
953     break;
954   case Builtin::BI__builtin_operator_new:
955   case Builtin::BI__builtin_operator_delete:
956     if (!getLangOpts().CPlusPlus) {
957       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
958         << (BuiltinID == Builtin::BI__builtin_operator_new
959                 ? "__builtin_operator_new"
960                 : "__builtin_operator_delete")
961         << "C++";
962       return ExprError();
963     }
964     // CodeGen assumes it can find the global new and delete to call,
965     // so ensure that they are declared.
966     DeclareGlobalNewDelete();
967     break;
968 
969   // check secure string manipulation functions where overflows
970   // are detectable at compile time
971   case Builtin::BI__builtin___memcpy_chk:
972   case Builtin::BI__builtin___memmove_chk:
973   case Builtin::BI__builtin___memset_chk:
974   case Builtin::BI__builtin___strlcat_chk:
975   case Builtin::BI__builtin___strlcpy_chk:
976   case Builtin::BI__builtin___strncat_chk:
977   case Builtin::BI__builtin___strncpy_chk:
978   case Builtin::BI__builtin___stpncpy_chk:
979     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
980     break;
981   case Builtin::BI__builtin___memccpy_chk:
982     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
983     break;
984   case Builtin::BI__builtin___snprintf_chk:
985   case Builtin::BI__builtin___vsnprintf_chk:
986     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
987     break;
988   case Builtin::BI__builtin_call_with_static_chain:
989     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
990       return ExprError();
991     break;
992   case Builtin::BI__exception_code:
993   case Builtin::BI_exception_code:
994     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
995                                  diag::err_seh___except_block))
996       return ExprError();
997     break;
998   case Builtin::BI__exception_info:
999   case Builtin::BI_exception_info:
1000     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1001                                  diag::err_seh___except_filter))
1002       return ExprError();
1003     break;
1004   case Builtin::BI__GetExceptionInfo:
1005     if (checkArgCount(*this, TheCall, 1))
1006       return ExprError();
1007 
1008     if (CheckCXXThrowOperand(
1009             TheCall->getLocStart(),
1010             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1011             TheCall))
1012       return ExprError();
1013 
1014     TheCall->setType(Context.VoidPtrTy);
1015     break;
1016   // OpenCL v2.0, s6.13.16 - Pipe functions
1017   case Builtin::BIread_pipe:
1018   case Builtin::BIwrite_pipe:
1019     // Since those two functions are declared with var args, we need a semantic
1020     // check for the argument.
1021     if (SemaBuiltinRWPipe(*this, TheCall))
1022       return ExprError();
1023     TheCall->setType(Context.IntTy);
1024     break;
1025   case Builtin::BIreserve_read_pipe:
1026   case Builtin::BIreserve_write_pipe:
1027   case Builtin::BIwork_group_reserve_read_pipe:
1028   case Builtin::BIwork_group_reserve_write_pipe:
1029   case Builtin::BIsub_group_reserve_read_pipe:
1030   case Builtin::BIsub_group_reserve_write_pipe:
1031     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1032       return ExprError();
1033     // Since return type of reserve_read/write_pipe built-in function is
1034     // reserve_id_t, which is not defined in the builtin def file , we used int
1035     // as return type and need to override the return type of these functions.
1036     TheCall->setType(Context.OCLReserveIDTy);
1037     break;
1038   case Builtin::BIcommit_read_pipe:
1039   case Builtin::BIcommit_write_pipe:
1040   case Builtin::BIwork_group_commit_read_pipe:
1041   case Builtin::BIwork_group_commit_write_pipe:
1042   case Builtin::BIsub_group_commit_read_pipe:
1043   case Builtin::BIsub_group_commit_write_pipe:
1044     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1045       return ExprError();
1046     break;
1047   case Builtin::BIget_pipe_num_packets:
1048   case Builtin::BIget_pipe_max_packets:
1049     if (SemaBuiltinPipePackets(*this, TheCall))
1050       return ExprError();
1051     TheCall->setType(Context.UnsignedIntTy);
1052     break;
1053   case Builtin::BIto_global:
1054   case Builtin::BIto_local:
1055   case Builtin::BIto_private:
1056     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1057       return ExprError();
1058     break;
1059   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1060   case Builtin::BIenqueue_kernel:
1061     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1062       return ExprError();
1063     break;
1064   case Builtin::BIget_kernel_work_group_size:
1065   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1066     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1067       return ExprError();
1068   }
1069 
1070   // Since the target specific builtins for each arch overlap, only check those
1071   // of the arch we are compiling for.
1072   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1073     switch (Context.getTargetInfo().getTriple().getArch()) {
1074       case llvm::Triple::arm:
1075       case llvm::Triple::armeb:
1076       case llvm::Triple::thumb:
1077       case llvm::Triple::thumbeb:
1078         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1079           return ExprError();
1080         break;
1081       case llvm::Triple::aarch64:
1082       case llvm::Triple::aarch64_be:
1083         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1084           return ExprError();
1085         break;
1086       case llvm::Triple::mips:
1087       case llvm::Triple::mipsel:
1088       case llvm::Triple::mips64:
1089       case llvm::Triple::mips64el:
1090         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1091           return ExprError();
1092         break;
1093       case llvm::Triple::systemz:
1094         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1095           return ExprError();
1096         break;
1097       case llvm::Triple::x86:
1098       case llvm::Triple::x86_64:
1099         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1100           return ExprError();
1101         break;
1102       case llvm::Triple::ppc:
1103       case llvm::Triple::ppc64:
1104       case llvm::Triple::ppc64le:
1105         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1106           return ExprError();
1107         break;
1108       default:
1109         break;
1110     }
1111   }
1112 
1113   return TheCallResult;
1114 }
1115 
1116 // Get the valid immediate range for the specified NEON type code.
1117 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1118   NeonTypeFlags Type(t);
1119   int IsQuad = ForceQuad ? true : Type.isQuad();
1120   switch (Type.getEltType()) {
1121   case NeonTypeFlags::Int8:
1122   case NeonTypeFlags::Poly8:
1123     return shift ? 7 : (8 << IsQuad) - 1;
1124   case NeonTypeFlags::Int16:
1125   case NeonTypeFlags::Poly16:
1126     return shift ? 15 : (4 << IsQuad) - 1;
1127   case NeonTypeFlags::Int32:
1128     return shift ? 31 : (2 << IsQuad) - 1;
1129   case NeonTypeFlags::Int64:
1130   case NeonTypeFlags::Poly64:
1131     return shift ? 63 : (1 << IsQuad) - 1;
1132   case NeonTypeFlags::Poly128:
1133     return shift ? 127 : (1 << IsQuad) - 1;
1134   case NeonTypeFlags::Float16:
1135     assert(!shift && "cannot shift float types!");
1136     return (4 << IsQuad) - 1;
1137   case NeonTypeFlags::Float32:
1138     assert(!shift && "cannot shift float types!");
1139     return (2 << IsQuad) - 1;
1140   case NeonTypeFlags::Float64:
1141     assert(!shift && "cannot shift float types!");
1142     return (1 << IsQuad) - 1;
1143   }
1144   llvm_unreachable("Invalid NeonTypeFlag!");
1145 }
1146 
1147 /// getNeonEltType - Return the QualType corresponding to the elements of
1148 /// the vector type specified by the NeonTypeFlags.  This is used to check
1149 /// the pointer arguments for Neon load/store intrinsics.
1150 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1151                                bool IsPolyUnsigned, bool IsInt64Long) {
1152   switch (Flags.getEltType()) {
1153   case NeonTypeFlags::Int8:
1154     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1155   case NeonTypeFlags::Int16:
1156     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1157   case NeonTypeFlags::Int32:
1158     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1159   case NeonTypeFlags::Int64:
1160     if (IsInt64Long)
1161       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1162     else
1163       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1164                                 : Context.LongLongTy;
1165   case NeonTypeFlags::Poly8:
1166     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1167   case NeonTypeFlags::Poly16:
1168     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1169   case NeonTypeFlags::Poly64:
1170     if (IsInt64Long)
1171       return Context.UnsignedLongTy;
1172     else
1173       return Context.UnsignedLongLongTy;
1174   case NeonTypeFlags::Poly128:
1175     break;
1176   case NeonTypeFlags::Float16:
1177     return Context.HalfTy;
1178   case NeonTypeFlags::Float32:
1179     return Context.FloatTy;
1180   case NeonTypeFlags::Float64:
1181     return Context.DoubleTy;
1182   }
1183   llvm_unreachable("Invalid NeonTypeFlag!");
1184 }
1185 
1186 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1187   llvm::APSInt Result;
1188   uint64_t mask = 0;
1189   unsigned TV = 0;
1190   int PtrArgNum = -1;
1191   bool HasConstPtr = false;
1192   switch (BuiltinID) {
1193 #define GET_NEON_OVERLOAD_CHECK
1194 #include "clang/Basic/arm_neon.inc"
1195 #undef GET_NEON_OVERLOAD_CHECK
1196   }
1197 
1198   // For NEON intrinsics which are overloaded on vector element type, validate
1199   // the immediate which specifies which variant to emit.
1200   unsigned ImmArg = TheCall->getNumArgs()-1;
1201   if (mask) {
1202     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1203       return true;
1204 
1205     TV = Result.getLimitedValue(64);
1206     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1207       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1208         << TheCall->getArg(ImmArg)->getSourceRange();
1209   }
1210 
1211   if (PtrArgNum >= 0) {
1212     // Check that pointer arguments have the specified type.
1213     Expr *Arg = TheCall->getArg(PtrArgNum);
1214     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1215       Arg = ICE->getSubExpr();
1216     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1217     QualType RHSTy = RHS.get()->getType();
1218 
1219     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1220     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
1221     bool IsInt64Long =
1222         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1223     QualType EltTy =
1224         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1225     if (HasConstPtr)
1226       EltTy = EltTy.withConst();
1227     QualType LHSTy = Context.getPointerType(EltTy);
1228     AssignConvertType ConvTy;
1229     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1230     if (RHS.isInvalid())
1231       return true;
1232     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1233                                  RHS.get(), AA_Assigning))
1234       return true;
1235   }
1236 
1237   // For NEON intrinsics which take an immediate value as part of the
1238   // instruction, range check them here.
1239   unsigned i = 0, l = 0, u = 0;
1240   switch (BuiltinID) {
1241   default:
1242     return false;
1243 #define GET_NEON_IMMEDIATE_CHECK
1244 #include "clang/Basic/arm_neon.inc"
1245 #undef GET_NEON_IMMEDIATE_CHECK
1246   }
1247 
1248   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1249 }
1250 
1251 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1252                                         unsigned MaxWidth) {
1253   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1254           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1255           BuiltinID == ARM::BI__builtin_arm_strex ||
1256           BuiltinID == ARM::BI__builtin_arm_stlex ||
1257           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1258           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1259           BuiltinID == AArch64::BI__builtin_arm_strex ||
1260           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1261          "unexpected ARM builtin");
1262   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1263                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1264                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1265                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1266 
1267   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1268 
1269   // Ensure that we have the proper number of arguments.
1270   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1271     return true;
1272 
1273   // Inspect the pointer argument of the atomic builtin.  This should always be
1274   // a pointer type, whose element is an integral scalar or pointer type.
1275   // Because it is a pointer type, we don't have to worry about any implicit
1276   // casts here.
1277   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1278   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1279   if (PointerArgRes.isInvalid())
1280     return true;
1281   PointerArg = PointerArgRes.get();
1282 
1283   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1284   if (!pointerType) {
1285     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1286       << PointerArg->getType() << PointerArg->getSourceRange();
1287     return true;
1288   }
1289 
1290   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1291   // task is to insert the appropriate casts into the AST. First work out just
1292   // what the appropriate type is.
1293   QualType ValType = pointerType->getPointeeType();
1294   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1295   if (IsLdrex)
1296     AddrType.addConst();
1297 
1298   // Issue a warning if the cast is dodgy.
1299   CastKind CastNeeded = CK_NoOp;
1300   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1301     CastNeeded = CK_BitCast;
1302     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1303       << PointerArg->getType()
1304       << Context.getPointerType(AddrType)
1305       << AA_Passing << PointerArg->getSourceRange();
1306   }
1307 
1308   // Finally, do the cast and replace the argument with the corrected version.
1309   AddrType = Context.getPointerType(AddrType);
1310   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1311   if (PointerArgRes.isInvalid())
1312     return true;
1313   PointerArg = PointerArgRes.get();
1314 
1315   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1316 
1317   // In general, we allow ints, floats and pointers to be loaded and stored.
1318   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1319       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1320     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1321       << PointerArg->getType() << PointerArg->getSourceRange();
1322     return true;
1323   }
1324 
1325   // But ARM doesn't have instructions to deal with 128-bit versions.
1326   if (Context.getTypeSize(ValType) > MaxWidth) {
1327     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1328     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1329       << PointerArg->getType() << PointerArg->getSourceRange();
1330     return true;
1331   }
1332 
1333   switch (ValType.getObjCLifetime()) {
1334   case Qualifiers::OCL_None:
1335   case Qualifiers::OCL_ExplicitNone:
1336     // okay
1337     break;
1338 
1339   case Qualifiers::OCL_Weak:
1340   case Qualifiers::OCL_Strong:
1341   case Qualifiers::OCL_Autoreleasing:
1342     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1343       << ValType << PointerArg->getSourceRange();
1344     return true;
1345   }
1346 
1347   if (IsLdrex) {
1348     TheCall->setType(ValType);
1349     return false;
1350   }
1351 
1352   // Initialize the argument to be stored.
1353   ExprResult ValArg = TheCall->getArg(0);
1354   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1355       Context, ValType, /*consume*/ false);
1356   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1357   if (ValArg.isInvalid())
1358     return true;
1359   TheCall->setArg(0, ValArg.get());
1360 
1361   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1362   // but the custom checker bypasses all default analysis.
1363   TheCall->setType(Context.IntTy);
1364   return false;
1365 }
1366 
1367 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1368   llvm::APSInt Result;
1369 
1370   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1371       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1372       BuiltinID == ARM::BI__builtin_arm_strex ||
1373       BuiltinID == ARM::BI__builtin_arm_stlex) {
1374     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1375   }
1376 
1377   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1378     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1379       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1380   }
1381 
1382   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1383       BuiltinID == ARM::BI__builtin_arm_wsr64)
1384     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1385 
1386   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1387       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1388       BuiltinID == ARM::BI__builtin_arm_wsr ||
1389       BuiltinID == ARM::BI__builtin_arm_wsrp)
1390     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1391 
1392   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1393     return true;
1394 
1395   // For intrinsics which take an immediate value as part of the instruction,
1396   // range check them here.
1397   unsigned i = 0, l = 0, u = 0;
1398   switch (BuiltinID) {
1399   default: return false;
1400   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1401   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1402   case ARM::BI__builtin_arm_vcvtr_f:
1403   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1404   case ARM::BI__builtin_arm_dmb:
1405   case ARM::BI__builtin_arm_dsb:
1406   case ARM::BI__builtin_arm_isb:
1407   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1408   }
1409 
1410   // FIXME: VFP Intrinsics should error if VFP not present.
1411   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1412 }
1413 
1414 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1415                                          CallExpr *TheCall) {
1416   llvm::APSInt Result;
1417 
1418   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1419       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1420       BuiltinID == AArch64::BI__builtin_arm_strex ||
1421       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1422     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1423   }
1424 
1425   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1426     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1427       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1428       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1429       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1430   }
1431 
1432   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1433       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1434     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1435 
1436   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1437       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1438       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1439       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1440     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1441 
1442   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1443     return true;
1444 
1445   // For intrinsics which take an immediate value as part of the instruction,
1446   // range check them here.
1447   unsigned i = 0, l = 0, u = 0;
1448   switch (BuiltinID) {
1449   default: return false;
1450   case AArch64::BI__builtin_arm_dmb:
1451   case AArch64::BI__builtin_arm_dsb:
1452   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1453   }
1454 
1455   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1456 }
1457 
1458 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1459   unsigned i = 0, l = 0, u = 0;
1460   switch (BuiltinID) {
1461   default: return false;
1462   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1463   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1464   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1465   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1466   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1467   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1468   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1469   }
1470 
1471   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1472 }
1473 
1474 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1475   unsigned i = 0, l = 0, u = 0;
1476   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1477                       BuiltinID == PPC::BI__builtin_divdeu ||
1478                       BuiltinID == PPC::BI__builtin_bpermd;
1479   bool IsTarget64Bit = Context.getTargetInfo()
1480                               .getTypeWidth(Context
1481                                             .getTargetInfo()
1482                                             .getIntPtrType()) == 64;
1483   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1484                        BuiltinID == PPC::BI__builtin_divweu ||
1485                        BuiltinID == PPC::BI__builtin_divde ||
1486                        BuiltinID == PPC::BI__builtin_divdeu;
1487 
1488   if (Is64BitBltin && !IsTarget64Bit)
1489       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1490              << TheCall->getSourceRange();
1491 
1492   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1493       (BuiltinID == PPC::BI__builtin_bpermd &&
1494        !Context.getTargetInfo().hasFeature("bpermd")))
1495     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1496            << TheCall->getSourceRange();
1497 
1498   switch (BuiltinID) {
1499   default: return false;
1500   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1501   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1502     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1503            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1504   case PPC::BI__builtin_tbegin:
1505   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1506   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1507   case PPC::BI__builtin_tabortwc:
1508   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1509   case PPC::BI__builtin_tabortwci:
1510   case PPC::BI__builtin_tabortdci:
1511     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1512            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1513   }
1514   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1515 }
1516 
1517 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1518                                            CallExpr *TheCall) {
1519   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1520     Expr *Arg = TheCall->getArg(0);
1521     llvm::APSInt AbortCode(32);
1522     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1523         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1524       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1525              << Arg->getSourceRange();
1526   }
1527 
1528   // For intrinsics which take an immediate value as part of the instruction,
1529   // range check them here.
1530   unsigned i = 0, l = 0, u = 0;
1531   switch (BuiltinID) {
1532   default: return false;
1533   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1534   case SystemZ::BI__builtin_s390_verimb:
1535   case SystemZ::BI__builtin_s390_verimh:
1536   case SystemZ::BI__builtin_s390_verimf:
1537   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1538   case SystemZ::BI__builtin_s390_vfaeb:
1539   case SystemZ::BI__builtin_s390_vfaeh:
1540   case SystemZ::BI__builtin_s390_vfaef:
1541   case SystemZ::BI__builtin_s390_vfaebs:
1542   case SystemZ::BI__builtin_s390_vfaehs:
1543   case SystemZ::BI__builtin_s390_vfaefs:
1544   case SystemZ::BI__builtin_s390_vfaezb:
1545   case SystemZ::BI__builtin_s390_vfaezh:
1546   case SystemZ::BI__builtin_s390_vfaezf:
1547   case SystemZ::BI__builtin_s390_vfaezbs:
1548   case SystemZ::BI__builtin_s390_vfaezhs:
1549   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1550   case SystemZ::BI__builtin_s390_vfidb:
1551     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1552            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1553   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1554   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1555   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1556   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1557   case SystemZ::BI__builtin_s390_vstrcb:
1558   case SystemZ::BI__builtin_s390_vstrch:
1559   case SystemZ::BI__builtin_s390_vstrcf:
1560   case SystemZ::BI__builtin_s390_vstrczb:
1561   case SystemZ::BI__builtin_s390_vstrczh:
1562   case SystemZ::BI__builtin_s390_vstrczf:
1563   case SystemZ::BI__builtin_s390_vstrcbs:
1564   case SystemZ::BI__builtin_s390_vstrchs:
1565   case SystemZ::BI__builtin_s390_vstrcfs:
1566   case SystemZ::BI__builtin_s390_vstrczbs:
1567   case SystemZ::BI__builtin_s390_vstrczhs:
1568   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1569   }
1570   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1571 }
1572 
1573 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1574 /// This checks that the target supports __builtin_cpu_supports and
1575 /// that the string argument is constant and valid.
1576 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1577   Expr *Arg = TheCall->getArg(0);
1578 
1579   // Check if the argument is a string literal.
1580   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1581     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1582            << Arg->getSourceRange();
1583 
1584   // Check the contents of the string.
1585   StringRef Feature =
1586       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1587   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1588     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1589            << Arg->getSourceRange();
1590   return false;
1591 }
1592 
1593 static bool isX86_64Builtin(unsigned BuiltinID) {
1594   // These builtins only work on x86-64 targets.
1595   switch (BuiltinID) {
1596   case X86::BI__builtin_ia32_addcarryx_u64:
1597   case X86::BI__builtin_ia32_addcarry_u64:
1598   case X86::BI__builtin_ia32_subborrow_u64:
1599   case X86::BI__builtin_ia32_readeflags_u64:
1600   case X86::BI__builtin_ia32_writeeflags_u64:
1601   case X86::BI__builtin_ia32_bextr_u64:
1602   case X86::BI__builtin_ia32_bextri_u64:
1603   case X86::BI__builtin_ia32_bzhi_di:
1604   case X86::BI__builtin_ia32_pdep_di:
1605   case X86::BI__builtin_ia32_pext_di:
1606   case X86::BI__builtin_ia32_crc32di:
1607   case X86::BI__builtin_ia32_fxsave64:
1608   case X86::BI__builtin_ia32_fxrstor64:
1609   case X86::BI__builtin_ia32_xsave64:
1610   case X86::BI__builtin_ia32_xrstor64:
1611   case X86::BI__builtin_ia32_xsaveopt64:
1612   case X86::BI__builtin_ia32_xrstors64:
1613   case X86::BI__builtin_ia32_xsavec64:
1614   case X86::BI__builtin_ia32_xsaves64:
1615   case X86::BI__builtin_ia32_rdfsbase64:
1616   case X86::BI__builtin_ia32_rdgsbase64:
1617   case X86::BI__builtin_ia32_wrfsbase64:
1618   case X86::BI__builtin_ia32_wrgsbase64:
1619   case X86::BI__builtin_ia32_pbroadcastq512_gpr_mask:
1620   case X86::BI__builtin_ia32_pbroadcastq256_gpr_mask:
1621   case X86::BI__builtin_ia32_pbroadcastq128_gpr_mask:
1622   case X86::BI__builtin_ia32_vcvtsd2si64:
1623   case X86::BI__builtin_ia32_vcvtsd2usi64:
1624   case X86::BI__builtin_ia32_vcvtss2si64:
1625   case X86::BI__builtin_ia32_vcvtss2usi64:
1626   case X86::BI__builtin_ia32_vcvttsd2si64:
1627   case X86::BI__builtin_ia32_vcvttsd2usi64:
1628   case X86::BI__builtin_ia32_vcvttss2si64:
1629   case X86::BI__builtin_ia32_vcvttss2usi64:
1630   case X86::BI__builtin_ia32_cvtss2si64:
1631   case X86::BI__builtin_ia32_cvttss2si64:
1632   case X86::BI__builtin_ia32_cvtsd2si64:
1633   case X86::BI__builtin_ia32_cvttsd2si64:
1634   case X86::BI__builtin_ia32_cvtsi2sd64:
1635   case X86::BI__builtin_ia32_cvtsi2ss64:
1636   case X86::BI__builtin_ia32_cvtusi2sd64:
1637   case X86::BI__builtin_ia32_cvtusi2ss64:
1638   case X86::BI__builtin_ia32_rdseed64_step:
1639     return true;
1640   }
1641 
1642   return false;
1643 }
1644 
1645 // Check if the rounding mode is legal.
1646 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1647   // Indicates if this instruction has rounding control or just SAE.
1648   bool HasRC = false;
1649 
1650   unsigned ArgNum = 0;
1651   switch (BuiltinID) {
1652   default:
1653     return false;
1654   case X86::BI__builtin_ia32_vcvttsd2si32:
1655   case X86::BI__builtin_ia32_vcvttsd2si64:
1656   case X86::BI__builtin_ia32_vcvttsd2usi32:
1657   case X86::BI__builtin_ia32_vcvttsd2usi64:
1658   case X86::BI__builtin_ia32_vcvttss2si32:
1659   case X86::BI__builtin_ia32_vcvttss2si64:
1660   case X86::BI__builtin_ia32_vcvttss2usi32:
1661   case X86::BI__builtin_ia32_vcvttss2usi64:
1662     ArgNum = 1;
1663     break;
1664   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1665   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1666   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1667   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1668   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1669   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1670   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1671   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1672   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1673   case X86::BI__builtin_ia32_exp2pd_mask:
1674   case X86::BI__builtin_ia32_exp2ps_mask:
1675   case X86::BI__builtin_ia32_getexppd512_mask:
1676   case X86::BI__builtin_ia32_getexpps512_mask:
1677   case X86::BI__builtin_ia32_rcp28pd_mask:
1678   case X86::BI__builtin_ia32_rcp28ps_mask:
1679   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1680   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1681   case X86::BI__builtin_ia32_vcomisd:
1682   case X86::BI__builtin_ia32_vcomiss:
1683   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1684     ArgNum = 3;
1685     break;
1686   case X86::BI__builtin_ia32_cmppd512_mask:
1687   case X86::BI__builtin_ia32_cmpps512_mask:
1688   case X86::BI__builtin_ia32_cmpsd_mask:
1689   case X86::BI__builtin_ia32_cmpss_mask:
1690   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1691   case X86::BI__builtin_ia32_getexpss128_round_mask:
1692   case X86::BI__builtin_ia32_rcp28sd_round_mask:
1693   case X86::BI__builtin_ia32_rcp28ss_round_mask:
1694   case X86::BI__builtin_ia32_reducepd512_mask:
1695   case X86::BI__builtin_ia32_reduceps512_mask:
1696   case X86::BI__builtin_ia32_rndscalepd_mask:
1697   case X86::BI__builtin_ia32_rndscaleps_mask:
1698   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1699   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1700     ArgNum = 4;
1701     break;
1702   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1703   case X86::BI__builtin_ia32_fixupimmps512_mask:
1704   case X86::BI__builtin_ia32_fixupimmsd_mask:
1705   case X86::BI__builtin_ia32_fixupimmss_mask:
1706   case X86::BI__builtin_ia32_rangepd512_mask:
1707   case X86::BI__builtin_ia32_rangeps512_mask:
1708   case X86::BI__builtin_ia32_rangesd128_round_mask:
1709   case X86::BI__builtin_ia32_rangess128_round_mask:
1710   case X86::BI__builtin_ia32_reducesd_mask:
1711   case X86::BI__builtin_ia32_reducess_mask:
1712   case X86::BI__builtin_ia32_rndscalesd_round_mask:
1713   case X86::BI__builtin_ia32_rndscaless_round_mask:
1714     ArgNum = 5;
1715     break;
1716   }
1717 
1718   llvm::APSInt Result;
1719 
1720   // We can't check the value of a dependent argument.
1721   Expr *Arg = TheCall->getArg(ArgNum);
1722   if (Arg->isTypeDependent() || Arg->isValueDependent())
1723     return false;
1724 
1725   // Check constant-ness first.
1726   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1727     return true;
1728 
1729   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1730   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1731   // combined with ROUND_NO_EXC.
1732   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1733       Result == 8/*ROUND_NO_EXC*/ ||
1734       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1735     return false;
1736 
1737   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1738     << Arg->getSourceRange();
1739 }
1740 
1741 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1742   if (BuiltinID == X86::BI__builtin_cpu_supports)
1743     return SemaBuiltinCpuSupports(*this, TheCall);
1744 
1745   if (BuiltinID == X86::BI__builtin_ms_va_start)
1746     return SemaBuiltinMSVAStart(TheCall);
1747 
1748   // Check for 64-bit only builtins on a 32-bit target.
1749   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
1750   if (TT.getArch() != llvm::Triple::x86_64 && isX86_64Builtin(BuiltinID))
1751     return Diag(TheCall->getCallee()->getLocStart(),
1752                 diag::err_x86_builtin_32_bit_tgt);
1753 
1754   // If the intrinsic has rounding or SAE make sure its valid.
1755   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
1756     return true;
1757 
1758   // For intrinsics which take an immediate value as part of the instruction,
1759   // range check them here.
1760   int i = 0, l = 0, u = 0;
1761   switch (BuiltinID) {
1762   default:
1763     return false;
1764   case X86::BI__builtin_ia32_extractf64x4_mask:
1765   case X86::BI__builtin_ia32_extracti64x4_mask:
1766   case X86::BI__builtin_ia32_extractf32x8_mask:
1767   case X86::BI__builtin_ia32_extracti32x8_mask:
1768   case X86::BI__builtin_ia32_extractf64x2_256_mask:
1769   case X86::BI__builtin_ia32_extracti64x2_256_mask:
1770   case X86::BI__builtin_ia32_extractf32x4_256_mask:
1771   case X86::BI__builtin_ia32_extracti32x4_256_mask:
1772     i = 1; l = 0; u = 1;
1773     break;
1774   case X86::BI_mm_prefetch:
1775   case X86::BI__builtin_ia32_extractf32x4_mask:
1776   case X86::BI__builtin_ia32_extracti32x4_mask:
1777   case X86::BI__builtin_ia32_extractf64x2_512_mask:
1778   case X86::BI__builtin_ia32_extracti64x2_512_mask:
1779     i = 1; l = 0; u = 3;
1780     break;
1781   case X86::BI__builtin_ia32_insertf32x8_mask:
1782   case X86::BI__builtin_ia32_inserti32x8_mask:
1783   case X86::BI__builtin_ia32_insertf64x4_mask:
1784   case X86::BI__builtin_ia32_inserti64x4_mask:
1785   case X86::BI__builtin_ia32_insertf64x2_256_mask:
1786   case X86::BI__builtin_ia32_inserti64x2_256_mask:
1787   case X86::BI__builtin_ia32_insertf32x4_256_mask:
1788   case X86::BI__builtin_ia32_inserti32x4_256_mask:
1789     i = 2; l = 0; u = 1;
1790     break;
1791   case X86::BI__builtin_ia32_sha1rnds4:
1792   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1793   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1794   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1795   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
1796   case X86::BI__builtin_ia32_insertf64x2_512_mask:
1797   case X86::BI__builtin_ia32_inserti64x2_512_mask:
1798   case X86::BI__builtin_ia32_insertf32x4_mask:
1799   case X86::BI__builtin_ia32_inserti32x4_mask:
1800     i = 2; l = 0; u = 3;
1801     break;
1802   case X86::BI__builtin_ia32_vpermil2pd:
1803   case X86::BI__builtin_ia32_vpermil2pd256:
1804   case X86::BI__builtin_ia32_vpermil2ps:
1805   case X86::BI__builtin_ia32_vpermil2ps256:
1806     i = 3; l = 0; u = 3;
1807     break;
1808   case X86::BI__builtin_ia32_cmpb128_mask:
1809   case X86::BI__builtin_ia32_cmpw128_mask:
1810   case X86::BI__builtin_ia32_cmpd128_mask:
1811   case X86::BI__builtin_ia32_cmpq128_mask:
1812   case X86::BI__builtin_ia32_cmpb256_mask:
1813   case X86::BI__builtin_ia32_cmpw256_mask:
1814   case X86::BI__builtin_ia32_cmpd256_mask:
1815   case X86::BI__builtin_ia32_cmpq256_mask:
1816   case X86::BI__builtin_ia32_cmpb512_mask:
1817   case X86::BI__builtin_ia32_cmpw512_mask:
1818   case X86::BI__builtin_ia32_cmpd512_mask:
1819   case X86::BI__builtin_ia32_cmpq512_mask:
1820   case X86::BI__builtin_ia32_ucmpb128_mask:
1821   case X86::BI__builtin_ia32_ucmpw128_mask:
1822   case X86::BI__builtin_ia32_ucmpd128_mask:
1823   case X86::BI__builtin_ia32_ucmpq128_mask:
1824   case X86::BI__builtin_ia32_ucmpb256_mask:
1825   case X86::BI__builtin_ia32_ucmpw256_mask:
1826   case X86::BI__builtin_ia32_ucmpd256_mask:
1827   case X86::BI__builtin_ia32_ucmpq256_mask:
1828   case X86::BI__builtin_ia32_ucmpb512_mask:
1829   case X86::BI__builtin_ia32_ucmpw512_mask:
1830   case X86::BI__builtin_ia32_ucmpd512_mask:
1831   case X86::BI__builtin_ia32_ucmpq512_mask:
1832   case X86::BI__builtin_ia32_vpcomub:
1833   case X86::BI__builtin_ia32_vpcomuw:
1834   case X86::BI__builtin_ia32_vpcomud:
1835   case X86::BI__builtin_ia32_vpcomuq:
1836   case X86::BI__builtin_ia32_vpcomb:
1837   case X86::BI__builtin_ia32_vpcomw:
1838   case X86::BI__builtin_ia32_vpcomd:
1839   case X86::BI__builtin_ia32_vpcomq:
1840     i = 2; l = 0; u = 7;
1841     break;
1842   case X86::BI__builtin_ia32_roundps:
1843   case X86::BI__builtin_ia32_roundpd:
1844   case X86::BI__builtin_ia32_roundps256:
1845   case X86::BI__builtin_ia32_roundpd256:
1846     i = 1; l = 0; u = 15;
1847     break;
1848   case X86::BI__builtin_ia32_roundss:
1849   case X86::BI__builtin_ia32_roundsd:
1850   case X86::BI__builtin_ia32_rangepd128_mask:
1851   case X86::BI__builtin_ia32_rangepd256_mask:
1852   case X86::BI__builtin_ia32_rangepd512_mask:
1853   case X86::BI__builtin_ia32_rangeps128_mask:
1854   case X86::BI__builtin_ia32_rangeps256_mask:
1855   case X86::BI__builtin_ia32_rangeps512_mask:
1856   case X86::BI__builtin_ia32_getmantsd_round_mask:
1857   case X86::BI__builtin_ia32_getmantss_round_mask:
1858     i = 2; l = 0; u = 15;
1859     break;
1860   case X86::BI__builtin_ia32_cmpps:
1861   case X86::BI__builtin_ia32_cmpss:
1862   case X86::BI__builtin_ia32_cmppd:
1863   case X86::BI__builtin_ia32_cmpsd:
1864   case X86::BI__builtin_ia32_cmpps256:
1865   case X86::BI__builtin_ia32_cmppd256:
1866   case X86::BI__builtin_ia32_cmpps128_mask:
1867   case X86::BI__builtin_ia32_cmppd128_mask:
1868   case X86::BI__builtin_ia32_cmpps256_mask:
1869   case X86::BI__builtin_ia32_cmppd256_mask:
1870   case X86::BI__builtin_ia32_cmpps512_mask:
1871   case X86::BI__builtin_ia32_cmppd512_mask:
1872   case X86::BI__builtin_ia32_cmpsd_mask:
1873   case X86::BI__builtin_ia32_cmpss_mask:
1874     i = 2; l = 0; u = 31;
1875     break;
1876   case X86::BI__builtin_ia32_xabort:
1877     i = 0; l = -128; u = 255;
1878     break;
1879   case X86::BI__builtin_ia32_pshufw:
1880   case X86::BI__builtin_ia32_aeskeygenassist128:
1881     i = 1; l = -128; u = 255;
1882     break;
1883   case X86::BI__builtin_ia32_vcvtps2ph:
1884   case X86::BI__builtin_ia32_vcvtps2ph256:
1885   case X86::BI__builtin_ia32_rndscaleps_128_mask:
1886   case X86::BI__builtin_ia32_rndscalepd_128_mask:
1887   case X86::BI__builtin_ia32_rndscaleps_256_mask:
1888   case X86::BI__builtin_ia32_rndscalepd_256_mask:
1889   case X86::BI__builtin_ia32_rndscaleps_mask:
1890   case X86::BI__builtin_ia32_rndscalepd_mask:
1891   case X86::BI__builtin_ia32_reducepd128_mask:
1892   case X86::BI__builtin_ia32_reducepd256_mask:
1893   case X86::BI__builtin_ia32_reducepd512_mask:
1894   case X86::BI__builtin_ia32_reduceps128_mask:
1895   case X86::BI__builtin_ia32_reduceps256_mask:
1896   case X86::BI__builtin_ia32_reduceps512_mask:
1897   case X86::BI__builtin_ia32_prold512_mask:
1898   case X86::BI__builtin_ia32_prolq512_mask:
1899   case X86::BI__builtin_ia32_prold128_mask:
1900   case X86::BI__builtin_ia32_prold256_mask:
1901   case X86::BI__builtin_ia32_prolq128_mask:
1902   case X86::BI__builtin_ia32_prolq256_mask:
1903   case X86::BI__builtin_ia32_prord128_mask:
1904   case X86::BI__builtin_ia32_prord256_mask:
1905   case X86::BI__builtin_ia32_prorq128_mask:
1906   case X86::BI__builtin_ia32_prorq256_mask:
1907   case X86::BI__builtin_ia32_psllwi512_mask:
1908   case X86::BI__builtin_ia32_psllwi128_mask:
1909   case X86::BI__builtin_ia32_psllwi256_mask:
1910   case X86::BI__builtin_ia32_psrldi128_mask:
1911   case X86::BI__builtin_ia32_psrldi256_mask:
1912   case X86::BI__builtin_ia32_psrldi512_mask:
1913   case X86::BI__builtin_ia32_psrlqi128_mask:
1914   case X86::BI__builtin_ia32_psrlqi256_mask:
1915   case X86::BI__builtin_ia32_psrlqi512_mask:
1916   case X86::BI__builtin_ia32_psrawi512_mask:
1917   case X86::BI__builtin_ia32_psrawi128_mask:
1918   case X86::BI__builtin_ia32_psrawi256_mask:
1919   case X86::BI__builtin_ia32_psrlwi512_mask:
1920   case X86::BI__builtin_ia32_psrlwi128_mask:
1921   case X86::BI__builtin_ia32_psrlwi256_mask:
1922   case X86::BI__builtin_ia32_psradi128_mask:
1923   case X86::BI__builtin_ia32_psradi256_mask:
1924   case X86::BI__builtin_ia32_psradi512_mask:
1925   case X86::BI__builtin_ia32_psraqi128_mask:
1926   case X86::BI__builtin_ia32_psraqi256_mask:
1927   case X86::BI__builtin_ia32_psraqi512_mask:
1928   case X86::BI__builtin_ia32_pslldi128_mask:
1929   case X86::BI__builtin_ia32_pslldi256_mask:
1930   case X86::BI__builtin_ia32_pslldi512_mask:
1931   case X86::BI__builtin_ia32_psllqi128_mask:
1932   case X86::BI__builtin_ia32_psllqi256_mask:
1933   case X86::BI__builtin_ia32_psllqi512_mask:
1934   case X86::BI__builtin_ia32_fpclasspd128_mask:
1935   case X86::BI__builtin_ia32_fpclasspd256_mask:
1936   case X86::BI__builtin_ia32_fpclassps128_mask:
1937   case X86::BI__builtin_ia32_fpclassps256_mask:
1938   case X86::BI__builtin_ia32_fpclassps512_mask:
1939   case X86::BI__builtin_ia32_fpclasspd512_mask:
1940   case X86::BI__builtin_ia32_fpclasssd_mask:
1941   case X86::BI__builtin_ia32_fpclassss_mask:
1942     i = 1; l = 0; u = 255;
1943     break;
1944   case X86::BI__builtin_ia32_palignr:
1945   case X86::BI__builtin_ia32_insertps128:
1946   case X86::BI__builtin_ia32_dpps:
1947   case X86::BI__builtin_ia32_dppd:
1948   case X86::BI__builtin_ia32_dpps256:
1949   case X86::BI__builtin_ia32_mpsadbw128:
1950   case X86::BI__builtin_ia32_mpsadbw256:
1951   case X86::BI__builtin_ia32_pcmpistrm128:
1952   case X86::BI__builtin_ia32_pcmpistri128:
1953   case X86::BI__builtin_ia32_pcmpistria128:
1954   case X86::BI__builtin_ia32_pcmpistric128:
1955   case X86::BI__builtin_ia32_pcmpistrio128:
1956   case X86::BI__builtin_ia32_pcmpistris128:
1957   case X86::BI__builtin_ia32_pcmpistriz128:
1958   case X86::BI__builtin_ia32_pclmulqdq128:
1959   case X86::BI__builtin_ia32_vperm2f128_pd256:
1960   case X86::BI__builtin_ia32_vperm2f128_ps256:
1961   case X86::BI__builtin_ia32_vperm2f128_si256:
1962   case X86::BI__builtin_ia32_permti256:
1963     i = 2; l = -128; u = 255;
1964     break;
1965   case X86::BI__builtin_ia32_palignr128:
1966   case X86::BI__builtin_ia32_palignr256:
1967   case X86::BI__builtin_ia32_palignr128_mask:
1968   case X86::BI__builtin_ia32_palignr256_mask:
1969   case X86::BI__builtin_ia32_palignr512_mask:
1970   case X86::BI__builtin_ia32_alignq512_mask:
1971   case X86::BI__builtin_ia32_alignd512_mask:
1972   case X86::BI__builtin_ia32_alignd128_mask:
1973   case X86::BI__builtin_ia32_alignd256_mask:
1974   case X86::BI__builtin_ia32_alignq128_mask:
1975   case X86::BI__builtin_ia32_alignq256_mask:
1976   case X86::BI__builtin_ia32_vcomisd:
1977   case X86::BI__builtin_ia32_vcomiss:
1978   case X86::BI__builtin_ia32_shuf_f32x4_mask:
1979   case X86::BI__builtin_ia32_shuf_f64x2_mask:
1980   case X86::BI__builtin_ia32_shuf_i32x4_mask:
1981   case X86::BI__builtin_ia32_shuf_i64x2_mask:
1982   case X86::BI__builtin_ia32_dbpsadbw128_mask:
1983   case X86::BI__builtin_ia32_dbpsadbw256_mask:
1984   case X86::BI__builtin_ia32_dbpsadbw512_mask:
1985     i = 2; l = 0; u = 255;
1986     break;
1987   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1988   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1989   case X86::BI__builtin_ia32_fixupimmps512_mask:
1990   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1991   case X86::BI__builtin_ia32_fixupimmsd_mask:
1992   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1993   case X86::BI__builtin_ia32_fixupimmss_mask:
1994   case X86::BI__builtin_ia32_fixupimmss_maskz:
1995   case X86::BI__builtin_ia32_fixupimmpd128_mask:
1996   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
1997   case X86::BI__builtin_ia32_fixupimmpd256_mask:
1998   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
1999   case X86::BI__builtin_ia32_fixupimmps128_mask:
2000   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2001   case X86::BI__builtin_ia32_fixupimmps256_mask:
2002   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2003   case X86::BI__builtin_ia32_pternlogd512_mask:
2004   case X86::BI__builtin_ia32_pternlogd512_maskz:
2005   case X86::BI__builtin_ia32_pternlogq512_mask:
2006   case X86::BI__builtin_ia32_pternlogq512_maskz:
2007   case X86::BI__builtin_ia32_pternlogd128_mask:
2008   case X86::BI__builtin_ia32_pternlogd128_maskz:
2009   case X86::BI__builtin_ia32_pternlogd256_mask:
2010   case X86::BI__builtin_ia32_pternlogd256_maskz:
2011   case X86::BI__builtin_ia32_pternlogq128_mask:
2012   case X86::BI__builtin_ia32_pternlogq128_maskz:
2013   case X86::BI__builtin_ia32_pternlogq256_mask:
2014   case X86::BI__builtin_ia32_pternlogq256_maskz:
2015     i = 3; l = 0; u = 255;
2016     break;
2017   case X86::BI__builtin_ia32_pcmpestrm128:
2018   case X86::BI__builtin_ia32_pcmpestri128:
2019   case X86::BI__builtin_ia32_pcmpestria128:
2020   case X86::BI__builtin_ia32_pcmpestric128:
2021   case X86::BI__builtin_ia32_pcmpestrio128:
2022   case X86::BI__builtin_ia32_pcmpestris128:
2023   case X86::BI__builtin_ia32_pcmpestriz128:
2024     i = 4; l = -128; u = 255;
2025     break;
2026   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2027   case X86::BI__builtin_ia32_rndscaless_round_mask:
2028     i = 4; l = 0; u = 255;
2029     break;
2030   }
2031   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2032 }
2033 
2034 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2035 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2036 /// Returns true when the format fits the function and the FormatStringInfo has
2037 /// been populated.
2038 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2039                                FormatStringInfo *FSI) {
2040   FSI->HasVAListArg = Format->getFirstArg() == 0;
2041   FSI->FormatIdx = Format->getFormatIdx() - 1;
2042   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2043 
2044   // The way the format attribute works in GCC, the implicit this argument
2045   // of member functions is counted. However, it doesn't appear in our own
2046   // lists, so decrement format_idx in that case.
2047   if (IsCXXMember) {
2048     if(FSI->FormatIdx == 0)
2049       return false;
2050     --FSI->FormatIdx;
2051     if (FSI->FirstDataArg != 0)
2052       --FSI->FirstDataArg;
2053   }
2054   return true;
2055 }
2056 
2057 /// Checks if a the given expression evaluates to null.
2058 ///
2059 /// \brief Returns true if the value evaluates to null.
2060 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2061   // If the expression has non-null type, it doesn't evaluate to null.
2062   if (auto nullability
2063         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2064     if (*nullability == NullabilityKind::NonNull)
2065       return false;
2066   }
2067 
2068   // As a special case, transparent unions initialized with zero are
2069   // considered null for the purposes of the nonnull attribute.
2070   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2071     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2072       if (const CompoundLiteralExpr *CLE =
2073           dyn_cast<CompoundLiteralExpr>(Expr))
2074         if (const InitListExpr *ILE =
2075             dyn_cast<InitListExpr>(CLE->getInitializer()))
2076           Expr = ILE->getInit(0);
2077   }
2078 
2079   bool Result;
2080   return (!Expr->isValueDependent() &&
2081           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2082           !Result);
2083 }
2084 
2085 static void CheckNonNullArgument(Sema &S,
2086                                  const Expr *ArgExpr,
2087                                  SourceLocation CallSiteLoc) {
2088   if (CheckNonNullExpr(S, ArgExpr))
2089     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2090            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2091 }
2092 
2093 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2094   FormatStringInfo FSI;
2095   if ((GetFormatStringType(Format) == FST_NSString) &&
2096       getFormatStringInfo(Format, false, &FSI)) {
2097     Idx = FSI.FormatIdx;
2098     return true;
2099   }
2100   return false;
2101 }
2102 /// \brief Diagnose use of %s directive in an NSString which is being passed
2103 /// as formatting string to formatting method.
2104 static void
2105 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2106                                         const NamedDecl *FDecl,
2107                                         Expr **Args,
2108                                         unsigned NumArgs) {
2109   unsigned Idx = 0;
2110   bool Format = false;
2111   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2112   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2113     Idx = 2;
2114     Format = true;
2115   }
2116   else
2117     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2118       if (S.GetFormatNSStringIdx(I, Idx)) {
2119         Format = true;
2120         break;
2121       }
2122     }
2123   if (!Format || NumArgs <= Idx)
2124     return;
2125   const Expr *FormatExpr = Args[Idx];
2126   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2127     FormatExpr = CSCE->getSubExpr();
2128   const StringLiteral *FormatString;
2129   if (const ObjCStringLiteral *OSL =
2130       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2131     FormatString = OSL->getString();
2132   else
2133     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2134   if (!FormatString)
2135     return;
2136   if (S.FormatStringHasSArg(FormatString)) {
2137     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2138       << "%s" << 1 << 1;
2139     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2140       << FDecl->getDeclName();
2141   }
2142 }
2143 
2144 /// Determine whether the given type has a non-null nullability annotation.
2145 static bool isNonNullType(ASTContext &ctx, QualType type) {
2146   if (auto nullability = type->getNullability(ctx))
2147     return *nullability == NullabilityKind::NonNull;
2148 
2149   return false;
2150 }
2151 
2152 static void CheckNonNullArguments(Sema &S,
2153                                   const NamedDecl *FDecl,
2154                                   const FunctionProtoType *Proto,
2155                                   ArrayRef<const Expr *> Args,
2156                                   SourceLocation CallSiteLoc) {
2157   assert((FDecl || Proto) && "Need a function declaration or prototype");
2158 
2159   // Check the attributes attached to the method/function itself.
2160   llvm::SmallBitVector NonNullArgs;
2161   if (FDecl) {
2162     // Handle the nonnull attribute on the function/method declaration itself.
2163     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2164       if (!NonNull->args_size()) {
2165         // Easy case: all pointer arguments are nonnull.
2166         for (const auto *Arg : Args)
2167           if (S.isValidPointerAttrType(Arg->getType()))
2168             CheckNonNullArgument(S, Arg, CallSiteLoc);
2169         return;
2170       }
2171 
2172       for (unsigned Val : NonNull->args()) {
2173         if (Val >= Args.size())
2174           continue;
2175         if (NonNullArgs.empty())
2176           NonNullArgs.resize(Args.size());
2177         NonNullArgs.set(Val);
2178       }
2179     }
2180   }
2181 
2182   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2183     // Handle the nonnull attribute on the parameters of the
2184     // function/method.
2185     ArrayRef<ParmVarDecl*> parms;
2186     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2187       parms = FD->parameters();
2188     else
2189       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2190 
2191     unsigned ParamIndex = 0;
2192     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2193          I != E; ++I, ++ParamIndex) {
2194       const ParmVarDecl *PVD = *I;
2195       if (PVD->hasAttr<NonNullAttr>() ||
2196           isNonNullType(S.Context, PVD->getType())) {
2197         if (NonNullArgs.empty())
2198           NonNullArgs.resize(Args.size());
2199 
2200         NonNullArgs.set(ParamIndex);
2201       }
2202     }
2203   } else {
2204     // If we have a non-function, non-method declaration but no
2205     // function prototype, try to dig out the function prototype.
2206     if (!Proto) {
2207       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2208         QualType type = VD->getType().getNonReferenceType();
2209         if (auto pointerType = type->getAs<PointerType>())
2210           type = pointerType->getPointeeType();
2211         else if (auto blockType = type->getAs<BlockPointerType>())
2212           type = blockType->getPointeeType();
2213         // FIXME: data member pointers?
2214 
2215         // Dig out the function prototype, if there is one.
2216         Proto = type->getAs<FunctionProtoType>();
2217       }
2218     }
2219 
2220     // Fill in non-null argument information from the nullability
2221     // information on the parameter types (if we have them).
2222     if (Proto) {
2223       unsigned Index = 0;
2224       for (auto paramType : Proto->getParamTypes()) {
2225         if (isNonNullType(S.Context, paramType)) {
2226           if (NonNullArgs.empty())
2227             NonNullArgs.resize(Args.size());
2228 
2229           NonNullArgs.set(Index);
2230         }
2231 
2232         ++Index;
2233       }
2234     }
2235   }
2236 
2237   // Check for non-null arguments.
2238   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2239        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2240     if (NonNullArgs[ArgIndex])
2241       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2242   }
2243 }
2244 
2245 /// Handles the checks for format strings, non-POD arguments to vararg
2246 /// functions, and NULL arguments passed to non-NULL parameters.
2247 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2248                      ArrayRef<const Expr *> Args, bool IsMemberFunction,
2249                      SourceLocation Loc, SourceRange Range,
2250                      VariadicCallType CallType) {
2251   // FIXME: We should check as much as we can in the template definition.
2252   if (CurContext->isDependentContext())
2253     return;
2254 
2255   // Printf and scanf checking.
2256   llvm::SmallBitVector CheckedVarArgs;
2257   if (FDecl) {
2258     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2259       // Only create vector if there are format attributes.
2260       CheckedVarArgs.resize(Args.size());
2261 
2262       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2263                            CheckedVarArgs);
2264     }
2265   }
2266 
2267   // Refuse POD arguments that weren't caught by the format string
2268   // checks above.
2269   if (CallType != VariadicDoesNotApply) {
2270     unsigned NumParams = Proto ? Proto->getNumParams()
2271                        : FDecl && isa<FunctionDecl>(FDecl)
2272                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2273                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2274                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2275                        : 0;
2276 
2277     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2278       // Args[ArgIdx] can be null in malformed code.
2279       if (const Expr *Arg = Args[ArgIdx]) {
2280         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2281           checkVariadicArgument(Arg, CallType);
2282       }
2283     }
2284   }
2285 
2286   if (FDecl || Proto) {
2287     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2288 
2289     // Type safety checking.
2290     if (FDecl) {
2291       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2292         CheckArgumentWithTypeTag(I, Args.data());
2293     }
2294   }
2295 }
2296 
2297 /// CheckConstructorCall - Check a constructor call for correctness and safety
2298 /// properties not enforced by the C type system.
2299 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2300                                 ArrayRef<const Expr *> Args,
2301                                 const FunctionProtoType *Proto,
2302                                 SourceLocation Loc) {
2303   VariadicCallType CallType =
2304     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2305   checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2306             CallType);
2307 }
2308 
2309 /// CheckFunctionCall - Check a direct function call for various correctness
2310 /// and safety properties not strictly enforced by the C type system.
2311 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2312                              const FunctionProtoType *Proto) {
2313   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2314                               isa<CXXMethodDecl>(FDecl);
2315   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2316                           IsMemberOperatorCall;
2317   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2318                                                   TheCall->getCallee());
2319   Expr** Args = TheCall->getArgs();
2320   unsigned NumArgs = TheCall->getNumArgs();
2321   if (IsMemberOperatorCall) {
2322     // If this is a call to a member operator, hide the first argument
2323     // from checkCall.
2324     // FIXME: Our choice of AST representation here is less than ideal.
2325     ++Args;
2326     --NumArgs;
2327   }
2328   checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
2329             IsMemberFunction, TheCall->getRParenLoc(),
2330             TheCall->getCallee()->getSourceRange(), CallType);
2331 
2332   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2333   // None of the checks below are needed for functions that don't have
2334   // simple names (e.g., C++ conversion functions).
2335   if (!FnInfo)
2336     return false;
2337 
2338   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
2339   if (getLangOpts().ObjC1)
2340     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2341 
2342   unsigned CMId = FDecl->getMemoryFunctionKind();
2343   if (CMId == 0)
2344     return false;
2345 
2346   // Handle memory setting and copying functions.
2347   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2348     CheckStrlcpycatArguments(TheCall, FnInfo);
2349   else if (CMId == Builtin::BIstrncat)
2350     CheckStrncatArguments(TheCall, FnInfo);
2351   else
2352     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2353 
2354   return false;
2355 }
2356 
2357 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2358                                ArrayRef<const Expr *> Args) {
2359   VariadicCallType CallType =
2360       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2361 
2362   checkCall(Method, nullptr, Args,
2363             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2364             CallType);
2365 
2366   return false;
2367 }
2368 
2369 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2370                             const FunctionProtoType *Proto) {
2371   QualType Ty;
2372   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2373     Ty = V->getType().getNonReferenceType();
2374   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2375     Ty = F->getType().getNonReferenceType();
2376   else
2377     return false;
2378 
2379   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2380       !Ty->isFunctionProtoType())
2381     return false;
2382 
2383   VariadicCallType CallType;
2384   if (!Proto || !Proto->isVariadic()) {
2385     CallType = VariadicDoesNotApply;
2386   } else if (Ty->isBlockPointerType()) {
2387     CallType = VariadicBlock;
2388   } else { // Ty->isFunctionPointerType()
2389     CallType = VariadicFunction;
2390   }
2391 
2392   checkCall(NDecl, Proto,
2393             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2394             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2395             TheCall->getCallee()->getSourceRange(), CallType);
2396 
2397   return false;
2398 }
2399 
2400 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2401 /// such as function pointers returned from functions.
2402 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2403   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2404                                                   TheCall->getCallee());
2405   checkCall(/*FDecl=*/nullptr, Proto,
2406             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2407             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2408             TheCall->getCallee()->getSourceRange(), CallType);
2409 
2410   return false;
2411 }
2412 
2413 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2414   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2415     return false;
2416 
2417   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2418   switch (Op) {
2419   case AtomicExpr::AO__c11_atomic_init:
2420     llvm_unreachable("There is no ordering argument for an init");
2421 
2422   case AtomicExpr::AO__c11_atomic_load:
2423   case AtomicExpr::AO__atomic_load_n:
2424   case AtomicExpr::AO__atomic_load:
2425     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2426            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2427 
2428   case AtomicExpr::AO__c11_atomic_store:
2429   case AtomicExpr::AO__atomic_store:
2430   case AtomicExpr::AO__atomic_store_n:
2431     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2432            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2433            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2434 
2435   default:
2436     return true;
2437   }
2438 }
2439 
2440 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2441                                          AtomicExpr::AtomicOp Op) {
2442   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2443   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2444 
2445   // All these operations take one of the following forms:
2446   enum {
2447     // C    __c11_atomic_init(A *, C)
2448     Init,
2449     // C    __c11_atomic_load(A *, int)
2450     Load,
2451     // void __atomic_load(A *, CP, int)
2452     LoadCopy,
2453     // void __atomic_store(A *, CP, int)
2454     Copy,
2455     // C    __c11_atomic_add(A *, M, int)
2456     Arithmetic,
2457     // C    __atomic_exchange_n(A *, CP, int)
2458     Xchg,
2459     // void __atomic_exchange(A *, C *, CP, int)
2460     GNUXchg,
2461     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2462     C11CmpXchg,
2463     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2464     GNUCmpXchg
2465   } Form = Init;
2466   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2467   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2468   // where:
2469   //   C is an appropriate type,
2470   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2471   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2472   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2473   //   the int parameters are for orderings.
2474 
2475   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2476                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2477                         AtomicExpr::AO__atomic_load,
2478                 "need to update code for modified C11 atomics");
2479   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2480                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2481   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2482              Op == AtomicExpr::AO__atomic_store_n ||
2483              Op == AtomicExpr::AO__atomic_exchange_n ||
2484              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2485   bool IsAddSub = false;
2486 
2487   switch (Op) {
2488   case AtomicExpr::AO__c11_atomic_init:
2489     Form = Init;
2490     break;
2491 
2492   case AtomicExpr::AO__c11_atomic_load:
2493   case AtomicExpr::AO__atomic_load_n:
2494     Form = Load;
2495     break;
2496 
2497   case AtomicExpr::AO__atomic_load:
2498     Form = LoadCopy;
2499     break;
2500 
2501   case AtomicExpr::AO__c11_atomic_store:
2502   case AtomicExpr::AO__atomic_store:
2503   case AtomicExpr::AO__atomic_store_n:
2504     Form = Copy;
2505     break;
2506 
2507   case AtomicExpr::AO__c11_atomic_fetch_add:
2508   case AtomicExpr::AO__c11_atomic_fetch_sub:
2509   case AtomicExpr::AO__atomic_fetch_add:
2510   case AtomicExpr::AO__atomic_fetch_sub:
2511   case AtomicExpr::AO__atomic_add_fetch:
2512   case AtomicExpr::AO__atomic_sub_fetch:
2513     IsAddSub = true;
2514     // Fall through.
2515   case AtomicExpr::AO__c11_atomic_fetch_and:
2516   case AtomicExpr::AO__c11_atomic_fetch_or:
2517   case AtomicExpr::AO__c11_atomic_fetch_xor:
2518   case AtomicExpr::AO__atomic_fetch_and:
2519   case AtomicExpr::AO__atomic_fetch_or:
2520   case AtomicExpr::AO__atomic_fetch_xor:
2521   case AtomicExpr::AO__atomic_fetch_nand:
2522   case AtomicExpr::AO__atomic_and_fetch:
2523   case AtomicExpr::AO__atomic_or_fetch:
2524   case AtomicExpr::AO__atomic_xor_fetch:
2525   case AtomicExpr::AO__atomic_nand_fetch:
2526     Form = Arithmetic;
2527     break;
2528 
2529   case AtomicExpr::AO__c11_atomic_exchange:
2530   case AtomicExpr::AO__atomic_exchange_n:
2531     Form = Xchg;
2532     break;
2533 
2534   case AtomicExpr::AO__atomic_exchange:
2535     Form = GNUXchg;
2536     break;
2537 
2538   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2539   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2540     Form = C11CmpXchg;
2541     break;
2542 
2543   case AtomicExpr::AO__atomic_compare_exchange:
2544   case AtomicExpr::AO__atomic_compare_exchange_n:
2545     Form = GNUCmpXchg;
2546     break;
2547   }
2548 
2549   // Check we have the right number of arguments.
2550   if (TheCall->getNumArgs() < NumArgs[Form]) {
2551     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2552       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2553       << TheCall->getCallee()->getSourceRange();
2554     return ExprError();
2555   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2556     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2557          diag::err_typecheck_call_too_many_args)
2558       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2559       << TheCall->getCallee()->getSourceRange();
2560     return ExprError();
2561   }
2562 
2563   // Inspect the first argument of the atomic operation.
2564   Expr *Ptr = TheCall->getArg(0);
2565   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2566   if (ConvertedPtr.isInvalid())
2567     return ExprError();
2568 
2569   Ptr = ConvertedPtr.get();
2570   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2571   if (!pointerType) {
2572     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2573       << Ptr->getType() << Ptr->getSourceRange();
2574     return ExprError();
2575   }
2576 
2577   // For a __c11 builtin, this should be a pointer to an _Atomic type.
2578   QualType AtomTy = pointerType->getPointeeType(); // 'A'
2579   QualType ValType = AtomTy; // 'C'
2580   if (IsC11) {
2581     if (!AtomTy->isAtomicType()) {
2582       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2583         << Ptr->getType() << Ptr->getSourceRange();
2584       return ExprError();
2585     }
2586     if (AtomTy.isConstQualified()) {
2587       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2588         << Ptr->getType() << Ptr->getSourceRange();
2589       return ExprError();
2590     }
2591     ValType = AtomTy->getAs<AtomicType>()->getValueType();
2592   } else if (Form != Load && Form != LoadCopy) {
2593     if (ValType.isConstQualified()) {
2594       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2595         << Ptr->getType() << Ptr->getSourceRange();
2596       return ExprError();
2597     }
2598   }
2599 
2600   // For an arithmetic operation, the implied arithmetic must be well-formed.
2601   if (Form == Arithmetic) {
2602     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2603     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2604       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2605         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2606       return ExprError();
2607     }
2608     if (!IsAddSub && !ValType->isIntegerType()) {
2609       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2610         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2611       return ExprError();
2612     }
2613     if (IsC11 && ValType->isPointerType() &&
2614         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2615                             diag::err_incomplete_type)) {
2616       return ExprError();
2617     }
2618   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2619     // For __atomic_*_n operations, the value type must be a scalar integral or
2620     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2621     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2622       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2623     return ExprError();
2624   }
2625 
2626   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2627       !AtomTy->isScalarType()) {
2628     // For GNU atomics, require a trivially-copyable type. This is not part of
2629     // the GNU atomics specification, but we enforce it for sanity.
2630     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2631       << Ptr->getType() << Ptr->getSourceRange();
2632     return ExprError();
2633   }
2634 
2635   switch (ValType.getObjCLifetime()) {
2636   case Qualifiers::OCL_None:
2637   case Qualifiers::OCL_ExplicitNone:
2638     // okay
2639     break;
2640 
2641   case Qualifiers::OCL_Weak:
2642   case Qualifiers::OCL_Strong:
2643   case Qualifiers::OCL_Autoreleasing:
2644     // FIXME: Can this happen? By this point, ValType should be known
2645     // to be trivially copyable.
2646     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2647       << ValType << Ptr->getSourceRange();
2648     return ExprError();
2649   }
2650 
2651   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
2652   // volatile-ness of the pointee-type inject itself into the result or the
2653   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2654   ValType.removeLocalVolatile();
2655   ValType.removeLocalConst();
2656   QualType ResultType = ValType;
2657   if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2658     ResultType = Context.VoidTy;
2659   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2660     ResultType = Context.BoolTy;
2661 
2662   // The type of a parameter passed 'by value'. In the GNU atomics, such
2663   // arguments are actually passed as pointers.
2664   QualType ByValType = ValType; // 'CP'
2665   if (!IsC11 && !IsN)
2666     ByValType = Ptr->getType();
2667 
2668   // The first argument --- the pointer --- has a fixed type; we
2669   // deduce the types of the rest of the arguments accordingly.  Walk
2670   // the remaining arguments, converting them to the deduced value type.
2671   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2672     QualType Ty;
2673     if (i < NumVals[Form] + 1) {
2674       switch (i) {
2675       case 1:
2676         // The second argument is the non-atomic operand. For arithmetic, this
2677         // is always passed by value, and for a compare_exchange it is always
2678         // passed by address. For the rest, GNU uses by-address and C11 uses
2679         // by-value.
2680         assert(Form != Load);
2681         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2682           Ty = ValType;
2683         else if (Form == Copy || Form == Xchg)
2684           Ty = ByValType;
2685         else if (Form == Arithmetic)
2686           Ty = Context.getPointerDiffType();
2687         else {
2688           Expr *ValArg = TheCall->getArg(i);
2689           unsigned AS = 0;
2690           // Keep address space of non-atomic pointer type.
2691           if (const PointerType *PtrTy =
2692                   ValArg->getType()->getAs<PointerType>()) {
2693             AS = PtrTy->getPointeeType().getAddressSpace();
2694           }
2695           Ty = Context.getPointerType(
2696               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2697         }
2698         break;
2699       case 2:
2700         // The third argument to compare_exchange / GNU exchange is a
2701         // (pointer to a) desired value.
2702         Ty = ByValType;
2703         break;
2704       case 3:
2705         // The fourth argument to GNU compare_exchange is a 'weak' flag.
2706         Ty = Context.BoolTy;
2707         break;
2708       }
2709     } else {
2710       // The order(s) are always converted to int.
2711       Ty = Context.IntTy;
2712     }
2713 
2714     InitializedEntity Entity =
2715         InitializedEntity::InitializeParameter(Context, Ty, false);
2716     ExprResult Arg = TheCall->getArg(i);
2717     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2718     if (Arg.isInvalid())
2719       return true;
2720     TheCall->setArg(i, Arg.get());
2721   }
2722 
2723   // Permute the arguments into a 'consistent' order.
2724   SmallVector<Expr*, 5> SubExprs;
2725   SubExprs.push_back(Ptr);
2726   switch (Form) {
2727   case Init:
2728     // Note, AtomicExpr::getVal1() has a special case for this atomic.
2729     SubExprs.push_back(TheCall->getArg(1)); // Val1
2730     break;
2731   case Load:
2732     SubExprs.push_back(TheCall->getArg(1)); // Order
2733     break;
2734   case LoadCopy:
2735   case Copy:
2736   case Arithmetic:
2737   case Xchg:
2738     SubExprs.push_back(TheCall->getArg(2)); // Order
2739     SubExprs.push_back(TheCall->getArg(1)); // Val1
2740     break;
2741   case GNUXchg:
2742     // Note, AtomicExpr::getVal2() has a special case for this atomic.
2743     SubExprs.push_back(TheCall->getArg(3)); // Order
2744     SubExprs.push_back(TheCall->getArg(1)); // Val1
2745     SubExprs.push_back(TheCall->getArg(2)); // Val2
2746     break;
2747   case C11CmpXchg:
2748     SubExprs.push_back(TheCall->getArg(3)); // Order
2749     SubExprs.push_back(TheCall->getArg(1)); // Val1
2750     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2751     SubExprs.push_back(TheCall->getArg(2)); // Val2
2752     break;
2753   case GNUCmpXchg:
2754     SubExprs.push_back(TheCall->getArg(4)); // Order
2755     SubExprs.push_back(TheCall->getArg(1)); // Val1
2756     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2757     SubExprs.push_back(TheCall->getArg(2)); // Val2
2758     SubExprs.push_back(TheCall->getArg(3)); // Weak
2759     break;
2760   }
2761 
2762   if (SubExprs.size() >= 2 && Form != Init) {
2763     llvm::APSInt Result(32);
2764     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2765         !isValidOrderingForOp(Result.getSExtValue(), Op))
2766       Diag(SubExprs[1]->getLocStart(),
2767            diag::warn_atomic_op_has_invalid_memory_order)
2768           << SubExprs[1]->getSourceRange();
2769   }
2770 
2771   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2772                                             SubExprs, ResultType, Op,
2773                                             TheCall->getRParenLoc());
2774 
2775   if ((Op == AtomicExpr::AO__c11_atomic_load ||
2776        (Op == AtomicExpr::AO__c11_atomic_store)) &&
2777       Context.AtomicUsesUnsupportedLibcall(AE))
2778     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2779     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2780 
2781   return AE;
2782 }
2783 
2784 /// checkBuiltinArgument - Given a call to a builtin function, perform
2785 /// normal type-checking on the given argument, updating the call in
2786 /// place.  This is useful when a builtin function requires custom
2787 /// type-checking for some of its arguments but not necessarily all of
2788 /// them.
2789 ///
2790 /// Returns true on error.
2791 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2792   FunctionDecl *Fn = E->getDirectCallee();
2793   assert(Fn && "builtin call without direct callee!");
2794 
2795   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2796   InitializedEntity Entity =
2797     InitializedEntity::InitializeParameter(S.Context, Param);
2798 
2799   ExprResult Arg = E->getArg(0);
2800   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2801   if (Arg.isInvalid())
2802     return true;
2803 
2804   E->setArg(ArgIndex, Arg.get());
2805   return false;
2806 }
2807 
2808 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
2809 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
2810 /// type of its first argument.  The main ActOnCallExpr routines have already
2811 /// promoted the types of arguments because all of these calls are prototyped as
2812 /// void(...).
2813 ///
2814 /// This function goes through and does final semantic checking for these
2815 /// builtins,
2816 ExprResult
2817 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
2818   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2819   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2820   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2821 
2822   // Ensure that we have at least one argument to do type inference from.
2823   if (TheCall->getNumArgs() < 1) {
2824     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2825       << 0 << 1 << TheCall->getNumArgs()
2826       << TheCall->getCallee()->getSourceRange();
2827     return ExprError();
2828   }
2829 
2830   // Inspect the first argument of the atomic builtin.  This should always be
2831   // a pointer type, whose element is an integral scalar or pointer type.
2832   // Because it is a pointer type, we don't have to worry about any implicit
2833   // casts here.
2834   // FIXME: We don't allow floating point scalars as input.
2835   Expr *FirstArg = TheCall->getArg(0);
2836   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2837   if (FirstArgResult.isInvalid())
2838     return ExprError();
2839   FirstArg = FirstArgResult.get();
2840   TheCall->setArg(0, FirstArg);
2841 
2842   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2843   if (!pointerType) {
2844     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2845       << FirstArg->getType() << FirstArg->getSourceRange();
2846     return ExprError();
2847   }
2848 
2849   QualType ValType = pointerType->getPointeeType();
2850   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2851       !ValType->isBlockPointerType()) {
2852     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2853       << FirstArg->getType() << FirstArg->getSourceRange();
2854     return ExprError();
2855   }
2856 
2857   switch (ValType.getObjCLifetime()) {
2858   case Qualifiers::OCL_None:
2859   case Qualifiers::OCL_ExplicitNone:
2860     // okay
2861     break;
2862 
2863   case Qualifiers::OCL_Weak:
2864   case Qualifiers::OCL_Strong:
2865   case Qualifiers::OCL_Autoreleasing:
2866     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2867       << ValType << FirstArg->getSourceRange();
2868     return ExprError();
2869   }
2870 
2871   // Strip any qualifiers off ValType.
2872   ValType = ValType.getUnqualifiedType();
2873 
2874   // The majority of builtins return a value, but a few have special return
2875   // types, so allow them to override appropriately below.
2876   QualType ResultType = ValType;
2877 
2878   // We need to figure out which concrete builtin this maps onto.  For example,
2879   // __sync_fetch_and_add with a 2 byte object turns into
2880   // __sync_fetch_and_add_2.
2881 #define BUILTIN_ROW(x) \
2882   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2883     Builtin::BI##x##_8, Builtin::BI##x##_16 }
2884 
2885   static const unsigned BuiltinIndices[][5] = {
2886     BUILTIN_ROW(__sync_fetch_and_add),
2887     BUILTIN_ROW(__sync_fetch_and_sub),
2888     BUILTIN_ROW(__sync_fetch_and_or),
2889     BUILTIN_ROW(__sync_fetch_and_and),
2890     BUILTIN_ROW(__sync_fetch_and_xor),
2891     BUILTIN_ROW(__sync_fetch_and_nand),
2892 
2893     BUILTIN_ROW(__sync_add_and_fetch),
2894     BUILTIN_ROW(__sync_sub_and_fetch),
2895     BUILTIN_ROW(__sync_and_and_fetch),
2896     BUILTIN_ROW(__sync_or_and_fetch),
2897     BUILTIN_ROW(__sync_xor_and_fetch),
2898     BUILTIN_ROW(__sync_nand_and_fetch),
2899 
2900     BUILTIN_ROW(__sync_val_compare_and_swap),
2901     BUILTIN_ROW(__sync_bool_compare_and_swap),
2902     BUILTIN_ROW(__sync_lock_test_and_set),
2903     BUILTIN_ROW(__sync_lock_release),
2904     BUILTIN_ROW(__sync_swap)
2905   };
2906 #undef BUILTIN_ROW
2907 
2908   // Determine the index of the size.
2909   unsigned SizeIndex;
2910   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
2911   case 1: SizeIndex = 0; break;
2912   case 2: SizeIndex = 1; break;
2913   case 4: SizeIndex = 2; break;
2914   case 8: SizeIndex = 3; break;
2915   case 16: SizeIndex = 4; break;
2916   default:
2917     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2918       << FirstArg->getType() << FirstArg->getSourceRange();
2919     return ExprError();
2920   }
2921 
2922   // Each of these builtins has one pointer argument, followed by some number of
2923   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2924   // that we ignore.  Find out which row of BuiltinIndices to read from as well
2925   // as the number of fixed args.
2926   unsigned BuiltinID = FDecl->getBuiltinID();
2927   unsigned BuiltinIndex, NumFixed = 1;
2928   bool WarnAboutSemanticsChange = false;
2929   switch (BuiltinID) {
2930   default: llvm_unreachable("Unknown overloaded atomic builtin!");
2931   case Builtin::BI__sync_fetch_and_add:
2932   case Builtin::BI__sync_fetch_and_add_1:
2933   case Builtin::BI__sync_fetch_and_add_2:
2934   case Builtin::BI__sync_fetch_and_add_4:
2935   case Builtin::BI__sync_fetch_and_add_8:
2936   case Builtin::BI__sync_fetch_and_add_16:
2937     BuiltinIndex = 0;
2938     break;
2939 
2940   case Builtin::BI__sync_fetch_and_sub:
2941   case Builtin::BI__sync_fetch_and_sub_1:
2942   case Builtin::BI__sync_fetch_and_sub_2:
2943   case Builtin::BI__sync_fetch_and_sub_4:
2944   case Builtin::BI__sync_fetch_and_sub_8:
2945   case Builtin::BI__sync_fetch_and_sub_16:
2946     BuiltinIndex = 1;
2947     break;
2948 
2949   case Builtin::BI__sync_fetch_and_or:
2950   case Builtin::BI__sync_fetch_and_or_1:
2951   case Builtin::BI__sync_fetch_and_or_2:
2952   case Builtin::BI__sync_fetch_and_or_4:
2953   case Builtin::BI__sync_fetch_and_or_8:
2954   case Builtin::BI__sync_fetch_and_or_16:
2955     BuiltinIndex = 2;
2956     break;
2957 
2958   case Builtin::BI__sync_fetch_and_and:
2959   case Builtin::BI__sync_fetch_and_and_1:
2960   case Builtin::BI__sync_fetch_and_and_2:
2961   case Builtin::BI__sync_fetch_and_and_4:
2962   case Builtin::BI__sync_fetch_and_and_8:
2963   case Builtin::BI__sync_fetch_and_and_16:
2964     BuiltinIndex = 3;
2965     break;
2966 
2967   case Builtin::BI__sync_fetch_and_xor:
2968   case Builtin::BI__sync_fetch_and_xor_1:
2969   case Builtin::BI__sync_fetch_and_xor_2:
2970   case Builtin::BI__sync_fetch_and_xor_4:
2971   case Builtin::BI__sync_fetch_and_xor_8:
2972   case Builtin::BI__sync_fetch_and_xor_16:
2973     BuiltinIndex = 4;
2974     break;
2975 
2976   case Builtin::BI__sync_fetch_and_nand:
2977   case Builtin::BI__sync_fetch_and_nand_1:
2978   case Builtin::BI__sync_fetch_and_nand_2:
2979   case Builtin::BI__sync_fetch_and_nand_4:
2980   case Builtin::BI__sync_fetch_and_nand_8:
2981   case Builtin::BI__sync_fetch_and_nand_16:
2982     BuiltinIndex = 5;
2983     WarnAboutSemanticsChange = true;
2984     break;
2985 
2986   case Builtin::BI__sync_add_and_fetch:
2987   case Builtin::BI__sync_add_and_fetch_1:
2988   case Builtin::BI__sync_add_and_fetch_2:
2989   case Builtin::BI__sync_add_and_fetch_4:
2990   case Builtin::BI__sync_add_and_fetch_8:
2991   case Builtin::BI__sync_add_and_fetch_16:
2992     BuiltinIndex = 6;
2993     break;
2994 
2995   case Builtin::BI__sync_sub_and_fetch:
2996   case Builtin::BI__sync_sub_and_fetch_1:
2997   case Builtin::BI__sync_sub_and_fetch_2:
2998   case Builtin::BI__sync_sub_and_fetch_4:
2999   case Builtin::BI__sync_sub_and_fetch_8:
3000   case Builtin::BI__sync_sub_and_fetch_16:
3001     BuiltinIndex = 7;
3002     break;
3003 
3004   case Builtin::BI__sync_and_and_fetch:
3005   case Builtin::BI__sync_and_and_fetch_1:
3006   case Builtin::BI__sync_and_and_fetch_2:
3007   case Builtin::BI__sync_and_and_fetch_4:
3008   case Builtin::BI__sync_and_and_fetch_8:
3009   case Builtin::BI__sync_and_and_fetch_16:
3010     BuiltinIndex = 8;
3011     break;
3012 
3013   case Builtin::BI__sync_or_and_fetch:
3014   case Builtin::BI__sync_or_and_fetch_1:
3015   case Builtin::BI__sync_or_and_fetch_2:
3016   case Builtin::BI__sync_or_and_fetch_4:
3017   case Builtin::BI__sync_or_and_fetch_8:
3018   case Builtin::BI__sync_or_and_fetch_16:
3019     BuiltinIndex = 9;
3020     break;
3021 
3022   case Builtin::BI__sync_xor_and_fetch:
3023   case Builtin::BI__sync_xor_and_fetch_1:
3024   case Builtin::BI__sync_xor_and_fetch_2:
3025   case Builtin::BI__sync_xor_and_fetch_4:
3026   case Builtin::BI__sync_xor_and_fetch_8:
3027   case Builtin::BI__sync_xor_and_fetch_16:
3028     BuiltinIndex = 10;
3029     break;
3030 
3031   case Builtin::BI__sync_nand_and_fetch:
3032   case Builtin::BI__sync_nand_and_fetch_1:
3033   case Builtin::BI__sync_nand_and_fetch_2:
3034   case Builtin::BI__sync_nand_and_fetch_4:
3035   case Builtin::BI__sync_nand_and_fetch_8:
3036   case Builtin::BI__sync_nand_and_fetch_16:
3037     BuiltinIndex = 11;
3038     WarnAboutSemanticsChange = true;
3039     break;
3040 
3041   case Builtin::BI__sync_val_compare_and_swap:
3042   case Builtin::BI__sync_val_compare_and_swap_1:
3043   case Builtin::BI__sync_val_compare_and_swap_2:
3044   case Builtin::BI__sync_val_compare_and_swap_4:
3045   case Builtin::BI__sync_val_compare_and_swap_8:
3046   case Builtin::BI__sync_val_compare_and_swap_16:
3047     BuiltinIndex = 12;
3048     NumFixed = 2;
3049     break;
3050 
3051   case Builtin::BI__sync_bool_compare_and_swap:
3052   case Builtin::BI__sync_bool_compare_and_swap_1:
3053   case Builtin::BI__sync_bool_compare_and_swap_2:
3054   case Builtin::BI__sync_bool_compare_and_swap_4:
3055   case Builtin::BI__sync_bool_compare_and_swap_8:
3056   case Builtin::BI__sync_bool_compare_and_swap_16:
3057     BuiltinIndex = 13;
3058     NumFixed = 2;
3059     ResultType = Context.BoolTy;
3060     break;
3061 
3062   case Builtin::BI__sync_lock_test_and_set:
3063   case Builtin::BI__sync_lock_test_and_set_1:
3064   case Builtin::BI__sync_lock_test_and_set_2:
3065   case Builtin::BI__sync_lock_test_and_set_4:
3066   case Builtin::BI__sync_lock_test_and_set_8:
3067   case Builtin::BI__sync_lock_test_and_set_16:
3068     BuiltinIndex = 14;
3069     break;
3070 
3071   case Builtin::BI__sync_lock_release:
3072   case Builtin::BI__sync_lock_release_1:
3073   case Builtin::BI__sync_lock_release_2:
3074   case Builtin::BI__sync_lock_release_4:
3075   case Builtin::BI__sync_lock_release_8:
3076   case Builtin::BI__sync_lock_release_16:
3077     BuiltinIndex = 15;
3078     NumFixed = 0;
3079     ResultType = Context.VoidTy;
3080     break;
3081 
3082   case Builtin::BI__sync_swap:
3083   case Builtin::BI__sync_swap_1:
3084   case Builtin::BI__sync_swap_2:
3085   case Builtin::BI__sync_swap_4:
3086   case Builtin::BI__sync_swap_8:
3087   case Builtin::BI__sync_swap_16:
3088     BuiltinIndex = 16;
3089     break;
3090   }
3091 
3092   // Now that we know how many fixed arguments we expect, first check that we
3093   // have at least that many.
3094   if (TheCall->getNumArgs() < 1+NumFixed) {
3095     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3096       << 0 << 1+NumFixed << TheCall->getNumArgs()
3097       << TheCall->getCallee()->getSourceRange();
3098     return ExprError();
3099   }
3100 
3101   if (WarnAboutSemanticsChange) {
3102     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3103       << TheCall->getCallee()->getSourceRange();
3104   }
3105 
3106   // Get the decl for the concrete builtin from this, we can tell what the
3107   // concrete integer type we should convert to is.
3108   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3109   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3110   FunctionDecl *NewBuiltinDecl;
3111   if (NewBuiltinID == BuiltinID)
3112     NewBuiltinDecl = FDecl;
3113   else {
3114     // Perform builtin lookup to avoid redeclaring it.
3115     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3116     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3117     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3118     assert(Res.getFoundDecl());
3119     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3120     if (!NewBuiltinDecl)
3121       return ExprError();
3122   }
3123 
3124   // The first argument --- the pointer --- has a fixed type; we
3125   // deduce the types of the rest of the arguments accordingly.  Walk
3126   // the remaining arguments, converting them to the deduced value type.
3127   for (unsigned i = 0; i != NumFixed; ++i) {
3128     ExprResult Arg = TheCall->getArg(i+1);
3129 
3130     // GCC does an implicit conversion to the pointer or integer ValType.  This
3131     // can fail in some cases (1i -> int**), check for this error case now.
3132     // Initialize the argument.
3133     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3134                                                    ValType, /*consume*/ false);
3135     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3136     if (Arg.isInvalid())
3137       return ExprError();
3138 
3139     // Okay, we have something that *can* be converted to the right type.  Check
3140     // to see if there is a potentially weird extension going on here.  This can
3141     // happen when you do an atomic operation on something like an char* and
3142     // pass in 42.  The 42 gets converted to char.  This is even more strange
3143     // for things like 45.123 -> char, etc.
3144     // FIXME: Do this check.
3145     TheCall->setArg(i+1, Arg.get());
3146   }
3147 
3148   ASTContext& Context = this->getASTContext();
3149 
3150   // Create a new DeclRefExpr to refer to the new decl.
3151   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3152       Context,
3153       DRE->getQualifierLoc(),
3154       SourceLocation(),
3155       NewBuiltinDecl,
3156       /*enclosing*/ false,
3157       DRE->getLocation(),
3158       Context.BuiltinFnTy,
3159       DRE->getValueKind());
3160 
3161   // Set the callee in the CallExpr.
3162   // FIXME: This loses syntactic information.
3163   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3164   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3165                                               CK_BuiltinFnToFnPtr);
3166   TheCall->setCallee(PromotedCall.get());
3167 
3168   // Change the result type of the call to match the original value type. This
3169   // is arbitrary, but the codegen for these builtins ins design to handle it
3170   // gracefully.
3171   TheCall->setType(ResultType);
3172 
3173   return TheCallResult;
3174 }
3175 
3176 /// SemaBuiltinNontemporalOverloaded - We have a call to
3177 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3178 /// overloaded function based on the pointer type of its last argument.
3179 ///
3180 /// This function goes through and does final semantic checking for these
3181 /// builtins.
3182 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3183   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3184   DeclRefExpr *DRE =
3185       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3186   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3187   unsigned BuiltinID = FDecl->getBuiltinID();
3188   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3189           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3190          "Unexpected nontemporal load/store builtin!");
3191   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3192   unsigned numArgs = isStore ? 2 : 1;
3193 
3194   // Ensure that we have the proper number of arguments.
3195   if (checkArgCount(*this, TheCall, numArgs))
3196     return ExprError();
3197 
3198   // Inspect the last argument of the nontemporal builtin.  This should always
3199   // be a pointer type, from which we imply the type of the memory access.
3200   // Because it is a pointer type, we don't have to worry about any implicit
3201   // casts here.
3202   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3203   ExprResult PointerArgResult =
3204       DefaultFunctionArrayLvalueConversion(PointerArg);
3205 
3206   if (PointerArgResult.isInvalid())
3207     return ExprError();
3208   PointerArg = PointerArgResult.get();
3209   TheCall->setArg(numArgs - 1, PointerArg);
3210 
3211   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3212   if (!pointerType) {
3213     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3214         << PointerArg->getType() << PointerArg->getSourceRange();
3215     return ExprError();
3216   }
3217 
3218   QualType ValType = pointerType->getPointeeType();
3219 
3220   // Strip any qualifiers off ValType.
3221   ValType = ValType.getUnqualifiedType();
3222   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3223       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3224       !ValType->isVectorType()) {
3225     Diag(DRE->getLocStart(),
3226          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3227         << PointerArg->getType() << PointerArg->getSourceRange();
3228     return ExprError();
3229   }
3230 
3231   if (!isStore) {
3232     TheCall->setType(ValType);
3233     return TheCallResult;
3234   }
3235 
3236   ExprResult ValArg = TheCall->getArg(0);
3237   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3238       Context, ValType, /*consume*/ false);
3239   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3240   if (ValArg.isInvalid())
3241     return ExprError();
3242 
3243   TheCall->setArg(0, ValArg.get());
3244   TheCall->setType(Context.VoidTy);
3245   return TheCallResult;
3246 }
3247 
3248 /// CheckObjCString - Checks that the argument to the builtin
3249 /// CFString constructor is correct
3250 /// Note: It might also make sense to do the UTF-16 conversion here (would
3251 /// simplify the backend).
3252 bool Sema::CheckObjCString(Expr *Arg) {
3253   Arg = Arg->IgnoreParenCasts();
3254   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3255 
3256   if (!Literal || !Literal->isAscii()) {
3257     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3258       << Arg->getSourceRange();
3259     return true;
3260   }
3261 
3262   if (Literal->containsNonAsciiOrNull()) {
3263     StringRef String = Literal->getString();
3264     unsigned NumBytes = String.size();
3265     SmallVector<UTF16, 128> ToBuf(NumBytes);
3266     const UTF8 *FromPtr = (const UTF8 *)String.data();
3267     UTF16 *ToPtr = &ToBuf[0];
3268 
3269     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
3270                                                  &ToPtr, ToPtr + NumBytes,
3271                                                  strictConversion);
3272     // Check for conversion failure.
3273     if (Result != conversionOK)
3274       Diag(Arg->getLocStart(),
3275            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3276   }
3277   return false;
3278 }
3279 
3280 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3281 /// for validity.  Emit an error and return true on failure; return false
3282 /// on success.
3283 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
3284   Expr *Fn = TheCall->getCallee();
3285   if (TheCall->getNumArgs() > 2) {
3286     Diag(TheCall->getArg(2)->getLocStart(),
3287          diag::err_typecheck_call_too_many_args)
3288       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3289       << Fn->getSourceRange()
3290       << SourceRange(TheCall->getArg(2)->getLocStart(),
3291                      (*(TheCall->arg_end()-1))->getLocEnd());
3292     return true;
3293   }
3294 
3295   if (TheCall->getNumArgs() < 2) {
3296     return Diag(TheCall->getLocEnd(),
3297       diag::err_typecheck_call_too_few_args_at_least)
3298       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3299   }
3300 
3301   // Type-check the first argument normally.
3302   if (checkBuiltinArgument(*this, TheCall, 0))
3303     return true;
3304 
3305   // Determine whether the current function is variadic or not.
3306   BlockScopeInfo *CurBlock = getCurBlock();
3307   bool isVariadic;
3308   if (CurBlock)
3309     isVariadic = CurBlock->TheDecl->isVariadic();
3310   else if (FunctionDecl *FD = getCurFunctionDecl())
3311     isVariadic = FD->isVariadic();
3312   else
3313     isVariadic = getCurMethodDecl()->isVariadic();
3314 
3315   if (!isVariadic) {
3316     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3317     return true;
3318   }
3319 
3320   // Verify that the second argument to the builtin is the last argument of the
3321   // current function or method.
3322   bool SecondArgIsLastNamedArgument = false;
3323   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3324 
3325   // These are valid if SecondArgIsLastNamedArgument is false after the next
3326   // block.
3327   QualType Type;
3328   SourceLocation ParamLoc;
3329   bool IsCRegister = false;
3330 
3331   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3332     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3333       // FIXME: This isn't correct for methods (results in bogus warning).
3334       // Get the last formal in the current function.
3335       const ParmVarDecl *LastArg;
3336       if (CurBlock)
3337         LastArg = CurBlock->TheDecl->parameters().back();
3338       else if (FunctionDecl *FD = getCurFunctionDecl())
3339         LastArg = FD->parameters().back();
3340       else
3341         LastArg = getCurMethodDecl()->parameters().back();
3342       SecondArgIsLastNamedArgument = PV == LastArg;
3343 
3344       Type = PV->getType();
3345       ParamLoc = PV->getLocation();
3346       IsCRegister =
3347           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3348     }
3349   }
3350 
3351   if (!SecondArgIsLastNamedArgument)
3352     Diag(TheCall->getArg(1)->getLocStart(),
3353          diag::warn_second_arg_of_va_start_not_last_named_param);
3354   else if (IsCRegister || Type->isReferenceType() ||
3355            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3356              // Promotable integers are UB, but enumerations need a bit of
3357              // extra checking to see what their promotable type actually is.
3358              if (!Type->isPromotableIntegerType())
3359                return false;
3360              if (!Type->isEnumeralType())
3361                return true;
3362              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3363              return !(ED &&
3364                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3365            }()) {
3366     unsigned Reason = 0;
3367     if (Type->isReferenceType())  Reason = 1;
3368     else if (IsCRegister)         Reason = 2;
3369     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3370     Diag(ParamLoc, diag::note_parameter_type) << Type;
3371   }
3372 
3373   TheCall->setType(Context.VoidTy);
3374   return false;
3375 }
3376 
3377 /// Check the arguments to '__builtin_va_start' for validity, and that
3378 /// it was called from a function of the native ABI.
3379 /// Emit an error and return true on failure; return false on success.
3380 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3381   // On x86-64 Unix, don't allow this in Win64 ABI functions.
3382   // On x64 Windows, don't allow this in System V ABI functions.
3383   // (Yes, that means there's no corresponding way to support variadic
3384   // System V ABI functions on Windows.)
3385   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3386     unsigned OS = Context.getTargetInfo().getTriple().getOS();
3387     clang::CallingConv CC = CC_C;
3388     if (const FunctionDecl *FD = getCurFunctionDecl())
3389       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3390     if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3391         (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3392       return Diag(TheCall->getCallee()->getLocStart(),
3393                   diag::err_va_start_used_in_wrong_abi_function)
3394              << (OS != llvm::Triple::Win32);
3395   }
3396   return SemaBuiltinVAStartImpl(TheCall);
3397 }
3398 
3399 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3400 /// it was called from a Win64 ABI function.
3401 /// Emit an error and return true on failure; return false on success.
3402 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3403   // This only makes sense for x86-64.
3404   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3405   Expr *Callee = TheCall->getCallee();
3406   if (TT.getArch() != llvm::Triple::x86_64)
3407     return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3408   // Don't allow this in System V ABI functions.
3409   clang::CallingConv CC = CC_C;
3410   if (const FunctionDecl *FD = getCurFunctionDecl())
3411     CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3412   if (CC == CC_X86_64SysV ||
3413       (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3414     return Diag(Callee->getLocStart(),
3415                 diag::err_ms_va_start_used_in_sysv_function);
3416   return SemaBuiltinVAStartImpl(TheCall);
3417 }
3418 
3419 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3420   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3421   //                 const char *named_addr);
3422 
3423   Expr *Func = Call->getCallee();
3424 
3425   if (Call->getNumArgs() < 3)
3426     return Diag(Call->getLocEnd(),
3427                 diag::err_typecheck_call_too_few_args_at_least)
3428            << 0 /*function call*/ << 3 << Call->getNumArgs();
3429 
3430   // Determine whether the current function is variadic or not.
3431   bool IsVariadic;
3432   if (BlockScopeInfo *CurBlock = getCurBlock())
3433     IsVariadic = CurBlock->TheDecl->isVariadic();
3434   else if (FunctionDecl *FD = getCurFunctionDecl())
3435     IsVariadic = FD->isVariadic();
3436   else if (ObjCMethodDecl *MD = getCurMethodDecl())
3437     IsVariadic = MD->isVariadic();
3438   else
3439     llvm_unreachable("unexpected statement type");
3440 
3441   if (!IsVariadic) {
3442     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3443     return true;
3444   }
3445 
3446   // Type-check the first argument normally.
3447   if (checkBuiltinArgument(*this, Call, 0))
3448     return true;
3449 
3450   const struct {
3451     unsigned ArgNo;
3452     QualType Type;
3453   } ArgumentTypes[] = {
3454     { 1, Context.getPointerType(Context.CharTy.withConst()) },
3455     { 2, Context.getSizeType() },
3456   };
3457 
3458   for (const auto &AT : ArgumentTypes) {
3459     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3460     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3461       continue;
3462     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3463       << Arg->getType() << AT.Type << 1 /* different class */
3464       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3465       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3466   }
3467 
3468   return false;
3469 }
3470 
3471 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3472 /// friends.  This is declared to take (...), so we have to check everything.
3473 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3474   if (TheCall->getNumArgs() < 2)
3475     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3476       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3477   if (TheCall->getNumArgs() > 2)
3478     return Diag(TheCall->getArg(2)->getLocStart(),
3479                 diag::err_typecheck_call_too_many_args)
3480       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3481       << SourceRange(TheCall->getArg(2)->getLocStart(),
3482                      (*(TheCall->arg_end()-1))->getLocEnd());
3483 
3484   ExprResult OrigArg0 = TheCall->getArg(0);
3485   ExprResult OrigArg1 = TheCall->getArg(1);
3486 
3487   // Do standard promotions between the two arguments, returning their common
3488   // type.
3489   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3490   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3491     return true;
3492 
3493   // Make sure any conversions are pushed back into the call; this is
3494   // type safe since unordered compare builtins are declared as "_Bool
3495   // foo(...)".
3496   TheCall->setArg(0, OrigArg0.get());
3497   TheCall->setArg(1, OrigArg1.get());
3498 
3499   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3500     return false;
3501 
3502   // If the common type isn't a real floating type, then the arguments were
3503   // invalid for this operation.
3504   if (Res.isNull() || !Res->isRealFloatingType())
3505     return Diag(OrigArg0.get()->getLocStart(),
3506                 diag::err_typecheck_call_invalid_ordered_compare)
3507       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3508       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3509 
3510   return false;
3511 }
3512 
3513 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3514 /// __builtin_isnan and friends.  This is declared to take (...), so we have
3515 /// to check everything. We expect the last argument to be a floating point
3516 /// value.
3517 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3518   if (TheCall->getNumArgs() < NumArgs)
3519     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3520       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3521   if (TheCall->getNumArgs() > NumArgs)
3522     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3523                 diag::err_typecheck_call_too_many_args)
3524       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3525       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3526                      (*(TheCall->arg_end()-1))->getLocEnd());
3527 
3528   Expr *OrigArg = TheCall->getArg(NumArgs-1);
3529 
3530   if (OrigArg->isTypeDependent())
3531     return false;
3532 
3533   // This operation requires a non-_Complex floating-point number.
3534   if (!OrigArg->getType()->isRealFloatingType())
3535     return Diag(OrigArg->getLocStart(),
3536                 diag::err_typecheck_call_invalid_unary_fp)
3537       << OrigArg->getType() << OrigArg->getSourceRange();
3538 
3539   // If this is an implicit conversion from float -> double, remove it.
3540   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3541     Expr *CastArg = Cast->getSubExpr();
3542     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3543       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3544              "promotion from float to double is the only expected cast here");
3545       Cast->setSubExpr(nullptr);
3546       TheCall->setArg(NumArgs-1, CastArg);
3547     }
3548   }
3549 
3550   return false;
3551 }
3552 
3553 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3554 // This is declared to take (...), so we have to check everything.
3555 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3556   if (TheCall->getNumArgs() < 2)
3557     return ExprError(Diag(TheCall->getLocEnd(),
3558                           diag::err_typecheck_call_too_few_args_at_least)
3559                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3560                      << TheCall->getSourceRange());
3561 
3562   // Determine which of the following types of shufflevector we're checking:
3563   // 1) unary, vector mask: (lhs, mask)
3564   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3565   QualType resType = TheCall->getArg(0)->getType();
3566   unsigned numElements = 0;
3567 
3568   if (!TheCall->getArg(0)->isTypeDependent() &&
3569       !TheCall->getArg(1)->isTypeDependent()) {
3570     QualType LHSType = TheCall->getArg(0)->getType();
3571     QualType RHSType = TheCall->getArg(1)->getType();
3572 
3573     if (!LHSType->isVectorType() || !RHSType->isVectorType())
3574       return ExprError(Diag(TheCall->getLocStart(),
3575                             diag::err_shufflevector_non_vector)
3576                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3577                                       TheCall->getArg(1)->getLocEnd()));
3578 
3579     numElements = LHSType->getAs<VectorType>()->getNumElements();
3580     unsigned numResElements = TheCall->getNumArgs() - 2;
3581 
3582     // Check to see if we have a call with 2 vector arguments, the unary shuffle
3583     // with mask.  If so, verify that RHS is an integer vector type with the
3584     // same number of elts as lhs.
3585     if (TheCall->getNumArgs() == 2) {
3586       if (!RHSType->hasIntegerRepresentation() ||
3587           RHSType->getAs<VectorType>()->getNumElements() != numElements)
3588         return ExprError(Diag(TheCall->getLocStart(),
3589                               diag::err_shufflevector_incompatible_vector)
3590                          << SourceRange(TheCall->getArg(1)->getLocStart(),
3591                                         TheCall->getArg(1)->getLocEnd()));
3592     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3593       return ExprError(Diag(TheCall->getLocStart(),
3594                             diag::err_shufflevector_incompatible_vector)
3595                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3596                                       TheCall->getArg(1)->getLocEnd()));
3597     } else if (numElements != numResElements) {
3598       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3599       resType = Context.getVectorType(eltType, numResElements,
3600                                       VectorType::GenericVector);
3601     }
3602   }
3603 
3604   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3605     if (TheCall->getArg(i)->isTypeDependent() ||
3606         TheCall->getArg(i)->isValueDependent())
3607       continue;
3608 
3609     llvm::APSInt Result(32);
3610     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3611       return ExprError(Diag(TheCall->getLocStart(),
3612                             diag::err_shufflevector_nonconstant_argument)
3613                        << TheCall->getArg(i)->getSourceRange());
3614 
3615     // Allow -1 which will be translated to undef in the IR.
3616     if (Result.isSigned() && Result.isAllOnesValue())
3617       continue;
3618 
3619     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3620       return ExprError(Diag(TheCall->getLocStart(),
3621                             diag::err_shufflevector_argument_too_large)
3622                        << TheCall->getArg(i)->getSourceRange());
3623   }
3624 
3625   SmallVector<Expr*, 32> exprs;
3626 
3627   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3628     exprs.push_back(TheCall->getArg(i));
3629     TheCall->setArg(i, nullptr);
3630   }
3631 
3632   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3633                                          TheCall->getCallee()->getLocStart(),
3634                                          TheCall->getRParenLoc());
3635 }
3636 
3637 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3638 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3639                                        SourceLocation BuiltinLoc,
3640                                        SourceLocation RParenLoc) {
3641   ExprValueKind VK = VK_RValue;
3642   ExprObjectKind OK = OK_Ordinary;
3643   QualType DstTy = TInfo->getType();
3644   QualType SrcTy = E->getType();
3645 
3646   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3647     return ExprError(Diag(BuiltinLoc,
3648                           diag::err_convertvector_non_vector)
3649                      << E->getSourceRange());
3650   if (!DstTy->isVectorType() && !DstTy->isDependentType())
3651     return ExprError(Diag(BuiltinLoc,
3652                           diag::err_convertvector_non_vector_type));
3653 
3654   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3655     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3656     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3657     if (SrcElts != DstElts)
3658       return ExprError(Diag(BuiltinLoc,
3659                             diag::err_convertvector_incompatible_vector)
3660                        << E->getSourceRange());
3661   }
3662 
3663   return new (Context)
3664       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3665 }
3666 
3667 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3668 // This is declared to take (const void*, ...) and can take two
3669 // optional constant int args.
3670 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3671   unsigned NumArgs = TheCall->getNumArgs();
3672 
3673   if (NumArgs > 3)
3674     return Diag(TheCall->getLocEnd(),
3675              diag::err_typecheck_call_too_many_args_at_most)
3676              << 0 /*function call*/ << 3 << NumArgs
3677              << TheCall->getSourceRange();
3678 
3679   // Argument 0 is checked for us and the remaining arguments must be
3680   // constant integers.
3681   for (unsigned i = 1; i != NumArgs; ++i)
3682     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3683       return true;
3684 
3685   return false;
3686 }
3687 
3688 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3689 // __assume does not evaluate its arguments, and should warn if its argument
3690 // has side effects.
3691 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3692   Expr *Arg = TheCall->getArg(0);
3693   if (Arg->isInstantiationDependent()) return false;
3694 
3695   if (Arg->HasSideEffects(Context))
3696     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3697       << Arg->getSourceRange()
3698       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3699 
3700   return false;
3701 }
3702 
3703 /// Handle __builtin_assume_aligned. This is declared
3704 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3705 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3706   unsigned NumArgs = TheCall->getNumArgs();
3707 
3708   if (NumArgs > 3)
3709     return Diag(TheCall->getLocEnd(),
3710              diag::err_typecheck_call_too_many_args_at_most)
3711              << 0 /*function call*/ << 3 << NumArgs
3712              << TheCall->getSourceRange();
3713 
3714   // The alignment must be a constant integer.
3715   Expr *Arg = TheCall->getArg(1);
3716 
3717   // We can't check the value of a dependent argument.
3718   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3719     llvm::APSInt Result;
3720     if (SemaBuiltinConstantArg(TheCall, 1, Result))
3721       return true;
3722 
3723     if (!Result.isPowerOf2())
3724       return Diag(TheCall->getLocStart(),
3725                   diag::err_alignment_not_power_of_two)
3726            << Arg->getSourceRange();
3727   }
3728 
3729   if (NumArgs > 2) {
3730     ExprResult Arg(TheCall->getArg(2));
3731     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3732       Context.getSizeType(), false);
3733     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3734     if (Arg.isInvalid()) return true;
3735     TheCall->setArg(2, Arg.get());
3736   }
3737 
3738   return false;
3739 }
3740 
3741 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3742 /// TheCall is a constant expression.
3743 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3744                                   llvm::APSInt &Result) {
3745   Expr *Arg = TheCall->getArg(ArgNum);
3746   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3747   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3748 
3749   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3750 
3751   if (!Arg->isIntegerConstantExpr(Result, Context))
3752     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
3753                 << FDecl->getDeclName() <<  Arg->getSourceRange();
3754 
3755   return false;
3756 }
3757 
3758 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3759 /// TheCall is a constant expression in the range [Low, High].
3760 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3761                                        int Low, int High) {
3762   llvm::APSInt Result;
3763 
3764   // We can't check the value of a dependent argument.
3765   Expr *Arg = TheCall->getArg(ArgNum);
3766   if (Arg->isTypeDependent() || Arg->isValueDependent())
3767     return false;
3768 
3769   // Check constant-ness first.
3770   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3771     return true;
3772 
3773   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
3774     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
3775       << Low << High << Arg->getSourceRange();
3776 
3777   return false;
3778 }
3779 
3780 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3781 /// TheCall is an ARM/AArch64 special register string literal.
3782 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3783                                     int ArgNum, unsigned ExpectedFieldNum,
3784                                     bool AllowName) {
3785   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3786                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3787                       BuiltinID == ARM::BI__builtin_arm_rsr ||
3788                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
3789                       BuiltinID == ARM::BI__builtin_arm_wsr ||
3790                       BuiltinID == ARM::BI__builtin_arm_wsrp;
3791   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3792                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3793                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
3794                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3795                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
3796                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
3797   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3798 
3799   // We can't check the value of a dependent argument.
3800   Expr *Arg = TheCall->getArg(ArgNum);
3801   if (Arg->isTypeDependent() || Arg->isValueDependent())
3802     return false;
3803 
3804   // Check if the argument is a string literal.
3805   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3806     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3807            << Arg->getSourceRange();
3808 
3809   // Check the type of special register given.
3810   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3811   SmallVector<StringRef, 6> Fields;
3812   Reg.split(Fields, ":");
3813 
3814   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3815     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3816            << Arg->getSourceRange();
3817 
3818   // If the string is the name of a register then we cannot check that it is
3819   // valid here but if the string is of one the forms described in ACLE then we
3820   // can check that the supplied fields are integers and within the valid
3821   // ranges.
3822   if (Fields.size() > 1) {
3823     bool FiveFields = Fields.size() == 5;
3824 
3825     bool ValidString = true;
3826     if (IsARMBuiltin) {
3827       ValidString &= Fields[0].startswith_lower("cp") ||
3828                      Fields[0].startswith_lower("p");
3829       if (ValidString)
3830         Fields[0] =
3831           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3832 
3833       ValidString &= Fields[2].startswith_lower("c");
3834       if (ValidString)
3835         Fields[2] = Fields[2].drop_front(1);
3836 
3837       if (FiveFields) {
3838         ValidString &= Fields[3].startswith_lower("c");
3839         if (ValidString)
3840           Fields[3] = Fields[3].drop_front(1);
3841       }
3842     }
3843 
3844     SmallVector<int, 5> Ranges;
3845     if (FiveFields)
3846       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3847     else
3848       Ranges.append({15, 7, 15});
3849 
3850     for (unsigned i=0; i<Fields.size(); ++i) {
3851       int IntField;
3852       ValidString &= !Fields[i].getAsInteger(10, IntField);
3853       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3854     }
3855 
3856     if (!ValidString)
3857       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3858              << Arg->getSourceRange();
3859 
3860   } else if (IsAArch64Builtin && Fields.size() == 1) {
3861     // If the register name is one of those that appear in the condition below
3862     // and the special register builtin being used is one of the write builtins,
3863     // then we require that the argument provided for writing to the register
3864     // is an integer constant expression. This is because it will be lowered to
3865     // an MSR (immediate) instruction, so we need to know the immediate at
3866     // compile time.
3867     if (TheCall->getNumArgs() != 2)
3868       return false;
3869 
3870     std::string RegLower = Reg.lower();
3871     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3872         RegLower != "pan" && RegLower != "uao")
3873       return false;
3874 
3875     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3876   }
3877 
3878   return false;
3879 }
3880 
3881 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3882 /// This checks that the target supports __builtin_longjmp and
3883 /// that val is a constant 1.
3884 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
3885   if (!Context.getTargetInfo().hasSjLjLowering())
3886     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3887              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3888 
3889   Expr *Arg = TheCall->getArg(1);
3890   llvm::APSInt Result;
3891 
3892   // TODO: This is less than ideal. Overload this to take a value.
3893   if (SemaBuiltinConstantArg(TheCall, 1, Result))
3894     return true;
3895 
3896   if (Result != 1)
3897     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3898              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3899 
3900   return false;
3901 }
3902 
3903 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3904 /// This checks that the target supports __builtin_setjmp.
3905 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3906   if (!Context.getTargetInfo().hasSjLjLowering())
3907     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3908              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3909   return false;
3910 }
3911 
3912 namespace {
3913 class UncoveredArgHandler {
3914   enum { Unknown = -1, AllCovered = -2 };
3915   signed FirstUncoveredArg;
3916   SmallVector<const Expr *, 4> DiagnosticExprs;
3917 
3918 public:
3919   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3920 
3921   bool hasUncoveredArg() const {
3922     return (FirstUncoveredArg >= 0);
3923   }
3924 
3925   unsigned getUncoveredArg() const {
3926     assert(hasUncoveredArg() && "no uncovered argument");
3927     return FirstUncoveredArg;
3928   }
3929 
3930   void setAllCovered() {
3931     // A string has been found with all arguments covered, so clear out
3932     // the diagnostics.
3933     DiagnosticExprs.clear();
3934     FirstUncoveredArg = AllCovered;
3935   }
3936 
3937   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3938     assert(NewFirstUncoveredArg >= 0 && "Outside range");
3939 
3940     // Don't update if a previous string covers all arguments.
3941     if (FirstUncoveredArg == AllCovered)
3942       return;
3943 
3944     // UncoveredArgHandler tracks the highest uncovered argument index
3945     // and with it all the strings that match this index.
3946     if (NewFirstUncoveredArg == FirstUncoveredArg)
3947       DiagnosticExprs.push_back(StrExpr);
3948     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3949       DiagnosticExprs.clear();
3950       DiagnosticExprs.push_back(StrExpr);
3951       FirstUncoveredArg = NewFirstUncoveredArg;
3952     }
3953   }
3954 
3955   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3956 };
3957 
3958 enum StringLiteralCheckType {
3959   SLCT_NotALiteral,
3960   SLCT_UncheckedLiteral,
3961   SLCT_CheckedLiteral
3962 };
3963 } // end anonymous namespace
3964 
3965 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
3966                                      BinaryOperatorKind BinOpKind,
3967                                      bool AddendIsRight) {
3968   unsigned BitWidth = Offset.getBitWidth();
3969   unsigned AddendBitWidth = Addend.getBitWidth();
3970   // There might be negative interim results.
3971   if (Addend.isUnsigned()) {
3972     Addend = Addend.zext(++AddendBitWidth);
3973     Addend.setIsSigned(true);
3974   }
3975   // Adjust the bit width of the APSInts.
3976   if (AddendBitWidth > BitWidth) {
3977     Offset = Offset.sext(AddendBitWidth);
3978     BitWidth = AddendBitWidth;
3979   } else if (BitWidth > AddendBitWidth) {
3980     Addend = Addend.sext(BitWidth);
3981   }
3982 
3983   bool Ov = false;
3984   llvm::APSInt ResOffset = Offset;
3985   if (BinOpKind == BO_Add)
3986     ResOffset = Offset.sadd_ov(Addend, Ov);
3987   else {
3988     assert(AddendIsRight && BinOpKind == BO_Sub &&
3989            "operator must be add or sub with addend on the right");
3990     ResOffset = Offset.ssub_ov(Addend, Ov);
3991   }
3992 
3993   // We add an offset to a pointer here so we should support an offset as big as
3994   // possible.
3995   if (Ov) {
3996     assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
3997     Offset = Offset.sext(2 * BitWidth);
3998     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
3999     return;
4000   }
4001 
4002   Offset = ResOffset;
4003 }
4004 
4005 namespace {
4006 // This is a wrapper class around StringLiteral to support offsetted string
4007 // literals as format strings. It takes the offset into account when returning
4008 // the string and its length or the source locations to display notes correctly.
4009 class FormatStringLiteral {
4010   const StringLiteral *FExpr;
4011   int64_t Offset;
4012 
4013  public:
4014   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4015       : FExpr(fexpr), Offset(Offset) {}
4016 
4017   StringRef getString() const {
4018     return FExpr->getString().drop_front(Offset);
4019   }
4020 
4021   unsigned getByteLength() const {
4022     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4023   }
4024   unsigned getLength() const { return FExpr->getLength() - Offset; }
4025   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4026 
4027   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4028 
4029   QualType getType() const { return FExpr->getType(); }
4030 
4031   bool isAscii() const { return FExpr->isAscii(); }
4032   bool isWide() const { return FExpr->isWide(); }
4033   bool isUTF8() const { return FExpr->isUTF8(); }
4034   bool isUTF16() const { return FExpr->isUTF16(); }
4035   bool isUTF32() const { return FExpr->isUTF32(); }
4036   bool isPascal() const { return FExpr->isPascal(); }
4037 
4038   SourceLocation getLocationOfByte(
4039       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4040       const TargetInfo &Target, unsigned *StartToken = nullptr,
4041       unsigned *StartTokenByteOffset = nullptr) const {
4042     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4043                                     StartToken, StartTokenByteOffset);
4044   }
4045 
4046   SourceLocation getLocStart() const LLVM_READONLY {
4047     return FExpr->getLocStart().getLocWithOffset(Offset);
4048   }
4049   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4050 };
4051 }  // end anonymous namespace
4052 
4053 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4054                               const Expr *OrigFormatExpr,
4055                               ArrayRef<const Expr *> Args,
4056                               bool HasVAListArg, unsigned format_idx,
4057                               unsigned firstDataArg,
4058                               Sema::FormatStringType Type,
4059                               bool inFunctionCall,
4060                               Sema::VariadicCallType CallType,
4061                               llvm::SmallBitVector &CheckedVarArgs,
4062                               UncoveredArgHandler &UncoveredArg);
4063 
4064 // Determine if an expression is a string literal or constant string.
4065 // If this function returns false on the arguments to a function expecting a
4066 // format string, we will usually need to emit a warning.
4067 // True string literals are then checked by CheckFormatString.
4068 static StringLiteralCheckType
4069 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4070                       bool HasVAListArg, unsigned format_idx,
4071                       unsigned firstDataArg, Sema::FormatStringType Type,
4072                       Sema::VariadicCallType CallType, bool InFunctionCall,
4073                       llvm::SmallBitVector &CheckedVarArgs,
4074                       UncoveredArgHandler &UncoveredArg,
4075                       llvm::APSInt Offset) {
4076  tryAgain:
4077   assert(Offset.isSigned() && "invalid offset");
4078 
4079   if (E->isTypeDependent() || E->isValueDependent())
4080     return SLCT_NotALiteral;
4081 
4082   E = E->IgnoreParenCasts();
4083 
4084   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4085     // Technically -Wformat-nonliteral does not warn about this case.
4086     // The behavior of printf and friends in this case is implementation
4087     // dependent.  Ideally if the format string cannot be null then
4088     // it should have a 'nonnull' attribute in the function prototype.
4089     return SLCT_UncheckedLiteral;
4090 
4091   switch (E->getStmtClass()) {
4092   case Stmt::BinaryConditionalOperatorClass:
4093   case Stmt::ConditionalOperatorClass: {
4094     // The expression is a literal if both sub-expressions were, and it was
4095     // completely checked only if both sub-expressions were checked.
4096     const AbstractConditionalOperator *C =
4097         cast<AbstractConditionalOperator>(E);
4098 
4099     // Determine whether it is necessary to check both sub-expressions, for
4100     // example, because the condition expression is a constant that can be
4101     // evaluated at compile time.
4102     bool CheckLeft = true, CheckRight = true;
4103 
4104     bool Cond;
4105     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4106       if (Cond)
4107         CheckRight = false;
4108       else
4109         CheckLeft = false;
4110     }
4111 
4112     // We need to maintain the offsets for the right and the left hand side
4113     // separately to check if every possible indexed expression is a valid
4114     // string literal. They might have different offsets for different string
4115     // literals in the end.
4116     StringLiteralCheckType Left;
4117     if (!CheckLeft)
4118       Left = SLCT_UncheckedLiteral;
4119     else {
4120       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4121                                    HasVAListArg, format_idx, firstDataArg,
4122                                    Type, CallType, InFunctionCall,
4123                                    CheckedVarArgs, UncoveredArg, Offset);
4124       if (Left == SLCT_NotALiteral || !CheckRight) {
4125         return Left;
4126       }
4127     }
4128 
4129     StringLiteralCheckType Right =
4130         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4131                               HasVAListArg, format_idx, firstDataArg,
4132                               Type, CallType, InFunctionCall, CheckedVarArgs,
4133                               UncoveredArg, Offset);
4134 
4135     return (CheckLeft && Left < Right) ? Left : Right;
4136   }
4137 
4138   case Stmt::ImplicitCastExprClass: {
4139     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4140     goto tryAgain;
4141   }
4142 
4143   case Stmt::OpaqueValueExprClass:
4144     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4145       E = src;
4146       goto tryAgain;
4147     }
4148     return SLCT_NotALiteral;
4149 
4150   case Stmt::PredefinedExprClass:
4151     // While __func__, etc., are technically not string literals, they
4152     // cannot contain format specifiers and thus are not a security
4153     // liability.
4154     return SLCT_UncheckedLiteral;
4155 
4156   case Stmt::DeclRefExprClass: {
4157     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4158 
4159     // As an exception, do not flag errors for variables binding to
4160     // const string literals.
4161     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4162       bool isConstant = false;
4163       QualType T = DR->getType();
4164 
4165       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4166         isConstant = AT->getElementType().isConstant(S.Context);
4167       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4168         isConstant = T.isConstant(S.Context) &&
4169                      PT->getPointeeType().isConstant(S.Context);
4170       } else if (T->isObjCObjectPointerType()) {
4171         // In ObjC, there is usually no "const ObjectPointer" type,
4172         // so don't check if the pointee type is constant.
4173         isConstant = T.isConstant(S.Context);
4174       }
4175 
4176       if (isConstant) {
4177         if (const Expr *Init = VD->getAnyInitializer()) {
4178           // Look through initializers like const char c[] = { "foo" }
4179           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4180             if (InitList->isStringLiteralInit())
4181               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4182           }
4183           return checkFormatStringExpr(S, Init, Args,
4184                                        HasVAListArg, format_idx,
4185                                        firstDataArg, Type, CallType,
4186                                        /*InFunctionCall*/ false, CheckedVarArgs,
4187                                        UncoveredArg, Offset);
4188         }
4189       }
4190 
4191       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4192       // special check to see if the format string is a function parameter
4193       // of the function calling the printf function.  If the function
4194       // has an attribute indicating it is a printf-like function, then we
4195       // should suppress warnings concerning non-literals being used in a call
4196       // to a vprintf function.  For example:
4197       //
4198       // void
4199       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4200       //      va_list ap;
4201       //      va_start(ap, fmt);
4202       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4203       //      ...
4204       // }
4205       if (HasVAListArg) {
4206         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4207           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4208             int PVIndex = PV->getFunctionScopeIndex() + 1;
4209             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4210               // adjust for implicit parameter
4211               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4212                 if (MD->isInstance())
4213                   ++PVIndex;
4214               // We also check if the formats are compatible.
4215               // We can't pass a 'scanf' string to a 'printf' function.
4216               if (PVIndex == PVFormat->getFormatIdx() &&
4217                   Type == S.GetFormatStringType(PVFormat))
4218                 return SLCT_UncheckedLiteral;
4219             }
4220           }
4221         }
4222       }
4223     }
4224 
4225     return SLCT_NotALiteral;
4226   }
4227 
4228   case Stmt::CallExprClass:
4229   case Stmt::CXXMemberCallExprClass: {
4230     const CallExpr *CE = cast<CallExpr>(E);
4231     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4232       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4233         unsigned ArgIndex = FA->getFormatIdx();
4234         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4235           if (MD->isInstance())
4236             --ArgIndex;
4237         const Expr *Arg = CE->getArg(ArgIndex - 1);
4238 
4239         return checkFormatStringExpr(S, Arg, Args,
4240                                      HasVAListArg, format_idx, firstDataArg,
4241                                      Type, CallType, InFunctionCall,
4242                                      CheckedVarArgs, UncoveredArg, Offset);
4243       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4244         unsigned BuiltinID = FD->getBuiltinID();
4245         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4246             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4247           const Expr *Arg = CE->getArg(0);
4248           return checkFormatStringExpr(S, Arg, Args,
4249                                        HasVAListArg, format_idx,
4250                                        firstDataArg, Type, CallType,
4251                                        InFunctionCall, CheckedVarArgs,
4252                                        UncoveredArg, Offset);
4253         }
4254       }
4255     }
4256 
4257     return SLCT_NotALiteral;
4258   }
4259   case Stmt::ObjCStringLiteralClass:
4260   case Stmt::StringLiteralClass: {
4261     const StringLiteral *StrE = nullptr;
4262 
4263     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4264       StrE = ObjCFExpr->getString();
4265     else
4266       StrE = cast<StringLiteral>(E);
4267 
4268     if (StrE) {
4269       if (Offset.isNegative() || Offset > StrE->getLength()) {
4270         // TODO: It would be better to have an explicit warning for out of
4271         // bounds literals.
4272         return SLCT_NotALiteral;
4273       }
4274       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4275       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4276                         firstDataArg, Type, InFunctionCall, CallType,
4277                         CheckedVarArgs, UncoveredArg);
4278       return SLCT_CheckedLiteral;
4279     }
4280 
4281     return SLCT_NotALiteral;
4282   }
4283   case Stmt::BinaryOperatorClass: {
4284     llvm::APSInt LResult;
4285     llvm::APSInt RResult;
4286 
4287     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4288 
4289     // A string literal + an int offset is still a string literal.
4290     if (BinOp->isAdditiveOp()) {
4291       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4292       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4293 
4294       if (LIsInt != RIsInt) {
4295         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4296 
4297         if (LIsInt) {
4298           if (BinOpKind == BO_Add) {
4299             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4300             E = BinOp->getRHS();
4301             goto tryAgain;
4302           }
4303         } else {
4304           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4305           E = BinOp->getLHS();
4306           goto tryAgain;
4307         }
4308       }
4309     }
4310 
4311     return SLCT_NotALiteral;
4312   }
4313   case Stmt::UnaryOperatorClass: {
4314     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4315     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4316     if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4317       llvm::APSInt IndexResult;
4318       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4319         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4320         E = ASE->getBase();
4321         goto tryAgain;
4322       }
4323     }
4324 
4325     return SLCT_NotALiteral;
4326   }
4327 
4328   default:
4329     return SLCT_NotALiteral;
4330   }
4331 }
4332 
4333 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4334   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4335   .Case("scanf", FST_Scanf)
4336   .Cases("printf", "printf0", FST_Printf)
4337   .Cases("NSString", "CFString", FST_NSString)
4338   .Case("strftime", FST_Strftime)
4339   .Case("strfmon", FST_Strfmon)
4340   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4341   .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4342   .Case("os_trace", FST_OSTrace)
4343   .Default(FST_Unknown);
4344 }
4345 
4346 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4347 /// functions) for correct use of format strings.
4348 /// Returns true if a format string has been fully checked.
4349 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4350                                 ArrayRef<const Expr *> Args,
4351                                 bool IsCXXMember,
4352                                 VariadicCallType CallType,
4353                                 SourceLocation Loc, SourceRange Range,
4354                                 llvm::SmallBitVector &CheckedVarArgs) {
4355   FormatStringInfo FSI;
4356   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4357     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4358                                 FSI.FirstDataArg, GetFormatStringType(Format),
4359                                 CallType, Loc, Range, CheckedVarArgs);
4360   return false;
4361 }
4362 
4363 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4364                                 bool HasVAListArg, unsigned format_idx,
4365                                 unsigned firstDataArg, FormatStringType Type,
4366                                 VariadicCallType CallType,
4367                                 SourceLocation Loc, SourceRange Range,
4368                                 llvm::SmallBitVector &CheckedVarArgs) {
4369   // CHECK: printf/scanf-like function is called with no format string.
4370   if (format_idx >= Args.size()) {
4371     Diag(Loc, diag::warn_missing_format_string) << Range;
4372     return false;
4373   }
4374 
4375   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4376 
4377   // CHECK: format string is not a string literal.
4378   //
4379   // Dynamically generated format strings are difficult to
4380   // automatically vet at compile time.  Requiring that format strings
4381   // are string literals: (1) permits the checking of format strings by
4382   // the compiler and thereby (2) can practically remove the source of
4383   // many format string exploits.
4384 
4385   // Format string can be either ObjC string (e.g. @"%d") or
4386   // C string (e.g. "%d")
4387   // ObjC string uses the same format specifiers as C string, so we can use
4388   // the same format string checking logic for both ObjC and C strings.
4389   UncoveredArgHandler UncoveredArg;
4390   StringLiteralCheckType CT =
4391       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4392                             format_idx, firstDataArg, Type, CallType,
4393                             /*IsFunctionCall*/ true, CheckedVarArgs,
4394                             UncoveredArg,
4395                             /*no string offset*/ llvm::APSInt(64, false) = 0);
4396 
4397   // Generate a diagnostic where an uncovered argument is detected.
4398   if (UncoveredArg.hasUncoveredArg()) {
4399     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4400     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4401     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4402   }
4403 
4404   if (CT != SLCT_NotALiteral)
4405     // Literal format string found, check done!
4406     return CT == SLCT_CheckedLiteral;
4407 
4408   // Strftime is particular as it always uses a single 'time' argument,
4409   // so it is safe to pass a non-literal string.
4410   if (Type == FST_Strftime)
4411     return false;
4412 
4413   // Do not emit diag when the string param is a macro expansion and the
4414   // format is either NSString or CFString. This is a hack to prevent
4415   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4416   // which are usually used in place of NS and CF string literals.
4417   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4418   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4419     return false;
4420 
4421   // If there are no arguments specified, warn with -Wformat-security, otherwise
4422   // warn only with -Wformat-nonliteral.
4423   if (Args.size() == firstDataArg) {
4424     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4425       << OrigFormatExpr->getSourceRange();
4426     switch (Type) {
4427     default:
4428       break;
4429     case FST_Kprintf:
4430     case FST_FreeBSDKPrintf:
4431     case FST_Printf:
4432       Diag(FormatLoc, diag::note_format_security_fixit)
4433         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4434       break;
4435     case FST_NSString:
4436       Diag(FormatLoc, diag::note_format_security_fixit)
4437         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
4438       break;
4439     }
4440   } else {
4441     Diag(FormatLoc, diag::warn_format_nonliteral)
4442       << OrigFormatExpr->getSourceRange();
4443   }
4444   return false;
4445 }
4446 
4447 namespace {
4448 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4449 protected:
4450   Sema &S;
4451   const FormatStringLiteral *FExpr;
4452   const Expr *OrigFormatExpr;
4453   const unsigned FirstDataArg;
4454   const unsigned NumDataArgs;
4455   const char *Beg; // Start of format string.
4456   const bool HasVAListArg;
4457   ArrayRef<const Expr *> Args;
4458   unsigned FormatIdx;
4459   llvm::SmallBitVector CoveredArgs;
4460   bool usesPositionalArgs;
4461   bool atFirstArg;
4462   bool inFunctionCall;
4463   Sema::VariadicCallType CallType;
4464   llvm::SmallBitVector &CheckedVarArgs;
4465   UncoveredArgHandler &UncoveredArg;
4466 
4467 public:
4468   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
4469                      const Expr *origFormatExpr, unsigned firstDataArg,
4470                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
4471                      ArrayRef<const Expr *> Args,
4472                      unsigned formatIdx, bool inFunctionCall,
4473                      Sema::VariadicCallType callType,
4474                      llvm::SmallBitVector &CheckedVarArgs,
4475                      UncoveredArgHandler &UncoveredArg)
4476     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
4477       FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4478       Beg(beg), HasVAListArg(hasVAListArg),
4479       Args(Args), FormatIdx(formatIdx),
4480       usesPositionalArgs(false), atFirstArg(true),
4481       inFunctionCall(inFunctionCall), CallType(callType),
4482       CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4483     CoveredArgs.resize(numDataArgs);
4484     CoveredArgs.reset();
4485   }
4486 
4487   void DoneProcessing();
4488 
4489   void HandleIncompleteSpecifier(const char *startSpecifier,
4490                                  unsigned specifierLen) override;
4491 
4492   void HandleInvalidLengthModifier(
4493                            const analyze_format_string::FormatSpecifier &FS,
4494                            const analyze_format_string::ConversionSpecifier &CS,
4495                            const char *startSpecifier, unsigned specifierLen,
4496                            unsigned DiagID);
4497 
4498   void HandleNonStandardLengthModifier(
4499                     const analyze_format_string::FormatSpecifier &FS,
4500                     const char *startSpecifier, unsigned specifierLen);
4501 
4502   void HandleNonStandardConversionSpecifier(
4503                     const analyze_format_string::ConversionSpecifier &CS,
4504                     const char *startSpecifier, unsigned specifierLen);
4505 
4506   void HandlePosition(const char *startPos, unsigned posLen) override;
4507 
4508   void HandleInvalidPosition(const char *startSpecifier,
4509                              unsigned specifierLen,
4510                              analyze_format_string::PositionContext p) override;
4511 
4512   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
4513 
4514   void HandleNullChar(const char *nullCharacter) override;
4515 
4516   template <typename Range>
4517   static void
4518   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4519                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4520                        bool IsStringLocation, Range StringRange,
4521                        ArrayRef<FixItHint> Fixit = None);
4522 
4523 protected:
4524   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4525                                         const char *startSpec,
4526                                         unsigned specifierLen,
4527                                         const char *csStart, unsigned csLen);
4528 
4529   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4530                                          const char *startSpec,
4531                                          unsigned specifierLen);
4532 
4533   SourceRange getFormatStringRange();
4534   CharSourceRange getSpecifierRange(const char *startSpecifier,
4535                                     unsigned specifierLen);
4536   SourceLocation getLocationOfByte(const char *x);
4537 
4538   const Expr *getDataArg(unsigned i) const;
4539 
4540   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4541                     const analyze_format_string::ConversionSpecifier &CS,
4542                     const char *startSpecifier, unsigned specifierLen,
4543                     unsigned argIndex);
4544 
4545   template <typename Range>
4546   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4547                             bool IsStringLocation, Range StringRange,
4548                             ArrayRef<FixItHint> Fixit = None);
4549 };
4550 } // end anonymous namespace
4551 
4552 SourceRange CheckFormatHandler::getFormatStringRange() {
4553   return OrigFormatExpr->getSourceRange();
4554 }
4555 
4556 CharSourceRange CheckFormatHandler::
4557 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
4558   SourceLocation Start = getLocationOfByte(startSpecifier);
4559   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
4560 
4561   // Advance the end SourceLocation by one due to half-open ranges.
4562   End = End.getLocWithOffset(1);
4563 
4564   return CharSourceRange::getCharRange(Start, End);
4565 }
4566 
4567 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
4568   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4569                                   S.getLangOpts(), S.Context.getTargetInfo());
4570 }
4571 
4572 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4573                                                    unsigned specifierLen){
4574   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4575                        getLocationOfByte(startSpecifier),
4576                        /*IsStringLocation*/true,
4577                        getSpecifierRange(startSpecifier, specifierLen));
4578 }
4579 
4580 void CheckFormatHandler::HandleInvalidLengthModifier(
4581     const analyze_format_string::FormatSpecifier &FS,
4582     const analyze_format_string::ConversionSpecifier &CS,
4583     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
4584   using namespace analyze_format_string;
4585 
4586   const LengthModifier &LM = FS.getLengthModifier();
4587   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4588 
4589   // See if we know how to fix this length modifier.
4590   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4591   if (FixedLM) {
4592     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4593                          getLocationOfByte(LM.getStart()),
4594                          /*IsStringLocation*/true,
4595                          getSpecifierRange(startSpecifier, specifierLen));
4596 
4597     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4598       << FixedLM->toString()
4599       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4600 
4601   } else {
4602     FixItHint Hint;
4603     if (DiagID == diag::warn_format_nonsensical_length)
4604       Hint = FixItHint::CreateRemoval(LMRange);
4605 
4606     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4607                          getLocationOfByte(LM.getStart()),
4608                          /*IsStringLocation*/true,
4609                          getSpecifierRange(startSpecifier, specifierLen),
4610                          Hint);
4611   }
4612 }
4613 
4614 void CheckFormatHandler::HandleNonStandardLengthModifier(
4615     const analyze_format_string::FormatSpecifier &FS,
4616     const char *startSpecifier, unsigned specifierLen) {
4617   using namespace analyze_format_string;
4618 
4619   const LengthModifier &LM = FS.getLengthModifier();
4620   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4621 
4622   // See if we know how to fix this length modifier.
4623   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4624   if (FixedLM) {
4625     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4626                            << LM.toString() << 0,
4627                          getLocationOfByte(LM.getStart()),
4628                          /*IsStringLocation*/true,
4629                          getSpecifierRange(startSpecifier, specifierLen));
4630 
4631     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4632       << FixedLM->toString()
4633       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4634 
4635   } else {
4636     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4637                            << LM.toString() << 0,
4638                          getLocationOfByte(LM.getStart()),
4639                          /*IsStringLocation*/true,
4640                          getSpecifierRange(startSpecifier, specifierLen));
4641   }
4642 }
4643 
4644 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4645     const analyze_format_string::ConversionSpecifier &CS,
4646     const char *startSpecifier, unsigned specifierLen) {
4647   using namespace analyze_format_string;
4648 
4649   // See if we know how to fix this conversion specifier.
4650   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
4651   if (FixedCS) {
4652     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4653                           << CS.toString() << /*conversion specifier*/1,
4654                          getLocationOfByte(CS.getStart()),
4655                          /*IsStringLocation*/true,
4656                          getSpecifierRange(startSpecifier, specifierLen));
4657 
4658     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4659     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4660       << FixedCS->toString()
4661       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4662   } else {
4663     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4664                           << CS.toString() << /*conversion specifier*/1,
4665                          getLocationOfByte(CS.getStart()),
4666                          /*IsStringLocation*/true,
4667                          getSpecifierRange(startSpecifier, specifierLen));
4668   }
4669 }
4670 
4671 void CheckFormatHandler::HandlePosition(const char *startPos,
4672                                         unsigned posLen) {
4673   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4674                                getLocationOfByte(startPos),
4675                                /*IsStringLocation*/true,
4676                                getSpecifierRange(startPos, posLen));
4677 }
4678 
4679 void
4680 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4681                                      analyze_format_string::PositionContext p) {
4682   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4683                          << (unsigned) p,
4684                        getLocationOfByte(startPos), /*IsStringLocation*/true,
4685                        getSpecifierRange(startPos, posLen));
4686 }
4687 
4688 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
4689                                             unsigned posLen) {
4690   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4691                                getLocationOfByte(startPos),
4692                                /*IsStringLocation*/true,
4693                                getSpecifierRange(startPos, posLen));
4694 }
4695 
4696 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
4697   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
4698     // The presence of a null character is likely an error.
4699     EmitFormatDiagnostic(
4700       S.PDiag(diag::warn_printf_format_string_contains_null_char),
4701       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4702       getFormatStringRange());
4703   }
4704 }
4705 
4706 // Note that this may return NULL if there was an error parsing or building
4707 // one of the argument expressions.
4708 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
4709   return Args[FirstDataArg + i];
4710 }
4711 
4712 void CheckFormatHandler::DoneProcessing() {
4713   // Does the number of data arguments exceed the number of
4714   // format conversions in the format string?
4715   if (!HasVAListArg) {
4716       // Find any arguments that weren't covered.
4717     CoveredArgs.flip();
4718     signed notCoveredArg = CoveredArgs.find_first();
4719     if (notCoveredArg >= 0) {
4720       assert((unsigned)notCoveredArg < NumDataArgs);
4721       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4722     } else {
4723       UncoveredArg.setAllCovered();
4724     }
4725   }
4726 }
4727 
4728 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4729                                    const Expr *ArgExpr) {
4730   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4731          "Invalid state");
4732 
4733   if (!ArgExpr)
4734     return;
4735 
4736   SourceLocation Loc = ArgExpr->getLocStart();
4737 
4738   if (S.getSourceManager().isInSystemMacro(Loc))
4739     return;
4740 
4741   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4742   for (auto E : DiagnosticExprs)
4743     PDiag << E->getSourceRange();
4744 
4745   CheckFormatHandler::EmitFormatDiagnostic(
4746                                   S, IsFunctionCall, DiagnosticExprs[0],
4747                                   PDiag, Loc, /*IsStringLocation*/false,
4748                                   DiagnosticExprs[0]->getSourceRange());
4749 }
4750 
4751 bool
4752 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4753                                                      SourceLocation Loc,
4754                                                      const char *startSpec,
4755                                                      unsigned specifierLen,
4756                                                      const char *csStart,
4757                                                      unsigned csLen) {
4758   bool keepGoing = true;
4759   if (argIndex < NumDataArgs) {
4760     // Consider the argument coverered, even though the specifier doesn't
4761     // make sense.
4762     CoveredArgs.set(argIndex);
4763   }
4764   else {
4765     // If argIndex exceeds the number of data arguments we
4766     // don't issue a warning because that is just a cascade of warnings (and
4767     // they may have intended '%%' anyway). We don't want to continue processing
4768     // the format string after this point, however, as we will like just get
4769     // gibberish when trying to match arguments.
4770     keepGoing = false;
4771   }
4772 
4773   StringRef Specifier(csStart, csLen);
4774 
4775   // If the specifier in non-printable, it could be the first byte of a UTF-8
4776   // sequence. In that case, print the UTF-8 code point. If not, print the byte
4777   // hex value.
4778   std::string CodePointStr;
4779   if (!llvm::sys::locale::isPrint(*csStart)) {
4780     UTF32 CodePoint;
4781     const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4782     const UTF8 *E =
4783         reinterpret_cast<const UTF8 *>(csStart + csLen);
4784     ConversionResult Result =
4785         llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4786 
4787     if (Result != conversionOK) {
4788       unsigned char FirstChar = *csStart;
4789       CodePoint = (UTF32)FirstChar;
4790     }
4791 
4792     llvm::raw_string_ostream OS(CodePointStr);
4793     if (CodePoint < 256)
4794       OS << "\\x" << llvm::format("%02x", CodePoint);
4795     else if (CodePoint <= 0xFFFF)
4796       OS << "\\u" << llvm::format("%04x", CodePoint);
4797     else
4798       OS << "\\U" << llvm::format("%08x", CodePoint);
4799     OS.flush();
4800     Specifier = CodePointStr;
4801   }
4802 
4803   EmitFormatDiagnostic(
4804       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4805       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4806 
4807   return keepGoing;
4808 }
4809 
4810 void
4811 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4812                                                       const char *startSpec,
4813                                                       unsigned specifierLen) {
4814   EmitFormatDiagnostic(
4815     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4816     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4817 }
4818 
4819 bool
4820 CheckFormatHandler::CheckNumArgs(
4821   const analyze_format_string::FormatSpecifier &FS,
4822   const analyze_format_string::ConversionSpecifier &CS,
4823   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4824 
4825   if (argIndex >= NumDataArgs) {
4826     PartialDiagnostic PDiag = FS.usesPositionalArg()
4827       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4828            << (argIndex+1) << NumDataArgs)
4829       : S.PDiag(diag::warn_printf_insufficient_data_args);
4830     EmitFormatDiagnostic(
4831       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4832       getSpecifierRange(startSpecifier, specifierLen));
4833 
4834     // Since more arguments than conversion tokens are given, by extension
4835     // all arguments are covered, so mark this as so.
4836     UncoveredArg.setAllCovered();
4837     return false;
4838   }
4839   return true;
4840 }
4841 
4842 template<typename Range>
4843 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4844                                               SourceLocation Loc,
4845                                               bool IsStringLocation,
4846                                               Range StringRange,
4847                                               ArrayRef<FixItHint> FixIt) {
4848   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
4849                        Loc, IsStringLocation, StringRange, FixIt);
4850 }
4851 
4852 /// \brief If the format string is not within the funcion call, emit a note
4853 /// so that the function call and string are in diagnostic messages.
4854 ///
4855 /// \param InFunctionCall if true, the format string is within the function
4856 /// call and only one diagnostic message will be produced.  Otherwise, an
4857 /// extra note will be emitted pointing to location of the format string.
4858 ///
4859 /// \param ArgumentExpr the expression that is passed as the format string
4860 /// argument in the function call.  Used for getting locations when two
4861 /// diagnostics are emitted.
4862 ///
4863 /// \param PDiag the callee should already have provided any strings for the
4864 /// diagnostic message.  This function only adds locations and fixits
4865 /// to diagnostics.
4866 ///
4867 /// \param Loc primary location for diagnostic.  If two diagnostics are
4868 /// required, one will be at Loc and a new SourceLocation will be created for
4869 /// the other one.
4870 ///
4871 /// \param IsStringLocation if true, Loc points to the format string should be
4872 /// used for the note.  Otherwise, Loc points to the argument list and will
4873 /// be used with PDiag.
4874 ///
4875 /// \param StringRange some or all of the string to highlight.  This is
4876 /// templated so it can accept either a CharSourceRange or a SourceRange.
4877 ///
4878 /// \param FixIt optional fix it hint for the format string.
4879 template <typename Range>
4880 void CheckFormatHandler::EmitFormatDiagnostic(
4881     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
4882     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
4883     Range StringRange, ArrayRef<FixItHint> FixIt) {
4884   if (InFunctionCall) {
4885     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4886     D << StringRange;
4887     D << FixIt;
4888   } else {
4889     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4890       << ArgumentExpr->getSourceRange();
4891 
4892     const Sema::SemaDiagnosticBuilder &Note =
4893       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4894              diag::note_format_string_defined);
4895 
4896     Note << StringRange;
4897     Note << FixIt;
4898   }
4899 }
4900 
4901 //===--- CHECK: Printf format string checking ------------------------------===//
4902 
4903 namespace {
4904 class CheckPrintfHandler : public CheckFormatHandler {
4905   bool ObjCContext;
4906 
4907 public:
4908   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
4909                      const Expr *origFormatExpr, unsigned firstDataArg,
4910                      unsigned numDataArgs, bool isObjC,
4911                      const char *beg, bool hasVAListArg,
4912                      ArrayRef<const Expr *> Args,
4913                      unsigned formatIdx, bool inFunctionCall,
4914                      Sema::VariadicCallType CallType,
4915                      llvm::SmallBitVector &CheckedVarArgs,
4916                      UncoveredArgHandler &UncoveredArg)
4917     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4918                          numDataArgs, beg, hasVAListArg, Args,
4919                          formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4920                          UncoveredArg),
4921       ObjCContext(isObjC)
4922   {}
4923 
4924   bool HandleInvalidPrintfConversionSpecifier(
4925                                       const analyze_printf::PrintfSpecifier &FS,
4926                                       const char *startSpecifier,
4927                                       unsigned specifierLen) override;
4928 
4929   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4930                              const char *startSpecifier,
4931                              unsigned specifierLen) override;
4932   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4933                        const char *StartSpecifier,
4934                        unsigned SpecifierLen,
4935                        const Expr *E);
4936 
4937   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4938                     const char *startSpecifier, unsigned specifierLen);
4939   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4940                            const analyze_printf::OptionalAmount &Amt,
4941                            unsigned type,
4942                            const char *startSpecifier, unsigned specifierLen);
4943   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4944                   const analyze_printf::OptionalFlag &flag,
4945                   const char *startSpecifier, unsigned specifierLen);
4946   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4947                          const analyze_printf::OptionalFlag &ignoredFlag,
4948                          const analyze_printf::OptionalFlag &flag,
4949                          const char *startSpecifier, unsigned specifierLen);
4950   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
4951                            const Expr *E);
4952 
4953   void HandleEmptyObjCModifierFlag(const char *startFlag,
4954                                    unsigned flagLen) override;
4955 
4956   void HandleInvalidObjCModifierFlag(const char *startFlag,
4957                                             unsigned flagLen) override;
4958 
4959   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4960                                            const char *flagsEnd,
4961                                            const char *conversionPosition)
4962                                              override;
4963 };
4964 } // end anonymous namespace
4965 
4966 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4967                                       const analyze_printf::PrintfSpecifier &FS,
4968                                       const char *startSpecifier,
4969                                       unsigned specifierLen) {
4970   const analyze_printf::PrintfConversionSpecifier &CS =
4971     FS.getConversionSpecifier();
4972 
4973   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4974                                           getLocationOfByte(CS.getStart()),
4975                                           startSpecifier, specifierLen,
4976                                           CS.getStart(), CS.getLength());
4977 }
4978 
4979 bool CheckPrintfHandler::HandleAmount(
4980                                const analyze_format_string::OptionalAmount &Amt,
4981                                unsigned k, const char *startSpecifier,
4982                                unsigned specifierLen) {
4983   if (Amt.hasDataArgument()) {
4984     if (!HasVAListArg) {
4985       unsigned argIndex = Amt.getArgIndex();
4986       if (argIndex >= NumDataArgs) {
4987         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4988                                << k,
4989                              getLocationOfByte(Amt.getStart()),
4990                              /*IsStringLocation*/true,
4991                              getSpecifierRange(startSpecifier, specifierLen));
4992         // Don't do any more checking.  We will just emit
4993         // spurious errors.
4994         return false;
4995       }
4996 
4997       // Type check the data argument.  It should be an 'int'.
4998       // Although not in conformance with C99, we also allow the argument to be
4999       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5000       // doesn't emit a warning for that case.
5001       CoveredArgs.set(argIndex);
5002       const Expr *Arg = getDataArg(argIndex);
5003       if (!Arg)
5004         return false;
5005 
5006       QualType T = Arg->getType();
5007 
5008       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5009       assert(AT.isValid());
5010 
5011       if (!AT.matchesType(S.Context, T)) {
5012         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5013                                << k << AT.getRepresentativeTypeName(S.Context)
5014                                << T << Arg->getSourceRange(),
5015                              getLocationOfByte(Amt.getStart()),
5016                              /*IsStringLocation*/true,
5017                              getSpecifierRange(startSpecifier, specifierLen));
5018         // Don't do any more checking.  We will just emit
5019         // spurious errors.
5020         return false;
5021       }
5022     }
5023   }
5024   return true;
5025 }
5026 
5027 void CheckPrintfHandler::HandleInvalidAmount(
5028                                       const analyze_printf::PrintfSpecifier &FS,
5029                                       const analyze_printf::OptionalAmount &Amt,
5030                                       unsigned type,
5031                                       const char *startSpecifier,
5032                                       unsigned specifierLen) {
5033   const analyze_printf::PrintfConversionSpecifier &CS =
5034     FS.getConversionSpecifier();
5035 
5036   FixItHint fixit =
5037     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5038       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5039                                  Amt.getConstantLength()))
5040       : FixItHint();
5041 
5042   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5043                          << type << CS.toString(),
5044                        getLocationOfByte(Amt.getStart()),
5045                        /*IsStringLocation*/true,
5046                        getSpecifierRange(startSpecifier, specifierLen),
5047                        fixit);
5048 }
5049 
5050 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5051                                     const analyze_printf::OptionalFlag &flag,
5052                                     const char *startSpecifier,
5053                                     unsigned specifierLen) {
5054   // Warn about pointless flag with a fixit removal.
5055   const analyze_printf::PrintfConversionSpecifier &CS =
5056     FS.getConversionSpecifier();
5057   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5058                          << flag.toString() << CS.toString(),
5059                        getLocationOfByte(flag.getPosition()),
5060                        /*IsStringLocation*/true,
5061                        getSpecifierRange(startSpecifier, specifierLen),
5062                        FixItHint::CreateRemoval(
5063                          getSpecifierRange(flag.getPosition(), 1)));
5064 }
5065 
5066 void CheckPrintfHandler::HandleIgnoredFlag(
5067                                 const analyze_printf::PrintfSpecifier &FS,
5068                                 const analyze_printf::OptionalFlag &ignoredFlag,
5069                                 const analyze_printf::OptionalFlag &flag,
5070                                 const char *startSpecifier,
5071                                 unsigned specifierLen) {
5072   // Warn about ignored flag with a fixit removal.
5073   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5074                          << ignoredFlag.toString() << flag.toString(),
5075                        getLocationOfByte(ignoredFlag.getPosition()),
5076                        /*IsStringLocation*/true,
5077                        getSpecifierRange(startSpecifier, specifierLen),
5078                        FixItHint::CreateRemoval(
5079                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5080 }
5081 
5082 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5083 //                            bool IsStringLocation, Range StringRange,
5084 //                            ArrayRef<FixItHint> Fixit = None);
5085 
5086 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5087                                                      unsigned flagLen) {
5088   // Warn about an empty flag.
5089   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5090                        getLocationOfByte(startFlag),
5091                        /*IsStringLocation*/true,
5092                        getSpecifierRange(startFlag, flagLen));
5093 }
5094 
5095 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5096                                                        unsigned flagLen) {
5097   // Warn about an invalid flag.
5098   auto Range = getSpecifierRange(startFlag, flagLen);
5099   StringRef flag(startFlag, flagLen);
5100   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5101                       getLocationOfByte(startFlag),
5102                       /*IsStringLocation*/true,
5103                       Range, FixItHint::CreateRemoval(Range));
5104 }
5105 
5106 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5107     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5108     // Warn about using '[...]' without a '@' conversion.
5109     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5110     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5111     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5112                          getLocationOfByte(conversionPosition),
5113                          /*IsStringLocation*/true,
5114                          Range, FixItHint::CreateRemoval(Range));
5115 }
5116 
5117 // Determines if the specified is a C++ class or struct containing
5118 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5119 // "c_str()").
5120 template<typename MemberKind>
5121 static llvm::SmallPtrSet<MemberKind*, 1>
5122 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5123   const RecordType *RT = Ty->getAs<RecordType>();
5124   llvm::SmallPtrSet<MemberKind*, 1> Results;
5125 
5126   if (!RT)
5127     return Results;
5128   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5129   if (!RD || !RD->getDefinition())
5130     return Results;
5131 
5132   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5133                  Sema::LookupMemberName);
5134   R.suppressDiagnostics();
5135 
5136   // We just need to include all members of the right kind turned up by the
5137   // filter, at this point.
5138   if (S.LookupQualifiedName(R, RT->getDecl()))
5139     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5140       NamedDecl *decl = (*I)->getUnderlyingDecl();
5141       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5142         Results.insert(FK);
5143     }
5144   return Results;
5145 }
5146 
5147 /// Check if we could call '.c_str()' on an object.
5148 ///
5149 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5150 /// allow the call, or if it would be ambiguous).
5151 bool Sema::hasCStrMethod(const Expr *E) {
5152   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5153   MethodSet Results =
5154       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5155   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5156        MI != ME; ++MI)
5157     if ((*MI)->getMinRequiredArguments() == 0)
5158       return true;
5159   return false;
5160 }
5161 
5162 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5163 // better diagnostic if so. AT is assumed to be valid.
5164 // Returns true when a c_str() conversion method is found.
5165 bool CheckPrintfHandler::checkForCStrMembers(
5166     const analyze_printf::ArgType &AT, const Expr *E) {
5167   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5168 
5169   MethodSet Results =
5170       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5171 
5172   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5173        MI != ME; ++MI) {
5174     const CXXMethodDecl *Method = *MI;
5175     if (Method->getMinRequiredArguments() == 0 &&
5176         AT.matchesType(S.Context, Method->getReturnType())) {
5177       // FIXME: Suggest parens if the expression needs them.
5178       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5179       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5180           << "c_str()"
5181           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5182       return true;
5183     }
5184   }
5185 
5186   return false;
5187 }
5188 
5189 bool
5190 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5191                                             &FS,
5192                                           const char *startSpecifier,
5193                                           unsigned specifierLen) {
5194   using namespace analyze_format_string;
5195   using namespace analyze_printf;
5196   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5197 
5198   if (FS.consumesDataArgument()) {
5199     if (atFirstArg) {
5200         atFirstArg = false;
5201         usesPositionalArgs = FS.usesPositionalArg();
5202     }
5203     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5204       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5205                                         startSpecifier, specifierLen);
5206       return false;
5207     }
5208   }
5209 
5210   // First check if the field width, precision, and conversion specifier
5211   // have matching data arguments.
5212   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5213                     startSpecifier, specifierLen)) {
5214     return false;
5215   }
5216 
5217   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5218                     startSpecifier, specifierLen)) {
5219     return false;
5220   }
5221 
5222   if (!CS.consumesDataArgument()) {
5223     // FIXME: Technically specifying a precision or field width here
5224     // makes no sense.  Worth issuing a warning at some point.
5225     return true;
5226   }
5227 
5228   // Consume the argument.
5229   unsigned argIndex = FS.getArgIndex();
5230   if (argIndex < NumDataArgs) {
5231     // The check to see if the argIndex is valid will come later.
5232     // We set the bit here because we may exit early from this
5233     // function if we encounter some other error.
5234     CoveredArgs.set(argIndex);
5235   }
5236 
5237   // FreeBSD kernel extensions.
5238   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5239       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5240     // We need at least two arguments.
5241     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5242       return false;
5243 
5244     // Claim the second argument.
5245     CoveredArgs.set(argIndex + 1);
5246 
5247     // Type check the first argument (int for %b, pointer for %D)
5248     const Expr *Ex = getDataArg(argIndex);
5249     const analyze_printf::ArgType &AT =
5250       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5251         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5252     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5253       EmitFormatDiagnostic(
5254         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5255         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5256         << false << Ex->getSourceRange(),
5257         Ex->getLocStart(), /*IsStringLocation*/false,
5258         getSpecifierRange(startSpecifier, specifierLen));
5259 
5260     // Type check the second argument (char * for both %b and %D)
5261     Ex = getDataArg(argIndex + 1);
5262     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5263     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5264       EmitFormatDiagnostic(
5265         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5266         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5267         << false << Ex->getSourceRange(),
5268         Ex->getLocStart(), /*IsStringLocation*/false,
5269         getSpecifierRange(startSpecifier, specifierLen));
5270 
5271      return true;
5272   }
5273 
5274   // Check for using an Objective-C specific conversion specifier
5275   // in a non-ObjC literal.
5276   if (!ObjCContext && CS.isObjCArg()) {
5277     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5278                                                   specifierLen);
5279   }
5280 
5281   // Check for invalid use of field width
5282   if (!FS.hasValidFieldWidth()) {
5283     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5284         startSpecifier, specifierLen);
5285   }
5286 
5287   // Check for invalid use of precision
5288   if (!FS.hasValidPrecision()) {
5289     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5290         startSpecifier, specifierLen);
5291   }
5292 
5293   // Check each flag does not conflict with any other component.
5294   if (!FS.hasValidThousandsGroupingPrefix())
5295     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5296   if (!FS.hasValidLeadingZeros())
5297     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5298   if (!FS.hasValidPlusPrefix())
5299     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5300   if (!FS.hasValidSpacePrefix())
5301     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5302   if (!FS.hasValidAlternativeForm())
5303     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5304   if (!FS.hasValidLeftJustified())
5305     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5306 
5307   // Check that flags are not ignored by another flag
5308   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5309     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5310         startSpecifier, specifierLen);
5311   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5312     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5313             startSpecifier, specifierLen);
5314 
5315   // Check the length modifier is valid with the given conversion specifier.
5316   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5317     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5318                                 diag::warn_format_nonsensical_length);
5319   else if (!FS.hasStandardLengthModifier())
5320     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5321   else if (!FS.hasStandardLengthConversionCombination())
5322     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5323                                 diag::warn_format_non_standard_conversion_spec);
5324 
5325   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5326     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5327 
5328   // The remaining checks depend on the data arguments.
5329   if (HasVAListArg)
5330     return true;
5331 
5332   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5333     return false;
5334 
5335   const Expr *Arg = getDataArg(argIndex);
5336   if (!Arg)
5337     return true;
5338 
5339   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5340 }
5341 
5342 static bool requiresParensToAddCast(const Expr *E) {
5343   // FIXME: We should have a general way to reason about operator
5344   // precedence and whether parens are actually needed here.
5345   // Take care of a few common cases where they aren't.
5346   const Expr *Inside = E->IgnoreImpCasts();
5347   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5348     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5349 
5350   switch (Inside->getStmtClass()) {
5351   case Stmt::ArraySubscriptExprClass:
5352   case Stmt::CallExprClass:
5353   case Stmt::CharacterLiteralClass:
5354   case Stmt::CXXBoolLiteralExprClass:
5355   case Stmt::DeclRefExprClass:
5356   case Stmt::FloatingLiteralClass:
5357   case Stmt::IntegerLiteralClass:
5358   case Stmt::MemberExprClass:
5359   case Stmt::ObjCArrayLiteralClass:
5360   case Stmt::ObjCBoolLiteralExprClass:
5361   case Stmt::ObjCBoxedExprClass:
5362   case Stmt::ObjCDictionaryLiteralClass:
5363   case Stmt::ObjCEncodeExprClass:
5364   case Stmt::ObjCIvarRefExprClass:
5365   case Stmt::ObjCMessageExprClass:
5366   case Stmt::ObjCPropertyRefExprClass:
5367   case Stmt::ObjCStringLiteralClass:
5368   case Stmt::ObjCSubscriptRefExprClass:
5369   case Stmt::ParenExprClass:
5370   case Stmt::StringLiteralClass:
5371   case Stmt::UnaryOperatorClass:
5372     return false;
5373   default:
5374     return true;
5375   }
5376 }
5377 
5378 static std::pair<QualType, StringRef>
5379 shouldNotPrintDirectly(const ASTContext &Context,
5380                        QualType IntendedTy,
5381                        const Expr *E) {
5382   // Use a 'while' to peel off layers of typedefs.
5383   QualType TyTy = IntendedTy;
5384   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5385     StringRef Name = UserTy->getDecl()->getName();
5386     QualType CastTy = llvm::StringSwitch<QualType>(Name)
5387       .Case("NSInteger", Context.LongTy)
5388       .Case("NSUInteger", Context.UnsignedLongTy)
5389       .Case("SInt32", Context.IntTy)
5390       .Case("UInt32", Context.UnsignedIntTy)
5391       .Default(QualType());
5392 
5393     if (!CastTy.isNull())
5394       return std::make_pair(CastTy, Name);
5395 
5396     TyTy = UserTy->desugar();
5397   }
5398 
5399   // Strip parens if necessary.
5400   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5401     return shouldNotPrintDirectly(Context,
5402                                   PE->getSubExpr()->getType(),
5403                                   PE->getSubExpr());
5404 
5405   // If this is a conditional expression, then its result type is constructed
5406   // via usual arithmetic conversions and thus there might be no necessary
5407   // typedef sugar there.  Recurse to operands to check for NSInteger &
5408   // Co. usage condition.
5409   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5410     QualType TrueTy, FalseTy;
5411     StringRef TrueName, FalseName;
5412 
5413     std::tie(TrueTy, TrueName) =
5414       shouldNotPrintDirectly(Context,
5415                              CO->getTrueExpr()->getType(),
5416                              CO->getTrueExpr());
5417     std::tie(FalseTy, FalseName) =
5418       shouldNotPrintDirectly(Context,
5419                              CO->getFalseExpr()->getType(),
5420                              CO->getFalseExpr());
5421 
5422     if (TrueTy == FalseTy)
5423       return std::make_pair(TrueTy, TrueName);
5424     else if (TrueTy.isNull())
5425       return std::make_pair(FalseTy, FalseName);
5426     else if (FalseTy.isNull())
5427       return std::make_pair(TrueTy, TrueName);
5428   }
5429 
5430   return std::make_pair(QualType(), StringRef());
5431 }
5432 
5433 bool
5434 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5435                                     const char *StartSpecifier,
5436                                     unsigned SpecifierLen,
5437                                     const Expr *E) {
5438   using namespace analyze_format_string;
5439   using namespace analyze_printf;
5440   // Now type check the data expression that matches the
5441   // format specifier.
5442   const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5443                                                     ObjCContext);
5444   if (!AT.isValid())
5445     return true;
5446 
5447   QualType ExprTy = E->getType();
5448   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5449     ExprTy = TET->getUnderlyingExpr()->getType();
5450   }
5451 
5452   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5453 
5454   if (match == analyze_printf::ArgType::Match) {
5455     return true;
5456   }
5457 
5458   // Look through argument promotions for our error message's reported type.
5459   // This includes the integral and floating promotions, but excludes array
5460   // and function pointer decay; seeing that an argument intended to be a
5461   // string has type 'char [6]' is probably more confusing than 'char *'.
5462   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5463     if (ICE->getCastKind() == CK_IntegralCast ||
5464         ICE->getCastKind() == CK_FloatingCast) {
5465       E = ICE->getSubExpr();
5466       ExprTy = E->getType();
5467 
5468       // Check if we didn't match because of an implicit cast from a 'char'
5469       // or 'short' to an 'int'.  This is done because printf is a varargs
5470       // function.
5471       if (ICE->getType() == S.Context.IntTy ||
5472           ICE->getType() == S.Context.UnsignedIntTy) {
5473         // All further checking is done on the subexpression.
5474         if (AT.matchesType(S.Context, ExprTy))
5475           return true;
5476       }
5477     }
5478   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5479     // Special case for 'a', which has type 'int' in C.
5480     // Note, however, that we do /not/ want to treat multibyte constants like
5481     // 'MooV' as characters! This form is deprecated but still exists.
5482     if (ExprTy == S.Context.IntTy)
5483       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5484         ExprTy = S.Context.CharTy;
5485   }
5486 
5487   // Look through enums to their underlying type.
5488   bool IsEnum = false;
5489   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5490     ExprTy = EnumTy->getDecl()->getIntegerType();
5491     IsEnum = true;
5492   }
5493 
5494   // %C in an Objective-C context prints a unichar, not a wchar_t.
5495   // If the argument is an integer of some kind, believe the %C and suggest
5496   // a cast instead of changing the conversion specifier.
5497   QualType IntendedTy = ExprTy;
5498   if (ObjCContext &&
5499       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5500     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5501         !ExprTy->isCharType()) {
5502       // 'unichar' is defined as a typedef of unsigned short, but we should
5503       // prefer using the typedef if it is visible.
5504       IntendedTy = S.Context.UnsignedShortTy;
5505 
5506       // While we are here, check if the value is an IntegerLiteral that happens
5507       // to be within the valid range.
5508       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5509         const llvm::APInt &V = IL->getValue();
5510         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5511           return true;
5512       }
5513 
5514       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5515                           Sema::LookupOrdinaryName);
5516       if (S.LookupName(Result, S.getCurScope())) {
5517         NamedDecl *ND = Result.getFoundDecl();
5518         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5519           if (TD->getUnderlyingType() == IntendedTy)
5520             IntendedTy = S.Context.getTypedefType(TD);
5521       }
5522     }
5523   }
5524 
5525   // Special-case some of Darwin's platform-independence types by suggesting
5526   // casts to primitive types that are known to be large enough.
5527   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
5528   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5529     QualType CastTy;
5530     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5531     if (!CastTy.isNull()) {
5532       IntendedTy = CastTy;
5533       ShouldNotPrintDirectly = true;
5534     }
5535   }
5536 
5537   // We may be able to offer a FixItHint if it is a supported type.
5538   PrintfSpecifier fixedFS = FS;
5539   bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
5540                                  S.Context, ObjCContext);
5541 
5542   if (success) {
5543     // Get the fix string from the fixed format specifier
5544     SmallString<16> buf;
5545     llvm::raw_svector_ostream os(buf);
5546     fixedFS.toString(os);
5547 
5548     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5549 
5550     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5551       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5552       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5553         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5554       }
5555       // In this case, the specifier is wrong and should be changed to match
5556       // the argument.
5557       EmitFormatDiagnostic(S.PDiag(diag)
5558                                << AT.getRepresentativeTypeName(S.Context)
5559                                << IntendedTy << IsEnum << E->getSourceRange(),
5560                            E->getLocStart(),
5561                            /*IsStringLocation*/ false, SpecRange,
5562                            FixItHint::CreateReplacement(SpecRange, os.str()));
5563     } else {
5564       // The canonical type for formatting this value is different from the
5565       // actual type of the expression. (This occurs, for example, with Darwin's
5566       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5567       // should be printed as 'long' for 64-bit compatibility.)
5568       // Rather than emitting a normal format/argument mismatch, we want to
5569       // add a cast to the recommended type (and correct the format string
5570       // if necessary).
5571       SmallString<16> CastBuf;
5572       llvm::raw_svector_ostream CastFix(CastBuf);
5573       CastFix << "(";
5574       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5575       CastFix << ")";
5576 
5577       SmallVector<FixItHint,4> Hints;
5578       if (!AT.matchesType(S.Context, IntendedTy))
5579         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5580 
5581       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5582         // If there's already a cast present, just replace it.
5583         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5584         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5585 
5586       } else if (!requiresParensToAddCast(E)) {
5587         // If the expression has high enough precedence,
5588         // just write the C-style cast.
5589         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5590                                                    CastFix.str()));
5591       } else {
5592         // Otherwise, add parens around the expression as well as the cast.
5593         CastFix << "(";
5594         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5595                                                    CastFix.str()));
5596 
5597         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
5598         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5599       }
5600 
5601       if (ShouldNotPrintDirectly) {
5602         // The expression has a type that should not be printed directly.
5603         // We extract the name from the typedef because we don't want to show
5604         // the underlying type in the diagnostic.
5605         StringRef Name;
5606         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5607           Name = TypedefTy->getDecl()->getName();
5608         else
5609           Name = CastTyName;
5610         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
5611                                << Name << IntendedTy << IsEnum
5612                                << E->getSourceRange(),
5613                              E->getLocStart(), /*IsStringLocation=*/false,
5614                              SpecRange, Hints);
5615       } else {
5616         // In this case, the expression could be printed using a different
5617         // specifier, but we've decided that the specifier is probably correct
5618         // and we should cast instead. Just use the normal warning message.
5619         EmitFormatDiagnostic(
5620           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5621             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
5622             << E->getSourceRange(),
5623           E->getLocStart(), /*IsStringLocation*/false,
5624           SpecRange, Hints);
5625       }
5626     }
5627   } else {
5628     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5629                                                    SpecifierLen);
5630     // Since the warning for passing non-POD types to variadic functions
5631     // was deferred until now, we emit a warning for non-POD
5632     // arguments here.
5633     switch (S.isValidVarArgType(ExprTy)) {
5634     case Sema::VAK_Valid:
5635     case Sema::VAK_ValidInCXX11: {
5636       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5637       if (match == analyze_printf::ArgType::NoMatchPedantic) {
5638         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5639       }
5640 
5641       EmitFormatDiagnostic(
5642           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5643                         << IsEnum << CSR << E->getSourceRange(),
5644           E->getLocStart(), /*IsStringLocation*/ false, CSR);
5645       break;
5646     }
5647     case Sema::VAK_Undefined:
5648     case Sema::VAK_MSVCUndefined:
5649       EmitFormatDiagnostic(
5650         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
5651           << S.getLangOpts().CPlusPlus11
5652           << ExprTy
5653           << CallType
5654           << AT.getRepresentativeTypeName(S.Context)
5655           << CSR
5656           << E->getSourceRange(),
5657         E->getLocStart(), /*IsStringLocation*/false, CSR);
5658       checkForCStrMembers(AT, E);
5659       break;
5660 
5661     case Sema::VAK_Invalid:
5662       if (ExprTy->isObjCObjectType())
5663         EmitFormatDiagnostic(
5664           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5665             << S.getLangOpts().CPlusPlus11
5666             << ExprTy
5667             << CallType
5668             << AT.getRepresentativeTypeName(S.Context)
5669             << CSR
5670             << E->getSourceRange(),
5671           E->getLocStart(), /*IsStringLocation*/false, CSR);
5672       else
5673         // FIXME: If this is an initializer list, suggest removing the braces
5674         // or inserting a cast to the target type.
5675         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5676           << isa<InitListExpr>(E) << ExprTy << CallType
5677           << AT.getRepresentativeTypeName(S.Context)
5678           << E->getSourceRange();
5679       break;
5680     }
5681 
5682     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5683            "format string specifier index out of range");
5684     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
5685   }
5686 
5687   return true;
5688 }
5689 
5690 //===--- CHECK: Scanf format string checking ------------------------------===//
5691 
5692 namespace {
5693 class CheckScanfHandler : public CheckFormatHandler {
5694 public:
5695   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
5696                     const Expr *origFormatExpr, unsigned firstDataArg,
5697                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
5698                     ArrayRef<const Expr *> Args,
5699                     unsigned formatIdx, bool inFunctionCall,
5700                     Sema::VariadicCallType CallType,
5701                     llvm::SmallBitVector &CheckedVarArgs,
5702                     UncoveredArgHandler &UncoveredArg)
5703     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5704                          numDataArgs, beg, hasVAListArg,
5705                          Args, formatIdx, inFunctionCall, CallType,
5706                          CheckedVarArgs, UncoveredArg)
5707   {}
5708 
5709   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5710                             const char *startSpecifier,
5711                             unsigned specifierLen) override;
5712 
5713   bool HandleInvalidScanfConversionSpecifier(
5714           const analyze_scanf::ScanfSpecifier &FS,
5715           const char *startSpecifier,
5716           unsigned specifierLen) override;
5717 
5718   void HandleIncompleteScanList(const char *start, const char *end) override;
5719 };
5720 } // end anonymous namespace
5721 
5722 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5723                                                  const char *end) {
5724   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5725                        getLocationOfByte(end), /*IsStringLocation*/true,
5726                        getSpecifierRange(start, end - start));
5727 }
5728 
5729 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5730                                         const analyze_scanf::ScanfSpecifier &FS,
5731                                         const char *startSpecifier,
5732                                         unsigned specifierLen) {
5733 
5734   const analyze_scanf::ScanfConversionSpecifier &CS =
5735     FS.getConversionSpecifier();
5736 
5737   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5738                                           getLocationOfByte(CS.getStart()),
5739                                           startSpecifier, specifierLen,
5740                                           CS.getStart(), CS.getLength());
5741 }
5742 
5743 bool CheckScanfHandler::HandleScanfSpecifier(
5744                                        const analyze_scanf::ScanfSpecifier &FS,
5745                                        const char *startSpecifier,
5746                                        unsigned specifierLen) {
5747   using namespace analyze_scanf;
5748   using namespace analyze_format_string;
5749 
5750   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
5751 
5752   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
5753   // be used to decide if we are using positional arguments consistently.
5754   if (FS.consumesDataArgument()) {
5755     if (atFirstArg) {
5756       atFirstArg = false;
5757       usesPositionalArgs = FS.usesPositionalArg();
5758     }
5759     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5760       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5761                                         startSpecifier, specifierLen);
5762       return false;
5763     }
5764   }
5765 
5766   // Check if the field with is non-zero.
5767   const OptionalAmount &Amt = FS.getFieldWidth();
5768   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5769     if (Amt.getConstantAmount() == 0) {
5770       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5771                                                    Amt.getConstantLength());
5772       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5773                            getLocationOfByte(Amt.getStart()),
5774                            /*IsStringLocation*/true, R,
5775                            FixItHint::CreateRemoval(R));
5776     }
5777   }
5778 
5779   if (!FS.consumesDataArgument()) {
5780     // FIXME: Technically specifying a precision or field width here
5781     // makes no sense.  Worth issuing a warning at some point.
5782     return true;
5783   }
5784 
5785   // Consume the argument.
5786   unsigned argIndex = FS.getArgIndex();
5787   if (argIndex < NumDataArgs) {
5788       // The check to see if the argIndex is valid will come later.
5789       // We set the bit here because we may exit early from this
5790       // function if we encounter some other error.
5791     CoveredArgs.set(argIndex);
5792   }
5793 
5794   // Check the length modifier is valid with the given conversion specifier.
5795   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5796     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5797                                 diag::warn_format_nonsensical_length);
5798   else if (!FS.hasStandardLengthModifier())
5799     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5800   else if (!FS.hasStandardLengthConversionCombination())
5801     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5802                                 diag::warn_format_non_standard_conversion_spec);
5803 
5804   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5805     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5806 
5807   // The remaining checks depend on the data arguments.
5808   if (HasVAListArg)
5809     return true;
5810 
5811   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5812     return false;
5813 
5814   // Check that the argument type matches the format specifier.
5815   const Expr *Ex = getDataArg(argIndex);
5816   if (!Ex)
5817     return true;
5818 
5819   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
5820 
5821   if (!AT.isValid()) {
5822     return true;
5823   }
5824 
5825   analyze_format_string::ArgType::MatchKind match =
5826       AT.matchesType(S.Context, Ex->getType());
5827   if (match == analyze_format_string::ArgType::Match) {
5828     return true;
5829   }
5830 
5831   ScanfSpecifier fixedFS = FS;
5832   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5833                                  S.getLangOpts(), S.Context);
5834 
5835   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5836   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5837     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5838   }
5839 
5840   if (success) {
5841     // Get the fix string from the fixed format specifier.
5842     SmallString<128> buf;
5843     llvm::raw_svector_ostream os(buf);
5844     fixedFS.toString(os);
5845 
5846     EmitFormatDiagnostic(
5847         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5848                       << Ex->getType() << false << Ex->getSourceRange(),
5849         Ex->getLocStart(),
5850         /*IsStringLocation*/ false,
5851         getSpecifierRange(startSpecifier, specifierLen),
5852         FixItHint::CreateReplacement(
5853             getSpecifierRange(startSpecifier, specifierLen), os.str()));
5854   } else {
5855     EmitFormatDiagnostic(S.PDiag(diag)
5856                              << AT.getRepresentativeTypeName(S.Context)
5857                              << Ex->getType() << false << Ex->getSourceRange(),
5858                          Ex->getLocStart(),
5859                          /*IsStringLocation*/ false,
5860                          getSpecifierRange(startSpecifier, specifierLen));
5861   }
5862 
5863   return true;
5864 }
5865 
5866 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
5867                               const Expr *OrigFormatExpr,
5868                               ArrayRef<const Expr *> Args,
5869                               bool HasVAListArg, unsigned format_idx,
5870                               unsigned firstDataArg,
5871                               Sema::FormatStringType Type,
5872                               bool inFunctionCall,
5873                               Sema::VariadicCallType CallType,
5874                               llvm::SmallBitVector &CheckedVarArgs,
5875                               UncoveredArgHandler &UncoveredArg) {
5876   // CHECK: is the format string a wide literal?
5877   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
5878     CheckFormatHandler::EmitFormatDiagnostic(
5879       S, inFunctionCall, Args[format_idx],
5880       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
5881       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
5882     return;
5883   }
5884 
5885   // Str - The format string.  NOTE: this is NOT null-terminated!
5886   StringRef StrRef = FExpr->getString();
5887   const char *Str = StrRef.data();
5888   // Account for cases where the string literal is truncated in a declaration.
5889   const ConstantArrayType *T =
5890     S.Context.getAsConstantArrayType(FExpr->getType());
5891   assert(T && "String literal not of constant array type!");
5892   size_t TypeSize = T->getSize().getZExtValue();
5893   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5894   const unsigned numDataArgs = Args.size() - firstDataArg;
5895 
5896   // Emit a warning if the string literal is truncated and does not contain an
5897   // embedded null character.
5898   if (TypeSize <= StrRef.size() &&
5899       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5900     CheckFormatHandler::EmitFormatDiagnostic(
5901         S, inFunctionCall, Args[format_idx],
5902         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
5903         FExpr->getLocStart(),
5904         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5905     return;
5906   }
5907 
5908   // CHECK: empty format string?
5909   if (StrLen == 0 && numDataArgs > 0) {
5910     CheckFormatHandler::EmitFormatDiagnostic(
5911       S, inFunctionCall, Args[format_idx],
5912       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
5913       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
5914     return;
5915   }
5916 
5917   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5918       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5919     CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5920                          numDataArgs, (Type == Sema::FST_NSString ||
5921                                        Type == Sema::FST_OSTrace),
5922                          Str, HasVAListArg, Args, format_idx,
5923                          inFunctionCall, CallType, CheckedVarArgs,
5924                          UncoveredArg);
5925 
5926     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
5927                                                   S.getLangOpts(),
5928                                                   S.Context.getTargetInfo(),
5929                                             Type == Sema::FST_FreeBSDKPrintf))
5930       H.DoneProcessing();
5931   } else if (Type == Sema::FST_Scanf) {
5932     CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
5933                         Str, HasVAListArg, Args, format_idx,
5934                         inFunctionCall, CallType, CheckedVarArgs,
5935                         UncoveredArg);
5936 
5937     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
5938                                                  S.getLangOpts(),
5939                                                  S.Context.getTargetInfo()))
5940       H.DoneProcessing();
5941   } // TODO: handle other formats
5942 }
5943 
5944 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5945   // Str - The format string.  NOTE: this is NOT null-terminated!
5946   StringRef StrRef = FExpr->getString();
5947   const char *Str = StrRef.data();
5948   // Account for cases where the string literal is truncated in a declaration.
5949   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5950   assert(T && "String literal not of constant array type!");
5951   size_t TypeSize = T->getSize().getZExtValue();
5952   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5953   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5954                                                          getLangOpts(),
5955                                                          Context.getTargetInfo());
5956 }
5957 
5958 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5959 
5960 // Returns the related absolute value function that is larger, of 0 if one
5961 // does not exist.
5962 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5963   switch (AbsFunction) {
5964   default:
5965     return 0;
5966 
5967   case Builtin::BI__builtin_abs:
5968     return Builtin::BI__builtin_labs;
5969   case Builtin::BI__builtin_labs:
5970     return Builtin::BI__builtin_llabs;
5971   case Builtin::BI__builtin_llabs:
5972     return 0;
5973 
5974   case Builtin::BI__builtin_fabsf:
5975     return Builtin::BI__builtin_fabs;
5976   case Builtin::BI__builtin_fabs:
5977     return Builtin::BI__builtin_fabsl;
5978   case Builtin::BI__builtin_fabsl:
5979     return 0;
5980 
5981   case Builtin::BI__builtin_cabsf:
5982     return Builtin::BI__builtin_cabs;
5983   case Builtin::BI__builtin_cabs:
5984     return Builtin::BI__builtin_cabsl;
5985   case Builtin::BI__builtin_cabsl:
5986     return 0;
5987 
5988   case Builtin::BIabs:
5989     return Builtin::BIlabs;
5990   case Builtin::BIlabs:
5991     return Builtin::BIllabs;
5992   case Builtin::BIllabs:
5993     return 0;
5994 
5995   case Builtin::BIfabsf:
5996     return Builtin::BIfabs;
5997   case Builtin::BIfabs:
5998     return Builtin::BIfabsl;
5999   case Builtin::BIfabsl:
6000     return 0;
6001 
6002   case Builtin::BIcabsf:
6003    return Builtin::BIcabs;
6004   case Builtin::BIcabs:
6005     return Builtin::BIcabsl;
6006   case Builtin::BIcabsl:
6007     return 0;
6008   }
6009 }
6010 
6011 // Returns the argument type of the absolute value function.
6012 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6013                                              unsigned AbsType) {
6014   if (AbsType == 0)
6015     return QualType();
6016 
6017   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6018   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6019   if (Error != ASTContext::GE_None)
6020     return QualType();
6021 
6022   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6023   if (!FT)
6024     return QualType();
6025 
6026   if (FT->getNumParams() != 1)
6027     return QualType();
6028 
6029   return FT->getParamType(0);
6030 }
6031 
6032 // Returns the best absolute value function, or zero, based on type and
6033 // current absolute value function.
6034 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6035                                    unsigned AbsFunctionKind) {
6036   unsigned BestKind = 0;
6037   uint64_t ArgSize = Context.getTypeSize(ArgType);
6038   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6039        Kind = getLargerAbsoluteValueFunction(Kind)) {
6040     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6041     if (Context.getTypeSize(ParamType) >= ArgSize) {
6042       if (BestKind == 0)
6043         BestKind = Kind;
6044       else if (Context.hasSameType(ParamType, ArgType)) {
6045         BestKind = Kind;
6046         break;
6047       }
6048     }
6049   }
6050   return BestKind;
6051 }
6052 
6053 enum AbsoluteValueKind {
6054   AVK_Integer,
6055   AVK_Floating,
6056   AVK_Complex
6057 };
6058 
6059 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6060   if (T->isIntegralOrEnumerationType())
6061     return AVK_Integer;
6062   if (T->isRealFloatingType())
6063     return AVK_Floating;
6064   if (T->isAnyComplexType())
6065     return AVK_Complex;
6066 
6067   llvm_unreachable("Type not integer, floating, or complex");
6068 }
6069 
6070 // Changes the absolute value function to a different type.  Preserves whether
6071 // the function is a builtin.
6072 static unsigned changeAbsFunction(unsigned AbsKind,
6073                                   AbsoluteValueKind ValueKind) {
6074   switch (ValueKind) {
6075   case AVK_Integer:
6076     switch (AbsKind) {
6077     default:
6078       return 0;
6079     case Builtin::BI__builtin_fabsf:
6080     case Builtin::BI__builtin_fabs:
6081     case Builtin::BI__builtin_fabsl:
6082     case Builtin::BI__builtin_cabsf:
6083     case Builtin::BI__builtin_cabs:
6084     case Builtin::BI__builtin_cabsl:
6085       return Builtin::BI__builtin_abs;
6086     case Builtin::BIfabsf:
6087     case Builtin::BIfabs:
6088     case Builtin::BIfabsl:
6089     case Builtin::BIcabsf:
6090     case Builtin::BIcabs:
6091     case Builtin::BIcabsl:
6092       return Builtin::BIabs;
6093     }
6094   case AVK_Floating:
6095     switch (AbsKind) {
6096     default:
6097       return 0;
6098     case Builtin::BI__builtin_abs:
6099     case Builtin::BI__builtin_labs:
6100     case Builtin::BI__builtin_llabs:
6101     case Builtin::BI__builtin_cabsf:
6102     case Builtin::BI__builtin_cabs:
6103     case Builtin::BI__builtin_cabsl:
6104       return Builtin::BI__builtin_fabsf;
6105     case Builtin::BIabs:
6106     case Builtin::BIlabs:
6107     case Builtin::BIllabs:
6108     case Builtin::BIcabsf:
6109     case Builtin::BIcabs:
6110     case Builtin::BIcabsl:
6111       return Builtin::BIfabsf;
6112     }
6113   case AVK_Complex:
6114     switch (AbsKind) {
6115     default:
6116       return 0;
6117     case Builtin::BI__builtin_abs:
6118     case Builtin::BI__builtin_labs:
6119     case Builtin::BI__builtin_llabs:
6120     case Builtin::BI__builtin_fabsf:
6121     case Builtin::BI__builtin_fabs:
6122     case Builtin::BI__builtin_fabsl:
6123       return Builtin::BI__builtin_cabsf;
6124     case Builtin::BIabs:
6125     case Builtin::BIlabs:
6126     case Builtin::BIllabs:
6127     case Builtin::BIfabsf:
6128     case Builtin::BIfabs:
6129     case Builtin::BIfabsl:
6130       return Builtin::BIcabsf;
6131     }
6132   }
6133   llvm_unreachable("Unable to convert function");
6134 }
6135 
6136 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6137   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6138   if (!FnInfo)
6139     return 0;
6140 
6141   switch (FDecl->getBuiltinID()) {
6142   default:
6143     return 0;
6144   case Builtin::BI__builtin_abs:
6145   case Builtin::BI__builtin_fabs:
6146   case Builtin::BI__builtin_fabsf:
6147   case Builtin::BI__builtin_fabsl:
6148   case Builtin::BI__builtin_labs:
6149   case Builtin::BI__builtin_llabs:
6150   case Builtin::BI__builtin_cabs:
6151   case Builtin::BI__builtin_cabsf:
6152   case Builtin::BI__builtin_cabsl:
6153   case Builtin::BIabs:
6154   case Builtin::BIlabs:
6155   case Builtin::BIllabs:
6156   case Builtin::BIfabs:
6157   case Builtin::BIfabsf:
6158   case Builtin::BIfabsl:
6159   case Builtin::BIcabs:
6160   case Builtin::BIcabsf:
6161   case Builtin::BIcabsl:
6162     return FDecl->getBuiltinID();
6163   }
6164   llvm_unreachable("Unknown Builtin type");
6165 }
6166 
6167 // If the replacement is valid, emit a note with replacement function.
6168 // Additionally, suggest including the proper header if not already included.
6169 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6170                             unsigned AbsKind, QualType ArgType) {
6171   bool EmitHeaderHint = true;
6172   const char *HeaderName = nullptr;
6173   const char *FunctionName = nullptr;
6174   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6175     FunctionName = "std::abs";
6176     if (ArgType->isIntegralOrEnumerationType()) {
6177       HeaderName = "cstdlib";
6178     } else if (ArgType->isRealFloatingType()) {
6179       HeaderName = "cmath";
6180     } else {
6181       llvm_unreachable("Invalid Type");
6182     }
6183 
6184     // Lookup all std::abs
6185     if (NamespaceDecl *Std = S.getStdNamespace()) {
6186       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6187       R.suppressDiagnostics();
6188       S.LookupQualifiedName(R, Std);
6189 
6190       for (const auto *I : R) {
6191         const FunctionDecl *FDecl = nullptr;
6192         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6193           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6194         } else {
6195           FDecl = dyn_cast<FunctionDecl>(I);
6196         }
6197         if (!FDecl)
6198           continue;
6199 
6200         // Found std::abs(), check that they are the right ones.
6201         if (FDecl->getNumParams() != 1)
6202           continue;
6203 
6204         // Check that the parameter type can handle the argument.
6205         QualType ParamType = FDecl->getParamDecl(0)->getType();
6206         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6207             S.Context.getTypeSize(ArgType) <=
6208                 S.Context.getTypeSize(ParamType)) {
6209           // Found a function, don't need the header hint.
6210           EmitHeaderHint = false;
6211           break;
6212         }
6213       }
6214     }
6215   } else {
6216     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6217     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6218 
6219     if (HeaderName) {
6220       DeclarationName DN(&S.Context.Idents.get(FunctionName));
6221       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6222       R.suppressDiagnostics();
6223       S.LookupName(R, S.getCurScope());
6224 
6225       if (R.isSingleResult()) {
6226         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6227         if (FD && FD->getBuiltinID() == AbsKind) {
6228           EmitHeaderHint = false;
6229         } else {
6230           return;
6231         }
6232       } else if (!R.empty()) {
6233         return;
6234       }
6235     }
6236   }
6237 
6238   S.Diag(Loc, diag::note_replace_abs_function)
6239       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6240 
6241   if (!HeaderName)
6242     return;
6243 
6244   if (!EmitHeaderHint)
6245     return;
6246 
6247   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6248                                                     << FunctionName;
6249 }
6250 
6251 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6252   if (!FDecl)
6253     return false;
6254 
6255   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6256     return false;
6257 
6258   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6259 
6260   while (ND && ND->isInlineNamespace()) {
6261     ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
6262   }
6263 
6264   if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6265     return false;
6266 
6267   if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6268     return false;
6269 
6270   return true;
6271 }
6272 
6273 // Warn when using the wrong abs() function.
6274 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6275                                       const FunctionDecl *FDecl,
6276                                       IdentifierInfo *FnInfo) {
6277   if (Call->getNumArgs() != 1)
6278     return;
6279 
6280   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6281   bool IsStdAbs = IsFunctionStdAbs(FDecl);
6282   if (AbsKind == 0 && !IsStdAbs)
6283     return;
6284 
6285   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6286   QualType ParamType = Call->getArg(0)->getType();
6287 
6288   // Unsigned types cannot be negative.  Suggest removing the absolute value
6289   // function call.
6290   if (ArgType->isUnsignedIntegerType()) {
6291     const char *FunctionName =
6292         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6293     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6294     Diag(Call->getExprLoc(), diag::note_remove_abs)
6295         << FunctionName
6296         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6297     return;
6298   }
6299 
6300   // Taking the absolute value of a pointer is very suspicious, they probably
6301   // wanted to index into an array, dereference a pointer, call a function, etc.
6302   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6303     unsigned DiagType = 0;
6304     if (ArgType->isFunctionType())
6305       DiagType = 1;
6306     else if (ArgType->isArrayType())
6307       DiagType = 2;
6308 
6309     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6310     return;
6311   }
6312 
6313   // std::abs has overloads which prevent most of the absolute value problems
6314   // from occurring.
6315   if (IsStdAbs)
6316     return;
6317 
6318   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6319   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6320 
6321   // The argument and parameter are the same kind.  Check if they are the right
6322   // size.
6323   if (ArgValueKind == ParamValueKind) {
6324     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6325       return;
6326 
6327     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6328     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6329         << FDecl << ArgType << ParamType;
6330 
6331     if (NewAbsKind == 0)
6332       return;
6333 
6334     emitReplacement(*this, Call->getExprLoc(),
6335                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6336     return;
6337   }
6338 
6339   // ArgValueKind != ParamValueKind
6340   // The wrong type of absolute value function was used.  Attempt to find the
6341   // proper one.
6342   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6343   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6344   if (NewAbsKind == 0)
6345     return;
6346 
6347   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6348       << FDecl << ParamValueKind << ArgValueKind;
6349 
6350   emitReplacement(*this, Call->getExprLoc(),
6351                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6352 }
6353 
6354 //===--- CHECK: Standard memory functions ---------------------------------===//
6355 
6356 /// \brief Takes the expression passed to the size_t parameter of functions
6357 /// such as memcmp, strncat, etc and warns if it's a comparison.
6358 ///
6359 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6360 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6361                                            IdentifierInfo *FnName,
6362                                            SourceLocation FnLoc,
6363                                            SourceLocation RParenLoc) {
6364   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6365   if (!Size)
6366     return false;
6367 
6368   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6369   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6370     return false;
6371 
6372   SourceRange SizeRange = Size->getSourceRange();
6373   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6374       << SizeRange << FnName;
6375   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
6376       << FnName << FixItHint::CreateInsertion(
6377                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
6378       << FixItHint::CreateRemoval(RParenLoc);
6379   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
6380       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
6381       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6382                                     ")");
6383 
6384   return true;
6385 }
6386 
6387 /// \brief Determine whether the given type is or contains a dynamic class type
6388 /// (e.g., whether it has a vtable).
6389 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6390                                                      bool &IsContained) {
6391   // Look through array types while ignoring qualifiers.
6392   const Type *Ty = T->getBaseElementTypeUnsafe();
6393   IsContained = false;
6394 
6395   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6396   RD = RD ? RD->getDefinition() : nullptr;
6397   if (!RD || RD->isInvalidDecl())
6398     return nullptr;
6399 
6400   if (RD->isDynamicClass())
6401     return RD;
6402 
6403   // Check all the fields.  If any bases were dynamic, the class is dynamic.
6404   // It's impossible for a class to transitively contain itself by value, so
6405   // infinite recursion is impossible.
6406   for (auto *FD : RD->fields()) {
6407     bool SubContained;
6408     if (const CXXRecordDecl *ContainedRD =
6409             getContainedDynamicClass(FD->getType(), SubContained)) {
6410       IsContained = true;
6411       return ContainedRD;
6412     }
6413   }
6414 
6415   return nullptr;
6416 }
6417 
6418 /// \brief If E is a sizeof expression, returns its argument expression,
6419 /// otherwise returns NULL.
6420 static const Expr *getSizeOfExprArg(const Expr *E) {
6421   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6422       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6423     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6424       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
6425 
6426   return nullptr;
6427 }
6428 
6429 /// \brief If E is a sizeof expression, returns its argument type.
6430 static QualType getSizeOfArgType(const Expr *E) {
6431   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6432       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6433     if (SizeOf->getKind() == clang::UETT_SizeOf)
6434       return SizeOf->getTypeOfArgument();
6435 
6436   return QualType();
6437 }
6438 
6439 /// \brief Check for dangerous or invalid arguments to memset().
6440 ///
6441 /// This issues warnings on known problematic, dangerous or unspecified
6442 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6443 /// function calls.
6444 ///
6445 /// \param Call The call expression to diagnose.
6446 void Sema::CheckMemaccessArguments(const CallExpr *Call,
6447                                    unsigned BId,
6448                                    IdentifierInfo *FnName) {
6449   assert(BId != 0);
6450 
6451   // It is possible to have a non-standard definition of memset.  Validate
6452   // we have enough arguments, and if not, abort further checking.
6453   unsigned ExpectedNumArgs =
6454       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
6455   if (Call->getNumArgs() < ExpectedNumArgs)
6456     return;
6457 
6458   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
6459                       BId == Builtin::BIstrndup ? 1 : 2);
6460   unsigned LenArg =
6461       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
6462   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
6463 
6464   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6465                                      Call->getLocStart(), Call->getRParenLoc()))
6466     return;
6467 
6468   // We have special checking when the length is a sizeof expression.
6469   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6470   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6471   llvm::FoldingSetNodeID SizeOfArgID;
6472 
6473   // Although widely used, 'bzero' is not a standard function. Be more strict
6474   // with the argument types before allowing diagnostics and only allow the
6475   // form bzero(ptr, sizeof(...)).
6476   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6477   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6478     return;
6479 
6480   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6481     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
6482     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
6483 
6484     QualType DestTy = Dest->getType();
6485     QualType PointeeTy;
6486     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
6487       PointeeTy = DestPtrTy->getPointeeType();
6488 
6489       // Never warn about void type pointers. This can be used to suppress
6490       // false positives.
6491       if (PointeeTy->isVoidType())
6492         continue;
6493 
6494       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6495       // actually comparing the expressions for equality. Because computing the
6496       // expression IDs can be expensive, we only do this if the diagnostic is
6497       // enabled.
6498       if (SizeOfArg &&
6499           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6500                            SizeOfArg->getExprLoc())) {
6501         // We only compute IDs for expressions if the warning is enabled, and
6502         // cache the sizeof arg's ID.
6503         if (SizeOfArgID == llvm::FoldingSetNodeID())
6504           SizeOfArg->Profile(SizeOfArgID, Context, true);
6505         llvm::FoldingSetNodeID DestID;
6506         Dest->Profile(DestID, Context, true);
6507         if (DestID == SizeOfArgID) {
6508           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6509           //       over sizeof(src) as well.
6510           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
6511           StringRef ReadableName = FnName->getName();
6512 
6513           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
6514             if (UnaryOp->getOpcode() == UO_AddrOf)
6515               ActionIdx = 1; // If its an address-of operator, just remove it.
6516           if (!PointeeTy->isIncompleteType() &&
6517               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
6518             ActionIdx = 2; // If the pointee's size is sizeof(char),
6519                            // suggest an explicit length.
6520 
6521           // If the function is defined as a builtin macro, do not show macro
6522           // expansion.
6523           SourceLocation SL = SizeOfArg->getExprLoc();
6524           SourceRange DSR = Dest->getSourceRange();
6525           SourceRange SSR = SizeOfArg->getSourceRange();
6526           SourceManager &SM = getSourceManager();
6527 
6528           if (SM.isMacroArgExpansion(SL)) {
6529             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6530             SL = SM.getSpellingLoc(SL);
6531             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6532                              SM.getSpellingLoc(DSR.getEnd()));
6533             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6534                              SM.getSpellingLoc(SSR.getEnd()));
6535           }
6536 
6537           DiagRuntimeBehavior(SL, SizeOfArg,
6538                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
6539                                 << ReadableName
6540                                 << PointeeTy
6541                                 << DestTy
6542                                 << DSR
6543                                 << SSR);
6544           DiagRuntimeBehavior(SL, SizeOfArg,
6545                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6546                                 << ActionIdx
6547                                 << SSR);
6548 
6549           break;
6550         }
6551       }
6552 
6553       // Also check for cases where the sizeof argument is the exact same
6554       // type as the memory argument, and where it points to a user-defined
6555       // record type.
6556       if (SizeOfArgTy != QualType()) {
6557         if (PointeeTy->isRecordType() &&
6558             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6559           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6560                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
6561                                 << FnName << SizeOfArgTy << ArgIdx
6562                                 << PointeeTy << Dest->getSourceRange()
6563                                 << LenExpr->getSourceRange());
6564           break;
6565         }
6566       }
6567     } else if (DestTy->isArrayType()) {
6568       PointeeTy = DestTy;
6569     }
6570 
6571     if (PointeeTy == QualType())
6572       continue;
6573 
6574     // Always complain about dynamic classes.
6575     bool IsContained;
6576     if (const CXXRecordDecl *ContainedRD =
6577             getContainedDynamicClass(PointeeTy, IsContained)) {
6578 
6579       unsigned OperationType = 0;
6580       // "overwritten" if we're warning about the destination for any call
6581       // but memcmp; otherwise a verb appropriate to the call.
6582       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6583         if (BId == Builtin::BImemcpy)
6584           OperationType = 1;
6585         else if(BId == Builtin::BImemmove)
6586           OperationType = 2;
6587         else if (BId == Builtin::BImemcmp)
6588           OperationType = 3;
6589       }
6590 
6591       DiagRuntimeBehavior(
6592         Dest->getExprLoc(), Dest,
6593         PDiag(diag::warn_dyn_class_memaccess)
6594           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6595           << FnName << IsContained << ContainedRD << OperationType
6596           << Call->getCallee()->getSourceRange());
6597     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6598              BId != Builtin::BImemset)
6599       DiagRuntimeBehavior(
6600         Dest->getExprLoc(), Dest,
6601         PDiag(diag::warn_arc_object_memaccess)
6602           << ArgIdx << FnName << PointeeTy
6603           << Call->getCallee()->getSourceRange());
6604     else
6605       continue;
6606 
6607     DiagRuntimeBehavior(
6608       Dest->getExprLoc(), Dest,
6609       PDiag(diag::note_bad_memaccess_silence)
6610         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6611     break;
6612   }
6613 }
6614 
6615 // A little helper routine: ignore addition and subtraction of integer literals.
6616 // This intentionally does not ignore all integer constant expressions because
6617 // we don't want to remove sizeof().
6618 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6619   Ex = Ex->IgnoreParenCasts();
6620 
6621   for (;;) {
6622     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6623     if (!BO || !BO->isAdditiveOp())
6624       break;
6625 
6626     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6627     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6628 
6629     if (isa<IntegerLiteral>(RHS))
6630       Ex = LHS;
6631     else if (isa<IntegerLiteral>(LHS))
6632       Ex = RHS;
6633     else
6634       break;
6635   }
6636 
6637   return Ex;
6638 }
6639 
6640 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6641                                                       ASTContext &Context) {
6642   // Only handle constant-sized or VLAs, but not flexible members.
6643   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6644     // Only issue the FIXIT for arrays of size > 1.
6645     if (CAT->getSize().getSExtValue() <= 1)
6646       return false;
6647   } else if (!Ty->isVariableArrayType()) {
6648     return false;
6649   }
6650   return true;
6651 }
6652 
6653 // Warn if the user has made the 'size' argument to strlcpy or strlcat
6654 // be the size of the source, instead of the destination.
6655 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6656                                     IdentifierInfo *FnName) {
6657 
6658   // Don't crash if the user has the wrong number of arguments
6659   unsigned NumArgs = Call->getNumArgs();
6660   if ((NumArgs != 3) && (NumArgs != 4))
6661     return;
6662 
6663   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6664   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
6665   const Expr *CompareWithSrc = nullptr;
6666 
6667   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6668                                      Call->getLocStart(), Call->getRParenLoc()))
6669     return;
6670 
6671   // Look for 'strlcpy(dst, x, sizeof(x))'
6672   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6673     CompareWithSrc = Ex;
6674   else {
6675     // Look for 'strlcpy(dst, x, strlen(x))'
6676     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
6677       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6678           SizeCall->getNumArgs() == 1)
6679         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6680     }
6681   }
6682 
6683   if (!CompareWithSrc)
6684     return;
6685 
6686   // Determine if the argument to sizeof/strlen is equal to the source
6687   // argument.  In principle there's all kinds of things you could do
6688   // here, for instance creating an == expression and evaluating it with
6689   // EvaluateAsBooleanCondition, but this uses a more direct technique:
6690   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6691   if (!SrcArgDRE)
6692     return;
6693 
6694   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6695   if (!CompareWithSrcDRE ||
6696       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6697     return;
6698 
6699   const Expr *OriginalSizeArg = Call->getArg(2);
6700   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6701     << OriginalSizeArg->getSourceRange() << FnName;
6702 
6703   // Output a FIXIT hint if the destination is an array (rather than a
6704   // pointer to an array).  This could be enhanced to handle some
6705   // pointers if we know the actual size, like if DstArg is 'array+2'
6706   // we could say 'sizeof(array)-2'.
6707   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
6708   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
6709     return;
6710 
6711   SmallString<128> sizeString;
6712   llvm::raw_svector_ostream OS(sizeString);
6713   OS << "sizeof(";
6714   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6715   OS << ")";
6716 
6717   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6718     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6719                                     OS.str());
6720 }
6721 
6722 /// Check if two expressions refer to the same declaration.
6723 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6724   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6725     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6726       return D1->getDecl() == D2->getDecl();
6727   return false;
6728 }
6729 
6730 static const Expr *getStrlenExprArg(const Expr *E) {
6731   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6732     const FunctionDecl *FD = CE->getDirectCallee();
6733     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
6734       return nullptr;
6735     return CE->getArg(0)->IgnoreParenCasts();
6736   }
6737   return nullptr;
6738 }
6739 
6740 // Warn on anti-patterns as the 'size' argument to strncat.
6741 // The correct size argument should look like following:
6742 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6743 void Sema::CheckStrncatArguments(const CallExpr *CE,
6744                                  IdentifierInfo *FnName) {
6745   // Don't crash if the user has the wrong number of arguments.
6746   if (CE->getNumArgs() < 3)
6747     return;
6748   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6749   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6750   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6751 
6752   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6753                                      CE->getRParenLoc()))
6754     return;
6755 
6756   // Identify common expressions, which are wrongly used as the size argument
6757   // to strncat and may lead to buffer overflows.
6758   unsigned PatternType = 0;
6759   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6760     // - sizeof(dst)
6761     if (referToTheSameDecl(SizeOfArg, DstArg))
6762       PatternType = 1;
6763     // - sizeof(src)
6764     else if (referToTheSameDecl(SizeOfArg, SrcArg))
6765       PatternType = 2;
6766   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6767     if (BE->getOpcode() == BO_Sub) {
6768       const Expr *L = BE->getLHS()->IgnoreParenCasts();
6769       const Expr *R = BE->getRHS()->IgnoreParenCasts();
6770       // - sizeof(dst) - strlen(dst)
6771       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6772           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6773         PatternType = 1;
6774       // - sizeof(src) - (anything)
6775       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6776         PatternType = 2;
6777     }
6778   }
6779 
6780   if (PatternType == 0)
6781     return;
6782 
6783   // Generate the diagnostic.
6784   SourceLocation SL = LenArg->getLocStart();
6785   SourceRange SR = LenArg->getSourceRange();
6786   SourceManager &SM = getSourceManager();
6787 
6788   // If the function is defined as a builtin macro, do not show macro expansion.
6789   if (SM.isMacroArgExpansion(SL)) {
6790     SL = SM.getSpellingLoc(SL);
6791     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6792                      SM.getSpellingLoc(SR.getEnd()));
6793   }
6794 
6795   // Check if the destination is an array (rather than a pointer to an array).
6796   QualType DstTy = DstArg->getType();
6797   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6798                                                                     Context);
6799   if (!isKnownSizeArray) {
6800     if (PatternType == 1)
6801       Diag(SL, diag::warn_strncat_wrong_size) << SR;
6802     else
6803       Diag(SL, diag::warn_strncat_src_size) << SR;
6804     return;
6805   }
6806 
6807   if (PatternType == 1)
6808     Diag(SL, diag::warn_strncat_large_size) << SR;
6809   else
6810     Diag(SL, diag::warn_strncat_src_size) << SR;
6811 
6812   SmallString<128> sizeString;
6813   llvm::raw_svector_ostream OS(sizeString);
6814   OS << "sizeof(";
6815   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6816   OS << ") - ";
6817   OS << "strlen(";
6818   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6819   OS << ") - 1";
6820 
6821   Diag(SL, diag::note_strncat_wrong_size)
6822     << FixItHint::CreateReplacement(SR, OS.str());
6823 }
6824 
6825 //===--- CHECK: Return Address of Stack Variable --------------------------===//
6826 
6827 static const Expr *EvalVal(const Expr *E,
6828                            SmallVectorImpl<const DeclRefExpr *> &refVars,
6829                            const Decl *ParentDecl);
6830 static const Expr *EvalAddr(const Expr *E,
6831                             SmallVectorImpl<const DeclRefExpr *> &refVars,
6832                             const Decl *ParentDecl);
6833 
6834 /// CheckReturnStackAddr - Check if a return statement returns the address
6835 ///   of a stack variable.
6836 static void
6837 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6838                      SourceLocation ReturnLoc) {
6839 
6840   const Expr *stackE = nullptr;
6841   SmallVector<const DeclRefExpr *, 8> refVars;
6842 
6843   // Perform checking for returned stack addresses, local blocks,
6844   // label addresses or references to temporaries.
6845   if (lhsType->isPointerType() ||
6846       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
6847     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
6848   } else if (lhsType->isReferenceType()) {
6849     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
6850   }
6851 
6852   if (!stackE)
6853     return; // Nothing suspicious was found.
6854 
6855   // Parameters are initalized in the calling scope, so taking the address
6856   // of a parameter reference doesn't need a warning.
6857   for (auto *DRE : refVars)
6858     if (isa<ParmVarDecl>(DRE->getDecl()))
6859       return;
6860 
6861   SourceLocation diagLoc;
6862   SourceRange diagRange;
6863   if (refVars.empty()) {
6864     diagLoc = stackE->getLocStart();
6865     diagRange = stackE->getSourceRange();
6866   } else {
6867     // We followed through a reference variable. 'stackE' contains the
6868     // problematic expression but we will warn at the return statement pointing
6869     // at the reference variable. We will later display the "trail" of
6870     // reference variables using notes.
6871     diagLoc = refVars[0]->getLocStart();
6872     diagRange = refVars[0]->getSourceRange();
6873   }
6874 
6875   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6876     // address of local var
6877     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
6878      << DR->getDecl()->getDeclName() << diagRange;
6879   } else if (isa<BlockExpr>(stackE)) { // local block.
6880     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
6881   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
6882     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
6883   } else { // local temporary.
6884     // If there is an LValue->RValue conversion, then the value of the
6885     // reference type is used, not the reference.
6886     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
6887       if (ICE->getCastKind() == CK_LValueToRValue) {
6888         return;
6889       }
6890     }
6891     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6892      << lhsType->isReferenceType() << diagRange;
6893   }
6894 
6895   // Display the "trail" of reference variables that we followed until we
6896   // found the problematic expression using notes.
6897   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
6898     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
6899     // If this var binds to another reference var, show the range of the next
6900     // var, otherwise the var binds to the problematic expression, in which case
6901     // show the range of the expression.
6902     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6903                                     : stackE->getSourceRange();
6904     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6905         << VD->getDeclName() << range;
6906   }
6907 }
6908 
6909 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6910 ///  check if the expression in a return statement evaluates to an address
6911 ///  to a location on the stack, a local block, an address of a label, or a
6912 ///  reference to local temporary. The recursion is used to traverse the
6913 ///  AST of the return expression, with recursion backtracking when we
6914 ///  encounter a subexpression that (1) clearly does not lead to one of the
6915 ///  above problematic expressions (2) is something we cannot determine leads to
6916 ///  a problematic expression based on such local checking.
6917 ///
6918 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
6919 ///  the expression that they point to. Such variables are added to the
6920 ///  'refVars' vector so that we know what the reference variable "trail" was.
6921 ///
6922 ///  EvalAddr processes expressions that are pointers that are used as
6923 ///  references (and not L-values).  EvalVal handles all other values.
6924 ///  At the base case of the recursion is a check for the above problematic
6925 ///  expressions.
6926 ///
6927 ///  This implementation handles:
6928 ///
6929 ///   * pointer-to-pointer casts
6930 ///   * implicit conversions from array references to pointers
6931 ///   * taking the address of fields
6932 ///   * arbitrary interplay between "&" and "*" operators
6933 ///   * pointer arithmetic from an address of a stack variable
6934 ///   * taking the address of an array element where the array is on the stack
6935 static const Expr *EvalAddr(const Expr *E,
6936                             SmallVectorImpl<const DeclRefExpr *> &refVars,
6937                             const Decl *ParentDecl) {
6938   if (E->isTypeDependent())
6939     return nullptr;
6940 
6941   // We should only be called for evaluating pointer expressions.
6942   assert((E->getType()->isAnyPointerType() ||
6943           E->getType()->isBlockPointerType() ||
6944           E->getType()->isObjCQualifiedIdType()) &&
6945          "EvalAddr only works on pointers");
6946 
6947   E = E->IgnoreParens();
6948 
6949   // Our "symbolic interpreter" is just a dispatch off the currently
6950   // viewed AST node.  We then recursively traverse the AST by calling
6951   // EvalAddr and EvalVal appropriately.
6952   switch (E->getStmtClass()) {
6953   case Stmt::DeclRefExprClass: {
6954     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6955 
6956     // If we leave the immediate function, the lifetime isn't about to end.
6957     if (DR->refersToEnclosingVariableOrCapture())
6958       return nullptr;
6959 
6960     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
6961       // If this is a reference variable, follow through to the expression that
6962       // it points to.
6963       if (V->hasLocalStorage() &&
6964           V->getType()->isReferenceType() && V->hasInit()) {
6965         // Add the reference variable to the "trail".
6966         refVars.push_back(DR);
6967         return EvalAddr(V->getInit(), refVars, ParentDecl);
6968       }
6969 
6970     return nullptr;
6971   }
6972 
6973   case Stmt::UnaryOperatorClass: {
6974     // The only unary operator that make sense to handle here
6975     // is AddrOf.  All others don't make sense as pointers.
6976     const UnaryOperator *U = cast<UnaryOperator>(E);
6977 
6978     if (U->getOpcode() == UO_AddrOf)
6979       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
6980     return nullptr;
6981   }
6982 
6983   case Stmt::BinaryOperatorClass: {
6984     // Handle pointer arithmetic.  All other binary operators are not valid
6985     // in this context.
6986     const BinaryOperator *B = cast<BinaryOperator>(E);
6987     BinaryOperatorKind op = B->getOpcode();
6988 
6989     if (op != BO_Add && op != BO_Sub)
6990       return nullptr;
6991 
6992     const Expr *Base = B->getLHS();
6993 
6994     // Determine which argument is the real pointer base.  It could be
6995     // the RHS argument instead of the LHS.
6996     if (!Base->getType()->isPointerType())
6997       Base = B->getRHS();
6998 
6999     assert(Base->getType()->isPointerType());
7000     return EvalAddr(Base, refVars, ParentDecl);
7001   }
7002 
7003   // For conditional operators we need to see if either the LHS or RHS are
7004   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7005   case Stmt::ConditionalOperatorClass: {
7006     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7007 
7008     // Handle the GNU extension for missing LHS.
7009     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7010     if (const Expr *LHSExpr = C->getLHS()) {
7011       // In C++, we can have a throw-expression, which has 'void' type.
7012       if (!LHSExpr->getType()->isVoidType())
7013         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7014           return LHS;
7015     }
7016 
7017     // In C++, we can have a throw-expression, which has 'void' type.
7018     if (C->getRHS()->getType()->isVoidType())
7019       return nullptr;
7020 
7021     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7022   }
7023 
7024   case Stmt::BlockExprClass:
7025     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7026       return E; // local block.
7027     return nullptr;
7028 
7029   case Stmt::AddrLabelExprClass:
7030     return E; // address of label.
7031 
7032   case Stmt::ExprWithCleanupsClass:
7033     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7034                     ParentDecl);
7035 
7036   // For casts, we need to handle conversions from arrays to
7037   // pointer values, and pointer-to-pointer conversions.
7038   case Stmt::ImplicitCastExprClass:
7039   case Stmt::CStyleCastExprClass:
7040   case Stmt::CXXFunctionalCastExprClass:
7041   case Stmt::ObjCBridgedCastExprClass:
7042   case Stmt::CXXStaticCastExprClass:
7043   case Stmt::CXXDynamicCastExprClass:
7044   case Stmt::CXXConstCastExprClass:
7045   case Stmt::CXXReinterpretCastExprClass: {
7046     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7047     switch (cast<CastExpr>(E)->getCastKind()) {
7048     case CK_LValueToRValue:
7049     case CK_NoOp:
7050     case CK_BaseToDerived:
7051     case CK_DerivedToBase:
7052     case CK_UncheckedDerivedToBase:
7053     case CK_Dynamic:
7054     case CK_CPointerToObjCPointerCast:
7055     case CK_BlockPointerToObjCPointerCast:
7056     case CK_AnyPointerToBlockPointerCast:
7057       return EvalAddr(SubExpr, refVars, ParentDecl);
7058 
7059     case CK_ArrayToPointerDecay:
7060       return EvalVal(SubExpr, refVars, ParentDecl);
7061 
7062     case CK_BitCast:
7063       if (SubExpr->getType()->isAnyPointerType() ||
7064           SubExpr->getType()->isBlockPointerType() ||
7065           SubExpr->getType()->isObjCQualifiedIdType())
7066         return EvalAddr(SubExpr, refVars, ParentDecl);
7067       else
7068         return nullptr;
7069 
7070     default:
7071       return nullptr;
7072     }
7073   }
7074 
7075   case Stmt::MaterializeTemporaryExprClass:
7076     if (const Expr *Result =
7077             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7078                      refVars, ParentDecl))
7079       return Result;
7080     return E;
7081 
7082   // Everything else: we simply don't reason about them.
7083   default:
7084     return nullptr;
7085   }
7086 }
7087 
7088 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7089 ///   See the comments for EvalAddr for more details.
7090 static const Expr *EvalVal(const Expr *E,
7091                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7092                            const Decl *ParentDecl) {
7093   do {
7094     // We should only be called for evaluating non-pointer expressions, or
7095     // expressions with a pointer type that are not used as references but
7096     // instead
7097     // are l-values (e.g., DeclRefExpr with a pointer type).
7098 
7099     // Our "symbolic interpreter" is just a dispatch off the currently
7100     // viewed AST node.  We then recursively traverse the AST by calling
7101     // EvalAddr and EvalVal appropriately.
7102 
7103     E = E->IgnoreParens();
7104     switch (E->getStmtClass()) {
7105     case Stmt::ImplicitCastExprClass: {
7106       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7107       if (IE->getValueKind() == VK_LValue) {
7108         E = IE->getSubExpr();
7109         continue;
7110       }
7111       return nullptr;
7112     }
7113 
7114     case Stmt::ExprWithCleanupsClass:
7115       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7116                      ParentDecl);
7117 
7118     case Stmt::DeclRefExprClass: {
7119       // When we hit a DeclRefExpr we are looking at code that refers to a
7120       // variable's name. If it's not a reference variable we check if it has
7121       // local storage within the function, and if so, return the expression.
7122       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7123 
7124       // If we leave the immediate function, the lifetime isn't about to end.
7125       if (DR->refersToEnclosingVariableOrCapture())
7126         return nullptr;
7127 
7128       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7129         // Check if it refers to itself, e.g. "int& i = i;".
7130         if (V == ParentDecl)
7131           return DR;
7132 
7133         if (V->hasLocalStorage()) {
7134           if (!V->getType()->isReferenceType())
7135             return DR;
7136 
7137           // Reference variable, follow through to the expression that
7138           // it points to.
7139           if (V->hasInit()) {
7140             // Add the reference variable to the "trail".
7141             refVars.push_back(DR);
7142             return EvalVal(V->getInit(), refVars, V);
7143           }
7144         }
7145       }
7146 
7147       return nullptr;
7148     }
7149 
7150     case Stmt::UnaryOperatorClass: {
7151       // The only unary operator that make sense to handle here
7152       // is Deref.  All others don't resolve to a "name."  This includes
7153       // handling all sorts of rvalues passed to a unary operator.
7154       const UnaryOperator *U = cast<UnaryOperator>(E);
7155 
7156       if (U->getOpcode() == UO_Deref)
7157         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7158 
7159       return nullptr;
7160     }
7161 
7162     case Stmt::ArraySubscriptExprClass: {
7163       // Array subscripts are potential references to data on the stack.  We
7164       // retrieve the DeclRefExpr* for the array variable if it indeed
7165       // has local storage.
7166       const auto *ASE = cast<ArraySubscriptExpr>(E);
7167       if (ASE->isTypeDependent())
7168         return nullptr;
7169       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7170     }
7171 
7172     case Stmt::OMPArraySectionExprClass: {
7173       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7174                       ParentDecl);
7175     }
7176 
7177     case Stmt::ConditionalOperatorClass: {
7178       // For conditional operators we need to see if either the LHS or RHS are
7179       // non-NULL Expr's.  If one is non-NULL, we return it.
7180       const ConditionalOperator *C = cast<ConditionalOperator>(E);
7181 
7182       // Handle the GNU extension for missing LHS.
7183       if (const Expr *LHSExpr = C->getLHS()) {
7184         // In C++, we can have a throw-expression, which has 'void' type.
7185         if (!LHSExpr->getType()->isVoidType())
7186           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7187             return LHS;
7188       }
7189 
7190       // In C++, we can have a throw-expression, which has 'void' type.
7191       if (C->getRHS()->getType()->isVoidType())
7192         return nullptr;
7193 
7194       return EvalVal(C->getRHS(), refVars, ParentDecl);
7195     }
7196 
7197     // Accesses to members are potential references to data on the stack.
7198     case Stmt::MemberExprClass: {
7199       const MemberExpr *M = cast<MemberExpr>(E);
7200 
7201       // Check for indirect access.  We only want direct field accesses.
7202       if (M->isArrow())
7203         return nullptr;
7204 
7205       // Check whether the member type is itself a reference, in which case
7206       // we're not going to refer to the member, but to what the member refers
7207       // to.
7208       if (M->getMemberDecl()->getType()->isReferenceType())
7209         return nullptr;
7210 
7211       return EvalVal(M->getBase(), refVars, ParentDecl);
7212     }
7213 
7214     case Stmt::MaterializeTemporaryExprClass:
7215       if (const Expr *Result =
7216               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7217                       refVars, ParentDecl))
7218         return Result;
7219       return E;
7220 
7221     default:
7222       // Check that we don't return or take the address of a reference to a
7223       // temporary. This is only useful in C++.
7224       if (!E->isTypeDependent() && E->isRValue())
7225         return E;
7226 
7227       // Everything else: we simply don't reason about them.
7228       return nullptr;
7229     }
7230   } while (true);
7231 }
7232 
7233 void
7234 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7235                          SourceLocation ReturnLoc,
7236                          bool isObjCMethod,
7237                          const AttrVec *Attrs,
7238                          const FunctionDecl *FD) {
7239   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7240 
7241   // Check if the return value is null but should not be.
7242   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7243        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7244       CheckNonNullExpr(*this, RetValExp))
7245     Diag(ReturnLoc, diag::warn_null_ret)
7246       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7247 
7248   // C++11 [basic.stc.dynamic.allocation]p4:
7249   //   If an allocation function declared with a non-throwing
7250   //   exception-specification fails to allocate storage, it shall return
7251   //   a null pointer. Any other allocation function that fails to allocate
7252   //   storage shall indicate failure only by throwing an exception [...]
7253   if (FD) {
7254     OverloadedOperatorKind Op = FD->getOverloadedOperator();
7255     if (Op == OO_New || Op == OO_Array_New) {
7256       const FunctionProtoType *Proto
7257         = FD->getType()->castAs<FunctionProtoType>();
7258       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7259           CheckNonNullExpr(*this, RetValExp))
7260         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7261           << FD << getLangOpts().CPlusPlus11;
7262     }
7263   }
7264 }
7265 
7266 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7267 
7268 /// Check for comparisons of floating point operands using != and ==.
7269 /// Issue a warning if these are no self-comparisons, as they are not likely
7270 /// to do what the programmer intended.
7271 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7272   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7273   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7274 
7275   // Special case: check for x == x (which is OK).
7276   // Do not emit warnings for such cases.
7277   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7278     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7279       if (DRL->getDecl() == DRR->getDecl())
7280         return;
7281 
7282   // Special case: check for comparisons against literals that can be exactly
7283   //  represented by APFloat.  In such cases, do not emit a warning.  This
7284   //  is a heuristic: often comparison against such literals are used to
7285   //  detect if a value in a variable has not changed.  This clearly can
7286   //  lead to false negatives.
7287   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7288     if (FLL->isExact())
7289       return;
7290   } else
7291     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7292       if (FLR->isExact())
7293         return;
7294 
7295   // Check for comparisons with builtin types.
7296   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7297     if (CL->getBuiltinCallee())
7298       return;
7299 
7300   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7301     if (CR->getBuiltinCallee())
7302       return;
7303 
7304   // Emit the diagnostic.
7305   Diag(Loc, diag::warn_floatingpoint_eq)
7306     << LHS->getSourceRange() << RHS->getSourceRange();
7307 }
7308 
7309 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7310 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7311 
7312 namespace {
7313 
7314 /// Structure recording the 'active' range of an integer-valued
7315 /// expression.
7316 struct IntRange {
7317   /// The number of bits active in the int.
7318   unsigned Width;
7319 
7320   /// True if the int is known not to have negative values.
7321   bool NonNegative;
7322 
7323   IntRange(unsigned Width, bool NonNegative)
7324     : Width(Width), NonNegative(NonNegative)
7325   {}
7326 
7327   /// Returns the range of the bool type.
7328   static IntRange forBoolType() {
7329     return IntRange(1, true);
7330   }
7331 
7332   /// Returns the range of an opaque value of the given integral type.
7333   static IntRange forValueOfType(ASTContext &C, QualType T) {
7334     return forValueOfCanonicalType(C,
7335                           T->getCanonicalTypeInternal().getTypePtr());
7336   }
7337 
7338   /// Returns the range of an opaque value of a canonical integral type.
7339   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
7340     assert(T->isCanonicalUnqualified());
7341 
7342     if (const VectorType *VT = dyn_cast<VectorType>(T))
7343       T = VT->getElementType().getTypePtr();
7344     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7345       T = CT->getElementType().getTypePtr();
7346     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7347       T = AT->getValueType().getTypePtr();
7348 
7349     // For enum types, use the known bit width of the enumerators.
7350     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
7351       EnumDecl *Enum = ET->getDecl();
7352       if (!Enum->isCompleteDefinition())
7353         return IntRange(C.getIntWidth(QualType(T, 0)), false);
7354 
7355       unsigned NumPositive = Enum->getNumPositiveBits();
7356       unsigned NumNegative = Enum->getNumNegativeBits();
7357 
7358       if (NumNegative == 0)
7359         return IntRange(NumPositive, true/*NonNegative*/);
7360       else
7361         return IntRange(std::max(NumPositive + 1, NumNegative),
7362                         false/*NonNegative*/);
7363     }
7364 
7365     const BuiltinType *BT = cast<BuiltinType>(T);
7366     assert(BT->isInteger());
7367 
7368     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7369   }
7370 
7371   /// Returns the "target" range of a canonical integral type, i.e.
7372   /// the range of values expressible in the type.
7373   ///
7374   /// This matches forValueOfCanonicalType except that enums have the
7375   /// full range of their type, not the range of their enumerators.
7376   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7377     assert(T->isCanonicalUnqualified());
7378 
7379     if (const VectorType *VT = dyn_cast<VectorType>(T))
7380       T = VT->getElementType().getTypePtr();
7381     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7382       T = CT->getElementType().getTypePtr();
7383     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7384       T = AT->getValueType().getTypePtr();
7385     if (const EnumType *ET = dyn_cast<EnumType>(T))
7386       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
7387 
7388     const BuiltinType *BT = cast<BuiltinType>(T);
7389     assert(BT->isInteger());
7390 
7391     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7392   }
7393 
7394   /// Returns the supremum of two ranges: i.e. their conservative merge.
7395   static IntRange join(IntRange L, IntRange R) {
7396     return IntRange(std::max(L.Width, R.Width),
7397                     L.NonNegative && R.NonNegative);
7398   }
7399 
7400   /// Returns the infinum of two ranges: i.e. their aggressive merge.
7401   static IntRange meet(IntRange L, IntRange R) {
7402     return IntRange(std::min(L.Width, R.Width),
7403                     L.NonNegative || R.NonNegative);
7404   }
7405 };
7406 
7407 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
7408   if (value.isSigned() && value.isNegative())
7409     return IntRange(value.getMinSignedBits(), false);
7410 
7411   if (value.getBitWidth() > MaxWidth)
7412     value = value.trunc(MaxWidth);
7413 
7414   // isNonNegative() just checks the sign bit without considering
7415   // signedness.
7416   return IntRange(value.getActiveBits(), true);
7417 }
7418 
7419 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7420                        unsigned MaxWidth) {
7421   if (result.isInt())
7422     return GetValueRange(C, result.getInt(), MaxWidth);
7423 
7424   if (result.isVector()) {
7425     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7426     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7427       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7428       R = IntRange::join(R, El);
7429     }
7430     return R;
7431   }
7432 
7433   if (result.isComplexInt()) {
7434     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7435     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7436     return IntRange::join(R, I);
7437   }
7438 
7439   // This can happen with lossless casts to intptr_t of "based" lvalues.
7440   // Assume it might use arbitrary bits.
7441   // FIXME: The only reason we need to pass the type in here is to get
7442   // the sign right on this one case.  It would be nice if APValue
7443   // preserved this.
7444   assert(result.isLValue() || result.isAddrLabelDiff());
7445   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
7446 }
7447 
7448 QualType GetExprType(const Expr *E) {
7449   QualType Ty = E->getType();
7450   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7451     Ty = AtomicRHS->getValueType();
7452   return Ty;
7453 }
7454 
7455 /// Pseudo-evaluate the given integer expression, estimating the
7456 /// range of values it might take.
7457 ///
7458 /// \param MaxWidth - the width to which the value will be truncated
7459 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
7460   E = E->IgnoreParens();
7461 
7462   // Try a full evaluation first.
7463   Expr::EvalResult result;
7464   if (E->EvaluateAsRValue(result, C))
7465     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
7466 
7467   // I think we only want to look through implicit casts here; if the
7468   // user has an explicit widening cast, we should treat the value as
7469   // being of the new, wider type.
7470   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
7471     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
7472       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7473 
7474     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
7475 
7476     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7477                          CE->getCastKind() == CK_BooleanToSignedIntegral;
7478 
7479     // Assume that non-integer casts can span the full range of the type.
7480     if (!isIntegerCast)
7481       return OutputTypeRange;
7482 
7483     IntRange SubRange
7484       = GetExprRange(C, CE->getSubExpr(),
7485                      std::min(MaxWidth, OutputTypeRange.Width));
7486 
7487     // Bail out if the subexpr's range is as wide as the cast type.
7488     if (SubRange.Width >= OutputTypeRange.Width)
7489       return OutputTypeRange;
7490 
7491     // Otherwise, we take the smaller width, and we're non-negative if
7492     // either the output type or the subexpr is.
7493     return IntRange(SubRange.Width,
7494                     SubRange.NonNegative || OutputTypeRange.NonNegative);
7495   }
7496 
7497   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
7498     // If we can fold the condition, just take that operand.
7499     bool CondResult;
7500     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7501       return GetExprRange(C, CondResult ? CO->getTrueExpr()
7502                                         : CO->getFalseExpr(),
7503                           MaxWidth);
7504 
7505     // Otherwise, conservatively merge.
7506     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7507     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7508     return IntRange::join(L, R);
7509   }
7510 
7511   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
7512     switch (BO->getOpcode()) {
7513 
7514     // Boolean-valued operations are single-bit and positive.
7515     case BO_LAnd:
7516     case BO_LOr:
7517     case BO_LT:
7518     case BO_GT:
7519     case BO_LE:
7520     case BO_GE:
7521     case BO_EQ:
7522     case BO_NE:
7523       return IntRange::forBoolType();
7524 
7525     // The type of the assignments is the type of the LHS, so the RHS
7526     // is not necessarily the same type.
7527     case BO_MulAssign:
7528     case BO_DivAssign:
7529     case BO_RemAssign:
7530     case BO_AddAssign:
7531     case BO_SubAssign:
7532     case BO_XorAssign:
7533     case BO_OrAssign:
7534       // TODO: bitfields?
7535       return IntRange::forValueOfType(C, GetExprType(E));
7536 
7537     // Simple assignments just pass through the RHS, which will have
7538     // been coerced to the LHS type.
7539     case BO_Assign:
7540       // TODO: bitfields?
7541       return GetExprRange(C, BO->getRHS(), MaxWidth);
7542 
7543     // Operations with opaque sources are black-listed.
7544     case BO_PtrMemD:
7545     case BO_PtrMemI:
7546       return IntRange::forValueOfType(C, GetExprType(E));
7547 
7548     // Bitwise-and uses the *infinum* of the two source ranges.
7549     case BO_And:
7550     case BO_AndAssign:
7551       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7552                             GetExprRange(C, BO->getRHS(), MaxWidth));
7553 
7554     // Left shift gets black-listed based on a judgement call.
7555     case BO_Shl:
7556       // ...except that we want to treat '1 << (blah)' as logically
7557       // positive.  It's an important idiom.
7558       if (IntegerLiteral *I
7559             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7560         if (I->getValue() == 1) {
7561           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
7562           return IntRange(R.Width, /*NonNegative*/ true);
7563         }
7564       }
7565       // fallthrough
7566 
7567     case BO_ShlAssign:
7568       return IntRange::forValueOfType(C, GetExprType(E));
7569 
7570     // Right shift by a constant can narrow its left argument.
7571     case BO_Shr:
7572     case BO_ShrAssign: {
7573       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7574 
7575       // If the shift amount is a positive constant, drop the width by
7576       // that much.
7577       llvm::APSInt shift;
7578       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7579           shift.isNonNegative()) {
7580         unsigned zext = shift.getZExtValue();
7581         if (zext >= L.Width)
7582           L.Width = (L.NonNegative ? 0 : 1);
7583         else
7584           L.Width -= zext;
7585       }
7586 
7587       return L;
7588     }
7589 
7590     // Comma acts as its right operand.
7591     case BO_Comma:
7592       return GetExprRange(C, BO->getRHS(), MaxWidth);
7593 
7594     // Black-list pointer subtractions.
7595     case BO_Sub:
7596       if (BO->getLHS()->getType()->isPointerType())
7597         return IntRange::forValueOfType(C, GetExprType(E));
7598       break;
7599 
7600     // The width of a division result is mostly determined by the size
7601     // of the LHS.
7602     case BO_Div: {
7603       // Don't 'pre-truncate' the operands.
7604       unsigned opWidth = C.getIntWidth(GetExprType(E));
7605       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7606 
7607       // If the divisor is constant, use that.
7608       llvm::APSInt divisor;
7609       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7610         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7611         if (log2 >= L.Width)
7612           L.Width = (L.NonNegative ? 0 : 1);
7613         else
7614           L.Width = std::min(L.Width - log2, MaxWidth);
7615         return L;
7616       }
7617 
7618       // Otherwise, just use the LHS's width.
7619       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7620       return IntRange(L.Width, L.NonNegative && R.NonNegative);
7621     }
7622 
7623     // The result of a remainder can't be larger than the result of
7624     // either side.
7625     case BO_Rem: {
7626       // Don't 'pre-truncate' the operands.
7627       unsigned opWidth = C.getIntWidth(GetExprType(E));
7628       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7629       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7630 
7631       IntRange meet = IntRange::meet(L, R);
7632       meet.Width = std::min(meet.Width, MaxWidth);
7633       return meet;
7634     }
7635 
7636     // The default behavior is okay for these.
7637     case BO_Mul:
7638     case BO_Add:
7639     case BO_Xor:
7640     case BO_Or:
7641       break;
7642     }
7643 
7644     // The default case is to treat the operation as if it were closed
7645     // on the narrowest type that encompasses both operands.
7646     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7647     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7648     return IntRange::join(L, R);
7649   }
7650 
7651   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
7652     switch (UO->getOpcode()) {
7653     // Boolean-valued operations are white-listed.
7654     case UO_LNot:
7655       return IntRange::forBoolType();
7656 
7657     // Operations with opaque sources are black-listed.
7658     case UO_Deref:
7659     case UO_AddrOf: // should be impossible
7660       return IntRange::forValueOfType(C, GetExprType(E));
7661 
7662     default:
7663       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7664     }
7665   }
7666 
7667   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
7668     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7669 
7670   if (const auto *BitField = E->getSourceBitField())
7671     return IntRange(BitField->getBitWidthValue(C),
7672                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
7673 
7674   return IntRange::forValueOfType(C, GetExprType(E));
7675 }
7676 
7677 IntRange GetExprRange(ASTContext &C, const Expr *E) {
7678   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
7679 }
7680 
7681 /// Checks whether the given value, which currently has the given
7682 /// source semantics, has the same value when coerced through the
7683 /// target semantics.
7684 bool IsSameFloatAfterCast(const llvm::APFloat &value,
7685                           const llvm::fltSemantics &Src,
7686                           const llvm::fltSemantics &Tgt) {
7687   llvm::APFloat truncated = value;
7688 
7689   bool ignored;
7690   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7691   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7692 
7693   return truncated.bitwiseIsEqual(value);
7694 }
7695 
7696 /// Checks whether the given value, which currently has the given
7697 /// source semantics, has the same value when coerced through the
7698 /// target semantics.
7699 ///
7700 /// The value might be a vector of floats (or a complex number).
7701 bool IsSameFloatAfterCast(const APValue &value,
7702                           const llvm::fltSemantics &Src,
7703                           const llvm::fltSemantics &Tgt) {
7704   if (value.isFloat())
7705     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7706 
7707   if (value.isVector()) {
7708     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7709       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7710         return false;
7711     return true;
7712   }
7713 
7714   assert(value.isComplexFloat());
7715   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7716           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7717 }
7718 
7719 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
7720 
7721 bool IsZero(Sema &S, Expr *E) {
7722   // Suppress cases where we are comparing against an enum constant.
7723   if (const DeclRefExpr *DR =
7724       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7725     if (isa<EnumConstantDecl>(DR->getDecl()))
7726       return false;
7727 
7728   // Suppress cases where the '0' value is expanded from a macro.
7729   if (E->getLocStart().isMacroID())
7730     return false;
7731 
7732   llvm::APSInt Value;
7733   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7734 }
7735 
7736 bool HasEnumType(Expr *E) {
7737   // Strip off implicit integral promotions.
7738   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7739     if (ICE->getCastKind() != CK_IntegralCast &&
7740         ICE->getCastKind() != CK_NoOp)
7741       break;
7742     E = ICE->getSubExpr();
7743   }
7744 
7745   return E->getType()->isEnumeralType();
7746 }
7747 
7748 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
7749   // Disable warning in template instantiations.
7750   if (!S.ActiveTemplateInstantiations.empty())
7751     return;
7752 
7753   BinaryOperatorKind op = E->getOpcode();
7754   if (E->isValueDependent())
7755     return;
7756 
7757   if (op == BO_LT && IsZero(S, E->getRHS())) {
7758     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
7759       << "< 0" << "false" << HasEnumType(E->getLHS())
7760       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7761   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
7762     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
7763       << ">= 0" << "true" << HasEnumType(E->getLHS())
7764       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7765   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
7766     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
7767       << "0 >" << "false" << HasEnumType(E->getRHS())
7768       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7769   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
7770     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
7771       << "0 <=" << "true" << HasEnumType(E->getRHS())
7772       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7773   }
7774 }
7775 
7776 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7777                                   Expr *Other, const llvm::APSInt &Value,
7778                                   bool RhsConstant) {
7779   // Disable warning in template instantiations.
7780   if (!S.ActiveTemplateInstantiations.empty())
7781     return;
7782 
7783   // TODO: Investigate using GetExprRange() to get tighter bounds
7784   // on the bit ranges.
7785   QualType OtherT = Other->getType();
7786   if (const auto *AT = OtherT->getAs<AtomicType>())
7787     OtherT = AT->getValueType();
7788   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7789   unsigned OtherWidth = OtherRange.Width;
7790 
7791   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7792 
7793   // 0 values are handled later by CheckTrivialUnsignedComparison().
7794   if ((Value == 0) && (!OtherIsBooleanType))
7795     return;
7796 
7797   BinaryOperatorKind op = E->getOpcode();
7798   bool IsTrue = true;
7799 
7800   // Used for diagnostic printout.
7801   enum {
7802     LiteralConstant = 0,
7803     CXXBoolLiteralTrue,
7804     CXXBoolLiteralFalse
7805   } LiteralOrBoolConstant = LiteralConstant;
7806 
7807   if (!OtherIsBooleanType) {
7808     QualType ConstantT = Constant->getType();
7809     QualType CommonT = E->getLHS()->getType();
7810 
7811     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7812       return;
7813     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7814            "comparison with non-integer type");
7815 
7816     bool ConstantSigned = ConstantT->isSignedIntegerType();
7817     bool CommonSigned = CommonT->isSignedIntegerType();
7818 
7819     bool EqualityOnly = false;
7820 
7821     if (CommonSigned) {
7822       // The common type is signed, therefore no signed to unsigned conversion.
7823       if (!OtherRange.NonNegative) {
7824         // Check that the constant is representable in type OtherT.
7825         if (ConstantSigned) {
7826           if (OtherWidth >= Value.getMinSignedBits())
7827             return;
7828         } else { // !ConstantSigned
7829           if (OtherWidth >= Value.getActiveBits() + 1)
7830             return;
7831         }
7832       } else { // !OtherSigned
7833                // Check that the constant is representable in type OtherT.
7834         // Negative values are out of range.
7835         if (ConstantSigned) {
7836           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7837             return;
7838         } else { // !ConstantSigned
7839           if (OtherWidth >= Value.getActiveBits())
7840             return;
7841         }
7842       }
7843     } else { // !CommonSigned
7844       if (OtherRange.NonNegative) {
7845         if (OtherWidth >= Value.getActiveBits())
7846           return;
7847       } else { // OtherSigned
7848         assert(!ConstantSigned &&
7849                "Two signed types converted to unsigned types.");
7850         // Check to see if the constant is representable in OtherT.
7851         if (OtherWidth > Value.getActiveBits())
7852           return;
7853         // Check to see if the constant is equivalent to a negative value
7854         // cast to CommonT.
7855         if (S.Context.getIntWidth(ConstantT) ==
7856                 S.Context.getIntWidth(CommonT) &&
7857             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7858           return;
7859         // The constant value rests between values that OtherT can represent
7860         // after conversion.  Relational comparison still works, but equality
7861         // comparisons will be tautological.
7862         EqualityOnly = true;
7863       }
7864     }
7865 
7866     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7867 
7868     if (op == BO_EQ || op == BO_NE) {
7869       IsTrue = op == BO_NE;
7870     } else if (EqualityOnly) {
7871       return;
7872     } else if (RhsConstant) {
7873       if (op == BO_GT || op == BO_GE)
7874         IsTrue = !PositiveConstant;
7875       else // op == BO_LT || op == BO_LE
7876         IsTrue = PositiveConstant;
7877     } else {
7878       if (op == BO_LT || op == BO_LE)
7879         IsTrue = !PositiveConstant;
7880       else // op == BO_GT || op == BO_GE
7881         IsTrue = PositiveConstant;
7882     }
7883   } else {
7884     // Other isKnownToHaveBooleanValue
7885     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7886     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7887     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7888 
7889     static const struct LinkedConditions {
7890       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7891       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7892       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7893       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7894       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7895       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7896 
7897     } TruthTable = {
7898         // Constant on LHS.              | Constant on RHS.              |
7899         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
7900         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7901         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7902         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7903         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7904         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7905         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7906       };
7907 
7908     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7909 
7910     enum ConstantValue ConstVal = Zero;
7911     if (Value.isUnsigned() || Value.isNonNegative()) {
7912       if (Value == 0) {
7913         LiteralOrBoolConstant =
7914             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7915         ConstVal = Zero;
7916       } else if (Value == 1) {
7917         LiteralOrBoolConstant =
7918             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7919         ConstVal = One;
7920       } else {
7921         LiteralOrBoolConstant = LiteralConstant;
7922         ConstVal = GT_One;
7923       }
7924     } else {
7925       ConstVal = LT_Zero;
7926     }
7927 
7928     CompareBoolWithConstantResult CmpRes;
7929 
7930     switch (op) {
7931     case BO_LT:
7932       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7933       break;
7934     case BO_GT:
7935       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7936       break;
7937     case BO_LE:
7938       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7939       break;
7940     case BO_GE:
7941       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7942       break;
7943     case BO_EQ:
7944       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7945       break;
7946     case BO_NE:
7947       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7948       break;
7949     default:
7950       CmpRes = Unkwn;
7951       break;
7952     }
7953 
7954     if (CmpRes == AFals) {
7955       IsTrue = false;
7956     } else if (CmpRes == ATrue) {
7957       IsTrue = true;
7958     } else {
7959       return;
7960     }
7961   }
7962 
7963   // If this is a comparison to an enum constant, include that
7964   // constant in the diagnostic.
7965   const EnumConstantDecl *ED = nullptr;
7966   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7967     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7968 
7969   SmallString<64> PrettySourceValue;
7970   llvm::raw_svector_ostream OS(PrettySourceValue);
7971   if (ED)
7972     OS << '\'' << *ED << "' (" << Value << ")";
7973   else
7974     OS << Value;
7975 
7976   S.DiagRuntimeBehavior(
7977     E->getOperatorLoc(), E,
7978     S.PDiag(diag::warn_out_of_range_compare)
7979         << OS.str() << LiteralOrBoolConstant
7980         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7981         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
7982 }
7983 
7984 /// Analyze the operands of the given comparison.  Implements the
7985 /// fallback case from AnalyzeComparison.
7986 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
7987   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7988   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7989 }
7990 
7991 /// \brief Implements -Wsign-compare.
7992 ///
7993 /// \param E the binary operator to check for warnings
7994 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
7995   // The type the comparison is being performed in.
7996   QualType T = E->getLHS()->getType();
7997 
7998   // Only analyze comparison operators where both sides have been converted to
7999   // the same type.
8000   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8001     return AnalyzeImpConvsInComparison(S, E);
8002 
8003   // Don't analyze value-dependent comparisons directly.
8004   if (E->isValueDependent())
8005     return AnalyzeImpConvsInComparison(S, E);
8006 
8007   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8008   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8009 
8010   bool IsComparisonConstant = false;
8011 
8012   // Check whether an integer constant comparison results in a value
8013   // of 'true' or 'false'.
8014   if (T->isIntegralType(S.Context)) {
8015     llvm::APSInt RHSValue;
8016     bool IsRHSIntegralLiteral =
8017       RHS->isIntegerConstantExpr(RHSValue, S.Context);
8018     llvm::APSInt LHSValue;
8019     bool IsLHSIntegralLiteral =
8020       LHS->isIntegerConstantExpr(LHSValue, S.Context);
8021     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8022         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8023     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8024       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8025     else
8026       IsComparisonConstant =
8027         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8028   } else if (!T->hasUnsignedIntegerRepresentation())
8029       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8030 
8031   // We don't do anything special if this isn't an unsigned integral
8032   // comparison:  we're only interested in integral comparisons, and
8033   // signed comparisons only happen in cases we don't care to warn about.
8034   //
8035   // We also don't care about value-dependent expressions or expressions
8036   // whose result is a constant.
8037   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
8038     return AnalyzeImpConvsInComparison(S, E);
8039 
8040   // Check to see if one of the (unmodified) operands is of different
8041   // signedness.
8042   Expr *signedOperand, *unsignedOperand;
8043   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8044     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8045            "unsigned comparison between two signed integer expressions?");
8046     signedOperand = LHS;
8047     unsignedOperand = RHS;
8048   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8049     signedOperand = RHS;
8050     unsignedOperand = LHS;
8051   } else {
8052     CheckTrivialUnsignedComparison(S, E);
8053     return AnalyzeImpConvsInComparison(S, E);
8054   }
8055 
8056   // Otherwise, calculate the effective range of the signed operand.
8057   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8058 
8059   // Go ahead and analyze implicit conversions in the operands.  Note
8060   // that we skip the implicit conversions on both sides.
8061   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8062   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8063 
8064   // If the signed range is non-negative, -Wsign-compare won't fire,
8065   // but we should still check for comparisons which are always true
8066   // or false.
8067   if (signedRange.NonNegative)
8068     return CheckTrivialUnsignedComparison(S, E);
8069 
8070   // For (in)equality comparisons, if the unsigned operand is a
8071   // constant which cannot collide with a overflowed signed operand,
8072   // then reinterpreting the signed operand as unsigned will not
8073   // change the result of the comparison.
8074   if (E->isEqualityOp()) {
8075     unsigned comparisonWidth = S.Context.getIntWidth(T);
8076     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8077 
8078     // We should never be unable to prove that the unsigned operand is
8079     // non-negative.
8080     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8081 
8082     if (unsignedRange.Width < comparisonWidth)
8083       return;
8084   }
8085 
8086   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8087     S.PDiag(diag::warn_mixed_sign_comparison)
8088       << LHS->getType() << RHS->getType()
8089       << LHS->getSourceRange() << RHS->getSourceRange());
8090 }
8091 
8092 /// Analyzes an attempt to assign the given value to a bitfield.
8093 ///
8094 /// Returns true if there was something fishy about the attempt.
8095 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8096                                SourceLocation InitLoc) {
8097   assert(Bitfield->isBitField());
8098   if (Bitfield->isInvalidDecl())
8099     return false;
8100 
8101   // White-list bool bitfields.
8102   if (Bitfield->getType()->isBooleanType())
8103     return false;
8104 
8105   // Ignore value- or type-dependent expressions.
8106   if (Bitfield->getBitWidth()->isValueDependent() ||
8107       Bitfield->getBitWidth()->isTypeDependent() ||
8108       Init->isValueDependent() ||
8109       Init->isTypeDependent())
8110     return false;
8111 
8112   Expr *OriginalInit = Init->IgnoreParenImpCasts();
8113 
8114   llvm::APSInt Value;
8115   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
8116     return false;
8117 
8118   unsigned OriginalWidth = Value.getBitWidth();
8119   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8120 
8121   if (!Value.isSigned() || Value.isNegative())
8122     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8123       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8124         OriginalWidth = Value.getMinSignedBits();
8125 
8126   if (OriginalWidth <= FieldWidth)
8127     return false;
8128 
8129   // Compute the value which the bitfield will contain.
8130   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8131   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
8132 
8133   // Check whether the stored value is equal to the original value.
8134   TruncatedValue = TruncatedValue.extend(OriginalWidth);
8135   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8136     return false;
8137 
8138   // Special-case bitfields of width 1: booleans are naturally 0/1, and
8139   // therefore don't strictly fit into a signed bitfield of width 1.
8140   if (FieldWidth == 1 && Value == 1)
8141     return false;
8142 
8143   std::string PrettyValue = Value.toString(10);
8144   std::string PrettyTrunc = TruncatedValue.toString(10);
8145 
8146   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8147     << PrettyValue << PrettyTrunc << OriginalInit->getType()
8148     << Init->getSourceRange();
8149 
8150   return true;
8151 }
8152 
8153 /// Analyze the given simple or compound assignment for warning-worthy
8154 /// operations.
8155 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8156   // Just recurse on the LHS.
8157   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8158 
8159   // We want to recurse on the RHS as normal unless we're assigning to
8160   // a bitfield.
8161   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8162     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8163                                   E->getOperatorLoc())) {
8164       // Recurse, ignoring any implicit conversions on the RHS.
8165       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8166                                         E->getOperatorLoc());
8167     }
8168   }
8169 
8170   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8171 }
8172 
8173 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8174 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8175                      SourceLocation CContext, unsigned diag,
8176                      bool pruneControlFlow = false) {
8177   if (pruneControlFlow) {
8178     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8179                           S.PDiag(diag)
8180                             << SourceType << T << E->getSourceRange()
8181                             << SourceRange(CContext));
8182     return;
8183   }
8184   S.Diag(E->getExprLoc(), diag)
8185     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8186 }
8187 
8188 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8189 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8190                      unsigned diag, bool pruneControlFlow = false) {
8191   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8192 }
8193 
8194 
8195 /// Diagnose an implicit cast from a floating point value to an integer value.
8196 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8197 
8198                              SourceLocation CContext) {
8199   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8200   const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8201 
8202   Expr *InnerE = E->IgnoreParenImpCasts();
8203   // We also want to warn on, e.g., "int i = -1.234"
8204   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8205     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8206       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8207 
8208   const bool IsLiteral =
8209       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8210 
8211   llvm::APFloat Value(0.0);
8212   bool IsConstant =
8213     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8214   if (!IsConstant) {
8215     return DiagnoseImpCast(S, E, T, CContext,
8216                            diag::warn_impcast_float_integer, PruneWarnings);
8217   }
8218 
8219   bool isExact = false;
8220 
8221   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8222                             T->hasUnsignedIntegerRepresentation());
8223   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8224                              &isExact) == llvm::APFloat::opOK &&
8225       isExact) {
8226     if (IsLiteral) return;
8227     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8228                            PruneWarnings);
8229   }
8230 
8231   unsigned DiagID = 0;
8232   if (IsLiteral) {
8233     // Warn on floating point literal to integer.
8234     DiagID = diag::warn_impcast_literal_float_to_integer;
8235   } else if (IntegerValue == 0) {
8236     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
8237       return DiagnoseImpCast(S, E, T, CContext,
8238                              diag::warn_impcast_float_integer, PruneWarnings);
8239     }
8240     // Warn on non-zero to zero conversion.
8241     DiagID = diag::warn_impcast_float_to_integer_zero;
8242   } else {
8243     if (IntegerValue.isUnsigned()) {
8244       if (!IntegerValue.isMaxValue()) {
8245         return DiagnoseImpCast(S, E, T, CContext,
8246                                diag::warn_impcast_float_integer, PruneWarnings);
8247       }
8248     } else {  // IntegerValue.isSigned()
8249       if (!IntegerValue.isMaxSignedValue() &&
8250           !IntegerValue.isMinSignedValue()) {
8251         return DiagnoseImpCast(S, E, T, CContext,
8252                                diag::warn_impcast_float_integer, PruneWarnings);
8253       }
8254     }
8255     // Warn on evaluatable floating point expression to integer conversion.
8256     DiagID = diag::warn_impcast_float_to_integer;
8257   }
8258 
8259   // FIXME: Force the precision of the source value down so we don't print
8260   // digits which are usually useless (we don't really care here if we
8261   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
8262   // would automatically print the shortest representation, but it's a bit
8263   // tricky to implement.
8264   SmallString<16> PrettySourceValue;
8265   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8266   precision = (precision * 59 + 195) / 196;
8267   Value.toString(PrettySourceValue, precision);
8268 
8269   SmallString<16> PrettyTargetValue;
8270   if (IsBool)
8271     PrettyTargetValue = Value.isZero() ? "false" : "true";
8272   else
8273     IntegerValue.toString(PrettyTargetValue);
8274 
8275   if (PruneWarnings) {
8276     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8277                           S.PDiag(DiagID)
8278                               << E->getType() << T.getUnqualifiedType()
8279                               << PrettySourceValue << PrettyTargetValue
8280                               << E->getSourceRange() << SourceRange(CContext));
8281   } else {
8282     S.Diag(E->getExprLoc(), DiagID)
8283         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8284         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8285   }
8286 }
8287 
8288 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8289   if (!Range.Width) return "0";
8290 
8291   llvm::APSInt ValueInRange = Value;
8292   ValueInRange.setIsSigned(!Range.NonNegative);
8293   ValueInRange = ValueInRange.trunc(Range.Width);
8294   return ValueInRange.toString(10);
8295 }
8296 
8297 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
8298   if (!isa<ImplicitCastExpr>(Ex))
8299     return false;
8300 
8301   Expr *InnerE = Ex->IgnoreParenImpCasts();
8302   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8303   const Type *Source =
8304     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8305   if (Target->isDependentType())
8306     return false;
8307 
8308   const BuiltinType *FloatCandidateBT =
8309     dyn_cast<BuiltinType>(ToBool ? Source : Target);
8310   const Type *BoolCandidateType = ToBool ? Target : Source;
8311 
8312   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8313           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8314 }
8315 
8316 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8317                                       SourceLocation CC) {
8318   unsigned NumArgs = TheCall->getNumArgs();
8319   for (unsigned i = 0; i < NumArgs; ++i) {
8320     Expr *CurrA = TheCall->getArg(i);
8321     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8322       continue;
8323 
8324     bool IsSwapped = ((i > 0) &&
8325         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8326     IsSwapped |= ((i < (NumArgs - 1)) &&
8327         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8328     if (IsSwapped) {
8329       // Warn on this floating-point to bool conversion.
8330       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8331                       CurrA->getType(), CC,
8332                       diag::warn_impcast_floating_point_to_bool);
8333     }
8334   }
8335 }
8336 
8337 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
8338   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8339                         E->getExprLoc()))
8340     return;
8341 
8342   // Don't warn on functions which have return type nullptr_t.
8343   if (isa<CallExpr>(E))
8344     return;
8345 
8346   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8347   const Expr::NullPointerConstantKind NullKind =
8348       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8349   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8350     return;
8351 
8352   // Return if target type is a safe conversion.
8353   if (T->isAnyPointerType() || T->isBlockPointerType() ||
8354       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8355     return;
8356 
8357   SourceLocation Loc = E->getSourceRange().getBegin();
8358 
8359   // Venture through the macro stacks to get to the source of macro arguments.
8360   // The new location is a better location than the complete location that was
8361   // passed in.
8362   while (S.SourceMgr.isMacroArgExpansion(Loc))
8363     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8364 
8365   while (S.SourceMgr.isMacroArgExpansion(CC))
8366     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8367 
8368   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
8369   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8370     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8371         Loc, S.SourceMgr, S.getLangOpts());
8372     if (MacroName == "NULL")
8373       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
8374   }
8375 
8376   // Only warn if the null and context location are in the same macro expansion.
8377   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8378     return;
8379 
8380   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8381       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8382       << FixItHint::CreateReplacement(Loc,
8383                                       S.getFixItZeroLiteralForType(T, Loc));
8384 }
8385 
8386 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8387                            ObjCArrayLiteral *ArrayLiteral);
8388 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8389                                 ObjCDictionaryLiteral *DictionaryLiteral);
8390 
8391 /// Check a single element within a collection literal against the
8392 /// target element type.
8393 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8394                                        Expr *Element, unsigned ElementKind) {
8395   // Skip a bitcast to 'id' or qualified 'id'.
8396   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8397     if (ICE->getCastKind() == CK_BitCast &&
8398         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8399       Element = ICE->getSubExpr();
8400   }
8401 
8402   QualType ElementType = Element->getType();
8403   ExprResult ElementResult(Element);
8404   if (ElementType->getAs<ObjCObjectPointerType>() &&
8405       S.CheckSingleAssignmentConstraints(TargetElementType,
8406                                          ElementResult,
8407                                          false, false)
8408         != Sema::Compatible) {
8409     S.Diag(Element->getLocStart(),
8410            diag::warn_objc_collection_literal_element)
8411       << ElementType << ElementKind << TargetElementType
8412       << Element->getSourceRange();
8413   }
8414 
8415   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8416     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8417   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8418     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8419 }
8420 
8421 /// Check an Objective-C array literal being converted to the given
8422 /// target type.
8423 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8424                            ObjCArrayLiteral *ArrayLiteral) {
8425   if (!S.NSArrayDecl)
8426     return;
8427 
8428   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8429   if (!TargetObjCPtr)
8430     return;
8431 
8432   if (TargetObjCPtr->isUnspecialized() ||
8433       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8434         != S.NSArrayDecl->getCanonicalDecl())
8435     return;
8436 
8437   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8438   if (TypeArgs.size() != 1)
8439     return;
8440 
8441   QualType TargetElementType = TypeArgs[0];
8442   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8443     checkObjCCollectionLiteralElement(S, TargetElementType,
8444                                       ArrayLiteral->getElement(I),
8445                                       0);
8446   }
8447 }
8448 
8449 /// Check an Objective-C dictionary literal being converted to the given
8450 /// target type.
8451 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8452                                 ObjCDictionaryLiteral *DictionaryLiteral) {
8453   if (!S.NSDictionaryDecl)
8454     return;
8455 
8456   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8457   if (!TargetObjCPtr)
8458     return;
8459 
8460   if (TargetObjCPtr->isUnspecialized() ||
8461       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8462         != S.NSDictionaryDecl->getCanonicalDecl())
8463     return;
8464 
8465   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8466   if (TypeArgs.size() != 2)
8467     return;
8468 
8469   QualType TargetKeyType = TypeArgs[0];
8470   QualType TargetObjectType = TypeArgs[1];
8471   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8472     auto Element = DictionaryLiteral->getKeyValueElement(I);
8473     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8474     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8475   }
8476 }
8477 
8478 // Helper function to filter out cases for constant width constant conversion.
8479 // Don't warn on char array initialization or for non-decimal values.
8480 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8481                                    SourceLocation CC) {
8482   // If initializing from a constant, and the constant starts with '0',
8483   // then it is a binary, octal, or hexadecimal.  Allow these constants
8484   // to fill all the bits, even if there is a sign change.
8485   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8486     const char FirstLiteralCharacter =
8487         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8488     if (FirstLiteralCharacter == '0')
8489       return false;
8490   }
8491 
8492   // If the CC location points to a '{', and the type is char, then assume
8493   // assume it is an array initialization.
8494   if (CC.isValid() && T->isCharType()) {
8495     const char FirstContextCharacter =
8496         S.getSourceManager().getCharacterData(CC)[0];
8497     if (FirstContextCharacter == '{')
8498       return false;
8499   }
8500 
8501   return true;
8502 }
8503 
8504 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
8505                              SourceLocation CC, bool *ICContext = nullptr) {
8506   if (E->isTypeDependent() || E->isValueDependent()) return;
8507 
8508   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8509   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8510   if (Source == Target) return;
8511   if (Target->isDependentType()) return;
8512 
8513   // If the conversion context location is invalid don't complain. We also
8514   // don't want to emit a warning if the issue occurs from the expansion of
8515   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8516   // delay this check as long as possible. Once we detect we are in that
8517   // scenario, we just return.
8518   if (CC.isInvalid())
8519     return;
8520 
8521   // Diagnose implicit casts to bool.
8522   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8523     if (isa<StringLiteral>(E))
8524       // Warn on string literal to bool.  Checks for string literals in logical
8525       // and expressions, for instance, assert(0 && "error here"), are
8526       // prevented by a check in AnalyzeImplicitConversions().
8527       return DiagnoseImpCast(S, E, T, CC,
8528                              diag::warn_impcast_string_literal_to_bool);
8529     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8530         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8531       // This covers the literal expressions that evaluate to Objective-C
8532       // objects.
8533       return DiagnoseImpCast(S, E, T, CC,
8534                              diag::warn_impcast_objective_c_literal_to_bool);
8535     }
8536     if (Source->isPointerType() || Source->canDecayToPointerType()) {
8537       // Warn on pointer to bool conversion that is always true.
8538       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8539                                      SourceRange(CC));
8540     }
8541   }
8542 
8543   // Check implicit casts from Objective-C collection literals to specialized
8544   // collection types, e.g., NSArray<NSString *> *.
8545   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8546     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8547   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8548     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8549 
8550   // Strip vector types.
8551   if (isa<VectorType>(Source)) {
8552     if (!isa<VectorType>(Target)) {
8553       if (S.SourceMgr.isInSystemMacro(CC))
8554         return;
8555       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
8556     }
8557 
8558     // If the vector cast is cast between two vectors of the same size, it is
8559     // a bitcast, not a conversion.
8560     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8561       return;
8562 
8563     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8564     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8565   }
8566   if (auto VecTy = dyn_cast<VectorType>(Target))
8567     Target = VecTy->getElementType().getTypePtr();
8568 
8569   // Strip complex types.
8570   if (isa<ComplexType>(Source)) {
8571     if (!isa<ComplexType>(Target)) {
8572       if (S.SourceMgr.isInSystemMacro(CC))
8573         return;
8574 
8575       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
8576     }
8577 
8578     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8579     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8580   }
8581 
8582   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8583   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8584 
8585   // If the source is floating point...
8586   if (SourceBT && SourceBT->isFloatingPoint()) {
8587     // ...and the target is floating point...
8588     if (TargetBT && TargetBT->isFloatingPoint()) {
8589       // ...then warn if we're dropping FP rank.
8590 
8591       // Builtin FP kinds are ordered by increasing FP rank.
8592       if (SourceBT->getKind() > TargetBT->getKind()) {
8593         // Don't warn about float constants that are precisely
8594         // representable in the target type.
8595         Expr::EvalResult result;
8596         if (E->EvaluateAsRValue(result, S.Context)) {
8597           // Value might be a float, a float vector, or a float complex.
8598           if (IsSameFloatAfterCast(result.Val,
8599                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8600                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
8601             return;
8602         }
8603 
8604         if (S.SourceMgr.isInSystemMacro(CC))
8605           return;
8606 
8607         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
8608       }
8609       // ... or possibly if we're increasing rank, too
8610       else if (TargetBT->getKind() > SourceBT->getKind()) {
8611         if (S.SourceMgr.isInSystemMacro(CC))
8612           return;
8613 
8614         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
8615       }
8616       return;
8617     }
8618 
8619     // If the target is integral, always warn.
8620     if (TargetBT && TargetBT->isInteger()) {
8621       if (S.SourceMgr.isInSystemMacro(CC))
8622         return;
8623 
8624       DiagnoseFloatingImpCast(S, E, T, CC);
8625     }
8626 
8627     // Detect the case where a call result is converted from floating-point to
8628     // to bool, and the final argument to the call is converted from bool, to
8629     // discover this typo:
8630     //
8631     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
8632     //
8633     // FIXME: This is an incredibly special case; is there some more general
8634     // way to detect this class of misplaced-parentheses bug?
8635     if (Target->isBooleanType() && isa<CallExpr>(E)) {
8636       // Check last argument of function call to see if it is an
8637       // implicit cast from a type matching the type the result
8638       // is being cast to.
8639       CallExpr *CEx = cast<CallExpr>(E);
8640       if (unsigned NumArgs = CEx->getNumArgs()) {
8641         Expr *LastA = CEx->getArg(NumArgs - 1);
8642         Expr *InnerE = LastA->IgnoreParenImpCasts();
8643         if (isa<ImplicitCastExpr>(LastA) &&
8644             InnerE->getType()->isBooleanType()) {
8645           // Warn on this floating-point to bool conversion
8646           DiagnoseImpCast(S, E, T, CC,
8647                           diag::warn_impcast_floating_point_to_bool);
8648         }
8649       }
8650     }
8651     return;
8652   }
8653 
8654   DiagnoseNullConversion(S, E, T, CC);
8655 
8656   S.DiscardMisalignedMemberAddress(Target, E);
8657 
8658   if (!Source->isIntegerType() || !Target->isIntegerType())
8659     return;
8660 
8661   // TODO: remove this early return once the false positives for constant->bool
8662   // in templates, macros, etc, are reduced or removed.
8663   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8664     return;
8665 
8666   IntRange SourceRange = GetExprRange(S.Context, E);
8667   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
8668 
8669   if (SourceRange.Width > TargetRange.Width) {
8670     // If the source is a constant, use a default-on diagnostic.
8671     // TODO: this should happen for bitfield stores, too.
8672     llvm::APSInt Value(32);
8673     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
8674       if (S.SourceMgr.isInSystemMacro(CC))
8675         return;
8676 
8677       std::string PrettySourceValue = Value.toString(10);
8678       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8679 
8680       S.DiagRuntimeBehavior(E->getExprLoc(), E,
8681         S.PDiag(diag::warn_impcast_integer_precision_constant)
8682             << PrettySourceValue << PrettyTargetValue
8683             << E->getType() << T << E->getSourceRange()
8684             << clang::SourceRange(CC));
8685       return;
8686     }
8687 
8688     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8689     if (S.SourceMgr.isInSystemMacro(CC))
8690       return;
8691 
8692     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
8693       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8694                              /* pruneControlFlow */ true);
8695     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
8696   }
8697 
8698   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8699       SourceRange.NonNegative && Source->isSignedIntegerType()) {
8700     // Warn when doing a signed to signed conversion, warn if the positive
8701     // source value is exactly the width of the target type, which will
8702     // cause a negative value to be stored.
8703 
8704     llvm::APSInt Value;
8705     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8706         !S.SourceMgr.isInSystemMacro(CC)) {
8707       if (isSameWidthConstantConversion(S, E, T, CC)) {
8708         std::string PrettySourceValue = Value.toString(10);
8709         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8710 
8711         S.DiagRuntimeBehavior(
8712             E->getExprLoc(), E,
8713             S.PDiag(diag::warn_impcast_integer_precision_constant)
8714                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8715                 << E->getSourceRange() << clang::SourceRange(CC));
8716         return;
8717       }
8718     }
8719 
8720     // Fall through for non-constants to give a sign conversion warning.
8721   }
8722 
8723   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8724       (!TargetRange.NonNegative && SourceRange.NonNegative &&
8725        SourceRange.Width == TargetRange.Width)) {
8726     if (S.SourceMgr.isInSystemMacro(CC))
8727       return;
8728 
8729     unsigned DiagID = diag::warn_impcast_integer_sign;
8730 
8731     // Traditionally, gcc has warned about this under -Wsign-compare.
8732     // We also want to warn about it in -Wconversion.
8733     // So if -Wconversion is off, use a completely identical diagnostic
8734     // in the sign-compare group.
8735     // The conditional-checking code will
8736     if (ICContext) {
8737       DiagID = diag::warn_impcast_integer_sign_conditional;
8738       *ICContext = true;
8739     }
8740 
8741     return DiagnoseImpCast(S, E, T, CC, DiagID);
8742   }
8743 
8744   // Diagnose conversions between different enumeration types.
8745   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8746   // type, to give us better diagnostics.
8747   QualType SourceType = E->getType();
8748   if (!S.getLangOpts().CPlusPlus) {
8749     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8750       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8751         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8752         SourceType = S.Context.getTypeDeclType(Enum);
8753         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8754       }
8755   }
8756 
8757   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8758     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
8759       if (SourceEnum->getDecl()->hasNameForLinkage() &&
8760           TargetEnum->getDecl()->hasNameForLinkage() &&
8761           SourceEnum != TargetEnum) {
8762         if (S.SourceMgr.isInSystemMacro(CC))
8763           return;
8764 
8765         return DiagnoseImpCast(S, E, SourceType, T, CC,
8766                                diag::warn_impcast_different_enum_types);
8767       }
8768 }
8769 
8770 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8771                               SourceLocation CC, QualType T);
8772 
8773 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
8774                              SourceLocation CC, bool &ICContext) {
8775   E = E->IgnoreParenImpCasts();
8776 
8777   if (isa<ConditionalOperator>(E))
8778     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
8779 
8780   AnalyzeImplicitConversions(S, E, CC);
8781   if (E->getType() != T)
8782     return CheckImplicitConversion(S, E, T, CC, &ICContext);
8783 }
8784 
8785 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8786                               SourceLocation CC, QualType T) {
8787   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
8788 
8789   bool Suspicious = false;
8790   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8791   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
8792 
8793   // If -Wconversion would have warned about either of the candidates
8794   // for a signedness conversion to the context type...
8795   if (!Suspicious) return;
8796 
8797   // ...but it's currently ignored...
8798   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
8799     return;
8800 
8801   // ...then check whether it would have warned about either of the
8802   // candidates for a signedness conversion to the condition type.
8803   if (E->getType() == T) return;
8804 
8805   Suspicious = false;
8806   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8807                           E->getType(), CC, &Suspicious);
8808   if (!Suspicious)
8809     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
8810                             E->getType(), CC, &Suspicious);
8811 }
8812 
8813 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8814 /// Input argument E is a logical expression.
8815 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
8816   if (S.getLangOpts().Bool)
8817     return;
8818   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8819 }
8820 
8821 /// AnalyzeImplicitConversions - Find and report any interesting
8822 /// implicit conversions in the given expression.  There are a couple
8823 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
8824 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
8825   QualType T = OrigE->getType();
8826   Expr *E = OrigE->IgnoreParenImpCasts();
8827 
8828   if (E->isTypeDependent() || E->isValueDependent())
8829     return;
8830 
8831   // For conditional operators, we analyze the arguments as if they
8832   // were being fed directly into the output.
8833   if (isa<ConditionalOperator>(E)) {
8834     ConditionalOperator *CO = cast<ConditionalOperator>(E);
8835     CheckConditionalOperator(S, CO, CC, T);
8836     return;
8837   }
8838 
8839   // Check implicit argument conversions for function calls.
8840   if (CallExpr *Call = dyn_cast<CallExpr>(E))
8841     CheckImplicitArgumentConversions(S, Call, CC);
8842 
8843   // Go ahead and check any implicit conversions we might have skipped.
8844   // The non-canonical typecheck is just an optimization;
8845   // CheckImplicitConversion will filter out dead implicit conversions.
8846   if (E->getType() != T)
8847     CheckImplicitConversion(S, E, T, CC);
8848 
8849   // Now continue drilling into this expression.
8850 
8851   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8852     // The bound subexpressions in a PseudoObjectExpr are not reachable
8853     // as transitive children.
8854     // FIXME: Use a more uniform representation for this.
8855     for (auto *SE : POE->semantics())
8856       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8857         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
8858   }
8859 
8860   // Skip past explicit casts.
8861   if (isa<ExplicitCastExpr>(E)) {
8862     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
8863     return AnalyzeImplicitConversions(S, E, CC);
8864   }
8865 
8866   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8867     // Do a somewhat different check with comparison operators.
8868     if (BO->isComparisonOp())
8869       return AnalyzeComparison(S, BO);
8870 
8871     // And with simple assignments.
8872     if (BO->getOpcode() == BO_Assign)
8873       return AnalyzeAssignment(S, BO);
8874   }
8875 
8876   // These break the otherwise-useful invariant below.  Fortunately,
8877   // we don't really need to recurse into them, because any internal
8878   // expressions should have been analyzed already when they were
8879   // built into statements.
8880   if (isa<StmtExpr>(E)) return;
8881 
8882   // Don't descend into unevaluated contexts.
8883   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
8884 
8885   // Now just recurse over the expression's children.
8886   CC = E->getExprLoc();
8887   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
8888   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
8889   for (Stmt *SubStmt : E->children()) {
8890     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
8891     if (!ChildExpr)
8892       continue;
8893 
8894     if (IsLogicalAndOperator &&
8895         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
8896       // Ignore checking string literals that are in logical and operators.
8897       // This is a common pattern for asserts.
8898       continue;
8899     AnalyzeImplicitConversions(S, ChildExpr, CC);
8900   }
8901 
8902   if (BO && BO->isLogicalOp()) {
8903     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8904     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8905       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
8906 
8907     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8908     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8909       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
8910   }
8911 
8912   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8913     if (U->getOpcode() == UO_LNot)
8914       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
8915 }
8916 
8917 } // end anonymous namespace
8918 
8919 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
8920                                             unsigned Start, unsigned End) {
8921   bool IllegalParams = false;
8922   for (unsigned I = Start; I <= End; ++I) {
8923     QualType Ty = TheCall->getArg(I)->getType();
8924     // Taking into account implicit conversions,
8925     // allow any integer within 32 bits range
8926     if (!Ty->isIntegerType() ||
8927         S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
8928       S.Diag(TheCall->getArg(I)->getLocStart(),
8929              diag::err_opencl_enqueue_kernel_invalid_local_size_type);
8930       IllegalParams = true;
8931     }
8932     // Potentially emit standard warnings for implicit conversions if enabled
8933     // using -Wconversion.
8934     CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
8935                             TheCall->getArg(I)->getLocStart());
8936   }
8937   return IllegalParams;
8938 }
8939 
8940 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8941 // Returns true when emitting a warning about taking the address of a reference.
8942 static bool CheckForReference(Sema &SemaRef, const Expr *E,
8943                               const PartialDiagnostic &PD) {
8944   E = E->IgnoreParenImpCasts();
8945 
8946   const FunctionDecl *FD = nullptr;
8947 
8948   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8949     if (!DRE->getDecl()->getType()->isReferenceType())
8950       return false;
8951   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8952     if (!M->getMemberDecl()->getType()->isReferenceType())
8953       return false;
8954   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
8955     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
8956       return false;
8957     FD = Call->getDirectCallee();
8958   } else {
8959     return false;
8960   }
8961 
8962   SemaRef.Diag(E->getExprLoc(), PD);
8963 
8964   // If possible, point to location of function.
8965   if (FD) {
8966     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8967   }
8968 
8969   return true;
8970 }
8971 
8972 // Returns true if the SourceLocation is expanded from any macro body.
8973 // Returns false if the SourceLocation is invalid, is from not in a macro
8974 // expansion, or is from expanded from a top-level macro argument.
8975 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8976   if (Loc.isInvalid())
8977     return false;
8978 
8979   while (Loc.isMacroID()) {
8980     if (SM.isMacroBodyExpansion(Loc))
8981       return true;
8982     Loc = SM.getImmediateMacroCallerLoc(Loc);
8983   }
8984 
8985   return false;
8986 }
8987 
8988 /// \brief Diagnose pointers that are always non-null.
8989 /// \param E the expression containing the pointer
8990 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8991 /// compared to a null pointer
8992 /// \param IsEqual True when the comparison is equal to a null pointer
8993 /// \param Range Extra SourceRange to highlight in the diagnostic
8994 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8995                                         Expr::NullPointerConstantKind NullKind,
8996                                         bool IsEqual, SourceRange Range) {
8997   if (!E)
8998     return;
8999 
9000   // Don't warn inside macros.
9001   if (E->getExprLoc().isMacroID()) {
9002     const SourceManager &SM = getSourceManager();
9003     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9004         IsInAnyMacroBody(SM, Range.getBegin()))
9005       return;
9006   }
9007   E = E->IgnoreImpCasts();
9008 
9009   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9010 
9011   if (isa<CXXThisExpr>(E)) {
9012     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9013                                 : diag::warn_this_bool_conversion;
9014     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9015     return;
9016   }
9017 
9018   bool IsAddressOf = false;
9019 
9020   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9021     if (UO->getOpcode() != UO_AddrOf)
9022       return;
9023     IsAddressOf = true;
9024     E = UO->getSubExpr();
9025   }
9026 
9027   if (IsAddressOf) {
9028     unsigned DiagID = IsCompare
9029                           ? diag::warn_address_of_reference_null_compare
9030                           : diag::warn_address_of_reference_bool_conversion;
9031     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9032                                          << IsEqual;
9033     if (CheckForReference(*this, E, PD)) {
9034       return;
9035     }
9036   }
9037 
9038   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9039     bool IsParam = isa<NonNullAttr>(NonnullAttr);
9040     std::string Str;
9041     llvm::raw_string_ostream S(Str);
9042     E->printPretty(S, nullptr, getPrintingPolicy());
9043     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9044                                 : diag::warn_cast_nonnull_to_bool;
9045     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9046       << E->getSourceRange() << Range << IsEqual;
9047     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9048   };
9049 
9050   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9051   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9052     if (auto *Callee = Call->getDirectCallee()) {
9053       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9054         ComplainAboutNonnullParamOrCall(A);
9055         return;
9056       }
9057     }
9058   }
9059 
9060   // Expect to find a single Decl.  Skip anything more complicated.
9061   ValueDecl *D = nullptr;
9062   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9063     D = R->getDecl();
9064   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9065     D = M->getMemberDecl();
9066   }
9067 
9068   // Weak Decls can be null.
9069   if (!D || D->isWeak())
9070     return;
9071 
9072   // Check for parameter decl with nonnull attribute
9073   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9074     if (getCurFunction() &&
9075         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9076       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9077         ComplainAboutNonnullParamOrCall(A);
9078         return;
9079       }
9080 
9081       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9082         auto ParamIter = llvm::find(FD->parameters(), PV);
9083         assert(ParamIter != FD->param_end());
9084         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9085 
9086         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9087           if (!NonNull->args_size()) {
9088               ComplainAboutNonnullParamOrCall(NonNull);
9089               return;
9090           }
9091 
9092           for (unsigned ArgNo : NonNull->args()) {
9093             if (ArgNo == ParamNo) {
9094               ComplainAboutNonnullParamOrCall(NonNull);
9095               return;
9096             }
9097           }
9098         }
9099       }
9100     }
9101   }
9102 
9103   QualType T = D->getType();
9104   const bool IsArray = T->isArrayType();
9105   const bool IsFunction = T->isFunctionType();
9106 
9107   // Address of function is used to silence the function warning.
9108   if (IsAddressOf && IsFunction) {
9109     return;
9110   }
9111 
9112   // Found nothing.
9113   if (!IsAddressOf && !IsFunction && !IsArray)
9114     return;
9115 
9116   // Pretty print the expression for the diagnostic.
9117   std::string Str;
9118   llvm::raw_string_ostream S(Str);
9119   E->printPretty(S, nullptr, getPrintingPolicy());
9120 
9121   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9122                               : diag::warn_impcast_pointer_to_bool;
9123   enum {
9124     AddressOf,
9125     FunctionPointer,
9126     ArrayPointer
9127   } DiagType;
9128   if (IsAddressOf)
9129     DiagType = AddressOf;
9130   else if (IsFunction)
9131     DiagType = FunctionPointer;
9132   else if (IsArray)
9133     DiagType = ArrayPointer;
9134   else
9135     llvm_unreachable("Could not determine diagnostic.");
9136   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9137                                 << Range << IsEqual;
9138 
9139   if (!IsFunction)
9140     return;
9141 
9142   // Suggest '&' to silence the function warning.
9143   Diag(E->getExprLoc(), diag::note_function_warning_silence)
9144       << FixItHint::CreateInsertion(E->getLocStart(), "&");
9145 
9146   // Check to see if '()' fixit should be emitted.
9147   QualType ReturnType;
9148   UnresolvedSet<4> NonTemplateOverloads;
9149   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9150   if (ReturnType.isNull())
9151     return;
9152 
9153   if (IsCompare) {
9154     // There are two cases here.  If there is null constant, the only suggest
9155     // for a pointer return type.  If the null is 0, then suggest if the return
9156     // type is a pointer or an integer type.
9157     if (!ReturnType->isPointerType()) {
9158       if (NullKind == Expr::NPCK_ZeroExpression ||
9159           NullKind == Expr::NPCK_ZeroLiteral) {
9160         if (!ReturnType->isIntegerType())
9161           return;
9162       } else {
9163         return;
9164       }
9165     }
9166   } else { // !IsCompare
9167     // For function to bool, only suggest if the function pointer has bool
9168     // return type.
9169     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9170       return;
9171   }
9172   Diag(E->getExprLoc(), diag::note_function_to_function_call)
9173       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9174 }
9175 
9176 /// Diagnoses "dangerous" implicit conversions within the given
9177 /// expression (which is a full expression).  Implements -Wconversion
9178 /// and -Wsign-compare.
9179 ///
9180 /// \param CC the "context" location of the implicit conversion, i.e.
9181 ///   the most location of the syntactic entity requiring the implicit
9182 ///   conversion
9183 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9184   // Don't diagnose in unevaluated contexts.
9185   if (isUnevaluatedContext())
9186     return;
9187 
9188   // Don't diagnose for value- or type-dependent expressions.
9189   if (E->isTypeDependent() || E->isValueDependent())
9190     return;
9191 
9192   // Check for array bounds violations in cases where the check isn't triggered
9193   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9194   // ArraySubscriptExpr is on the RHS of a variable initialization.
9195   CheckArrayAccess(E);
9196 
9197   // This is not the right CC for (e.g.) a variable initialization.
9198   AnalyzeImplicitConversions(*this, E, CC);
9199 }
9200 
9201 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9202 /// Input argument E is a logical expression.
9203 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9204   ::CheckBoolLikeConversion(*this, E, CC);
9205 }
9206 
9207 /// Diagnose when expression is an integer constant expression and its evaluation
9208 /// results in integer overflow
9209 void Sema::CheckForIntOverflow (Expr *E) {
9210   // Use a work list to deal with nested struct initializers.
9211   SmallVector<Expr *, 2> Exprs(1, E);
9212 
9213   do {
9214     Expr *E = Exprs.pop_back_val();
9215 
9216     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9217       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9218       continue;
9219     }
9220 
9221     if (auto InitList = dyn_cast<InitListExpr>(E))
9222       Exprs.append(InitList->inits().begin(), InitList->inits().end());
9223   } while (!Exprs.empty());
9224 }
9225 
9226 namespace {
9227 /// \brief Visitor for expressions which looks for unsequenced operations on the
9228 /// same object.
9229 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9230   typedef EvaluatedExprVisitor<SequenceChecker> Base;
9231 
9232   /// \brief A tree of sequenced regions within an expression. Two regions are
9233   /// unsequenced if one is an ancestor or a descendent of the other. When we
9234   /// finish processing an expression with sequencing, such as a comma
9235   /// expression, we fold its tree nodes into its parent, since they are
9236   /// unsequenced with respect to nodes we will visit later.
9237   class SequenceTree {
9238     struct Value {
9239       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9240       unsigned Parent : 31;
9241       unsigned Merged : 1;
9242     };
9243     SmallVector<Value, 8> Values;
9244 
9245   public:
9246     /// \brief A region within an expression which may be sequenced with respect
9247     /// to some other region.
9248     class Seq {
9249       explicit Seq(unsigned N) : Index(N) {}
9250       unsigned Index;
9251       friend class SequenceTree;
9252     public:
9253       Seq() : Index(0) {}
9254     };
9255 
9256     SequenceTree() { Values.push_back(Value(0)); }
9257     Seq root() const { return Seq(0); }
9258 
9259     /// \brief Create a new sequence of operations, which is an unsequenced
9260     /// subset of \p Parent. This sequence of operations is sequenced with
9261     /// respect to other children of \p Parent.
9262     Seq allocate(Seq Parent) {
9263       Values.push_back(Value(Parent.Index));
9264       return Seq(Values.size() - 1);
9265     }
9266 
9267     /// \brief Merge a sequence of operations into its parent.
9268     void merge(Seq S) {
9269       Values[S.Index].Merged = true;
9270     }
9271 
9272     /// \brief Determine whether two operations are unsequenced. This operation
9273     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9274     /// should have been merged into its parent as appropriate.
9275     bool isUnsequenced(Seq Cur, Seq Old) {
9276       unsigned C = representative(Cur.Index);
9277       unsigned Target = representative(Old.Index);
9278       while (C >= Target) {
9279         if (C == Target)
9280           return true;
9281         C = Values[C].Parent;
9282       }
9283       return false;
9284     }
9285 
9286   private:
9287     /// \brief Pick a representative for a sequence.
9288     unsigned representative(unsigned K) {
9289       if (Values[K].Merged)
9290         // Perform path compression as we go.
9291         return Values[K].Parent = representative(Values[K].Parent);
9292       return K;
9293     }
9294   };
9295 
9296   /// An object for which we can track unsequenced uses.
9297   typedef NamedDecl *Object;
9298 
9299   /// Different flavors of object usage which we track. We only track the
9300   /// least-sequenced usage of each kind.
9301   enum UsageKind {
9302     /// A read of an object. Multiple unsequenced reads are OK.
9303     UK_Use,
9304     /// A modification of an object which is sequenced before the value
9305     /// computation of the expression, such as ++n in C++.
9306     UK_ModAsValue,
9307     /// A modification of an object which is not sequenced before the value
9308     /// computation of the expression, such as n++.
9309     UK_ModAsSideEffect,
9310 
9311     UK_Count = UK_ModAsSideEffect + 1
9312   };
9313 
9314   struct Usage {
9315     Usage() : Use(nullptr), Seq() {}
9316     Expr *Use;
9317     SequenceTree::Seq Seq;
9318   };
9319 
9320   struct UsageInfo {
9321     UsageInfo() : Diagnosed(false) {}
9322     Usage Uses[UK_Count];
9323     /// Have we issued a diagnostic for this variable already?
9324     bool Diagnosed;
9325   };
9326   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9327 
9328   Sema &SemaRef;
9329   /// Sequenced regions within the expression.
9330   SequenceTree Tree;
9331   /// Declaration modifications and references which we have seen.
9332   UsageInfoMap UsageMap;
9333   /// The region we are currently within.
9334   SequenceTree::Seq Region;
9335   /// Filled in with declarations which were modified as a side-effect
9336   /// (that is, post-increment operations).
9337   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
9338   /// Expressions to check later. We defer checking these to reduce
9339   /// stack usage.
9340   SmallVectorImpl<Expr *> &WorkList;
9341 
9342   /// RAII object wrapping the visitation of a sequenced subexpression of an
9343   /// expression. At the end of this process, the side-effects of the evaluation
9344   /// become sequenced with respect to the value computation of the result, so
9345   /// we downgrade any UK_ModAsSideEffect within the evaluation to
9346   /// UK_ModAsValue.
9347   struct SequencedSubexpression {
9348     SequencedSubexpression(SequenceChecker &Self)
9349       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9350       Self.ModAsSideEffect = &ModAsSideEffect;
9351     }
9352     ~SequencedSubexpression() {
9353       for (auto &M : llvm::reverse(ModAsSideEffect)) {
9354         UsageInfo &U = Self.UsageMap[M.first];
9355         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
9356         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9357         SideEffectUsage = M.second;
9358       }
9359       Self.ModAsSideEffect = OldModAsSideEffect;
9360     }
9361 
9362     SequenceChecker &Self;
9363     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9364     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
9365   };
9366 
9367   /// RAII object wrapping the visitation of a subexpression which we might
9368   /// choose to evaluate as a constant. If any subexpression is evaluated and
9369   /// found to be non-constant, this allows us to suppress the evaluation of
9370   /// the outer expression.
9371   class EvaluationTracker {
9372   public:
9373     EvaluationTracker(SequenceChecker &Self)
9374         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9375       Self.EvalTracker = this;
9376     }
9377     ~EvaluationTracker() {
9378       Self.EvalTracker = Prev;
9379       if (Prev)
9380         Prev->EvalOK &= EvalOK;
9381     }
9382 
9383     bool evaluate(const Expr *E, bool &Result) {
9384       if (!EvalOK || E->isValueDependent())
9385         return false;
9386       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9387       return EvalOK;
9388     }
9389 
9390   private:
9391     SequenceChecker &Self;
9392     EvaluationTracker *Prev;
9393     bool EvalOK;
9394   } *EvalTracker;
9395 
9396   /// \brief Find the object which is produced by the specified expression,
9397   /// if any.
9398   Object getObject(Expr *E, bool Mod) const {
9399     E = E->IgnoreParenCasts();
9400     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9401       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9402         return getObject(UO->getSubExpr(), Mod);
9403     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9404       if (BO->getOpcode() == BO_Comma)
9405         return getObject(BO->getRHS(), Mod);
9406       if (Mod && BO->isAssignmentOp())
9407         return getObject(BO->getLHS(), Mod);
9408     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9409       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9410       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9411         return ME->getMemberDecl();
9412     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9413       // FIXME: If this is a reference, map through to its value.
9414       return DRE->getDecl();
9415     return nullptr;
9416   }
9417 
9418   /// \brief Note that an object was modified or used by an expression.
9419   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9420     Usage &U = UI.Uses[UK];
9421     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9422       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9423         ModAsSideEffect->push_back(std::make_pair(O, U));
9424       U.Use = Ref;
9425       U.Seq = Region;
9426     }
9427   }
9428   /// \brief Check whether a modification or use conflicts with a prior usage.
9429   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9430                   bool IsModMod) {
9431     if (UI.Diagnosed)
9432       return;
9433 
9434     const Usage &U = UI.Uses[OtherKind];
9435     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9436       return;
9437 
9438     Expr *Mod = U.Use;
9439     Expr *ModOrUse = Ref;
9440     if (OtherKind == UK_Use)
9441       std::swap(Mod, ModOrUse);
9442 
9443     SemaRef.Diag(Mod->getExprLoc(),
9444                  IsModMod ? diag::warn_unsequenced_mod_mod
9445                           : diag::warn_unsequenced_mod_use)
9446       << O << SourceRange(ModOrUse->getExprLoc());
9447     UI.Diagnosed = true;
9448   }
9449 
9450   void notePreUse(Object O, Expr *Use) {
9451     UsageInfo &U = UsageMap[O];
9452     // Uses conflict with other modifications.
9453     checkUsage(O, U, Use, UK_ModAsValue, false);
9454   }
9455   void notePostUse(Object O, Expr *Use) {
9456     UsageInfo &U = UsageMap[O];
9457     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9458     addUsage(U, O, Use, UK_Use);
9459   }
9460 
9461   void notePreMod(Object O, Expr *Mod) {
9462     UsageInfo &U = UsageMap[O];
9463     // Modifications conflict with other modifications and with uses.
9464     checkUsage(O, U, Mod, UK_ModAsValue, true);
9465     checkUsage(O, U, Mod, UK_Use, false);
9466   }
9467   void notePostMod(Object O, Expr *Use, UsageKind UK) {
9468     UsageInfo &U = UsageMap[O];
9469     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9470     addUsage(U, O, Use, UK);
9471   }
9472 
9473 public:
9474   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
9475       : Base(S.Context), SemaRef(S), Region(Tree.root()),
9476         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
9477     Visit(E);
9478   }
9479 
9480   void VisitStmt(Stmt *S) {
9481     // Skip all statements which aren't expressions for now.
9482   }
9483 
9484   void VisitExpr(Expr *E) {
9485     // By default, just recurse to evaluated subexpressions.
9486     Base::VisitStmt(E);
9487   }
9488 
9489   void VisitCastExpr(CastExpr *E) {
9490     Object O = Object();
9491     if (E->getCastKind() == CK_LValueToRValue)
9492       O = getObject(E->getSubExpr(), false);
9493 
9494     if (O)
9495       notePreUse(O, E);
9496     VisitExpr(E);
9497     if (O)
9498       notePostUse(O, E);
9499   }
9500 
9501   void VisitBinComma(BinaryOperator *BO) {
9502     // C++11 [expr.comma]p1:
9503     //   Every value computation and side effect associated with the left
9504     //   expression is sequenced before every value computation and side
9505     //   effect associated with the right expression.
9506     SequenceTree::Seq LHS = Tree.allocate(Region);
9507     SequenceTree::Seq RHS = Tree.allocate(Region);
9508     SequenceTree::Seq OldRegion = Region;
9509 
9510     {
9511       SequencedSubexpression SeqLHS(*this);
9512       Region = LHS;
9513       Visit(BO->getLHS());
9514     }
9515 
9516     Region = RHS;
9517     Visit(BO->getRHS());
9518 
9519     Region = OldRegion;
9520 
9521     // Forget that LHS and RHS are sequenced. They are both unsequenced
9522     // with respect to other stuff.
9523     Tree.merge(LHS);
9524     Tree.merge(RHS);
9525   }
9526 
9527   void VisitBinAssign(BinaryOperator *BO) {
9528     // The modification is sequenced after the value computation of the LHS
9529     // and RHS, so check it before inspecting the operands and update the
9530     // map afterwards.
9531     Object O = getObject(BO->getLHS(), true);
9532     if (!O)
9533       return VisitExpr(BO);
9534 
9535     notePreMod(O, BO);
9536 
9537     // C++11 [expr.ass]p7:
9538     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9539     //   only once.
9540     //
9541     // Therefore, for a compound assignment operator, O is considered used
9542     // everywhere except within the evaluation of E1 itself.
9543     if (isa<CompoundAssignOperator>(BO))
9544       notePreUse(O, BO);
9545 
9546     Visit(BO->getLHS());
9547 
9548     if (isa<CompoundAssignOperator>(BO))
9549       notePostUse(O, BO);
9550 
9551     Visit(BO->getRHS());
9552 
9553     // C++11 [expr.ass]p1:
9554     //   the assignment is sequenced [...] before the value computation of the
9555     //   assignment expression.
9556     // C11 6.5.16/3 has no such rule.
9557     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9558                                                        : UK_ModAsSideEffect);
9559   }
9560 
9561   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9562     VisitBinAssign(CAO);
9563   }
9564 
9565   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9566   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9567   void VisitUnaryPreIncDec(UnaryOperator *UO) {
9568     Object O = getObject(UO->getSubExpr(), true);
9569     if (!O)
9570       return VisitExpr(UO);
9571 
9572     notePreMod(O, UO);
9573     Visit(UO->getSubExpr());
9574     // C++11 [expr.pre.incr]p1:
9575     //   the expression ++x is equivalent to x+=1
9576     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9577                                                        : UK_ModAsSideEffect);
9578   }
9579 
9580   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9581   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9582   void VisitUnaryPostIncDec(UnaryOperator *UO) {
9583     Object O = getObject(UO->getSubExpr(), true);
9584     if (!O)
9585       return VisitExpr(UO);
9586 
9587     notePreMod(O, UO);
9588     Visit(UO->getSubExpr());
9589     notePostMod(O, UO, UK_ModAsSideEffect);
9590   }
9591 
9592   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9593   void VisitBinLOr(BinaryOperator *BO) {
9594     // The side-effects of the LHS of an '&&' are sequenced before the
9595     // value computation of the RHS, and hence before the value computation
9596     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9597     // as if they were unconditionally sequenced.
9598     EvaluationTracker Eval(*this);
9599     {
9600       SequencedSubexpression Sequenced(*this);
9601       Visit(BO->getLHS());
9602     }
9603 
9604     bool Result;
9605     if (Eval.evaluate(BO->getLHS(), Result)) {
9606       if (!Result)
9607         Visit(BO->getRHS());
9608     } else {
9609       // Check for unsequenced operations in the RHS, treating it as an
9610       // entirely separate evaluation.
9611       //
9612       // FIXME: If there are operations in the RHS which are unsequenced
9613       // with respect to operations outside the RHS, and those operations
9614       // are unconditionally evaluated, diagnose them.
9615       WorkList.push_back(BO->getRHS());
9616     }
9617   }
9618   void VisitBinLAnd(BinaryOperator *BO) {
9619     EvaluationTracker Eval(*this);
9620     {
9621       SequencedSubexpression Sequenced(*this);
9622       Visit(BO->getLHS());
9623     }
9624 
9625     bool Result;
9626     if (Eval.evaluate(BO->getLHS(), Result)) {
9627       if (Result)
9628         Visit(BO->getRHS());
9629     } else {
9630       WorkList.push_back(BO->getRHS());
9631     }
9632   }
9633 
9634   // Only visit the condition, unless we can be sure which subexpression will
9635   // be chosen.
9636   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
9637     EvaluationTracker Eval(*this);
9638     {
9639       SequencedSubexpression Sequenced(*this);
9640       Visit(CO->getCond());
9641     }
9642 
9643     bool Result;
9644     if (Eval.evaluate(CO->getCond(), Result))
9645       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
9646     else {
9647       WorkList.push_back(CO->getTrueExpr());
9648       WorkList.push_back(CO->getFalseExpr());
9649     }
9650   }
9651 
9652   void VisitCallExpr(CallExpr *CE) {
9653     // C++11 [intro.execution]p15:
9654     //   When calling a function [...], every value computation and side effect
9655     //   associated with any argument expression, or with the postfix expression
9656     //   designating the called function, is sequenced before execution of every
9657     //   expression or statement in the body of the function [and thus before
9658     //   the value computation of its result].
9659     SequencedSubexpression Sequenced(*this);
9660     Base::VisitCallExpr(CE);
9661 
9662     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9663   }
9664 
9665   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
9666     // This is a call, so all subexpressions are sequenced before the result.
9667     SequencedSubexpression Sequenced(*this);
9668 
9669     if (!CCE->isListInitialization())
9670       return VisitExpr(CCE);
9671 
9672     // In C++11, list initializations are sequenced.
9673     SmallVector<SequenceTree::Seq, 32> Elts;
9674     SequenceTree::Seq Parent = Region;
9675     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9676                                         E = CCE->arg_end();
9677          I != E; ++I) {
9678       Region = Tree.allocate(Parent);
9679       Elts.push_back(Region);
9680       Visit(*I);
9681     }
9682 
9683     // Forget that the initializers are sequenced.
9684     Region = Parent;
9685     for (unsigned I = 0; I < Elts.size(); ++I)
9686       Tree.merge(Elts[I]);
9687   }
9688 
9689   void VisitInitListExpr(InitListExpr *ILE) {
9690     if (!SemaRef.getLangOpts().CPlusPlus11)
9691       return VisitExpr(ILE);
9692 
9693     // In C++11, list initializations are sequenced.
9694     SmallVector<SequenceTree::Seq, 32> Elts;
9695     SequenceTree::Seq Parent = Region;
9696     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9697       Expr *E = ILE->getInit(I);
9698       if (!E) continue;
9699       Region = Tree.allocate(Parent);
9700       Elts.push_back(Region);
9701       Visit(E);
9702     }
9703 
9704     // Forget that the initializers are sequenced.
9705     Region = Parent;
9706     for (unsigned I = 0; I < Elts.size(); ++I)
9707       Tree.merge(Elts[I]);
9708   }
9709 };
9710 } // end anonymous namespace
9711 
9712 void Sema::CheckUnsequencedOperations(Expr *E) {
9713   SmallVector<Expr *, 8> WorkList;
9714   WorkList.push_back(E);
9715   while (!WorkList.empty()) {
9716     Expr *Item = WorkList.pop_back_val();
9717     SequenceChecker(*this, Item, WorkList);
9718   }
9719 }
9720 
9721 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9722                               bool IsConstexpr) {
9723   CheckImplicitConversions(E, CheckLoc);
9724   if (!E->isInstantiationDependent())
9725     CheckUnsequencedOperations(E);
9726   if (!IsConstexpr && !E->isValueDependent())
9727     CheckForIntOverflow(E);
9728   DiagnoseMisalignedMembers();
9729 }
9730 
9731 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9732                                        FieldDecl *BitField,
9733                                        Expr *Init) {
9734   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9735 }
9736 
9737 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9738                                          SourceLocation Loc) {
9739   if (!PType->isVariablyModifiedType())
9740     return;
9741   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9742     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9743     return;
9744   }
9745   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9746     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9747     return;
9748   }
9749   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9750     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9751     return;
9752   }
9753 
9754   const ArrayType *AT = S.Context.getAsArrayType(PType);
9755   if (!AT)
9756     return;
9757 
9758   if (AT->getSizeModifier() != ArrayType::Star) {
9759     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9760     return;
9761   }
9762 
9763   S.Diag(Loc, diag::err_array_star_in_function_definition);
9764 }
9765 
9766 /// CheckParmsForFunctionDef - Check that the parameters of the given
9767 /// function are appropriate for the definition of a function. This
9768 /// takes care of any checks that cannot be performed on the
9769 /// declaration itself, e.g., that the types of each of the function
9770 /// parameters are complete.
9771 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
9772                                     bool CheckParameterNames) {
9773   bool HasInvalidParm = false;
9774   for (ParmVarDecl *Param : Parameters) {
9775     // C99 6.7.5.3p4: the parameters in a parameter type list in a
9776     // function declarator that is part of a function definition of
9777     // that function shall not have incomplete type.
9778     //
9779     // This is also C++ [dcl.fct]p6.
9780     if (!Param->isInvalidDecl() &&
9781         RequireCompleteType(Param->getLocation(), Param->getType(),
9782                             diag::err_typecheck_decl_incomplete_type)) {
9783       Param->setInvalidDecl();
9784       HasInvalidParm = true;
9785     }
9786 
9787     // C99 6.9.1p5: If the declarator includes a parameter type list, the
9788     // declaration of each parameter shall include an identifier.
9789     if (CheckParameterNames &&
9790         Param->getIdentifier() == nullptr &&
9791         !Param->isImplicit() &&
9792         !getLangOpts().CPlusPlus)
9793       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9794 
9795     // C99 6.7.5.3p12:
9796     //   If the function declarator is not part of a definition of that
9797     //   function, parameters may have incomplete type and may use the [*]
9798     //   notation in their sequences of declarator specifiers to specify
9799     //   variable length array types.
9800     QualType PType = Param->getOriginalType();
9801     // FIXME: This diagnostic should point the '[*]' if source-location
9802     // information is added for it.
9803     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
9804 
9805     // MSVC destroys objects passed by value in the callee.  Therefore a
9806     // function definition which takes such a parameter must be able to call the
9807     // object's destructor.  However, we don't perform any direct access check
9808     // on the dtor.
9809     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9810                                        .getCXXABI()
9811                                        .areArgsDestroyedLeftToRightInCallee()) {
9812       if (!Param->isInvalidDecl()) {
9813         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9814           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9815           if (!ClassDecl->isInvalidDecl() &&
9816               !ClassDecl->hasIrrelevantDestructor() &&
9817               !ClassDecl->isDependentContext()) {
9818             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9819             MarkFunctionReferenced(Param->getLocation(), Destructor);
9820             DiagnoseUseOfDecl(Destructor, Param->getLocation());
9821           }
9822         }
9823       }
9824     }
9825 
9826     // Parameters with the pass_object_size attribute only need to be marked
9827     // constant at function definitions. Because we lack information about
9828     // whether we're on a declaration or definition when we're instantiating the
9829     // attribute, we need to check for constness here.
9830     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9831       if (!Param->getType().isConstQualified())
9832         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9833             << Attr->getSpelling() << 1;
9834   }
9835 
9836   return HasInvalidParm;
9837 }
9838 
9839 /// CheckCastAlign - Implements -Wcast-align, which warns when a
9840 /// pointer cast increases the alignment requirements.
9841 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9842   // This is actually a lot of work to potentially be doing on every
9843   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
9844   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
9845     return;
9846 
9847   // Ignore dependent types.
9848   if (T->isDependentType() || Op->getType()->isDependentType())
9849     return;
9850 
9851   // Require that the destination be a pointer type.
9852   const PointerType *DestPtr = T->getAs<PointerType>();
9853   if (!DestPtr) return;
9854 
9855   // If the destination has alignment 1, we're done.
9856   QualType DestPointee = DestPtr->getPointeeType();
9857   if (DestPointee->isIncompleteType()) return;
9858   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9859   if (DestAlign.isOne()) return;
9860 
9861   // Require that the source be a pointer type.
9862   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9863   if (!SrcPtr) return;
9864   QualType SrcPointee = SrcPtr->getPointeeType();
9865 
9866   // Whitelist casts from cv void*.  We already implicitly
9867   // whitelisted casts to cv void*, since they have alignment 1.
9868   // Also whitelist casts involving incomplete types, which implicitly
9869   // includes 'void'.
9870   if (SrcPointee->isIncompleteType()) return;
9871 
9872   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9873   if (SrcAlign >= DestAlign) return;
9874 
9875   Diag(TRange.getBegin(), diag::warn_cast_align)
9876     << Op->getType() << T
9877     << static_cast<unsigned>(SrcAlign.getQuantity())
9878     << static_cast<unsigned>(DestAlign.getQuantity())
9879     << TRange << Op->getSourceRange();
9880 }
9881 
9882 /// \brief Check whether this array fits the idiom of a size-one tail padded
9883 /// array member of a struct.
9884 ///
9885 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
9886 /// commonly used to emulate flexible arrays in C89 code.
9887 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
9888                                     const NamedDecl *ND) {
9889   if (Size != 1 || !ND) return false;
9890 
9891   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9892   if (!FD) return false;
9893 
9894   // Don't consider sizes resulting from macro expansions or template argument
9895   // substitution to form C89 tail-padded arrays.
9896 
9897   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
9898   while (TInfo) {
9899     TypeLoc TL = TInfo->getTypeLoc();
9900     // Look through typedefs.
9901     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9902       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
9903       TInfo = TDL->getTypeSourceInfo();
9904       continue;
9905     }
9906     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9907       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
9908       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9909         return false;
9910     }
9911     break;
9912   }
9913 
9914   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
9915   if (!RD) return false;
9916   if (RD->isUnion()) return false;
9917   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9918     if (!CRD->isStandardLayout()) return false;
9919   }
9920 
9921   // See if this is the last field decl in the record.
9922   const Decl *D = FD;
9923   while ((D = D->getNextDeclInContext()))
9924     if (isa<FieldDecl>(D))
9925       return false;
9926   return true;
9927 }
9928 
9929 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
9930                             const ArraySubscriptExpr *ASE,
9931                             bool AllowOnePastEnd, bool IndexNegated) {
9932   IndexExpr = IndexExpr->IgnoreParenImpCasts();
9933   if (IndexExpr->isValueDependent())
9934     return;
9935 
9936   const Type *EffectiveType =
9937       BaseExpr->getType()->getPointeeOrArrayElementType();
9938   BaseExpr = BaseExpr->IgnoreParenCasts();
9939   const ConstantArrayType *ArrayTy =
9940     Context.getAsConstantArrayType(BaseExpr->getType());
9941   if (!ArrayTy)
9942     return;
9943 
9944   llvm::APSInt index;
9945   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
9946     return;
9947   if (IndexNegated)
9948     index = -index;
9949 
9950   const NamedDecl *ND = nullptr;
9951   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9952     ND = dyn_cast<NamedDecl>(DRE->getDecl());
9953   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9954     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9955 
9956   if (index.isUnsigned() || !index.isNegative()) {
9957     llvm::APInt size = ArrayTy->getSize();
9958     if (!size.isStrictlyPositive())
9959       return;
9960 
9961     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
9962     if (BaseType != EffectiveType) {
9963       // Make sure we're comparing apples to apples when comparing index to size
9964       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9965       uint64_t array_typesize = Context.getTypeSize(BaseType);
9966       // Handle ptrarith_typesize being zero, such as when casting to void*
9967       if (!ptrarith_typesize) ptrarith_typesize = 1;
9968       if (ptrarith_typesize != array_typesize) {
9969         // There's a cast to a different size type involved
9970         uint64_t ratio = array_typesize / ptrarith_typesize;
9971         // TODO: Be smarter about handling cases where array_typesize is not a
9972         // multiple of ptrarith_typesize
9973         if (ptrarith_typesize * ratio == array_typesize)
9974           size *= llvm::APInt(size.getBitWidth(), ratio);
9975       }
9976     }
9977 
9978     if (size.getBitWidth() > index.getBitWidth())
9979       index = index.zext(size.getBitWidth());
9980     else if (size.getBitWidth() < index.getBitWidth())
9981       size = size.zext(index.getBitWidth());
9982 
9983     // For array subscripting the index must be less than size, but for pointer
9984     // arithmetic also allow the index (offset) to be equal to size since
9985     // computing the next address after the end of the array is legal and
9986     // commonly done e.g. in C++ iterators and range-based for loops.
9987     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
9988       return;
9989 
9990     // Also don't warn for arrays of size 1 which are members of some
9991     // structure. These are often used to approximate flexible arrays in C89
9992     // code.
9993     if (IsTailPaddedMemberArray(*this, size, ND))
9994       return;
9995 
9996     // Suppress the warning if the subscript expression (as identified by the
9997     // ']' location) and the index expression are both from macro expansions
9998     // within a system header.
9999     if (ASE) {
10000       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10001           ASE->getRBracketLoc());
10002       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10003         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10004             IndexExpr->getLocStart());
10005         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10006           return;
10007       }
10008     }
10009 
10010     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10011     if (ASE)
10012       DiagID = diag::warn_array_index_exceeds_bounds;
10013 
10014     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10015                         PDiag(DiagID) << index.toString(10, true)
10016                           << size.toString(10, true)
10017                           << (unsigned)size.getLimitedValue(~0U)
10018                           << IndexExpr->getSourceRange());
10019   } else {
10020     unsigned DiagID = diag::warn_array_index_precedes_bounds;
10021     if (!ASE) {
10022       DiagID = diag::warn_ptr_arith_precedes_bounds;
10023       if (index.isNegative()) index = -index;
10024     }
10025 
10026     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10027                         PDiag(DiagID) << index.toString(10, true)
10028                           << IndexExpr->getSourceRange());
10029   }
10030 
10031   if (!ND) {
10032     // Try harder to find a NamedDecl to point at in the note.
10033     while (const ArraySubscriptExpr *ASE =
10034            dyn_cast<ArraySubscriptExpr>(BaseExpr))
10035       BaseExpr = ASE->getBase()->IgnoreParenCasts();
10036     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10037       ND = dyn_cast<NamedDecl>(DRE->getDecl());
10038     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10039       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10040   }
10041 
10042   if (ND)
10043     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10044                         PDiag(diag::note_array_index_out_of_bounds)
10045                           << ND->getDeclName());
10046 }
10047 
10048 void Sema::CheckArrayAccess(const Expr *expr) {
10049   int AllowOnePastEnd = 0;
10050   while (expr) {
10051     expr = expr->IgnoreParenImpCasts();
10052     switch (expr->getStmtClass()) {
10053       case Stmt::ArraySubscriptExprClass: {
10054         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10055         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
10056                          AllowOnePastEnd > 0);
10057         return;
10058       }
10059       case Stmt::OMPArraySectionExprClass: {
10060         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10061         if (ASE->getLowerBound())
10062           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10063                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
10064         return;
10065       }
10066       case Stmt::UnaryOperatorClass: {
10067         // Only unwrap the * and & unary operators
10068         const UnaryOperator *UO = cast<UnaryOperator>(expr);
10069         expr = UO->getSubExpr();
10070         switch (UO->getOpcode()) {
10071           case UO_AddrOf:
10072             AllowOnePastEnd++;
10073             break;
10074           case UO_Deref:
10075             AllowOnePastEnd--;
10076             break;
10077           default:
10078             return;
10079         }
10080         break;
10081       }
10082       case Stmt::ConditionalOperatorClass: {
10083         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10084         if (const Expr *lhs = cond->getLHS())
10085           CheckArrayAccess(lhs);
10086         if (const Expr *rhs = cond->getRHS())
10087           CheckArrayAccess(rhs);
10088         return;
10089       }
10090       default:
10091         return;
10092     }
10093   }
10094 }
10095 
10096 //===--- CHECK: Objective-C retain cycles ----------------------------------//
10097 
10098 namespace {
10099   struct RetainCycleOwner {
10100     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
10101     VarDecl *Variable;
10102     SourceRange Range;
10103     SourceLocation Loc;
10104     bool Indirect;
10105 
10106     void setLocsFrom(Expr *e) {
10107       Loc = e->getExprLoc();
10108       Range = e->getSourceRange();
10109     }
10110   };
10111 } // end anonymous namespace
10112 
10113 /// Consider whether capturing the given variable can possibly lead to
10114 /// a retain cycle.
10115 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
10116   // In ARC, it's captured strongly iff the variable has __strong
10117   // lifetime.  In MRR, it's captured strongly if the variable is
10118   // __block and has an appropriate type.
10119   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10120     return false;
10121 
10122   owner.Variable = var;
10123   if (ref)
10124     owner.setLocsFrom(ref);
10125   return true;
10126 }
10127 
10128 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
10129   while (true) {
10130     e = e->IgnoreParens();
10131     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10132       switch (cast->getCastKind()) {
10133       case CK_BitCast:
10134       case CK_LValueBitCast:
10135       case CK_LValueToRValue:
10136       case CK_ARCReclaimReturnedObject:
10137         e = cast->getSubExpr();
10138         continue;
10139 
10140       default:
10141         return false;
10142       }
10143     }
10144 
10145     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10146       ObjCIvarDecl *ivar = ref->getDecl();
10147       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10148         return false;
10149 
10150       // Try to find a retain cycle in the base.
10151       if (!findRetainCycleOwner(S, ref->getBase(), owner))
10152         return false;
10153 
10154       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10155       owner.Indirect = true;
10156       return true;
10157     }
10158 
10159     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10160       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10161       if (!var) return false;
10162       return considerVariable(var, ref, owner);
10163     }
10164 
10165     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10166       if (member->isArrow()) return false;
10167 
10168       // Don't count this as an indirect ownership.
10169       e = member->getBase();
10170       continue;
10171     }
10172 
10173     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10174       // Only pay attention to pseudo-objects on property references.
10175       ObjCPropertyRefExpr *pre
10176         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10177                                               ->IgnoreParens());
10178       if (!pre) return false;
10179       if (pre->isImplicitProperty()) return false;
10180       ObjCPropertyDecl *property = pre->getExplicitProperty();
10181       if (!property->isRetaining() &&
10182           !(property->getPropertyIvarDecl() &&
10183             property->getPropertyIvarDecl()->getType()
10184               .getObjCLifetime() == Qualifiers::OCL_Strong))
10185           return false;
10186 
10187       owner.Indirect = true;
10188       if (pre->isSuperReceiver()) {
10189         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10190         if (!owner.Variable)
10191           return false;
10192         owner.Loc = pre->getLocation();
10193         owner.Range = pre->getSourceRange();
10194         return true;
10195       }
10196       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10197                               ->getSourceExpr());
10198       continue;
10199     }
10200 
10201     // Array ivars?
10202 
10203     return false;
10204   }
10205 }
10206 
10207 namespace {
10208   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10209     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10210       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10211         Context(Context), Variable(variable), Capturer(nullptr),
10212         VarWillBeReased(false) {}
10213     ASTContext &Context;
10214     VarDecl *Variable;
10215     Expr *Capturer;
10216     bool VarWillBeReased;
10217 
10218     void VisitDeclRefExpr(DeclRefExpr *ref) {
10219       if (ref->getDecl() == Variable && !Capturer)
10220         Capturer = ref;
10221     }
10222 
10223     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10224       if (Capturer) return;
10225       Visit(ref->getBase());
10226       if (Capturer && ref->isFreeIvar())
10227         Capturer = ref;
10228     }
10229 
10230     void VisitBlockExpr(BlockExpr *block) {
10231       // Look inside nested blocks
10232       if (block->getBlockDecl()->capturesVariable(Variable))
10233         Visit(block->getBlockDecl()->getBody());
10234     }
10235 
10236     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10237       if (Capturer) return;
10238       if (OVE->getSourceExpr())
10239         Visit(OVE->getSourceExpr());
10240     }
10241     void VisitBinaryOperator(BinaryOperator *BinOp) {
10242       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10243         return;
10244       Expr *LHS = BinOp->getLHS();
10245       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10246         if (DRE->getDecl() != Variable)
10247           return;
10248         if (Expr *RHS = BinOp->getRHS()) {
10249           RHS = RHS->IgnoreParenCasts();
10250           llvm::APSInt Value;
10251           VarWillBeReased =
10252             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10253         }
10254       }
10255     }
10256   };
10257 } // end anonymous namespace
10258 
10259 /// Check whether the given argument is a block which captures a
10260 /// variable.
10261 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10262   assert(owner.Variable && owner.Loc.isValid());
10263 
10264   e = e->IgnoreParenCasts();
10265 
10266   // Look through [^{...} copy] and Block_copy(^{...}).
10267   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10268     Selector Cmd = ME->getSelector();
10269     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10270       e = ME->getInstanceReceiver();
10271       if (!e)
10272         return nullptr;
10273       e = e->IgnoreParenCasts();
10274     }
10275   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10276     if (CE->getNumArgs() == 1) {
10277       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
10278       if (Fn) {
10279         const IdentifierInfo *FnI = Fn->getIdentifier();
10280         if (FnI && FnI->isStr("_Block_copy")) {
10281           e = CE->getArg(0)->IgnoreParenCasts();
10282         }
10283       }
10284     }
10285   }
10286 
10287   BlockExpr *block = dyn_cast<BlockExpr>(e);
10288   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
10289     return nullptr;
10290 
10291   FindCaptureVisitor visitor(S.Context, owner.Variable);
10292   visitor.Visit(block->getBlockDecl()->getBody());
10293   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
10294 }
10295 
10296 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10297                                 RetainCycleOwner &owner) {
10298   assert(capturer);
10299   assert(owner.Variable && owner.Loc.isValid());
10300 
10301   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10302     << owner.Variable << capturer->getSourceRange();
10303   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10304     << owner.Indirect << owner.Range;
10305 }
10306 
10307 /// Check for a keyword selector that starts with the word 'add' or
10308 /// 'set'.
10309 static bool isSetterLikeSelector(Selector sel) {
10310   if (sel.isUnarySelector()) return false;
10311 
10312   StringRef str = sel.getNameForSlot(0);
10313   while (!str.empty() && str.front() == '_') str = str.substr(1);
10314   if (str.startswith("set"))
10315     str = str.substr(3);
10316   else if (str.startswith("add")) {
10317     // Specially whitelist 'addOperationWithBlock:'.
10318     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10319       return false;
10320     str = str.substr(3);
10321   }
10322   else
10323     return false;
10324 
10325   if (str.empty()) return true;
10326   return !isLowercase(str.front());
10327 }
10328 
10329 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10330                                                     ObjCMessageExpr *Message) {
10331   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10332                                                 Message->getReceiverInterface(),
10333                                                 NSAPI::ClassId_NSMutableArray);
10334   if (!IsMutableArray) {
10335     return None;
10336   }
10337 
10338   Selector Sel = Message->getSelector();
10339 
10340   Optional<NSAPI::NSArrayMethodKind> MKOpt =
10341     S.NSAPIObj->getNSArrayMethodKind(Sel);
10342   if (!MKOpt) {
10343     return None;
10344   }
10345 
10346   NSAPI::NSArrayMethodKind MK = *MKOpt;
10347 
10348   switch (MK) {
10349     case NSAPI::NSMutableArr_addObject:
10350     case NSAPI::NSMutableArr_insertObjectAtIndex:
10351     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10352       return 0;
10353     case NSAPI::NSMutableArr_replaceObjectAtIndex:
10354       return 1;
10355 
10356     default:
10357       return None;
10358   }
10359 
10360   return None;
10361 }
10362 
10363 static
10364 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10365                                                   ObjCMessageExpr *Message) {
10366   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10367                                             Message->getReceiverInterface(),
10368                                             NSAPI::ClassId_NSMutableDictionary);
10369   if (!IsMutableDictionary) {
10370     return None;
10371   }
10372 
10373   Selector Sel = Message->getSelector();
10374 
10375   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10376     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10377   if (!MKOpt) {
10378     return None;
10379   }
10380 
10381   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10382 
10383   switch (MK) {
10384     case NSAPI::NSMutableDict_setObjectForKey:
10385     case NSAPI::NSMutableDict_setValueForKey:
10386     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10387       return 0;
10388 
10389     default:
10390       return None;
10391   }
10392 
10393   return None;
10394 }
10395 
10396 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
10397   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10398                                                 Message->getReceiverInterface(),
10399                                                 NSAPI::ClassId_NSMutableSet);
10400 
10401   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10402                                             Message->getReceiverInterface(),
10403                                             NSAPI::ClassId_NSMutableOrderedSet);
10404   if (!IsMutableSet && !IsMutableOrderedSet) {
10405     return None;
10406   }
10407 
10408   Selector Sel = Message->getSelector();
10409 
10410   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10411   if (!MKOpt) {
10412     return None;
10413   }
10414 
10415   NSAPI::NSSetMethodKind MK = *MKOpt;
10416 
10417   switch (MK) {
10418     case NSAPI::NSMutableSet_addObject:
10419     case NSAPI::NSOrderedSet_setObjectAtIndex:
10420     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10421     case NSAPI::NSOrderedSet_insertObjectAtIndex:
10422       return 0;
10423     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10424       return 1;
10425   }
10426 
10427   return None;
10428 }
10429 
10430 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10431   if (!Message->isInstanceMessage()) {
10432     return;
10433   }
10434 
10435   Optional<int> ArgOpt;
10436 
10437   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10438       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10439       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10440     return;
10441   }
10442 
10443   int ArgIndex = *ArgOpt;
10444 
10445   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10446   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10447     Arg = OE->getSourceExpr()->IgnoreImpCasts();
10448   }
10449 
10450   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10451     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10452       if (ArgRE->isObjCSelfExpr()) {
10453         Diag(Message->getSourceRange().getBegin(),
10454              diag::warn_objc_circular_container)
10455           << ArgRE->getDecl()->getName() << StringRef("super");
10456       }
10457     }
10458   } else {
10459     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10460 
10461     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10462       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10463     }
10464 
10465     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10466       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10467         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10468           ValueDecl *Decl = ReceiverRE->getDecl();
10469           Diag(Message->getSourceRange().getBegin(),
10470                diag::warn_objc_circular_container)
10471             << Decl->getName() << Decl->getName();
10472           if (!ArgRE->isObjCSelfExpr()) {
10473             Diag(Decl->getLocation(),
10474                  diag::note_objc_circular_container_declared_here)
10475               << Decl->getName();
10476           }
10477         }
10478       }
10479     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10480       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10481         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10482           ObjCIvarDecl *Decl = IvarRE->getDecl();
10483           Diag(Message->getSourceRange().getBegin(),
10484                diag::warn_objc_circular_container)
10485             << Decl->getName() << Decl->getName();
10486           Diag(Decl->getLocation(),
10487                diag::note_objc_circular_container_declared_here)
10488             << Decl->getName();
10489         }
10490       }
10491     }
10492   }
10493 }
10494 
10495 /// Check a message send to see if it's likely to cause a retain cycle.
10496 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10497   // Only check instance methods whose selector looks like a setter.
10498   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10499     return;
10500 
10501   // Try to find a variable that the receiver is strongly owned by.
10502   RetainCycleOwner owner;
10503   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
10504     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
10505       return;
10506   } else {
10507     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10508     owner.Variable = getCurMethodDecl()->getSelfDecl();
10509     owner.Loc = msg->getSuperLoc();
10510     owner.Range = msg->getSuperLoc();
10511   }
10512 
10513   // Check whether the receiver is captured by any of the arguments.
10514   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10515     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10516       return diagnoseRetainCycle(*this, capturer, owner);
10517 }
10518 
10519 /// Check a property assign to see if it's likely to cause a retain cycle.
10520 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10521   RetainCycleOwner owner;
10522   if (!findRetainCycleOwner(*this, receiver, owner))
10523     return;
10524 
10525   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10526     diagnoseRetainCycle(*this, capturer, owner);
10527 }
10528 
10529 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10530   RetainCycleOwner Owner;
10531   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
10532     return;
10533 
10534   // Because we don't have an expression for the variable, we have to set the
10535   // location explicitly here.
10536   Owner.Loc = Var->getLocation();
10537   Owner.Range = Var->getSourceRange();
10538 
10539   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10540     diagnoseRetainCycle(*this, Capturer, Owner);
10541 }
10542 
10543 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10544                                      Expr *RHS, bool isProperty) {
10545   // Check if RHS is an Objective-C object literal, which also can get
10546   // immediately zapped in a weak reference.  Note that we explicitly
10547   // allow ObjCStringLiterals, since those are designed to never really die.
10548   RHS = RHS->IgnoreParenImpCasts();
10549 
10550   // This enum needs to match with the 'select' in
10551   // warn_objc_arc_literal_assign (off-by-1).
10552   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10553   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10554     return false;
10555 
10556   S.Diag(Loc, diag::warn_arc_literal_assign)
10557     << (unsigned) Kind
10558     << (isProperty ? 0 : 1)
10559     << RHS->getSourceRange();
10560 
10561   return true;
10562 }
10563 
10564 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10565                                     Qualifiers::ObjCLifetime LT,
10566                                     Expr *RHS, bool isProperty) {
10567   // Strip off any implicit cast added to get to the one ARC-specific.
10568   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10569     if (cast->getCastKind() == CK_ARCConsumeObject) {
10570       S.Diag(Loc, diag::warn_arc_retained_assign)
10571         << (LT == Qualifiers::OCL_ExplicitNone)
10572         << (isProperty ? 0 : 1)
10573         << RHS->getSourceRange();
10574       return true;
10575     }
10576     RHS = cast->getSubExpr();
10577   }
10578 
10579   if (LT == Qualifiers::OCL_Weak &&
10580       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10581     return true;
10582 
10583   return false;
10584 }
10585 
10586 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10587                               QualType LHS, Expr *RHS) {
10588   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10589 
10590   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10591     return false;
10592 
10593   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10594     return true;
10595 
10596   return false;
10597 }
10598 
10599 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10600                               Expr *LHS, Expr *RHS) {
10601   QualType LHSType;
10602   // PropertyRef on LHS type need be directly obtained from
10603   // its declaration as it has a PseudoType.
10604   ObjCPropertyRefExpr *PRE
10605     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10606   if (PRE && !PRE->isImplicitProperty()) {
10607     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10608     if (PD)
10609       LHSType = PD->getType();
10610   }
10611 
10612   if (LHSType.isNull())
10613     LHSType = LHS->getType();
10614 
10615   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10616 
10617   if (LT == Qualifiers::OCL_Weak) {
10618     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
10619       getCurFunction()->markSafeWeakUse(LHS);
10620   }
10621 
10622   if (checkUnsafeAssigns(Loc, LHSType, RHS))
10623     return;
10624 
10625   // FIXME. Check for other life times.
10626   if (LT != Qualifiers::OCL_None)
10627     return;
10628 
10629   if (PRE) {
10630     if (PRE->isImplicitProperty())
10631       return;
10632     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10633     if (!PD)
10634       return;
10635 
10636     unsigned Attributes = PD->getPropertyAttributes();
10637     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
10638       // when 'assign' attribute was not explicitly specified
10639       // by user, ignore it and rely on property type itself
10640       // for lifetime info.
10641       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10642       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10643           LHSType->isObjCRetainableType())
10644         return;
10645 
10646       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10647         if (cast->getCastKind() == CK_ARCConsumeObject) {
10648           Diag(Loc, diag::warn_arc_retained_property_assign)
10649           << RHS->getSourceRange();
10650           return;
10651         }
10652         RHS = cast->getSubExpr();
10653       }
10654     }
10655     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
10656       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10657         return;
10658     }
10659   }
10660 }
10661 
10662 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10663 
10664 namespace {
10665 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10666                                  SourceLocation StmtLoc,
10667                                  const NullStmt *Body) {
10668   // Do not warn if the body is a macro that expands to nothing, e.g:
10669   //
10670   // #define CALL(x)
10671   // if (condition)
10672   //   CALL(0);
10673   //
10674   if (Body->hasLeadingEmptyMacro())
10675     return false;
10676 
10677   // Get line numbers of statement and body.
10678   bool StmtLineInvalid;
10679   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
10680                                                       &StmtLineInvalid);
10681   if (StmtLineInvalid)
10682     return false;
10683 
10684   bool BodyLineInvalid;
10685   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10686                                                       &BodyLineInvalid);
10687   if (BodyLineInvalid)
10688     return false;
10689 
10690   // Warn if null statement and body are on the same line.
10691   if (StmtLine != BodyLine)
10692     return false;
10693 
10694   return true;
10695 }
10696 } // end anonymous namespace
10697 
10698 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10699                                  const Stmt *Body,
10700                                  unsigned DiagID) {
10701   // Since this is a syntactic check, don't emit diagnostic for template
10702   // instantiations, this just adds noise.
10703   if (CurrentInstantiationScope)
10704     return;
10705 
10706   // The body should be a null statement.
10707   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10708   if (!NBody)
10709     return;
10710 
10711   // Do the usual checks.
10712   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10713     return;
10714 
10715   Diag(NBody->getSemiLoc(), DiagID);
10716   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10717 }
10718 
10719 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10720                                  const Stmt *PossibleBody) {
10721   assert(!CurrentInstantiationScope); // Ensured by caller
10722 
10723   SourceLocation StmtLoc;
10724   const Stmt *Body;
10725   unsigned DiagID;
10726   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10727     StmtLoc = FS->getRParenLoc();
10728     Body = FS->getBody();
10729     DiagID = diag::warn_empty_for_body;
10730   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10731     StmtLoc = WS->getCond()->getSourceRange().getEnd();
10732     Body = WS->getBody();
10733     DiagID = diag::warn_empty_while_body;
10734   } else
10735     return; // Neither `for' nor `while'.
10736 
10737   // The body should be a null statement.
10738   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10739   if (!NBody)
10740     return;
10741 
10742   // Skip expensive checks if diagnostic is disabled.
10743   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
10744     return;
10745 
10746   // Do the usual checks.
10747   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10748     return;
10749 
10750   // `for(...);' and `while(...);' are popular idioms, so in order to keep
10751   // noise level low, emit diagnostics only if for/while is followed by a
10752   // CompoundStmt, e.g.:
10753   //    for (int i = 0; i < n; i++);
10754   //    {
10755   //      a(i);
10756   //    }
10757   // or if for/while is followed by a statement with more indentation
10758   // than for/while itself:
10759   //    for (int i = 0; i < n; i++);
10760   //      a(i);
10761   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10762   if (!ProbableTypo) {
10763     bool BodyColInvalid;
10764     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10765                              PossibleBody->getLocStart(),
10766                              &BodyColInvalid);
10767     if (BodyColInvalid)
10768       return;
10769 
10770     bool StmtColInvalid;
10771     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10772                              S->getLocStart(),
10773                              &StmtColInvalid);
10774     if (StmtColInvalid)
10775       return;
10776 
10777     if (BodyCol > StmtCol)
10778       ProbableTypo = true;
10779   }
10780 
10781   if (ProbableTypo) {
10782     Diag(NBody->getSemiLoc(), DiagID);
10783     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10784   }
10785 }
10786 
10787 //===--- CHECK: Warn on self move with std::move. -------------------------===//
10788 
10789 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10790 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10791                              SourceLocation OpLoc) {
10792   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10793     return;
10794 
10795   if (!ActiveTemplateInstantiations.empty())
10796     return;
10797 
10798   // Strip parens and casts away.
10799   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10800   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10801 
10802   // Check for a call expression
10803   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10804   if (!CE || CE->getNumArgs() != 1)
10805     return;
10806 
10807   // Check for a call to std::move
10808   const FunctionDecl *FD = CE->getDirectCallee();
10809   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10810       !FD->getIdentifier()->isStr("move"))
10811     return;
10812 
10813   // Get argument from std::move
10814   RHSExpr = CE->getArg(0);
10815 
10816   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10817   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10818 
10819   // Two DeclRefExpr's, check that the decls are the same.
10820   if (LHSDeclRef && RHSDeclRef) {
10821     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10822       return;
10823     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10824         RHSDeclRef->getDecl()->getCanonicalDecl())
10825       return;
10826 
10827     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10828                                         << LHSExpr->getSourceRange()
10829                                         << RHSExpr->getSourceRange();
10830     return;
10831   }
10832 
10833   // Member variables require a different approach to check for self moves.
10834   // MemberExpr's are the same if every nested MemberExpr refers to the same
10835   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10836   // the base Expr's are CXXThisExpr's.
10837   const Expr *LHSBase = LHSExpr;
10838   const Expr *RHSBase = RHSExpr;
10839   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10840   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10841   if (!LHSME || !RHSME)
10842     return;
10843 
10844   while (LHSME && RHSME) {
10845     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10846         RHSME->getMemberDecl()->getCanonicalDecl())
10847       return;
10848 
10849     LHSBase = LHSME->getBase();
10850     RHSBase = RHSME->getBase();
10851     LHSME = dyn_cast<MemberExpr>(LHSBase);
10852     RHSME = dyn_cast<MemberExpr>(RHSBase);
10853   }
10854 
10855   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10856   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10857   if (LHSDeclRef && RHSDeclRef) {
10858     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10859       return;
10860     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10861         RHSDeclRef->getDecl()->getCanonicalDecl())
10862       return;
10863 
10864     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10865                                         << LHSExpr->getSourceRange()
10866                                         << RHSExpr->getSourceRange();
10867     return;
10868   }
10869 
10870   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10871     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10872                                         << LHSExpr->getSourceRange()
10873                                         << RHSExpr->getSourceRange();
10874 }
10875 
10876 //===--- Layout compatibility ----------------------------------------------//
10877 
10878 namespace {
10879 
10880 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10881 
10882 /// \brief Check if two enumeration types are layout-compatible.
10883 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10884   // C++11 [dcl.enum] p8:
10885   // Two enumeration types are layout-compatible if they have the same
10886   // underlying type.
10887   return ED1->isComplete() && ED2->isComplete() &&
10888          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10889 }
10890 
10891 /// \brief Check if two fields are layout-compatible.
10892 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10893   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10894     return false;
10895 
10896   if (Field1->isBitField() != Field2->isBitField())
10897     return false;
10898 
10899   if (Field1->isBitField()) {
10900     // Make sure that the bit-fields are the same length.
10901     unsigned Bits1 = Field1->getBitWidthValue(C);
10902     unsigned Bits2 = Field2->getBitWidthValue(C);
10903 
10904     if (Bits1 != Bits2)
10905       return false;
10906   }
10907 
10908   return true;
10909 }
10910 
10911 /// \brief Check if two standard-layout structs are layout-compatible.
10912 /// (C++11 [class.mem] p17)
10913 bool isLayoutCompatibleStruct(ASTContext &C,
10914                               RecordDecl *RD1,
10915                               RecordDecl *RD2) {
10916   // If both records are C++ classes, check that base classes match.
10917   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10918     // If one of records is a CXXRecordDecl we are in C++ mode,
10919     // thus the other one is a CXXRecordDecl, too.
10920     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10921     // Check number of base classes.
10922     if (D1CXX->getNumBases() != D2CXX->getNumBases())
10923       return false;
10924 
10925     // Check the base classes.
10926     for (CXXRecordDecl::base_class_const_iterator
10927                Base1 = D1CXX->bases_begin(),
10928            BaseEnd1 = D1CXX->bases_end(),
10929               Base2 = D2CXX->bases_begin();
10930          Base1 != BaseEnd1;
10931          ++Base1, ++Base2) {
10932       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10933         return false;
10934     }
10935   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10936     // If only RD2 is a C++ class, it should have zero base classes.
10937     if (D2CXX->getNumBases() > 0)
10938       return false;
10939   }
10940 
10941   // Check the fields.
10942   RecordDecl::field_iterator Field2 = RD2->field_begin(),
10943                              Field2End = RD2->field_end(),
10944                              Field1 = RD1->field_begin(),
10945                              Field1End = RD1->field_end();
10946   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10947     if (!isLayoutCompatible(C, *Field1, *Field2))
10948       return false;
10949   }
10950   if (Field1 != Field1End || Field2 != Field2End)
10951     return false;
10952 
10953   return true;
10954 }
10955 
10956 /// \brief Check if two standard-layout unions are layout-compatible.
10957 /// (C++11 [class.mem] p18)
10958 bool isLayoutCompatibleUnion(ASTContext &C,
10959                              RecordDecl *RD1,
10960                              RecordDecl *RD2) {
10961   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
10962   for (auto *Field2 : RD2->fields())
10963     UnmatchedFields.insert(Field2);
10964 
10965   for (auto *Field1 : RD1->fields()) {
10966     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10967         I = UnmatchedFields.begin(),
10968         E = UnmatchedFields.end();
10969 
10970     for ( ; I != E; ++I) {
10971       if (isLayoutCompatible(C, Field1, *I)) {
10972         bool Result = UnmatchedFields.erase(*I);
10973         (void) Result;
10974         assert(Result);
10975         break;
10976       }
10977     }
10978     if (I == E)
10979       return false;
10980   }
10981 
10982   return UnmatchedFields.empty();
10983 }
10984 
10985 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10986   if (RD1->isUnion() != RD2->isUnion())
10987     return false;
10988 
10989   if (RD1->isUnion())
10990     return isLayoutCompatibleUnion(C, RD1, RD2);
10991   else
10992     return isLayoutCompatibleStruct(C, RD1, RD2);
10993 }
10994 
10995 /// \brief Check if two types are layout-compatible in C++11 sense.
10996 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10997   if (T1.isNull() || T2.isNull())
10998     return false;
10999 
11000   // C++11 [basic.types] p11:
11001   // If two types T1 and T2 are the same type, then T1 and T2 are
11002   // layout-compatible types.
11003   if (C.hasSameType(T1, T2))
11004     return true;
11005 
11006   T1 = T1.getCanonicalType().getUnqualifiedType();
11007   T2 = T2.getCanonicalType().getUnqualifiedType();
11008 
11009   const Type::TypeClass TC1 = T1->getTypeClass();
11010   const Type::TypeClass TC2 = T2->getTypeClass();
11011 
11012   if (TC1 != TC2)
11013     return false;
11014 
11015   if (TC1 == Type::Enum) {
11016     return isLayoutCompatible(C,
11017                               cast<EnumType>(T1)->getDecl(),
11018                               cast<EnumType>(T2)->getDecl());
11019   } else if (TC1 == Type::Record) {
11020     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11021       return false;
11022 
11023     return isLayoutCompatible(C,
11024                               cast<RecordType>(T1)->getDecl(),
11025                               cast<RecordType>(T2)->getDecl());
11026   }
11027 
11028   return false;
11029 }
11030 } // end anonymous namespace
11031 
11032 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11033 
11034 namespace {
11035 /// \brief Given a type tag expression find the type tag itself.
11036 ///
11037 /// \param TypeExpr Type tag expression, as it appears in user's code.
11038 ///
11039 /// \param VD Declaration of an identifier that appears in a type tag.
11040 ///
11041 /// \param MagicValue Type tag magic value.
11042 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11043                      const ValueDecl **VD, uint64_t *MagicValue) {
11044   while(true) {
11045     if (!TypeExpr)
11046       return false;
11047 
11048     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11049 
11050     switch (TypeExpr->getStmtClass()) {
11051     case Stmt::UnaryOperatorClass: {
11052       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11053       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11054         TypeExpr = UO->getSubExpr();
11055         continue;
11056       }
11057       return false;
11058     }
11059 
11060     case Stmt::DeclRefExprClass: {
11061       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11062       *VD = DRE->getDecl();
11063       return true;
11064     }
11065 
11066     case Stmt::IntegerLiteralClass: {
11067       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11068       llvm::APInt MagicValueAPInt = IL->getValue();
11069       if (MagicValueAPInt.getActiveBits() <= 64) {
11070         *MagicValue = MagicValueAPInt.getZExtValue();
11071         return true;
11072       } else
11073         return false;
11074     }
11075 
11076     case Stmt::BinaryConditionalOperatorClass:
11077     case Stmt::ConditionalOperatorClass: {
11078       const AbstractConditionalOperator *ACO =
11079           cast<AbstractConditionalOperator>(TypeExpr);
11080       bool Result;
11081       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11082         if (Result)
11083           TypeExpr = ACO->getTrueExpr();
11084         else
11085           TypeExpr = ACO->getFalseExpr();
11086         continue;
11087       }
11088       return false;
11089     }
11090 
11091     case Stmt::BinaryOperatorClass: {
11092       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11093       if (BO->getOpcode() == BO_Comma) {
11094         TypeExpr = BO->getRHS();
11095         continue;
11096       }
11097       return false;
11098     }
11099 
11100     default:
11101       return false;
11102     }
11103   }
11104 }
11105 
11106 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
11107 ///
11108 /// \param TypeExpr Expression that specifies a type tag.
11109 ///
11110 /// \param MagicValues Registered magic values.
11111 ///
11112 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11113 ///        kind.
11114 ///
11115 /// \param TypeInfo Information about the corresponding C type.
11116 ///
11117 /// \returns true if the corresponding C type was found.
11118 bool GetMatchingCType(
11119         const IdentifierInfo *ArgumentKind,
11120         const Expr *TypeExpr, const ASTContext &Ctx,
11121         const llvm::DenseMap<Sema::TypeTagMagicValue,
11122                              Sema::TypeTagData> *MagicValues,
11123         bool &FoundWrongKind,
11124         Sema::TypeTagData &TypeInfo) {
11125   FoundWrongKind = false;
11126 
11127   // Variable declaration that has type_tag_for_datatype attribute.
11128   const ValueDecl *VD = nullptr;
11129 
11130   uint64_t MagicValue;
11131 
11132   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11133     return false;
11134 
11135   if (VD) {
11136     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11137       if (I->getArgumentKind() != ArgumentKind) {
11138         FoundWrongKind = true;
11139         return false;
11140       }
11141       TypeInfo.Type = I->getMatchingCType();
11142       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11143       TypeInfo.MustBeNull = I->getMustBeNull();
11144       return true;
11145     }
11146     return false;
11147   }
11148 
11149   if (!MagicValues)
11150     return false;
11151 
11152   llvm::DenseMap<Sema::TypeTagMagicValue,
11153                  Sema::TypeTagData>::const_iterator I =
11154       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11155   if (I == MagicValues->end())
11156     return false;
11157 
11158   TypeInfo = I->second;
11159   return true;
11160 }
11161 } // end anonymous namespace
11162 
11163 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11164                                       uint64_t MagicValue, QualType Type,
11165                                       bool LayoutCompatible,
11166                                       bool MustBeNull) {
11167   if (!TypeTagForDatatypeMagicValues)
11168     TypeTagForDatatypeMagicValues.reset(
11169         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11170 
11171   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11172   (*TypeTagForDatatypeMagicValues)[Magic] =
11173       TypeTagData(Type, LayoutCompatible, MustBeNull);
11174 }
11175 
11176 namespace {
11177 bool IsSameCharType(QualType T1, QualType T2) {
11178   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11179   if (!BT1)
11180     return false;
11181 
11182   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11183   if (!BT2)
11184     return false;
11185 
11186   BuiltinType::Kind T1Kind = BT1->getKind();
11187   BuiltinType::Kind T2Kind = BT2->getKind();
11188 
11189   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
11190          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
11191          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11192          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11193 }
11194 } // end anonymous namespace
11195 
11196 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11197                                     const Expr * const *ExprArgs) {
11198   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11199   bool IsPointerAttr = Attr->getIsPointer();
11200 
11201   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11202   bool FoundWrongKind;
11203   TypeTagData TypeInfo;
11204   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11205                         TypeTagForDatatypeMagicValues.get(),
11206                         FoundWrongKind, TypeInfo)) {
11207     if (FoundWrongKind)
11208       Diag(TypeTagExpr->getExprLoc(),
11209            diag::warn_type_tag_for_datatype_wrong_kind)
11210         << TypeTagExpr->getSourceRange();
11211     return;
11212   }
11213 
11214   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11215   if (IsPointerAttr) {
11216     // Skip implicit cast of pointer to `void *' (as a function argument).
11217     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11218       if (ICE->getType()->isVoidPointerType() &&
11219           ICE->getCastKind() == CK_BitCast)
11220         ArgumentExpr = ICE->getSubExpr();
11221   }
11222   QualType ArgumentType = ArgumentExpr->getType();
11223 
11224   // Passing a `void*' pointer shouldn't trigger a warning.
11225   if (IsPointerAttr && ArgumentType->isVoidPointerType())
11226     return;
11227 
11228   if (TypeInfo.MustBeNull) {
11229     // Type tag with matching void type requires a null pointer.
11230     if (!ArgumentExpr->isNullPointerConstant(Context,
11231                                              Expr::NPC_ValueDependentIsNotNull)) {
11232       Diag(ArgumentExpr->getExprLoc(),
11233            diag::warn_type_safety_null_pointer_required)
11234           << ArgumentKind->getName()
11235           << ArgumentExpr->getSourceRange()
11236           << TypeTagExpr->getSourceRange();
11237     }
11238     return;
11239   }
11240 
11241   QualType RequiredType = TypeInfo.Type;
11242   if (IsPointerAttr)
11243     RequiredType = Context.getPointerType(RequiredType);
11244 
11245   bool mismatch = false;
11246   if (!TypeInfo.LayoutCompatible) {
11247     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11248 
11249     // C++11 [basic.fundamental] p1:
11250     // Plain char, signed char, and unsigned char are three distinct types.
11251     //
11252     // But we treat plain `char' as equivalent to `signed char' or `unsigned
11253     // char' depending on the current char signedness mode.
11254     if (mismatch)
11255       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11256                                            RequiredType->getPointeeType())) ||
11257           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11258         mismatch = false;
11259   } else
11260     if (IsPointerAttr)
11261       mismatch = !isLayoutCompatible(Context,
11262                                      ArgumentType->getPointeeType(),
11263                                      RequiredType->getPointeeType());
11264     else
11265       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11266 
11267   if (mismatch)
11268     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
11269         << ArgumentType << ArgumentKind
11270         << TypeInfo.LayoutCompatible << RequiredType
11271         << ArgumentExpr->getSourceRange()
11272         << TypeTagExpr->getSourceRange();
11273 }
11274 
11275 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11276                                          CharUnits Alignment) {
11277   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11278 }
11279 
11280 void Sema::DiagnoseMisalignedMembers() {
11281   for (MisalignedMember &m : MisalignedMembers) {
11282     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11283         << m.MD << m.RD << m.E->getSourceRange();
11284   }
11285   MisalignedMembers.clear();
11286 }
11287 
11288 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11289   if (!T->isPointerType())
11290     return;
11291   if (isa<UnaryOperator>(E) &&
11292       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11293     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11294     if (isa<MemberExpr>(Op)) {
11295       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11296                           MisalignedMember(Op));
11297       if (MA != MisalignedMembers.end() &&
11298           Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)
11299         MisalignedMembers.erase(MA);
11300     }
11301   }
11302 }
11303 
11304 void Sema::RefersToMemberWithReducedAlignment(
11305     Expr *E,
11306     std::function<void(Expr *, RecordDecl *, ValueDecl *, CharUnits)> Action) {
11307   const auto *ME = dyn_cast<MemberExpr>(E);
11308   while (ME && isa<FieldDecl>(ME->getMemberDecl())) {
11309     QualType BaseType = ME->getBase()->getType();
11310     if (ME->isArrow())
11311       BaseType = BaseType->getPointeeType();
11312     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11313 
11314     ValueDecl *MD = ME->getMemberDecl();
11315     bool ByteAligned = Context.getTypeAlignInChars(MD->getType()).isOne();
11316     if (ByteAligned) // Attribute packed does not have any effect.
11317       break;
11318 
11319     if (!ByteAligned &&
11320         (RD->hasAttr<PackedAttr>() || (MD->hasAttr<PackedAttr>()))) {
11321       CharUnits Alignment = std::min(Context.getTypeAlignInChars(MD->getType()),
11322                                      Context.getTypeAlignInChars(BaseType));
11323       // Notify that this expression designates a member with reduced alignment
11324       Action(E, RD, MD, Alignment);
11325       break;
11326     }
11327     ME = dyn_cast<MemberExpr>(ME->getBase());
11328   }
11329 }
11330 
11331 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11332   using namespace std::placeholders;
11333   RefersToMemberWithReducedAlignment(
11334       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11335                      _2, _3, _4));
11336 }
11337 
11338