]> granicus.if.org Git - clang/blob - lib/StaticAnalyzer/Checkers/ObjCGenericsChecker.cpp
a8cf646390a72e2c15b46b0efe1000ff34f98174
[clang] / lib / StaticAnalyzer / Checkers / ObjCGenericsChecker.cpp
1 //=== ObjCGenericsChecker.cpp - Path sensitive checker for Generics *- C++ -*=//
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 checker tries to find type errors that the compiler is not able to catch
11 // due to the implicit conversions that were introduced for backward
12 // compatibility.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "ClangSACheckers.h"
17 #include "clang/AST/ParentMap.h"
18 #include "clang/AST/RecursiveASTVisitor.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20 #include "clang/StaticAnalyzer/Core/Checker.h"
21 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
25
26 using namespace clang;
27 using namespace ento;
28
29 // ProgramState trait - a map from symbol to its specialized type.
30 REGISTER_MAP_WITH_PROGRAMSTATE(TypeParamMap, SymbolRef,
31                                const ObjCObjectPointerType *)
32
33 namespace {
34 class ObjCGenericsChecker
35     : public Checker<check::DeadSymbols, check::PreObjCMessage,
36                      check::PostObjCMessage, check::PostStmt<CastExpr>> {
37 public:
38   void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
39   void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
40   void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
41   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
42
43 private:
44   mutable std::unique_ptr<BugType> ObjCGenericsBugType;
45   void initBugType() const {
46     if (!ObjCGenericsBugType)
47       ObjCGenericsBugType.reset(
48           new BugType(this, "Generics", categories::CoreFoundationObjectiveC));
49   }
50
51   class GenericsBugVisitor : public BugReporterVisitorImpl<GenericsBugVisitor> {
52   public:
53     GenericsBugVisitor(SymbolRef S) : Sym(S) {}
54
55     void Profile(llvm::FoldingSetNodeID &ID) const override {
56       static int X = 0;
57       ID.AddPointer(&X);
58       ID.AddPointer(Sym);
59     }
60
61     PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
62                                    const ExplodedNode *PrevN,
63                                    BugReporterContext &BRC,
64                                    BugReport &BR) override;
65
66   private:
67     // The tracked symbol.
68     SymbolRef Sym;
69   };
70
71   void reportGenericsBug(const ObjCObjectPointerType *From,
72                          const ObjCObjectPointerType *To, ExplodedNode *N,
73                          SymbolRef Sym, CheckerContext &C,
74                          const Stmt *ReportedNode = nullptr) const;
75
76   void checkReturnType(const ObjCMessageExpr *MessageExpr,
77                        const ObjCObjectPointerType *TrackedType, SymbolRef Sym,
78                        const ObjCMethodDecl *Method,
79                        ArrayRef<QualType> TypeArgs, bool SubscriptOrProperty,
80                        CheckerContext &C) const;
81 };
82 } // end anonymous namespace
83
84 void ObjCGenericsChecker::reportGenericsBug(const ObjCObjectPointerType *From,
85                                             const ObjCObjectPointerType *To,
86                                             ExplodedNode *N, SymbolRef Sym,
87                                             CheckerContext &C,
88                                             const Stmt *ReportedNode) const {
89   initBugType();
90   SmallString<192> Buf;
91   llvm::raw_svector_ostream OS(Buf);
92   OS << "Conversion from value of type '";
93   QualType::print(From, Qualifiers(), OS, C.getLangOpts(), llvm::Twine());
94   OS << "' to incompatible type '";
95   QualType::print(To, Qualifiers(), OS, C.getLangOpts(), llvm::Twine());
96   OS << "'";
97   std::unique_ptr<BugReport> R(
98       new BugReport(*ObjCGenericsBugType, OS.str(), N));
99   R->markInteresting(Sym);
100   R->addVisitor(llvm::make_unique<GenericsBugVisitor>(Sym));
101   if (ReportedNode)
102     R->addRange(ReportedNode->getSourceRange());
103   C.emitReport(std::move(R));
104 }
105
106 PathDiagnosticPiece *ObjCGenericsChecker::GenericsBugVisitor::VisitNode(
107     const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
108     BugReport &BR) {
109   ProgramStateRef state = N->getState();
110   ProgramStateRef statePrev = PrevN->getState();
111
112   const ObjCObjectPointerType *const *TrackedType =
113       state->get<TypeParamMap>(Sym);
114   const ObjCObjectPointerType *const *TrackedTypePrev =
115       statePrev->get<TypeParamMap>(Sym);
116   if (!TrackedType)
117     return nullptr;
118
119   if (TrackedTypePrev && *TrackedTypePrev == *TrackedType)
120     return nullptr;
121
122   // Retrieve the associated statement.
123   const Stmt *S = nullptr;
124   ProgramPoint ProgLoc = N->getLocation();
125   if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
126     S = SP->getStmt();
127   }
128
129   if (!S)
130     return nullptr;
131
132   const LangOptions &LangOpts = BRC.getASTContext().getLangOpts();
133
134   SmallString<256> Buf;
135   llvm::raw_svector_ostream OS(Buf);
136   OS << "Type '";
137   QualType::print(*TrackedType, Qualifiers(), OS, LangOpts, llvm::Twine());
138   OS << "' is inferred from ";
139
140   if (const auto *ExplicitCast = dyn_cast<ExplicitCastExpr>(S)) {
141     OS << "explicit cast (from '";
142     QualType::print(ExplicitCast->getSubExpr()->getType().getTypePtr(),
143                     Qualifiers(), OS, LangOpts, llvm::Twine());
144     OS << "' to '";
145     QualType::print(ExplicitCast->getType().getTypePtr(), Qualifiers(), OS,
146                     LangOpts, llvm::Twine());
147     OS << "')";
148   } else if (const auto *ImplicitCast = dyn_cast<ImplicitCastExpr>(S)) {
149     OS << "implicit cast (from '";
150     QualType::print(ImplicitCast->getSubExpr()->getType().getTypePtr(),
151                     Qualifiers(), OS, LangOpts, llvm::Twine());
152     OS << "' to '";
153     QualType::print(ImplicitCast->getType().getTypePtr(), Qualifiers(), OS,
154                     LangOpts, llvm::Twine());
155     OS << "')";
156   } else {
157     OS << "this context";
158   }
159
160   // Generate the extra diagnostic.
161   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
162                              N->getLocationContext());
163   return new PathDiagnosticEventPiece(Pos, OS.str(), true, nullptr);
164 }
165
166 /// Clean up the states stored by the checker.
167 void ObjCGenericsChecker::checkDeadSymbols(SymbolReaper &SR,
168                                            CheckerContext &C) const {
169   if (!SR.hasDeadSymbols())
170     return;
171
172   ProgramStateRef State = C.getState();
173   TypeParamMapTy TyParMap = State->get<TypeParamMap>();
174   for (TypeParamMapTy::iterator I = TyParMap.begin(), E = TyParMap.end();
175        I != E; ++I) {
176     if (SR.isDead(I->first)) {
177       State = State->remove<TypeParamMap>(I->first);
178     }
179   }
180 }
181
182 static const ObjCObjectPointerType *getMostInformativeDerivedClassImpl(
183     const ObjCObjectPointerType *From, const ObjCObjectPointerType *To,
184     const ObjCObjectPointerType *MostInformativeCandidate, ASTContext &C) {
185   // Checking if from and to are the same classes modulo specialization.
186   if (From->getInterfaceDecl()->getCanonicalDecl() ==
187       To->getInterfaceDecl()->getCanonicalDecl()) {
188     if (To->isSpecialized()) {
189       assert(MostInformativeCandidate->isSpecialized());
190       return MostInformativeCandidate;
191     }
192     return From;
193   }
194   const auto *SuperOfTo =
195       To->getObjectType()->getSuperClassType()->getAs<ObjCObjectType>();
196   assert(SuperOfTo);
197   QualType SuperPtrOfToQual =
198       C.getObjCObjectPointerType(QualType(SuperOfTo, 0));
199   const auto *SuperPtrOfTo = SuperPtrOfToQual->getAs<ObjCObjectPointerType>();
200   if (To->isUnspecialized())
201     return getMostInformativeDerivedClassImpl(From, SuperPtrOfTo, SuperPtrOfTo,
202                                               C);
203   else
204     return getMostInformativeDerivedClassImpl(From, SuperPtrOfTo,
205                                               MostInformativeCandidate, C);
206 }
207
208 /// A downcast may loose specialization information. E. g.:
209 ///   MutableMap<T, U> : Map
210 /// The downcast to MutableMap looses the information about the types of the
211 /// Map (due to the type parameters are not being forwarded to Map), and in
212 /// general there is no way to recover that information from the
213 /// declaration. In order to have to most information, lets find the most
214 /// derived type that has all the type parameters forwarded.
215 ///
216 /// Get the a subclass of \p From (which has a lower bound \p To) that do not
217 /// loose information about type parameters. \p To has to be a subclass of
218 /// \p From. From has to be specialized.
219 static const ObjCObjectPointerType *
220 getMostInformativeDerivedClass(const ObjCObjectPointerType *From,
221                                const ObjCObjectPointerType *To, ASTContext &C) {
222   return getMostInformativeDerivedClassImpl(From, To, To, C);
223 }
224
225 /// Inputs:
226 ///   \param StaticLowerBound Static lower bound for a symbol. The dynamic lower
227 ///   bound might be the subclass of this type.
228 ///   \param StaticUpperBound A static upper bound for a symbol.
229 ///   \p StaticLowerBound expected to be the subclass of \p StaticUpperBound.
230 ///   \param Current The type that was inferred for a symbol in a previous
231 ///   context. Might be null when this is the first time that inference happens.
232 /// Precondition:
233 ///   \p StaticLowerBound or \p StaticUpperBound is specialized. If \p Current
234 ///   is not null, it is specialized.
235 /// Possible cases:
236 ///   (1) The \p Current is null and \p StaticLowerBound <: \p StaticUpperBound
237 ///   (2) \p StaticLowerBound <: \p Current <: \p StaticUpperBound
238 ///   (3) \p Current <: \p StaticLowerBound <: \p StaticUpperBound
239 ///   (4) \p StaticLowerBound <: \p StaticUpperBound <: \p Current
240 /// Effect:
241 ///   Use getMostInformativeDerivedClass with the upper and lower bound of the
242 ///   set {\p StaticLowerBound, \p Current, \p StaticUpperBound}. The computed
243 ///   lower bound must be specialized. If the result differs from \p Current or
244 ///   \p Current is null, store the result.
245 static bool
246 storeWhenMoreInformative(ProgramStateRef &State, SymbolRef Sym,
247                          const ObjCObjectPointerType *const *Current,
248                          const ObjCObjectPointerType *StaticLowerBound,
249                          const ObjCObjectPointerType *StaticUpperBound,
250                          ASTContext &C) {
251   // Precondition
252   assert(StaticUpperBound->isSpecialized() ||
253          StaticLowerBound->isSpecialized());
254   assert(!Current || (*Current)->isSpecialized());
255
256   // Case (1)
257   if (!Current) {
258     if (StaticUpperBound->isUnspecialized()) {
259       State = State->set<TypeParamMap>(Sym, StaticLowerBound);
260       return true;
261     }
262     // Upper bound is specialized.
263     const ObjCObjectPointerType *WithMostInfo =
264         getMostInformativeDerivedClass(StaticUpperBound, StaticLowerBound, C);
265     State = State->set<TypeParamMap>(Sym, WithMostInfo);
266     return true;
267   }
268
269   // Case (3)
270   if (C.canAssignObjCInterfaces(StaticLowerBound, *Current)) {
271     return false;
272   }
273
274   // Case (4)
275   if (C.canAssignObjCInterfaces(*Current, StaticUpperBound)) {
276     // The type arguments might not be forwarded at any point of inheritance.
277     const ObjCObjectPointerType *WithMostInfo =
278         getMostInformativeDerivedClass(*Current, StaticUpperBound, C);
279     WithMostInfo =
280         getMostInformativeDerivedClass(WithMostInfo, StaticLowerBound, C);
281     if (WithMostInfo == *Current)
282       return false;
283     State = State->set<TypeParamMap>(Sym, WithMostInfo);
284     return true;
285   }
286
287   // Case (2)
288   const ObjCObjectPointerType *WithMostInfo =
289       getMostInformativeDerivedClass(*Current, StaticLowerBound, C);
290   if (WithMostInfo != *Current) {
291     State = State->set<TypeParamMap>(Sym, WithMostInfo);
292     return true;
293   }
294
295   return false;
296 }
297
298 /// Type inference based on static type information that is available for the
299 /// cast and the tracked type information for the given symbol. When the tracked
300 /// symbol and the destination type of the cast are unrelated, report an error.
301 void ObjCGenericsChecker::checkPostStmt(const CastExpr *CE,
302                                         CheckerContext &C) const {
303   if (CE->getCastKind() != CK_BitCast)
304     return;
305
306   QualType OriginType = CE->getSubExpr()->getType();
307   QualType DestType = CE->getType();
308
309   const auto *OrigObjectPtrType = OriginType->getAs<ObjCObjectPointerType>();
310   const auto *DestObjectPtrType = DestType->getAs<ObjCObjectPointerType>();
311
312   if (!OrigObjectPtrType || !DestObjectPtrType)
313     return;
314
315   ASTContext &ASTCtxt = C.getASTContext();
316
317   // This checker detects the subtyping relationships using the assignment
318   // rules. In order to be able to do this the kindofness must be stripped
319   // first. The checker treats every type as kindof type anyways: when the
320   // tracked type is the subtype of the static type it tries to look up the
321   // methods in the tracked type first.
322   OrigObjectPtrType = OrigObjectPtrType->stripObjCKindOfTypeAndQuals(ASTCtxt);
323   DestObjectPtrType = DestObjectPtrType->stripObjCKindOfTypeAndQuals(ASTCtxt);
324
325   // TODO: erase tracked information when there is a cast to unrelated type
326   //       and everything is unspecialized statically.
327   if (OrigObjectPtrType->isUnspecialized() &&
328       DestObjectPtrType->isUnspecialized())
329     return;
330
331   ProgramStateRef State = C.getState();
332   SymbolRef Sym = State->getSVal(CE, C.getLocationContext()).getAsSymbol();
333   if (!Sym)
334     return;
335
336   // Check which assignments are legal.
337   bool OrigToDest =
338       ASTCtxt.canAssignObjCInterfaces(DestObjectPtrType, OrigObjectPtrType);
339   bool DestToOrig =
340       ASTCtxt.canAssignObjCInterfaces(OrigObjectPtrType, DestObjectPtrType);
341   const ObjCObjectPointerType *const *TrackedType =
342       State->get<TypeParamMap>(Sym);
343
344   // Downcasts and upcasts handled in an uniform way regardless of being
345   // explicit. Explicit casts however can happen between mismatched types.
346   if (isa<ExplicitCastExpr>(CE) && !OrigToDest && !DestToOrig) {
347     // Mismatched types. If the DestType specialized, store it. Forget the
348     // tracked type otherwise.
349     if (DestObjectPtrType->isSpecialized()) {
350       State = State->set<TypeParamMap>(Sym, DestObjectPtrType);
351       C.addTransition(State);
352     } else if (TrackedType) {
353       State = State->remove<TypeParamMap>(Sym);
354       C.addTransition(State);
355     }
356     return;
357   }
358
359   // The tracked type should be the sub or super class of the static destination
360   // type. When an (implicit) upcast or a downcast happens according to static
361   // types, and there is no subtyping relationship between the tracked and the
362   // static destination types, it indicates an error.
363   if (TrackedType &&
364       !ASTCtxt.canAssignObjCInterfaces(DestObjectPtrType, *TrackedType) &&
365       !ASTCtxt.canAssignObjCInterfaces(*TrackedType, DestObjectPtrType)) {
366     static CheckerProgramPointTag IllegalConv(this, "IllegalConversion");
367     ExplodedNode *N = C.addTransition(State, &IllegalConv);
368     reportGenericsBug(*TrackedType, DestObjectPtrType, N, Sym, C);
369     return;
370   }
371
372   // Handle downcasts and upcasts.
373
374   const ObjCObjectPointerType *LowerBound = DestObjectPtrType;
375   const ObjCObjectPointerType *UpperBound = OrigObjectPtrType;
376   if (OrigToDest && !DestToOrig)
377     std::swap(LowerBound, UpperBound);
378
379   // The id type is not a real bound. Eliminate it.
380   LowerBound = LowerBound->isObjCIdType() ? UpperBound : LowerBound;
381   UpperBound = UpperBound->isObjCIdType() ? LowerBound : UpperBound;
382
383   if (storeWhenMoreInformative(State, Sym, TrackedType, LowerBound, UpperBound,
384                                ASTCtxt)) {
385     C.addTransition(State);
386   }
387 }
388
389 static const Expr *stripCastsAndSugar(const Expr *E) {
390   E = E->IgnoreParenImpCasts();
391   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
392     E = POE->getSyntacticForm()->IgnoreParenImpCasts();
393   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
394     E = OVE->getSourceExpr()->IgnoreParenImpCasts();
395   return E;
396 }
397
398 /// This callback is used to infer the types for Class variables. This info is
399 /// used later to validate messages that sent to classes. Class variables are
400 /// initialized with by invoking the 'class' method on a class.
401 void ObjCGenericsChecker::checkPostObjCMessage(const ObjCMethodCall &M,
402                                                CheckerContext &C) const {
403   const ObjCMessageExpr *MessageExpr = M.getOriginExpr();
404
405   SymbolRef Sym = M.getReturnValue().getAsSymbol();
406   if (!Sym)
407     return;
408
409   Selector Sel = MessageExpr->getSelector();
410   // We are only interested in cases where the class method is invoked on a
411   // class. This method is provided by the runtime and available on all classes.
412   if (MessageExpr->getReceiverKind() != ObjCMessageExpr::Class ||
413       Sel.getAsString() != "class")
414     return;
415
416   QualType ReceiverType = MessageExpr->getClassReceiver();
417   const auto *ReceiverClassType = ReceiverType->getAs<ObjCObjectType>();
418   QualType ReceiverClassPointerType =
419       C.getASTContext().getObjCObjectPointerType(
420           QualType(ReceiverClassType, 0));
421
422   if (!ReceiverClassType->isSpecialized())
423     return;
424   const auto *InferredType =
425       ReceiverClassPointerType->getAs<ObjCObjectPointerType>();
426   assert(InferredType);
427
428   ProgramStateRef State = C.getState();
429   State = State->set<TypeParamMap>(Sym, InferredType);
430   C.addTransition(State);
431 }
432
433 static bool isObjCTypeParamDependent(QualType Type) {
434   // It is illegal to typedef parameterized types inside an interface. Therfore
435   // an Objective-C type can only be dependent on a type parameter when the type
436   // parameter structurally present in the type itself.
437   class IsObjCTypeParamDependentTypeVisitor
438       : public RecursiveASTVisitor<IsObjCTypeParamDependentTypeVisitor> {
439   public:
440     IsObjCTypeParamDependentTypeVisitor() : Result(false) {}
441     bool VisitTypedefType(const TypedefType *Type) {
442       if (isa<ObjCTypeParamDecl>(Type->getDecl())) {
443         Result = true;
444         return false;
445       }
446       return true;
447     }
448
449     bool Result;
450   };
451
452   IsObjCTypeParamDependentTypeVisitor Visitor;
453   Visitor.TraverseType(Type);
454   return Visitor.Result;
455 }
456
457 /// A method might not be available in the interface indicated by the static
458 /// type. However it might be available in the tracked type. In order to
459 /// properly substitute the type parameters we need the declaration context of
460 /// the method. The more specialized the enclosing class of the method is, the
461 /// more likely that the parameter substitution will be successful.
462 static const ObjCMethodDecl *
463 findMethodDecl(const ObjCMessageExpr *MessageExpr,
464                const ObjCObjectPointerType *TrackedType, ASTContext &ASTCtxt) {
465   const ObjCMethodDecl *Method = nullptr;
466
467   QualType ReceiverType = MessageExpr->getReceiverType();
468   const auto *ReceiverObjectPtrType =
469       ReceiverType->getAs<ObjCObjectPointerType>();
470
471   // Do this "devirtualization" on instance and class methods only. Trust the
472   // static type on super and super class calls.
473   if (MessageExpr->getReceiverKind() == ObjCMessageExpr::Instance ||
474       MessageExpr->getReceiverKind() == ObjCMessageExpr::Class) {
475     // When the receiver type is id, Class, or some super class of the tracked
476     // type, look up the method in the tracked type, not in the receiver type.
477     // This way we preserve more information.
478     if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType() ||
479         ASTCtxt.canAssignObjCInterfaces(ReceiverObjectPtrType, TrackedType)) {
480       const ObjCInterfaceDecl *InterfaceDecl = TrackedType->getInterfaceDecl();
481       // The method might not be found.
482       Selector Sel = MessageExpr->getSelector();
483       Method = InterfaceDecl->lookupInstanceMethod(Sel);
484       if (!Method)
485         Method = InterfaceDecl->lookupClassMethod(Sel);
486     }
487   }
488
489   // Fallback to statick method lookup when the one based on the tracked type
490   // failed.
491   return Method ? Method : MessageExpr->getMethodDecl();
492 }
493
494 /// Validate that the return type of a message expression is used correctly.
495 void ObjCGenericsChecker::checkReturnType(
496     const ObjCMessageExpr *MessageExpr,
497     const ObjCObjectPointerType *TrackedType, SymbolRef Sym,
498     const ObjCMethodDecl *Method, ArrayRef<QualType> TypeArgs,
499     bool SubscriptOrProperty, CheckerContext &C) const {
500   QualType StaticResultType = Method->getReturnType();
501   ASTContext &ASTCtxt = C.getASTContext();
502   // Check whether the result type was a type parameter.
503   bool IsDeclaredAsInstanceType =
504       StaticResultType == ASTCtxt.getObjCInstanceType();
505   if (!isObjCTypeParamDependent(StaticResultType) && !IsDeclaredAsInstanceType)
506     return;
507
508   QualType ResultType = Method->getReturnType().substObjCTypeArgs(
509       ASTCtxt, TypeArgs, ObjCSubstitutionContext::Result);
510   if (IsDeclaredAsInstanceType)
511     ResultType = QualType(TrackedType, 0);
512
513   const Stmt *Parent =
514       C.getCurrentAnalysisDeclContext()->getParentMap().getParent(MessageExpr);
515   if (SubscriptOrProperty) {
516     // Properties and subscripts are not direct parents.
517     Parent =
518         C.getCurrentAnalysisDeclContext()->getParentMap().getParent(Parent);
519   }
520
521   const auto *ImplicitCast = dyn_cast_or_null<ImplicitCastExpr>(Parent);
522   if (!ImplicitCast || ImplicitCast->getCastKind() != CK_BitCast)
523     return;
524
525   const auto *ExprTypeAboveCast =
526       ImplicitCast->getType()->getAs<ObjCObjectPointerType>();
527   const auto *ResultPtrType = ResultType->getAs<ObjCObjectPointerType>();
528
529   if (!ExprTypeAboveCast || !ResultPtrType)
530     return;
531
532   // Only warn on unrelated types to avoid too many false positives on
533   // downcasts.
534   if (!ASTCtxt.canAssignObjCInterfaces(ExprTypeAboveCast, ResultPtrType) &&
535       !ASTCtxt.canAssignObjCInterfaces(ResultPtrType, ExprTypeAboveCast)) {
536     static CheckerProgramPointTag Tag(this, "ReturnTypeMismatch");
537     ExplodedNode *N = C.addTransition(C.getState(), &Tag);
538     reportGenericsBug(ResultPtrType, ExprTypeAboveCast, N, Sym, C);
539     return;
540   }
541 }
542
543 /// When the receiver has a tracked type, use that type to validate the
544 /// argumments of the message expression and the return value.
545 void ObjCGenericsChecker::checkPreObjCMessage(const ObjCMethodCall &M,
546                                               CheckerContext &C) const {
547   ProgramStateRef State = C.getState();
548   SymbolRef Sym = M.getReceiverSVal().getAsSymbol();
549   if (!Sym)
550     return;
551
552   const ObjCObjectPointerType *const *TrackedType =
553       State->get<TypeParamMap>(Sym);
554   if (!TrackedType)
555     return;
556
557   // Get the type arguments from tracked type and substitute type arguments
558   // before do the semantic check.
559
560   ASTContext &ASTCtxt = C.getASTContext();
561   const ObjCMessageExpr *MessageExpr = M.getOriginExpr();
562   const ObjCMethodDecl *Method =
563       findMethodDecl(MessageExpr, *TrackedType, ASTCtxt);
564
565   // It is possible to call non-existent methods in Obj-C.
566   if (!Method)
567     return;
568
569   Optional<ArrayRef<QualType>> TypeArgs =
570       (*TrackedType)->getObjCSubstitutions(Method->getDeclContext());
571   // This case might happen when there is an unspecialized override of a
572   // specialized method.
573   if (!TypeArgs)
574     return;
575
576   for (unsigned i = 0; i < Method->param_size(); i++) {
577     const Expr *Arg = MessageExpr->getArg(i);
578     const ParmVarDecl *Param = Method->parameters()[i];
579
580     QualType OrigParamType = Param->getType();
581     if (!isObjCTypeParamDependent(OrigParamType))
582       continue;
583
584     QualType ParamType = OrigParamType.substObjCTypeArgs(
585         ASTCtxt, *TypeArgs, ObjCSubstitutionContext::Parameter);
586     // Check if it can be assigned
587     const auto *ParamObjectPtrType = ParamType->getAs<ObjCObjectPointerType>();
588     const auto *ArgObjectPtrType =
589         stripCastsAndSugar(Arg)->getType()->getAs<ObjCObjectPointerType>();
590     if (!ParamObjectPtrType || !ArgObjectPtrType)
591       continue;
592
593     // Check if we have more concrete tracked type that is not a super type of
594     // the static argument type.
595     SVal ArgSVal = M.getArgSVal(i);
596     SymbolRef ArgSym = ArgSVal.getAsSymbol();
597     if (ArgSym) {
598       const ObjCObjectPointerType *const *TrackedArgType =
599           State->get<TypeParamMap>(ArgSym);
600       if (TrackedArgType &&
601           ASTCtxt.canAssignObjCInterfaces(ArgObjectPtrType, *TrackedArgType)) {
602         ArgObjectPtrType = *TrackedArgType;
603       }
604     }
605
606     // Warn when argument is incompatible with the parameter.
607     if (!ASTCtxt.canAssignObjCInterfaces(ParamObjectPtrType,
608                                          ArgObjectPtrType)) {
609       static CheckerProgramPointTag Tag(this, "ArgTypeMismatch");
610       ExplodedNode *N = C.addTransition(State, &Tag);
611       reportGenericsBug(ArgObjectPtrType, ParamObjectPtrType, N, Sym, C, Arg);
612       return;
613     }
614   }
615
616   checkReturnType(MessageExpr, *TrackedType, Sym, Method, *TypeArgs,
617                   M.getMessageKind() != OCM_Message, C);
618 }
619
620 /// Register checker.
621 void ento::registerObjCGenericsChecker(CheckerManager &mgr) {
622   mgr.registerChecker<ObjCGenericsChecker>();
623 }