1 //===---------------- SemaCodeComplete.cpp - Code Completion ----*- 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 file defines the code-completion semantic actions.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "clang/AST/DeclCXX.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/Basic/CharInfo.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/MacroInfo.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Sema/CodeCompleteConsumer.h"
22 #include "clang/Sema/Lookup.h"
23 #include "clang/Sema/Overload.h"
24 #include "clang/Sema/Scope.h"
25 #include "clang/Sema/ScopeInfo.h"
26 #include "clang/Sema/SemaInternal.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/StringSwitch.h"
33 #include "llvm/ADT/Twine.h"
34 #include <list>
35 #include <map>
36 #include <vector>
37 
38 using namespace clang;
39 using namespace sema;
40 
41 namespace {
42   /// \brief A container of code-completion results.
43   class ResultBuilder {
44   public:
45     /// \brief The type of a name-lookup filter, which can be provided to the
46     /// name-lookup routines to specify which declarations should be included in
47     /// the result set (when it returns true) and which declarations should be
48     /// filtered out (returns false).
49     typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
50 
51     typedef CodeCompletionResult Result;
52 
53   private:
54     /// \brief The actual results we have found.
55     std::vector<Result> Results;
56 
57     /// \brief A record of all of the declarations we have found and placed
58     /// into the result set, used to ensure that no declaration ever gets into
59     /// the result set twice.
60     llvm::SmallPtrSet<const Decl*, 16> AllDeclsFound;
61 
62     typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
63 
64     /// \brief An entry in the shadow map, which is optimized to store
65     /// a single (declaration, index) mapping (the common case) but
66     /// can also store a list of (declaration, index) mappings.
67     class ShadowMapEntry {
68       typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
69 
70       /// \brief Contains either the solitary NamedDecl * or a vector
71       /// of (declaration, index) pairs.
72       llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector*> DeclOrVector;
73 
74       /// \brief When the entry contains a single declaration, this is
75       /// the index associated with that entry.
76       unsigned SingleDeclIndex;
77 
78     public:
79       ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
80 
81       void Add(const NamedDecl *ND, unsigned Index) {
82         if (DeclOrVector.isNull()) {
83           // 0 - > 1 elements: just set the single element information.
84           DeclOrVector = ND;
85           SingleDeclIndex = Index;
86           return;
87         }
88 
89         if (const NamedDecl *PrevND =
90                 DeclOrVector.dyn_cast<const NamedDecl *>()) {
91           // 1 -> 2 elements: create the vector of results and push in the
92           // existing declaration.
93           DeclIndexPairVector *Vec = new DeclIndexPairVector;
94           Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
95           DeclOrVector = Vec;
96         }
97 
98         // Add the new element to the end of the vector.
99         DeclOrVector.get<DeclIndexPairVector*>()->push_back(
100                                                     DeclIndexPair(ND, Index));
101       }
102 
103       void Destroy() {
104         if (DeclIndexPairVector *Vec
105               = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
106           delete Vec;
107           DeclOrVector = ((NamedDecl *)nullptr);
108         }
109       }
110 
111       // Iteration.
112       class iterator;
113       iterator begin() const;
114       iterator end() const;
115     };
116 
117     /// \brief A mapping from declaration names to the declarations that have
118     /// this name within a particular scope and their index within the list of
119     /// results.
120     typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
121 
122     /// \brief The semantic analysis object for which results are being
123     /// produced.
124     Sema &SemaRef;
125 
126     /// \brief The allocator used to allocate new code-completion strings.
127     CodeCompletionAllocator &Allocator;
128 
129     CodeCompletionTUInfo &CCTUInfo;
130 
131     /// \brief If non-NULL, a filter function used to remove any code-completion
132     /// results that are not desirable.
133     LookupFilter Filter;
134 
135     /// \brief Whether we should allow declarations as
136     /// nested-name-specifiers that would otherwise be filtered out.
137     bool AllowNestedNameSpecifiers;
138 
139     /// \brief If set, the type that we would prefer our resulting value
140     /// declarations to have.
141     ///
142     /// Closely matching the preferred type gives a boost to a result's
143     /// priority.
144     CanQualType PreferredType;
145 
146     /// \brief A list of shadow maps, which is used to model name hiding at
147     /// different levels of, e.g., the inheritance hierarchy.
148     std::list<ShadowMap> ShadowMaps;
149 
150     /// \brief If we're potentially referring to a C++ member function, the set
151     /// of qualifiers applied to the object type.
152     Qualifiers ObjectTypeQualifiers;
153 
154     /// \brief Whether the \p ObjectTypeQualifiers field is active.
155     bool HasObjectTypeQualifiers;
156 
157     /// \brief The selector that we prefer.
158     Selector PreferredSelector;
159 
160     /// \brief The completion context in which we are gathering results.
161     CodeCompletionContext CompletionContext;
162 
163     /// \brief If we are in an instance method definition, the \@implementation
164     /// object.
165     ObjCImplementationDecl *ObjCImplementation;
166 
167     void AdjustResultPriorityForDecl(Result &R);
168 
169     void MaybeAddConstructorResults(Result R);
170 
171   public:
172     explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
173                            CodeCompletionTUInfo &CCTUInfo,
174                            const CodeCompletionContext &CompletionContext,
175                            LookupFilter Filter = nullptr)
176       : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
177         Filter(Filter),
178         AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
179         CompletionContext(CompletionContext),
180         ObjCImplementation(nullptr)
181     {
182       // If this is an Objective-C instance method definition, dig out the
183       // corresponding implementation.
184       switch (CompletionContext.getKind()) {
185       case CodeCompletionContext::CCC_Expression:
186       case CodeCompletionContext::CCC_ObjCMessageReceiver:
187       case CodeCompletionContext::CCC_ParenthesizedExpression:
188       case CodeCompletionContext::CCC_Statement:
189       case CodeCompletionContext::CCC_Recovery:
190         if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
191           if (Method->isInstanceMethod())
192             if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
193               ObjCImplementation = Interface->getImplementation();
194         break;
195 
196       default:
197         break;
198       }
199     }
200 
201     /// \brief Determine the priority for a reference to the given declaration.
202     unsigned getBasePriority(const NamedDecl *D);
203 
204     /// \brief Whether we should include code patterns in the completion
205     /// results.
206     bool includeCodePatterns() const {
207       return SemaRef.CodeCompleter &&
208              SemaRef.CodeCompleter->includeCodePatterns();
209     }
210 
211     /// \brief Set the filter used for code-completion results.
212     void setFilter(LookupFilter Filter) {
213       this->Filter = Filter;
214     }
215 
216     Result *data() { return Results.empty()? nullptr : &Results.front(); }
217     unsigned size() const { return Results.size(); }
218     bool empty() const { return Results.empty(); }
219 
220     /// \brief Specify the preferred type.
221     void setPreferredType(QualType T) {
222       PreferredType = SemaRef.Context.getCanonicalType(T);
223     }
224 
225     /// \brief Set the cv-qualifiers on the object type, for us in filtering
226     /// calls to member functions.
227     ///
228     /// When there are qualifiers in this set, they will be used to filter
229     /// out member functions that aren't available (because there will be a
230     /// cv-qualifier mismatch) or prefer functions with an exact qualifier
231     /// match.
232     void setObjectTypeQualifiers(Qualifiers Quals) {
233       ObjectTypeQualifiers = Quals;
234       HasObjectTypeQualifiers = true;
235     }
236 
237     /// \brief Set the preferred selector.
238     ///
239     /// When an Objective-C method declaration result is added, and that
240     /// method's selector matches this preferred selector, we give that method
241     /// a slight priority boost.
242     void setPreferredSelector(Selector Sel) {
243       PreferredSelector = Sel;
244     }
245 
246     /// \brief Retrieve the code-completion context for which results are
247     /// being collected.
248     const CodeCompletionContext &getCompletionContext() const {
249       return CompletionContext;
250     }
251 
252     /// \brief Specify whether nested-name-specifiers are allowed.
253     void allowNestedNameSpecifiers(bool Allow = true) {
254       AllowNestedNameSpecifiers = Allow;
255     }
256 
257     /// \brief Return the semantic analysis object for which we are collecting
258     /// code completion results.
259     Sema &getSema() const { return SemaRef; }
260 
261     /// \brief Retrieve the allocator used to allocate code completion strings.
262     CodeCompletionAllocator &getAllocator() const { return Allocator; }
263 
264     CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
265 
266     /// \brief Determine whether the given declaration is at all interesting
267     /// as a code-completion result.
268     ///
269     /// \param ND the declaration that we are inspecting.
270     ///
271     /// \param AsNestedNameSpecifier will be set true if this declaration is
272     /// only interesting when it is a nested-name-specifier.
273     bool isInterestingDecl(const NamedDecl *ND,
274                            bool &AsNestedNameSpecifier) const;
275 
276     /// \brief Check whether the result is hidden by the Hiding declaration.
277     ///
278     /// \returns true if the result is hidden and cannot be found, false if
279     /// the hidden result could still be found. When false, \p R may be
280     /// modified to describe how the result can be found (e.g., via extra
281     /// qualification).
282     bool CheckHiddenResult(Result &R, DeclContext *CurContext,
283                            const NamedDecl *Hiding);
284 
285     /// \brief Add a new result to this result set (if it isn't already in one
286     /// of the shadow maps), or replace an existing result (for, e.g., a
287     /// redeclaration).
288     ///
289     /// \param R the result to add (if it is unique).
290     ///
291     /// \param CurContext the context in which this result will be named.
292     void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
293 
294     /// \brief Add a new result to this result set, where we already know
295     /// the hiding declaration (if any).
296     ///
297     /// \param R the result to add (if it is unique).
298     ///
299     /// \param CurContext the context in which this result will be named.
300     ///
301     /// \param Hiding the declaration that hides the result.
302     ///
303     /// \param InBaseClass whether the result was found in a base
304     /// class of the searched context.
305     void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
306                    bool InBaseClass);
307 
308     /// \brief Add a new non-declaration result to this result set.
309     void AddResult(Result R);
310 
311     /// \brief Enter into a new scope.
312     void EnterNewScope();
313 
314     /// \brief Exit from the current scope.
315     void ExitScope();
316 
317     /// \brief Ignore this declaration, if it is seen again.
318     void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
319 
320     /// \name Name lookup predicates
321     ///
322     /// These predicates can be passed to the name lookup functions to filter the
323     /// results of name lookup. All of the predicates have the same type, so that
324     ///
325     //@{
326     bool IsOrdinaryName(const NamedDecl *ND) const;
327     bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
328     bool IsIntegralConstantValue(const NamedDecl *ND) const;
329     bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
330     bool IsNestedNameSpecifier(const NamedDecl *ND) const;
331     bool IsEnum(const NamedDecl *ND) const;
332     bool IsClassOrStruct(const NamedDecl *ND) const;
333     bool IsUnion(const NamedDecl *ND) const;
334     bool IsNamespace(const NamedDecl *ND) const;
335     bool IsNamespaceOrAlias(const NamedDecl *ND) const;
336     bool IsType(const NamedDecl *ND) const;
337     bool IsMember(const NamedDecl *ND) const;
338     bool IsObjCIvar(const NamedDecl *ND) const;
339     bool IsObjCMessageReceiver(const NamedDecl *ND) const;
340     bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
341     bool IsObjCCollection(const NamedDecl *ND) const;
342     bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
343     //@}
344   };
345 }
346 
347 class ResultBuilder::ShadowMapEntry::iterator {
348   llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
349   unsigned SingleDeclIndex;
350 
351 public:
352   typedef DeclIndexPair value_type;
353   typedef value_type reference;
354   typedef std::ptrdiff_t difference_type;
355   typedef std::input_iterator_tag iterator_category;
356 
357   class pointer {
358     DeclIndexPair Value;
359 
360   public:
361     pointer(const DeclIndexPair &Value) : Value(Value) { }
362 
363     const DeclIndexPair *operator->() const {
364       return &Value;
365     }
366   };
367 
368   iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
369 
370   iterator(const NamedDecl *SingleDecl, unsigned Index)
371     : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
372 
373   iterator(const DeclIndexPair *Iterator)
374     : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
375 
376   iterator &operator++() {
377     if (DeclOrIterator.is<const NamedDecl *>()) {
378       DeclOrIterator = (NamedDecl *)nullptr;
379       SingleDeclIndex = 0;
380       return *this;
381     }
382 
383     const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
384     ++I;
385     DeclOrIterator = I;
386     return *this;
387   }
388 
389   /*iterator operator++(int) {
390     iterator tmp(*this);
391     ++(*this);
392     return tmp;
393   }*/
394 
395   reference operator*() const {
396     if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
397       return reference(ND, SingleDeclIndex);
398 
399     return *DeclOrIterator.get<const DeclIndexPair*>();
400   }
401 
402   pointer operator->() const {
403     return pointer(**this);
404   }
405 
406   friend bool operator==(const iterator &X, const iterator &Y) {
407     return X.DeclOrIterator.getOpaqueValue()
408                                   == Y.DeclOrIterator.getOpaqueValue() &&
409       X.SingleDeclIndex == Y.SingleDeclIndex;
410   }
411 
412   friend bool operator!=(const iterator &X, const iterator &Y) {
413     return !(X == Y);
414   }
415 };
416 
417 ResultBuilder::ShadowMapEntry::iterator
418 ResultBuilder::ShadowMapEntry::begin() const {
419   if (DeclOrVector.isNull())
420     return iterator();
421 
422   if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
423     return iterator(ND, SingleDeclIndex);
424 
425   return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
426 }
427 
428 ResultBuilder::ShadowMapEntry::iterator
429 ResultBuilder::ShadowMapEntry::end() const {
430   if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
431     return iterator();
432 
433   return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
434 }
435 
436 /// \brief Compute the qualification required to get from the current context
437 /// (\p CurContext) to the target context (\p TargetContext).
438 ///
439 /// \param Context the AST context in which the qualification will be used.
440 ///
441 /// \param CurContext the context where an entity is being named, which is
442 /// typically based on the current scope.
443 ///
444 /// \param TargetContext the context in which the named entity actually
445 /// resides.
446 ///
447 /// \returns a nested name specifier that refers into the target context, or
448 /// NULL if no qualification is needed.
449 static NestedNameSpecifier *
450 getRequiredQualification(ASTContext &Context,
451                          const DeclContext *CurContext,
452                          const DeclContext *TargetContext) {
453   SmallVector<const DeclContext *, 4> TargetParents;
454 
455   for (const DeclContext *CommonAncestor = TargetContext;
456        CommonAncestor && !CommonAncestor->Encloses(CurContext);
457        CommonAncestor = CommonAncestor->getLookupParent()) {
458     if (CommonAncestor->isTransparentContext() ||
459         CommonAncestor->isFunctionOrMethod())
460       continue;
461 
462     TargetParents.push_back(CommonAncestor);
463   }
464 
465   NestedNameSpecifier *Result = nullptr;
466   while (!TargetParents.empty()) {
467     const DeclContext *Parent = TargetParents.pop_back_val();
468 
469     if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
470       if (!Namespace->getIdentifier())
471         continue;
472 
473       Result = NestedNameSpecifier::Create(Context, Result, Namespace);
474     }
475     else if (const TagDecl *TD = dyn_cast<TagDecl>(Parent))
476       Result = NestedNameSpecifier::Create(Context, Result,
477                                            false,
478                                      Context.getTypeDeclType(TD).getTypePtr());
479   }
480   return Result;
481 }
482 
483 /// Determine whether \p Id is a name reserved for the implementation (C99
484 /// 7.1.3, C++ [lib.global.names]).
485 static bool isReservedName(const IdentifierInfo *Id,
486                            bool doubleUnderscoreOnly = false) {
487   if (Id->getLength() < 2)
488     return false;
489   const char *Name = Id->getNameStart();
490   return Name[0] == '_' &&
491          (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z' &&
492                              !doubleUnderscoreOnly));
493 }
494 
495 // Some declarations have reserved names that we don't want to ever show.
496 // Filter out names reserved for the implementation if they come from a
497 // system header.
498 static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
499   const IdentifierInfo *Id = ND->getIdentifier();
500   if (!Id)
501     return false;
502 
503   // Ignore reserved names for compiler provided decls.
504   if (isReservedName(Id) && ND->getLocation().isInvalid())
505     return true;
506 
507   // For system headers ignore only double-underscore names.
508   // This allows for system headers providing private symbols with a single
509   // underscore.
510   if (isReservedName(Id, /*doubleUnderscoreOnly=*/true) &&
511        SemaRef.SourceMgr.isInSystemHeader(
512            SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
513       return true;
514 
515   return false;
516 }
517 
518 bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
519                                       bool &AsNestedNameSpecifier) const {
520   AsNestedNameSpecifier = false;
521 
522   auto *Named = ND;
523   ND = ND->getUnderlyingDecl();
524 
525   // Skip unnamed entities.
526   if (!ND->getDeclName())
527     return false;
528 
529   // Friend declarations and declarations introduced due to friends are never
530   // added as results.
531   if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
532     return false;
533 
534   // Class template (partial) specializations are never added as results.
535   if (isa<ClassTemplateSpecializationDecl>(ND) ||
536       isa<ClassTemplatePartialSpecializationDecl>(ND))
537     return false;
538 
539   // Using declarations themselves are never added as results.
540   if (isa<UsingDecl>(ND))
541     return false;
542 
543   if (shouldIgnoreDueToReservedName(ND, SemaRef))
544     return false;
545 
546   if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
547       (isa<NamespaceDecl>(ND) &&
548        Filter != &ResultBuilder::IsNamespace &&
549        Filter != &ResultBuilder::IsNamespaceOrAlias &&
550        Filter != nullptr))
551     AsNestedNameSpecifier = true;
552 
553   // Filter out any unwanted results.
554   if (Filter && !(this->*Filter)(Named)) {
555     // Check whether it is interesting as a nested-name-specifier.
556     if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
557         IsNestedNameSpecifier(ND) &&
558         (Filter != &ResultBuilder::IsMember ||
559          (isa<CXXRecordDecl>(ND) &&
560           cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
561       AsNestedNameSpecifier = true;
562       return true;
563     }
564 
565     return false;
566   }
567   // ... then it must be interesting!
568   return true;
569 }
570 
571 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
572                                       const NamedDecl *Hiding) {
573   // In C, there is no way to refer to a hidden name.
574   // FIXME: This isn't true; we can find a tag name hidden by an ordinary
575   // name if we introduce the tag type.
576   if (!SemaRef.getLangOpts().CPlusPlus)
577     return true;
578 
579   const DeclContext *HiddenCtx =
580       R.Declaration->getDeclContext()->getRedeclContext();
581 
582   // There is no way to qualify a name declared in a function or method.
583   if (HiddenCtx->isFunctionOrMethod())
584     return true;
585 
586   if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
587     return true;
588 
589   // We can refer to the result with the appropriate qualification. Do it.
590   R.Hidden = true;
591   R.QualifierIsInformative = false;
592 
593   if (!R.Qualifier)
594     R.Qualifier = getRequiredQualification(SemaRef.Context,
595                                            CurContext,
596                                            R.Declaration->getDeclContext());
597   return false;
598 }
599 
600 /// \brief A simplified classification of types used to determine whether two
601 /// types are "similar enough" when adjusting priorities.
602 SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
603   switch (T->getTypeClass()) {
604   case Type::Builtin:
605     switch (cast<BuiltinType>(T)->getKind()) {
606       case BuiltinType::Void:
607         return STC_Void;
608 
609       case BuiltinType::NullPtr:
610         return STC_Pointer;
611 
612       case BuiltinType::Overload:
613       case BuiltinType::Dependent:
614         return STC_Other;
615 
616       case BuiltinType::ObjCId:
617       case BuiltinType::ObjCClass:
618       case BuiltinType::ObjCSel:
619         return STC_ObjectiveC;
620 
621       default:
622         return STC_Arithmetic;
623     }
624 
625   case Type::Complex:
626     return STC_Arithmetic;
627 
628   case Type::Pointer:
629     return STC_Pointer;
630 
631   case Type::BlockPointer:
632     return STC_Block;
633 
634   case Type::LValueReference:
635   case Type::RValueReference:
636     return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
637 
638   case Type::ConstantArray:
639   case Type::IncompleteArray:
640   case Type::VariableArray:
641   case Type::DependentSizedArray:
642     return STC_Array;
643 
644   case Type::DependentSizedExtVector:
645   case Type::Vector:
646   case Type::ExtVector:
647     return STC_Arithmetic;
648 
649   case Type::FunctionProto:
650   case Type::FunctionNoProto:
651     return STC_Function;
652 
653   case Type::Record:
654     return STC_Record;
655 
656   case Type::Enum:
657     return STC_Arithmetic;
658 
659   case Type::ObjCObject:
660   case Type::ObjCInterface:
661   case Type::ObjCObjectPointer:
662     return STC_ObjectiveC;
663 
664   default:
665     return STC_Other;
666   }
667 }
668 
669 /// \brief Get the type that a given expression will have if this declaration
670 /// is used as an expression in its "typical" code-completion form.
671 QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
672   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
673 
674   if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND))
675     return C.getTypeDeclType(Type);
676   if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
677     return C.getObjCInterfaceType(Iface);
678 
679   QualType T;
680   if (const FunctionDecl *Function = ND->getAsFunction())
681     T = Function->getCallResultType();
682   else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
683     T = Method->getSendResultType();
684   else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
685     T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
686   else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
687     T = Property->getType();
688   else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND))
689     T = Value->getType();
690   else
691     return QualType();
692 
693   // Dig through references, function pointers, and block pointers to
694   // get down to the likely type of an expression when the entity is
695   // used.
696   do {
697     if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
698       T = Ref->getPointeeType();
699       continue;
700     }
701 
702     if (const PointerType *Pointer = T->getAs<PointerType>()) {
703       if (Pointer->getPointeeType()->isFunctionType()) {
704         T = Pointer->getPointeeType();
705         continue;
706       }
707 
708       break;
709     }
710 
711     if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
712       T = Block->getPointeeType();
713       continue;
714     }
715 
716     if (const FunctionType *Function = T->getAs<FunctionType>()) {
717       T = Function->getReturnType();
718       continue;
719     }
720 
721     break;
722   } while (true);
723 
724   return T;
725 }
726 
727 unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
728   if (!ND)
729     return CCP_Unlikely;
730 
731   // Context-based decisions.
732   const DeclContext *LexicalDC = ND->getLexicalDeclContext();
733   if (LexicalDC->isFunctionOrMethod()) {
734     // _cmd is relatively rare
735     if (const ImplicitParamDecl *ImplicitParam =
736         dyn_cast<ImplicitParamDecl>(ND))
737       if (ImplicitParam->getIdentifier() &&
738           ImplicitParam->getIdentifier()->isStr("_cmd"))
739         return CCP_ObjC_cmd;
740 
741     return CCP_LocalDeclaration;
742   }
743 
744   const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
745   if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
746     // Explicit destructor calls are very rare.
747     if (isa<CXXDestructorDecl>(ND))
748       return CCP_Unlikely;
749     // Explicit operator and conversion function calls are also very rare.
750     auto DeclNameKind = ND->getDeclName().getNameKind();
751     if (DeclNameKind == DeclarationName::CXXOperatorName ||
752         DeclNameKind == DeclarationName::CXXLiteralOperatorName ||
753         DeclNameKind == DeclarationName::CXXConversionFunctionName)
754       return CCP_Unlikely;
755     return CCP_MemberDeclaration;
756   }
757 
758   // Content-based decisions.
759   if (isa<EnumConstantDecl>(ND))
760     return CCP_Constant;
761 
762   // Use CCP_Type for type declarations unless we're in a statement, Objective-C
763   // message receiver, or parenthesized expression context. There, it's as
764   // likely that the user will want to write a type as other declarations.
765   if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
766       !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
767         CompletionContext.getKind()
768           == CodeCompletionContext::CCC_ObjCMessageReceiver ||
769         CompletionContext.getKind()
770           == CodeCompletionContext::CCC_ParenthesizedExpression))
771     return CCP_Type;
772 
773   return CCP_Declaration;
774 }
775 
776 void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
777   // If this is an Objective-C method declaration whose selector matches our
778   // preferred selector, give it a priority boost.
779   if (!PreferredSelector.isNull())
780     if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
781       if (PreferredSelector == Method->getSelector())
782         R.Priority += CCD_SelectorMatch;
783 
784   // If we have a preferred type, adjust the priority for results with exactly-
785   // matching or nearly-matching types.
786   if (!PreferredType.isNull()) {
787     QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
788     if (!T.isNull()) {
789       CanQualType TC = SemaRef.Context.getCanonicalType(T);
790       // Check for exactly-matching types (modulo qualifiers).
791       if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
792         R.Priority /= CCF_ExactTypeMatch;
793       // Check for nearly-matching types, based on classification of each.
794       else if ((getSimplifiedTypeClass(PreferredType)
795                                                == getSimplifiedTypeClass(TC)) &&
796                !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
797         R.Priority /= CCF_SimilarTypeMatch;
798     }
799   }
800 }
801 
802 void ResultBuilder::MaybeAddConstructorResults(Result R) {
803   if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
804       !CompletionContext.wantConstructorResults())
805     return;
806 
807   ASTContext &Context = SemaRef.Context;
808   const NamedDecl *D = R.Declaration;
809   const CXXRecordDecl *Record = nullptr;
810   if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
811     Record = ClassTemplate->getTemplatedDecl();
812   else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
813     // Skip specializations and partial specializations.
814     if (isa<ClassTemplateSpecializationDecl>(Record))
815       return;
816   } else {
817     // There are no constructors here.
818     return;
819   }
820 
821   Record = Record->getDefinition();
822   if (!Record)
823     return;
824 
825 
826   QualType RecordTy = Context.getTypeDeclType(Record);
827   DeclarationName ConstructorName
828     = Context.DeclarationNames.getCXXConstructorName(
829                                            Context.getCanonicalType(RecordTy));
830   DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
831   for (DeclContext::lookup_iterator I = Ctors.begin(),
832                                           E = Ctors.end();
833        I != E; ++I) {
834     R.Declaration = *I;
835     R.CursorKind = getCursorKindForDecl(R.Declaration);
836     Results.push_back(R);
837   }
838 }
839 
840 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
841   assert(!ShadowMaps.empty() && "Must enter into a results scope");
842 
843   if (R.Kind != Result::RK_Declaration) {
844     // For non-declaration results, just add the result.
845     Results.push_back(R);
846     return;
847   }
848 
849   // Look through using declarations.
850   if (const UsingShadowDecl *Using =
851           dyn_cast<UsingShadowDecl>(R.Declaration)) {
852     MaybeAddResult(Result(Using->getTargetDecl(),
853                           getBasePriority(Using->getTargetDecl()),
854                           R.Qualifier),
855                    CurContext);
856     return;
857   }
858 
859   const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
860   unsigned IDNS = CanonDecl->getIdentifierNamespace();
861 
862   bool AsNestedNameSpecifier = false;
863   if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
864     return;
865 
866   // C++ constructors are never found by name lookup.
867   if (isa<CXXConstructorDecl>(R.Declaration))
868     return;
869 
870   ShadowMap &SMap = ShadowMaps.back();
871   ShadowMapEntry::iterator I, IEnd;
872   ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
873   if (NamePos != SMap.end()) {
874     I = NamePos->second.begin();
875     IEnd = NamePos->second.end();
876   }
877 
878   for (; I != IEnd; ++I) {
879     const NamedDecl *ND = I->first;
880     unsigned Index = I->second;
881     if (ND->getCanonicalDecl() == CanonDecl) {
882       // This is a redeclaration. Always pick the newer declaration.
883       Results[Index].Declaration = R.Declaration;
884 
885       // We're done.
886       return;
887     }
888   }
889 
890   // This is a new declaration in this scope. However, check whether this
891   // declaration name is hidden by a similarly-named declaration in an outer
892   // scope.
893   std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
894   --SMEnd;
895   for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
896     ShadowMapEntry::iterator I, IEnd;
897     ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
898     if (NamePos != SM->end()) {
899       I = NamePos->second.begin();
900       IEnd = NamePos->second.end();
901     }
902     for (; I != IEnd; ++I) {
903       // A tag declaration does not hide a non-tag declaration.
904       if (I->first->hasTagIdentifierNamespace() &&
905           (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
906                    Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
907         continue;
908 
909       // Protocols are in distinct namespaces from everything else.
910       if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
911            || (IDNS & Decl::IDNS_ObjCProtocol)) &&
912           I->first->getIdentifierNamespace() != IDNS)
913         continue;
914 
915       // The newly-added result is hidden by an entry in the shadow map.
916       if (CheckHiddenResult(R, CurContext, I->first))
917         return;
918 
919       break;
920     }
921   }
922 
923   // Make sure that any given declaration only shows up in the result set once.
924   if (!AllDeclsFound.insert(CanonDecl).second)
925     return;
926 
927   // If the filter is for nested-name-specifiers, then this result starts a
928   // nested-name-specifier.
929   if (AsNestedNameSpecifier) {
930     R.StartsNestedNameSpecifier = true;
931     R.Priority = CCP_NestedNameSpecifier;
932   } else
933       AdjustResultPriorityForDecl(R);
934 
935   // If this result is supposed to have an informative qualifier, add one.
936   if (R.QualifierIsInformative && !R.Qualifier &&
937       !R.StartsNestedNameSpecifier) {
938     const DeclContext *Ctx = R.Declaration->getDeclContext();
939     if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
940       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
941                                                 Namespace);
942     else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
943       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
944                       false, SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
945     else
946       R.QualifierIsInformative = false;
947   }
948 
949   // Insert this result into the set of results and into the current shadow
950   // map.
951   SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
952   Results.push_back(R);
953 
954   if (!AsNestedNameSpecifier)
955     MaybeAddConstructorResults(R);
956 }
957 
958 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
959                               NamedDecl *Hiding, bool InBaseClass = false) {
960   if (R.Kind != Result::RK_Declaration) {
961     // For non-declaration results, just add the result.
962     Results.push_back(R);
963     return;
964   }
965 
966   // Look through using declarations.
967   if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
968     AddResult(Result(Using->getTargetDecl(),
969                      getBasePriority(Using->getTargetDecl()),
970                      R.Qualifier),
971               CurContext, Hiding);
972     return;
973   }
974 
975   bool AsNestedNameSpecifier = false;
976   if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
977     return;
978 
979   // C++ constructors are never found by name lookup.
980   if (isa<CXXConstructorDecl>(R.Declaration))
981     return;
982 
983   if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
984     return;
985 
986   // Make sure that any given declaration only shows up in the result set once.
987   if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
988     return;
989 
990   // If the filter is for nested-name-specifiers, then this result starts a
991   // nested-name-specifier.
992   if (AsNestedNameSpecifier) {
993     R.StartsNestedNameSpecifier = true;
994     R.Priority = CCP_NestedNameSpecifier;
995   }
996   else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
997            isa<CXXRecordDecl>(R.Declaration->getDeclContext()
998                                                   ->getRedeclContext()))
999     R.QualifierIsInformative = true;
1000 
1001   // If this result is supposed to have an informative qualifier, add one.
1002   if (R.QualifierIsInformative && !R.Qualifier &&
1003       !R.StartsNestedNameSpecifier) {
1004     const DeclContext *Ctx = R.Declaration->getDeclContext();
1005     if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1006       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
1007                                                 Namespace);
1008     else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
1009       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, false,
1010                             SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1011     else
1012       R.QualifierIsInformative = false;
1013   }
1014 
1015   // Adjust the priority if this result comes from a base class.
1016   if (InBaseClass)
1017     R.Priority += CCD_InBaseClass;
1018 
1019   AdjustResultPriorityForDecl(R);
1020 
1021   if (HasObjectTypeQualifiers)
1022     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
1023       if (Method->isInstance()) {
1024         Qualifiers MethodQuals
1025                         = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1026         if (ObjectTypeQualifiers == MethodQuals)
1027           R.Priority += CCD_ObjectQualifierMatch;
1028         else if (ObjectTypeQualifiers - MethodQuals) {
1029           // The method cannot be invoked, because doing so would drop
1030           // qualifiers.
1031           return;
1032         }
1033       }
1034 
1035   // Insert this result into the set of results.
1036   Results.push_back(R);
1037 
1038   if (!AsNestedNameSpecifier)
1039     MaybeAddConstructorResults(R);
1040 }
1041 
1042 void ResultBuilder::AddResult(Result R) {
1043   assert(R.Kind != Result::RK_Declaration &&
1044           "Declaration results need more context");
1045   Results.push_back(R);
1046 }
1047 
1048 /// \brief Enter into a new scope.
1049 void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1050 
1051 /// \brief Exit from the current scope.
1052 void ResultBuilder::ExitScope() {
1053   for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1054                         EEnd = ShadowMaps.back().end();
1055        E != EEnd;
1056        ++E)
1057     E->second.Destroy();
1058 
1059   ShadowMaps.pop_back();
1060 }
1061 
1062 /// \brief Determines whether this given declaration will be found by
1063 /// ordinary name lookup.
1064 bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1065   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1066 
1067   // If name lookup finds a local extern declaration, then we are in a
1068   // context where it behaves like an ordinary name.
1069   unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1070   if (SemaRef.getLangOpts().CPlusPlus)
1071     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1072   else if (SemaRef.getLangOpts().ObjC1) {
1073     if (isa<ObjCIvarDecl>(ND))
1074       return true;
1075   }
1076 
1077   return ND->getIdentifierNamespace() & IDNS;
1078 }
1079 
1080 /// \brief Determines whether this given declaration will be found by
1081 /// ordinary name lookup but is not a type name.
1082 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1083   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1084   if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1085     return false;
1086 
1087   unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1088   if (SemaRef.getLangOpts().CPlusPlus)
1089     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1090   else if (SemaRef.getLangOpts().ObjC1) {
1091     if (isa<ObjCIvarDecl>(ND))
1092       return true;
1093   }
1094 
1095   return ND->getIdentifierNamespace() & IDNS;
1096 }
1097 
1098 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1099   if (!IsOrdinaryNonTypeName(ND))
1100     return 0;
1101 
1102   if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1103     if (VD->getType()->isIntegralOrEnumerationType())
1104       return true;
1105 
1106   return false;
1107 }
1108 
1109 /// \brief Determines whether this given declaration will be found by
1110 /// ordinary name lookup.
1111 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1112   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1113 
1114   unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1115   if (SemaRef.getLangOpts().CPlusPlus)
1116     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
1117 
1118   return (ND->getIdentifierNamespace() & IDNS) &&
1119     !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1120     !isa<ObjCPropertyDecl>(ND);
1121 }
1122 
1123 /// \brief Determines whether the given declaration is suitable as the
1124 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1125 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1126   // Allow us to find class templates, too.
1127   if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1128     ND = ClassTemplate->getTemplatedDecl();
1129 
1130   return SemaRef.isAcceptableNestedNameSpecifier(ND);
1131 }
1132 
1133 /// \brief Determines whether the given declaration is an enumeration.
1134 bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1135   return isa<EnumDecl>(ND);
1136 }
1137 
1138 /// \brief Determines whether the given declaration is a class or struct.
1139 bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1140   // Allow us to find class templates, too.
1141   if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1142     ND = ClassTemplate->getTemplatedDecl();
1143 
1144   // For purposes of this check, interfaces match too.
1145   if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1146     return RD->getTagKind() == TTK_Class ||
1147     RD->getTagKind() == TTK_Struct ||
1148     RD->getTagKind() == TTK_Interface;
1149 
1150   return false;
1151 }
1152 
1153 /// \brief Determines whether the given declaration is a union.
1154 bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1155   // Allow us to find class templates, too.
1156   if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1157     ND = ClassTemplate->getTemplatedDecl();
1158 
1159   if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1160     return RD->getTagKind() == TTK_Union;
1161 
1162   return false;
1163 }
1164 
1165 /// \brief Determines whether the given declaration is a namespace.
1166 bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1167   return isa<NamespaceDecl>(ND);
1168 }
1169 
1170 /// \brief Determines whether the given declaration is a namespace or
1171 /// namespace alias.
1172 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1173   return isa<NamespaceDecl>(ND->getUnderlyingDecl());
1174 }
1175 
1176 /// \brief Determines whether the given declaration is a type.
1177 bool ResultBuilder::IsType(const NamedDecl *ND) const {
1178   ND = ND->getUnderlyingDecl();
1179   return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1180 }
1181 
1182 /// \brief Determines which members of a class should be visible via
1183 /// "." or "->".  Only value declarations, nested name specifiers, and
1184 /// using declarations thereof should show up.
1185 bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1186   ND = ND->getUnderlyingDecl();
1187   return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1188          isa<ObjCPropertyDecl>(ND);
1189 }
1190 
1191 static bool isObjCReceiverType(ASTContext &C, QualType T) {
1192   T = C.getCanonicalType(T);
1193   switch (T->getTypeClass()) {
1194   case Type::ObjCObject:
1195   case Type::ObjCInterface:
1196   case Type::ObjCObjectPointer:
1197     return true;
1198 
1199   case Type::Builtin:
1200     switch (cast<BuiltinType>(T)->getKind()) {
1201     case BuiltinType::ObjCId:
1202     case BuiltinType::ObjCClass:
1203     case BuiltinType::ObjCSel:
1204       return true;
1205 
1206     default:
1207       break;
1208     }
1209     return false;
1210 
1211   default:
1212     break;
1213   }
1214 
1215   if (!C.getLangOpts().CPlusPlus)
1216     return false;
1217 
1218   // FIXME: We could perform more analysis here to determine whether a
1219   // particular class type has any conversions to Objective-C types. For now,
1220   // just accept all class types.
1221   return T->isDependentType() || T->isRecordType();
1222 }
1223 
1224 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1225   QualType T = getDeclUsageType(SemaRef.Context, ND);
1226   if (T.isNull())
1227     return false;
1228 
1229   T = SemaRef.Context.getBaseElementType(T);
1230   return isObjCReceiverType(SemaRef.Context, T);
1231 }
1232 
1233 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const {
1234   if (IsObjCMessageReceiver(ND))
1235     return true;
1236 
1237   const VarDecl *Var = dyn_cast<VarDecl>(ND);
1238   if (!Var)
1239     return false;
1240 
1241   return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1242 }
1243 
1244 bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1245   if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1246       (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1247     return false;
1248 
1249   QualType T = getDeclUsageType(SemaRef.Context, ND);
1250   if (T.isNull())
1251     return false;
1252 
1253   T = SemaRef.Context.getBaseElementType(T);
1254   return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1255          T->isObjCIdType() ||
1256          (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1257 }
1258 
1259 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1260   return false;
1261 }
1262 
1263 /// \brief Determines whether the given declaration is an Objective-C
1264 /// instance variable.
1265 bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1266   return isa<ObjCIvarDecl>(ND);
1267 }
1268 
1269 namespace {
1270   /// \brief Visible declaration consumer that adds a code-completion result
1271   /// for each visible declaration.
1272   class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1273     ResultBuilder &Results;
1274     DeclContext *CurContext;
1275 
1276   public:
1277     CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1278       : Results(Results), CurContext(CurContext) { }
1279 
1280     void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1281                    bool InBaseClass) override {
1282       bool Accessible = true;
1283       if (Ctx)
1284         Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
1285 
1286       ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1287                                    false, Accessible);
1288       Results.AddResult(Result, CurContext, Hiding, InBaseClass);
1289     }
1290   };
1291 }
1292 
1293 /// \brief Add type specifiers for the current language as keyword results.
1294 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1295                                     ResultBuilder &Results) {
1296   typedef CodeCompletionResult Result;
1297   Results.AddResult(Result("short", CCP_Type));
1298   Results.AddResult(Result("long", CCP_Type));
1299   Results.AddResult(Result("signed", CCP_Type));
1300   Results.AddResult(Result("unsigned", CCP_Type));
1301   Results.AddResult(Result("void", CCP_Type));
1302   Results.AddResult(Result("char", CCP_Type));
1303   Results.AddResult(Result("int", CCP_Type));
1304   Results.AddResult(Result("float", CCP_Type));
1305   Results.AddResult(Result("double", CCP_Type));
1306   Results.AddResult(Result("enum", CCP_Type));
1307   Results.AddResult(Result("struct", CCP_Type));
1308   Results.AddResult(Result("union", CCP_Type));
1309   Results.AddResult(Result("const", CCP_Type));
1310   Results.AddResult(Result("volatile", CCP_Type));
1311 
1312   if (LangOpts.C99) {
1313     // C99-specific
1314     Results.AddResult(Result("_Complex", CCP_Type));
1315     Results.AddResult(Result("_Imaginary", CCP_Type));
1316     Results.AddResult(Result("_Bool", CCP_Type));
1317     Results.AddResult(Result("restrict", CCP_Type));
1318   }
1319 
1320   CodeCompletionBuilder Builder(Results.getAllocator(),
1321                                 Results.getCodeCompletionTUInfo());
1322   if (LangOpts.CPlusPlus) {
1323     // C++-specific
1324     Results.AddResult(Result("bool", CCP_Type +
1325                              (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
1326     Results.AddResult(Result("class", CCP_Type));
1327     Results.AddResult(Result("wchar_t", CCP_Type));
1328 
1329     // typename qualified-id
1330     Builder.AddTypedTextChunk("typename");
1331     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1332     Builder.AddPlaceholderChunk("qualifier");
1333     Builder.AddTextChunk("::");
1334     Builder.AddPlaceholderChunk("name");
1335     Results.AddResult(Result(Builder.TakeString()));
1336 
1337     if (LangOpts.CPlusPlus11) {
1338       Results.AddResult(Result("auto", CCP_Type));
1339       Results.AddResult(Result("char16_t", CCP_Type));
1340       Results.AddResult(Result("char32_t", CCP_Type));
1341 
1342       Builder.AddTypedTextChunk("decltype");
1343       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1344       Builder.AddPlaceholderChunk("expression");
1345       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1346       Results.AddResult(Result(Builder.TakeString()));
1347     }
1348   } else
1349     Results.AddResult(Result("__auto_type", CCP_Type));
1350 
1351   // GNU extensions
1352   if (LangOpts.GNUMode) {
1353     // FIXME: Enable when we actually support decimal floating point.
1354     //    Results.AddResult(Result("_Decimal32"));
1355     //    Results.AddResult(Result("_Decimal64"));
1356     //    Results.AddResult(Result("_Decimal128"));
1357 
1358     Builder.AddTypedTextChunk("typeof");
1359     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1360     Builder.AddPlaceholderChunk("expression");
1361     Results.AddResult(Result(Builder.TakeString()));
1362 
1363     Builder.AddTypedTextChunk("typeof");
1364     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1365     Builder.AddPlaceholderChunk("type");
1366     Builder.AddChunk(CodeCompletionString::CK_RightParen);
1367     Results.AddResult(Result(Builder.TakeString()));
1368   }
1369 
1370   // Nullability
1371   Results.AddResult(Result("_Nonnull", CCP_Type));
1372   Results.AddResult(Result("_Null_unspecified", CCP_Type));
1373   Results.AddResult(Result("_Nullable", CCP_Type));
1374 }
1375 
1376 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1377                                  const LangOptions &LangOpts,
1378                                  ResultBuilder &Results) {
1379   typedef CodeCompletionResult Result;
1380   // Note: we don't suggest either "auto" or "register", because both
1381   // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1382   // in C++0x as a type specifier.
1383   Results.AddResult(Result("extern"));
1384   Results.AddResult(Result("static"));
1385 
1386   if (LangOpts.CPlusPlus11) {
1387     CodeCompletionAllocator &Allocator = Results.getAllocator();
1388     CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1389 
1390     // alignas
1391     Builder.AddTypedTextChunk("alignas");
1392     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1393     Builder.AddPlaceholderChunk("expression");
1394     Builder.AddChunk(CodeCompletionString::CK_RightParen);
1395     Results.AddResult(Result(Builder.TakeString()));
1396 
1397     Results.AddResult(Result("constexpr"));
1398     Results.AddResult(Result("thread_local"));
1399   }
1400 }
1401 
1402 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1403                                   const LangOptions &LangOpts,
1404                                   ResultBuilder &Results) {
1405   typedef CodeCompletionResult Result;
1406   switch (CCC) {
1407   case Sema::PCC_Class:
1408   case Sema::PCC_MemberTemplate:
1409     if (LangOpts.CPlusPlus) {
1410       Results.AddResult(Result("explicit"));
1411       Results.AddResult(Result("friend"));
1412       Results.AddResult(Result("mutable"));
1413       Results.AddResult(Result("virtual"));
1414     }
1415     // Fall through
1416 
1417   case Sema::PCC_ObjCInterface:
1418   case Sema::PCC_ObjCImplementation:
1419   case Sema::PCC_Namespace:
1420   case Sema::PCC_Template:
1421     if (LangOpts.CPlusPlus || LangOpts.C99)
1422       Results.AddResult(Result("inline"));
1423     break;
1424 
1425   case Sema::PCC_ObjCInstanceVariableList:
1426   case Sema::PCC_Expression:
1427   case Sema::PCC_Statement:
1428   case Sema::PCC_ForInit:
1429   case Sema::PCC_Condition:
1430   case Sema::PCC_RecoveryInFunction:
1431   case Sema::PCC_Type:
1432   case Sema::PCC_ParenthesizedExpression:
1433   case Sema::PCC_LocalDeclarationSpecifiers:
1434     break;
1435   }
1436 }
1437 
1438 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1439 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1440 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1441                                      ResultBuilder &Results,
1442                                      bool NeedAt);
1443 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1444                                          ResultBuilder &Results,
1445                                          bool NeedAt);
1446 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1447                                     ResultBuilder &Results,
1448                                     bool NeedAt);
1449 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1450 
1451 static void AddTypedefResult(ResultBuilder &Results) {
1452   CodeCompletionBuilder Builder(Results.getAllocator(),
1453                                 Results.getCodeCompletionTUInfo());
1454   Builder.AddTypedTextChunk("typedef");
1455   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1456   Builder.AddPlaceholderChunk("type");
1457   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1458   Builder.AddPlaceholderChunk("name");
1459   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1460 }
1461 
1462 static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1463                                const LangOptions &LangOpts) {
1464   switch (CCC) {
1465   case Sema::PCC_Namespace:
1466   case Sema::PCC_Class:
1467   case Sema::PCC_ObjCInstanceVariableList:
1468   case Sema::PCC_Template:
1469   case Sema::PCC_MemberTemplate:
1470   case Sema::PCC_Statement:
1471   case Sema::PCC_RecoveryInFunction:
1472   case Sema::PCC_Type:
1473   case Sema::PCC_ParenthesizedExpression:
1474   case Sema::PCC_LocalDeclarationSpecifiers:
1475     return true;
1476 
1477   case Sema::PCC_Expression:
1478   case Sema::PCC_Condition:
1479     return LangOpts.CPlusPlus;
1480 
1481   case Sema::PCC_ObjCInterface:
1482   case Sema::PCC_ObjCImplementation:
1483     return false;
1484 
1485   case Sema::PCC_ForInit:
1486     return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
1487   }
1488 
1489   llvm_unreachable("Invalid ParserCompletionContext!");
1490 }
1491 
1492 static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1493                                                   const Preprocessor &PP) {
1494   PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1495   Policy.AnonymousTagLocations = false;
1496   Policy.SuppressStrongLifetime = true;
1497   Policy.SuppressUnwrittenScope = true;
1498   return Policy;
1499 }
1500 
1501 /// \brief Retrieve a printing policy suitable for code completion.
1502 static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1503   return getCompletionPrintingPolicy(S.Context, S.PP);
1504 }
1505 
1506 /// \brief Retrieve the string representation of the given type as a string
1507 /// that has the appropriate lifetime for code completion.
1508 ///
1509 /// This routine provides a fast path where we provide constant strings for
1510 /// common type names.
1511 static const char *GetCompletionTypeString(QualType T,
1512                                            ASTContext &Context,
1513                                            const PrintingPolicy &Policy,
1514                                            CodeCompletionAllocator &Allocator) {
1515   if (!T.getLocalQualifiers()) {
1516     // Built-in type names are constant strings.
1517     if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1518       return BT->getNameAsCString(Policy);
1519 
1520     // Anonymous tag types are constant strings.
1521     if (const TagType *TagT = dyn_cast<TagType>(T))
1522       if (TagDecl *Tag = TagT->getDecl())
1523         if (!Tag->hasNameForLinkage()) {
1524           switch (Tag->getTagKind()) {
1525           case TTK_Struct: return "struct <anonymous>";
1526           case TTK_Interface: return "__interface <anonymous>";
1527           case TTK_Class:  return "class <anonymous>";
1528           case TTK_Union:  return "union <anonymous>";
1529           case TTK_Enum:   return "enum <anonymous>";
1530           }
1531         }
1532   }
1533 
1534   // Slow path: format the type as a string.
1535   std::string Result;
1536   T.getAsStringInternal(Result, Policy);
1537   return Allocator.CopyString(Result);
1538 }
1539 
1540 /// \brief Add a completion for "this", if we're in a member function.
1541 static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1542   QualType ThisTy = S.getCurrentThisType();
1543   if (ThisTy.isNull())
1544     return;
1545 
1546   CodeCompletionAllocator &Allocator = Results.getAllocator();
1547   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1548   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1549   Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1550                                                      S.Context,
1551                                                      Policy,
1552                                                      Allocator));
1553   Builder.AddTypedTextChunk("this");
1554   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1555 }
1556 
1557 static void AddStaticAssertResult(CodeCompletionBuilder &Builder,
1558                                   ResultBuilder &Results,
1559                                   const LangOptions &LangOpts) {
1560   if (!LangOpts.CPlusPlus11)
1561     return;
1562 
1563   Builder.AddTypedTextChunk("static_assert");
1564   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1565   Builder.AddPlaceholderChunk("expression");
1566   Builder.AddChunk(CodeCompletionString::CK_Comma);
1567   Builder.AddPlaceholderChunk("message");
1568   Builder.AddChunk(CodeCompletionString::CK_RightParen);
1569   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1570 }
1571 
1572 /// \brief Add language constructs that show up for "ordinary" names.
1573 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
1574                                    Scope *S,
1575                                    Sema &SemaRef,
1576                                    ResultBuilder &Results) {
1577   CodeCompletionAllocator &Allocator = Results.getAllocator();
1578   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1579 
1580   typedef CodeCompletionResult Result;
1581   switch (CCC) {
1582   case Sema::PCC_Namespace:
1583     if (SemaRef.getLangOpts().CPlusPlus) {
1584       if (Results.includeCodePatterns()) {
1585         // namespace <identifier> { declarations }
1586         Builder.AddTypedTextChunk("namespace");
1587         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1588         Builder.AddPlaceholderChunk("identifier");
1589         Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1590         Builder.AddPlaceholderChunk("declarations");
1591         Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1592         Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1593         Results.AddResult(Result(Builder.TakeString()));
1594       }
1595 
1596       // namespace identifier = identifier ;
1597       Builder.AddTypedTextChunk("namespace");
1598       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1599       Builder.AddPlaceholderChunk("name");
1600       Builder.AddChunk(CodeCompletionString::CK_Equal);
1601       Builder.AddPlaceholderChunk("namespace");
1602       Results.AddResult(Result(Builder.TakeString()));
1603 
1604       // Using directives
1605       Builder.AddTypedTextChunk("using");
1606       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1607       Builder.AddTextChunk("namespace");
1608       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1609       Builder.AddPlaceholderChunk("identifier");
1610       Results.AddResult(Result(Builder.TakeString()));
1611 
1612       // asm(string-literal)
1613       Builder.AddTypedTextChunk("asm");
1614       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1615       Builder.AddPlaceholderChunk("string-literal");
1616       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1617       Results.AddResult(Result(Builder.TakeString()));
1618 
1619       if (Results.includeCodePatterns()) {
1620         // Explicit template instantiation
1621         Builder.AddTypedTextChunk("template");
1622         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1623         Builder.AddPlaceholderChunk("declaration");
1624         Results.AddResult(Result(Builder.TakeString()));
1625       }
1626     }
1627 
1628     if (SemaRef.getLangOpts().ObjC1)
1629       AddObjCTopLevelResults(Results, true);
1630 
1631     AddTypedefResult(Results);
1632     // Fall through
1633 
1634   case Sema::PCC_Class:
1635     if (SemaRef.getLangOpts().CPlusPlus) {
1636       // Using declaration
1637       Builder.AddTypedTextChunk("using");
1638       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1639       Builder.AddPlaceholderChunk("qualifier");
1640       Builder.AddTextChunk("::");
1641       Builder.AddPlaceholderChunk("name");
1642       Results.AddResult(Result(Builder.TakeString()));
1643 
1644       // using typename qualifier::name (only in a dependent context)
1645       if (SemaRef.CurContext->isDependentContext()) {
1646         Builder.AddTypedTextChunk("using");
1647         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1648         Builder.AddTextChunk("typename");
1649         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1650         Builder.AddPlaceholderChunk("qualifier");
1651         Builder.AddTextChunk("::");
1652         Builder.AddPlaceholderChunk("name");
1653         Results.AddResult(Result(Builder.TakeString()));
1654       }
1655 
1656       AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
1657 
1658       if (CCC == Sema::PCC_Class) {
1659         AddTypedefResult(Results);
1660 
1661         bool IsNotInheritanceScope =
1662             !(S->getFlags() & Scope::ClassInheritanceScope);
1663         // public:
1664         Builder.AddTypedTextChunk("public");
1665         if (IsNotInheritanceScope && Results.includeCodePatterns())
1666           Builder.AddChunk(CodeCompletionString::CK_Colon);
1667         Results.AddResult(Result(Builder.TakeString()));
1668 
1669         // protected:
1670         Builder.AddTypedTextChunk("protected");
1671         if (IsNotInheritanceScope && Results.includeCodePatterns())
1672           Builder.AddChunk(CodeCompletionString::CK_Colon);
1673         Results.AddResult(Result(Builder.TakeString()));
1674 
1675         // private:
1676         Builder.AddTypedTextChunk("private");
1677         if (IsNotInheritanceScope && Results.includeCodePatterns())
1678           Builder.AddChunk(CodeCompletionString::CK_Colon);
1679         Results.AddResult(Result(Builder.TakeString()));
1680       }
1681     }
1682     // Fall through
1683 
1684   case Sema::PCC_Template:
1685   case Sema::PCC_MemberTemplate:
1686     if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
1687       // template < parameters >
1688       Builder.AddTypedTextChunk("template");
1689       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1690       Builder.AddPlaceholderChunk("parameters");
1691       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1692       Results.AddResult(Result(Builder.TakeString()));
1693     }
1694 
1695     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1696     AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1697     break;
1698 
1699   case Sema::PCC_ObjCInterface:
1700     AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1701     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1702     AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1703     break;
1704 
1705   case Sema::PCC_ObjCImplementation:
1706     AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1707     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1708     AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1709     break;
1710 
1711   case Sema::PCC_ObjCInstanceVariableList:
1712     AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
1713     break;
1714 
1715   case Sema::PCC_RecoveryInFunction:
1716   case Sema::PCC_Statement: {
1717     AddTypedefResult(Results);
1718 
1719     if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1720         SemaRef.getLangOpts().CXXExceptions) {
1721       Builder.AddTypedTextChunk("try");
1722       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1723       Builder.AddPlaceholderChunk("statements");
1724       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1725       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1726       Builder.AddTextChunk("catch");
1727       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1728       Builder.AddPlaceholderChunk("declaration");
1729       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1730       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1731       Builder.AddPlaceholderChunk("statements");
1732       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1733       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1734       Results.AddResult(Result(Builder.TakeString()));
1735     }
1736     if (SemaRef.getLangOpts().ObjC1)
1737       AddObjCStatementResults(Results, true);
1738 
1739     if (Results.includeCodePatterns()) {
1740       // if (condition) { statements }
1741       Builder.AddTypedTextChunk("if");
1742       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1743       if (SemaRef.getLangOpts().CPlusPlus)
1744         Builder.AddPlaceholderChunk("condition");
1745       else
1746         Builder.AddPlaceholderChunk("expression");
1747       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1748       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1749       Builder.AddPlaceholderChunk("statements");
1750       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1751       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1752       Results.AddResult(Result(Builder.TakeString()));
1753 
1754       // switch (condition) { }
1755       Builder.AddTypedTextChunk("switch");
1756       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1757       if (SemaRef.getLangOpts().CPlusPlus)
1758         Builder.AddPlaceholderChunk("condition");
1759       else
1760         Builder.AddPlaceholderChunk("expression");
1761       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1762       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1763       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1764       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1765       Results.AddResult(Result(Builder.TakeString()));
1766     }
1767 
1768     // Switch-specific statements.
1769     if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
1770       // case expression:
1771       Builder.AddTypedTextChunk("case");
1772       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1773       Builder.AddPlaceholderChunk("expression");
1774       Builder.AddChunk(CodeCompletionString::CK_Colon);
1775       Results.AddResult(Result(Builder.TakeString()));
1776 
1777       // default:
1778       Builder.AddTypedTextChunk("default");
1779       Builder.AddChunk(CodeCompletionString::CK_Colon);
1780       Results.AddResult(Result(Builder.TakeString()));
1781     }
1782 
1783     if (Results.includeCodePatterns()) {
1784       /// while (condition) { statements }
1785       Builder.AddTypedTextChunk("while");
1786       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1787       if (SemaRef.getLangOpts().CPlusPlus)
1788         Builder.AddPlaceholderChunk("condition");
1789       else
1790         Builder.AddPlaceholderChunk("expression");
1791       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1792       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1793       Builder.AddPlaceholderChunk("statements");
1794       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1795       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1796       Results.AddResult(Result(Builder.TakeString()));
1797 
1798       // do { statements } while ( expression );
1799       Builder.AddTypedTextChunk("do");
1800       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1801       Builder.AddPlaceholderChunk("statements");
1802       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1803       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1804       Builder.AddTextChunk("while");
1805       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1806       Builder.AddPlaceholderChunk("expression");
1807       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1808       Results.AddResult(Result(Builder.TakeString()));
1809 
1810       // for ( for-init-statement ; condition ; expression ) { statements }
1811       Builder.AddTypedTextChunk("for");
1812       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1813       if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
1814         Builder.AddPlaceholderChunk("init-statement");
1815       else
1816         Builder.AddPlaceholderChunk("init-expression");
1817       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1818       Builder.AddPlaceholderChunk("condition");
1819       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1820       Builder.AddPlaceholderChunk("inc-expression");
1821       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1822       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1823       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1824       Builder.AddPlaceholderChunk("statements");
1825       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1826       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1827       Results.AddResult(Result(Builder.TakeString()));
1828     }
1829 
1830     if (S->getContinueParent()) {
1831       // continue ;
1832       Builder.AddTypedTextChunk("continue");
1833       Results.AddResult(Result(Builder.TakeString()));
1834     }
1835 
1836     if (S->getBreakParent()) {
1837       // break ;
1838       Builder.AddTypedTextChunk("break");
1839       Results.AddResult(Result(Builder.TakeString()));
1840     }
1841 
1842     // "return expression ;" or "return ;", depending on whether we
1843     // know the function is void or not.
1844     bool isVoid = false;
1845     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1846       isVoid = Function->getReturnType()->isVoidType();
1847     else if (ObjCMethodDecl *Method
1848                                  = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1849       isVoid = Method->getReturnType()->isVoidType();
1850     else if (SemaRef.getCurBlock() &&
1851              !SemaRef.getCurBlock()->ReturnType.isNull())
1852       isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
1853     Builder.AddTypedTextChunk("return");
1854     if (!isVoid) {
1855       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1856       Builder.AddPlaceholderChunk("expression");
1857     }
1858     Results.AddResult(Result(Builder.TakeString()));
1859 
1860     // goto identifier ;
1861     Builder.AddTypedTextChunk("goto");
1862     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1863     Builder.AddPlaceholderChunk("label");
1864     Results.AddResult(Result(Builder.TakeString()));
1865 
1866     // Using directives
1867     Builder.AddTypedTextChunk("using");
1868     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1869     Builder.AddTextChunk("namespace");
1870     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1871     Builder.AddPlaceholderChunk("identifier");
1872     Results.AddResult(Result(Builder.TakeString()));
1873 
1874     AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
1875   }
1876   LLVM_FALLTHROUGH;
1877 
1878   // Fall through (for statement expressions).
1879   case Sema::PCC_ForInit:
1880   case Sema::PCC_Condition:
1881     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1882     // Fall through: conditions and statements can have expressions.
1883     LLVM_FALLTHROUGH;
1884 
1885   case Sema::PCC_ParenthesizedExpression:
1886     if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1887         CCC == Sema::PCC_ParenthesizedExpression) {
1888       // (__bridge <type>)<expression>
1889       Builder.AddTypedTextChunk("__bridge");
1890       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1891       Builder.AddPlaceholderChunk("type");
1892       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1893       Builder.AddPlaceholderChunk("expression");
1894       Results.AddResult(Result(Builder.TakeString()));
1895 
1896       // (__bridge_transfer <Objective-C type>)<expression>
1897       Builder.AddTypedTextChunk("__bridge_transfer");
1898       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1899       Builder.AddPlaceholderChunk("Objective-C type");
1900       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1901       Builder.AddPlaceholderChunk("expression");
1902       Results.AddResult(Result(Builder.TakeString()));
1903 
1904       // (__bridge_retained <CF type>)<expression>
1905       Builder.AddTypedTextChunk("__bridge_retained");
1906       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1907       Builder.AddPlaceholderChunk("CF type");
1908       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1909       Builder.AddPlaceholderChunk("expression");
1910       Results.AddResult(Result(Builder.TakeString()));
1911     }
1912     // Fall through
1913     LLVM_FALLTHROUGH;
1914 
1915   case Sema::PCC_Expression: {
1916     if (SemaRef.getLangOpts().CPlusPlus) {
1917       // 'this', if we're in a non-static member function.
1918       addThisCompletion(SemaRef, Results);
1919 
1920       // true
1921       Builder.AddResultTypeChunk("bool");
1922       Builder.AddTypedTextChunk("true");
1923       Results.AddResult(Result(Builder.TakeString()));
1924 
1925       // false
1926       Builder.AddResultTypeChunk("bool");
1927       Builder.AddTypedTextChunk("false");
1928       Results.AddResult(Result(Builder.TakeString()));
1929 
1930       if (SemaRef.getLangOpts().RTTI) {
1931         // dynamic_cast < type-id > ( expression )
1932         Builder.AddTypedTextChunk("dynamic_cast");
1933         Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1934         Builder.AddPlaceholderChunk("type");
1935         Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1936         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1937         Builder.AddPlaceholderChunk("expression");
1938         Builder.AddChunk(CodeCompletionString::CK_RightParen);
1939         Results.AddResult(Result(Builder.TakeString()));
1940       }
1941 
1942       // static_cast < type-id > ( expression )
1943       Builder.AddTypedTextChunk("static_cast");
1944       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1945       Builder.AddPlaceholderChunk("type");
1946       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1947       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1948       Builder.AddPlaceholderChunk("expression");
1949       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1950       Results.AddResult(Result(Builder.TakeString()));
1951 
1952       // reinterpret_cast < type-id > ( expression )
1953       Builder.AddTypedTextChunk("reinterpret_cast");
1954       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1955       Builder.AddPlaceholderChunk("type");
1956       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1957       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1958       Builder.AddPlaceholderChunk("expression");
1959       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1960       Results.AddResult(Result(Builder.TakeString()));
1961 
1962       // const_cast < type-id > ( expression )
1963       Builder.AddTypedTextChunk("const_cast");
1964       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1965       Builder.AddPlaceholderChunk("type");
1966       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1967       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1968       Builder.AddPlaceholderChunk("expression");
1969       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1970       Results.AddResult(Result(Builder.TakeString()));
1971 
1972       if (SemaRef.getLangOpts().RTTI) {
1973         // typeid ( expression-or-type )
1974         Builder.AddResultTypeChunk("std::type_info");
1975         Builder.AddTypedTextChunk("typeid");
1976         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1977         Builder.AddPlaceholderChunk("expression-or-type");
1978         Builder.AddChunk(CodeCompletionString::CK_RightParen);
1979         Results.AddResult(Result(Builder.TakeString()));
1980       }
1981 
1982       // new T ( ... )
1983       Builder.AddTypedTextChunk("new");
1984       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1985       Builder.AddPlaceholderChunk("type");
1986       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1987       Builder.AddPlaceholderChunk("expressions");
1988       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1989       Results.AddResult(Result(Builder.TakeString()));
1990 
1991       // new T [ ] ( ... )
1992       Builder.AddTypedTextChunk("new");
1993       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1994       Builder.AddPlaceholderChunk("type");
1995       Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1996       Builder.AddPlaceholderChunk("size");
1997       Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1998       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1999       Builder.AddPlaceholderChunk("expressions");
2000       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2001       Results.AddResult(Result(Builder.TakeString()));
2002 
2003       // delete expression
2004       Builder.AddResultTypeChunk("void");
2005       Builder.AddTypedTextChunk("delete");
2006       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2007       Builder.AddPlaceholderChunk("expression");
2008       Results.AddResult(Result(Builder.TakeString()));
2009 
2010       // delete [] expression
2011       Builder.AddResultTypeChunk("void");
2012       Builder.AddTypedTextChunk("delete");
2013       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2014       Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2015       Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2016       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2017       Builder.AddPlaceholderChunk("expression");
2018       Results.AddResult(Result(Builder.TakeString()));
2019 
2020       if (SemaRef.getLangOpts().CXXExceptions) {
2021         // throw expression
2022         Builder.AddResultTypeChunk("void");
2023         Builder.AddTypedTextChunk("throw");
2024         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2025         Builder.AddPlaceholderChunk("expression");
2026         Results.AddResult(Result(Builder.TakeString()));
2027       }
2028 
2029       // FIXME: Rethrow?
2030 
2031       if (SemaRef.getLangOpts().CPlusPlus11) {
2032         // nullptr
2033         Builder.AddResultTypeChunk("std::nullptr_t");
2034         Builder.AddTypedTextChunk("nullptr");
2035         Results.AddResult(Result(Builder.TakeString()));
2036 
2037         // alignof
2038         Builder.AddResultTypeChunk("size_t");
2039         Builder.AddTypedTextChunk("alignof");
2040         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2041         Builder.AddPlaceholderChunk("type");
2042         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2043         Results.AddResult(Result(Builder.TakeString()));
2044 
2045         // noexcept
2046         Builder.AddResultTypeChunk("bool");
2047         Builder.AddTypedTextChunk("noexcept");
2048         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2049         Builder.AddPlaceholderChunk("expression");
2050         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2051         Results.AddResult(Result(Builder.TakeString()));
2052 
2053         // sizeof... expression
2054         Builder.AddResultTypeChunk("size_t");
2055         Builder.AddTypedTextChunk("sizeof...");
2056         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2057         Builder.AddPlaceholderChunk("parameter-pack");
2058         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2059         Results.AddResult(Result(Builder.TakeString()));
2060       }
2061     }
2062 
2063     if (SemaRef.getLangOpts().ObjC1) {
2064       // Add "super", if we're in an Objective-C class with a superclass.
2065       if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2066         // The interface can be NULL.
2067         if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2068           if (ID->getSuperClass()) {
2069             std::string SuperType;
2070             SuperType = ID->getSuperClass()->getNameAsString();
2071             if (Method->isInstanceMethod())
2072               SuperType += " *";
2073 
2074             Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2075             Builder.AddTypedTextChunk("super");
2076             Results.AddResult(Result(Builder.TakeString()));
2077           }
2078       }
2079 
2080       AddObjCExpressionResults(Results, true);
2081     }
2082 
2083     if (SemaRef.getLangOpts().C11) {
2084       // _Alignof
2085       Builder.AddResultTypeChunk("size_t");
2086       if (SemaRef.PP.isMacroDefined("alignof"))
2087         Builder.AddTypedTextChunk("alignof");
2088       else
2089         Builder.AddTypedTextChunk("_Alignof");
2090       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2091       Builder.AddPlaceholderChunk("type");
2092       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2093       Results.AddResult(Result(Builder.TakeString()));
2094     }
2095 
2096     // sizeof expression
2097     Builder.AddResultTypeChunk("size_t");
2098     Builder.AddTypedTextChunk("sizeof");
2099     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2100     Builder.AddPlaceholderChunk("expression-or-type");
2101     Builder.AddChunk(CodeCompletionString::CK_RightParen);
2102     Results.AddResult(Result(Builder.TakeString()));
2103     break;
2104   }
2105 
2106   case Sema::PCC_Type:
2107   case Sema::PCC_LocalDeclarationSpecifiers:
2108     break;
2109   }
2110 
2111   if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2112     AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2113 
2114   if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
2115     Results.AddResult(Result("operator"));
2116 }
2117 
2118 /// \brief If the given declaration has an associated type, add it as a result
2119 /// type chunk.
2120 static void AddResultTypeChunk(ASTContext &Context,
2121                                const PrintingPolicy &Policy,
2122                                const NamedDecl *ND,
2123                                QualType BaseType,
2124                                CodeCompletionBuilder &Result) {
2125   if (!ND)
2126     return;
2127 
2128   // Skip constructors and conversion functions, which have their return types
2129   // built into their names.
2130   if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2131     return;
2132 
2133   // Determine the type of the declaration (if it has a type).
2134   QualType T;
2135   if (const FunctionDecl *Function = ND->getAsFunction())
2136     T = Function->getReturnType();
2137   else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2138     if (!BaseType.isNull())
2139       T = Method->getSendResultType(BaseType);
2140     else
2141       T = Method->getReturnType();
2142   } else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
2143     T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2144   else if (isa<UnresolvedUsingValueDecl>(ND)) {
2145     /* Do nothing: ignore unresolved using declarations*/
2146   } else if (const ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2147     if (!BaseType.isNull())
2148       T = Ivar->getUsageType(BaseType);
2149     else
2150       T = Ivar->getType();
2151   } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
2152     T = Value->getType();
2153   } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2154     if (!BaseType.isNull())
2155       T = Property->getUsageType(BaseType);
2156     else
2157       T = Property->getType();
2158   }
2159 
2160   if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2161     return;
2162 
2163   Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
2164                                                     Result.getAllocator()));
2165 }
2166 
2167 static void MaybeAddSentinel(Preprocessor &PP,
2168                              const NamedDecl *FunctionOrMethod,
2169                              CodeCompletionBuilder &Result) {
2170   if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2171     if (Sentinel->getSentinel() == 0) {
2172       if (PP.getLangOpts().ObjC1 && PP.isMacroDefined("nil"))
2173         Result.AddTextChunk(", nil");
2174       else if (PP.isMacroDefined("NULL"))
2175         Result.AddTextChunk(", NULL");
2176       else
2177         Result.AddTextChunk(", (void*)0");
2178     }
2179 }
2180 
2181 static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2182                                              QualType &Type) {
2183   std::string Result;
2184   if (ObjCQuals & Decl::OBJC_TQ_In)
2185     Result += "in ";
2186   else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2187     Result += "inout ";
2188   else if (ObjCQuals & Decl::OBJC_TQ_Out)
2189     Result += "out ";
2190   if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2191     Result += "bycopy ";
2192   else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2193     Result += "byref ";
2194   if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2195     Result += "oneway ";
2196   if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2197     if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2198       switch (*nullability) {
2199       case NullabilityKind::NonNull:
2200         Result += "nonnull ";
2201         break;
2202 
2203       case NullabilityKind::Nullable:
2204         Result += "nullable ";
2205         break;
2206 
2207       case NullabilityKind::Unspecified:
2208         Result += "null_unspecified ";
2209         break;
2210       }
2211     }
2212   }
2213   return Result;
2214 }
2215 
2216 /// \brief Tries to find the most appropriate type location for an Objective-C
2217 /// block placeholder.
2218 ///
2219 /// This function ignores things like typedefs and qualifiers in order to
2220 /// present the most relevant and accurate block placeholders in code completion
2221 /// results.
2222 static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
2223                                          FunctionTypeLoc &Block,
2224                                          FunctionProtoTypeLoc &BlockProto,
2225                                          bool SuppressBlock = false) {
2226   if (!TSInfo)
2227     return;
2228   TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2229   while (true) {
2230     // Look through typedefs.
2231     if (!SuppressBlock) {
2232       if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2233         if (TypeSourceInfo *InnerTSInfo =
2234                 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2235           TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2236           continue;
2237         }
2238       }
2239 
2240       // Look through qualified types
2241       if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2242         TL = QualifiedTL.getUnqualifiedLoc();
2243         continue;
2244       }
2245 
2246       if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2247         TL = AttrTL.getModifiedLoc();
2248         continue;
2249       }
2250     }
2251 
2252     // Try to get the function prototype behind the block pointer type,
2253     // then we're done.
2254     if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2255       TL = BlockPtr.getPointeeLoc().IgnoreParens();
2256       Block = TL.getAs<FunctionTypeLoc>();
2257       BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2258     }
2259     break;
2260   }
2261 }
2262 
2263 static std::string
2264 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2265                        FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2266                        bool SuppressBlockName = false,
2267                        bool SuppressBlock = false,
2268                        Optional<ArrayRef<QualType>> ObjCSubsts = None);
2269 
2270 static std::string FormatFunctionParameter(const PrintingPolicy &Policy,
2271                                            const ParmVarDecl *Param,
2272                                            bool SuppressName = false,
2273                                            bool SuppressBlock = false,
2274                                Optional<ArrayRef<QualType>> ObjCSubsts = None) {
2275   bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2276   if (Param->getType()->isDependentType() ||
2277       !Param->getType()->isBlockPointerType()) {
2278     // The argument for a dependent or non-block parameter is a placeholder
2279     // containing that parameter's type.
2280     std::string Result;
2281 
2282     if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2283       Result = Param->getIdentifier()->getName();
2284 
2285     QualType Type = Param->getType();
2286     if (ObjCSubsts)
2287       Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2288                                     ObjCSubstitutionContext::Parameter);
2289     if (ObjCMethodParam) {
2290       Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2291                                                Type);
2292       Result += Type.getAsString(Policy) + ")";
2293       if (Param->getIdentifier() && !SuppressName)
2294         Result += Param->getIdentifier()->getName();
2295     } else {
2296       Type.getAsStringInternal(Result, Policy);
2297     }
2298     return Result;
2299   }
2300 
2301   // The argument for a block pointer parameter is a block literal with
2302   // the appropriate type.
2303   FunctionTypeLoc Block;
2304   FunctionProtoTypeLoc BlockProto;
2305   findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2306                                SuppressBlock);
2307   // Try to retrieve the block type information from the property if this is a
2308   // parameter in a setter.
2309   if (!Block && ObjCMethodParam &&
2310       cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2311     if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2312                              ->findPropertyDecl(/*CheckOverrides=*/false))
2313       findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2314                                    SuppressBlock);
2315   }
2316 
2317   if (!Block) {
2318     // We were unable to find a FunctionProtoTypeLoc with parameter names
2319     // for the block; just use the parameter type as a placeholder.
2320     std::string Result;
2321     if (!ObjCMethodParam && Param->getIdentifier())
2322       Result = Param->getIdentifier()->getName();
2323 
2324     QualType Type = Param->getType().getUnqualifiedType();
2325 
2326     if (ObjCMethodParam) {
2327       Result = Type.getAsString(Policy);
2328       std::string Quals =
2329           formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type);
2330       if (!Quals.empty())
2331         Result = "(" + Quals + " " + Result + ")";
2332       if (Result.back() != ')')
2333         Result += " ";
2334       if (Param->getIdentifier())
2335         Result += Param->getIdentifier()->getName();
2336     } else {
2337       Type.getAsStringInternal(Result, Policy);
2338     }
2339 
2340     return Result;
2341   }
2342 
2343   // We have the function prototype behind the block pointer type, as it was
2344   // written in the source.
2345   return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
2346                                 /*SuppressBlockName=*/false, SuppressBlock,
2347                                 ObjCSubsts);
2348 }
2349 
2350 /// \brief Returns a placeholder string that corresponds to an Objective-C block
2351 /// declaration.
2352 ///
2353 /// \param BlockDecl A declaration with an Objective-C block type.
2354 ///
2355 /// \param Block The most relevant type location for that block type.
2356 ///
2357 /// \param SuppressBlockName Determines wether or not the name of the block
2358 /// declaration is included in the resulting string.
2359 static std::string
2360 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2361                        FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2362                        bool SuppressBlockName, bool SuppressBlock,
2363                        Optional<ArrayRef<QualType>> ObjCSubsts) {
2364   std::string Result;
2365   QualType ResultType = Block.getTypePtr()->getReturnType();
2366   if (ObjCSubsts)
2367     ResultType =
2368         ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
2369                                      ObjCSubstitutionContext::Result);
2370   if (!ResultType->isVoidType() || SuppressBlock)
2371     ResultType.getAsStringInternal(Result, Policy);
2372 
2373   // Format the parameter list.
2374   std::string Params;
2375   if (!BlockProto || Block.getNumParams() == 0) {
2376     if (BlockProto && BlockProto.getTypePtr()->isVariadic())
2377       Params = "(...)";
2378     else
2379       Params = "(void)";
2380   } else {
2381     Params += "(";
2382     for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
2383       if (I)
2384         Params += ", ";
2385       Params += FormatFunctionParameter(Policy, Block.getParam(I),
2386                                         /*SuppressName=*/false,
2387                                         /*SuppressBlock=*/true, ObjCSubsts);
2388 
2389       if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
2390         Params += ", ...";
2391     }
2392     Params += ")";
2393   }
2394 
2395   if (SuppressBlock) {
2396     // Format as a parameter.
2397     Result = Result + " (^";
2398     if (!SuppressBlockName && BlockDecl->getIdentifier())
2399       Result += BlockDecl->getIdentifier()->getName();
2400     Result += ")";
2401     Result += Params;
2402   } else {
2403     // Format as a block literal argument.
2404     Result = '^' + Result;
2405     Result += Params;
2406 
2407     if (!SuppressBlockName && BlockDecl->getIdentifier())
2408       Result += BlockDecl->getIdentifier()->getName();
2409   }
2410 
2411   return Result;
2412 }
2413 
2414 static std::string GetDefaultValueString(const ParmVarDecl *Param,
2415                                          const SourceManager &SM,
2416                                          const LangOptions &LangOpts) {
2417   const SourceRange SrcRange = Param->getDefaultArgRange();
2418   CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
2419   bool Invalid = CharSrcRange.isInvalid();
2420   if (Invalid)
2421     return "";
2422   StringRef srcText = Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
2423   if (Invalid)
2424     return "";
2425 
2426   if (srcText.empty() || srcText == "=") {
2427     // Lexer can't determine the value.
2428     // This happens if the code is incorrect (for example class is forward declared).
2429     return "";
2430   }
2431   std::string DefValue(srcText.str());
2432   // FIXME: remove this check if the Lexer::getSourceText value is fixed and
2433   // this value always has (or always does not have) '=' in front of it
2434   if (DefValue.at(0) != '=') {
2435     // If we don't have '=' in front of value.
2436     // Lexer returns built-in types values without '=' and user-defined types values with it.
2437     return " = " + DefValue;
2438   }
2439   return " " + DefValue;
2440 }
2441 
2442 /// \brief Add function parameter chunks to the given code completion string.
2443 static void AddFunctionParameterChunks(Preprocessor &PP,
2444                                        const PrintingPolicy &Policy,
2445                                        const FunctionDecl *Function,
2446                                        CodeCompletionBuilder &Result,
2447                                        unsigned Start = 0,
2448                                        bool InOptional = false) {
2449   bool FirstParameter = true;
2450 
2451   for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
2452     const ParmVarDecl *Param = Function->getParamDecl(P);
2453 
2454     if (Param->hasDefaultArg() && !InOptional) {
2455       // When we see an optional default argument, put that argument and
2456       // the remaining default arguments into a new, optional string.
2457       CodeCompletionBuilder Opt(Result.getAllocator(),
2458                                 Result.getCodeCompletionTUInfo());
2459       if (!FirstParameter)
2460         Opt.AddChunk(CodeCompletionString::CK_Comma);
2461       AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
2462       Result.AddOptionalChunk(Opt.TakeString());
2463       break;
2464     }
2465 
2466     if (FirstParameter)
2467       FirstParameter = false;
2468     else
2469       Result.AddChunk(CodeCompletionString::CK_Comma);
2470 
2471     InOptional = false;
2472 
2473     // Format the placeholder string.
2474     std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
2475     if (Param->hasDefaultArg())
2476       PlaceholderStr += GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
2477 
2478     if (Function->isVariadic() && P == N - 1)
2479       PlaceholderStr += ", ...";
2480 
2481     // Add the placeholder string.
2482     Result.AddPlaceholderChunk(
2483                              Result.getAllocator().CopyString(PlaceholderStr));
2484   }
2485 
2486   if (const FunctionProtoType *Proto
2487         = Function->getType()->getAs<FunctionProtoType>())
2488     if (Proto->isVariadic()) {
2489       if (Proto->getNumParams() == 0)
2490         Result.AddPlaceholderChunk("...");
2491 
2492       MaybeAddSentinel(PP, Function, Result);
2493     }
2494 }
2495 
2496 /// \brief Add template parameter chunks to the given code completion string.
2497 static void AddTemplateParameterChunks(ASTContext &Context,
2498                                        const PrintingPolicy &Policy,
2499                                        const TemplateDecl *Template,
2500                                        CodeCompletionBuilder &Result,
2501                                        unsigned MaxParameters = 0,
2502                                        unsigned Start = 0,
2503                                        bool InDefaultArg = false) {
2504   bool FirstParameter = true;
2505 
2506   // Prefer to take the template parameter names from the first declaration of
2507   // the template.
2508   Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2509 
2510   TemplateParameterList *Params = Template->getTemplateParameters();
2511   TemplateParameterList::iterator PEnd = Params->end();
2512   if (MaxParameters)
2513     PEnd = Params->begin() + MaxParameters;
2514   for (TemplateParameterList::iterator P = Params->begin() + Start;
2515        P != PEnd; ++P) {
2516     bool HasDefaultArg = false;
2517     std::string PlaceholderStr;
2518     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2519       if (TTP->wasDeclaredWithTypename())
2520         PlaceholderStr = "typename";
2521       else
2522         PlaceholderStr = "class";
2523 
2524       if (TTP->getIdentifier()) {
2525         PlaceholderStr += ' ';
2526         PlaceholderStr += TTP->getIdentifier()->getName();
2527       }
2528 
2529       HasDefaultArg = TTP->hasDefaultArgument();
2530     } else if (NonTypeTemplateParmDecl *NTTP
2531                                     = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
2532       if (NTTP->getIdentifier())
2533         PlaceholderStr = NTTP->getIdentifier()->getName();
2534       NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
2535       HasDefaultArg = NTTP->hasDefaultArgument();
2536     } else {
2537       assert(isa<TemplateTemplateParmDecl>(*P));
2538       TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2539 
2540       // Since putting the template argument list into the placeholder would
2541       // be very, very long, we just use an abbreviation.
2542       PlaceholderStr = "template<...> class";
2543       if (TTP->getIdentifier()) {
2544         PlaceholderStr += ' ';
2545         PlaceholderStr += TTP->getIdentifier()->getName();
2546       }
2547 
2548       HasDefaultArg = TTP->hasDefaultArgument();
2549     }
2550 
2551     if (HasDefaultArg && !InDefaultArg) {
2552       // When we see an optional default argument, put that argument and
2553       // the remaining default arguments into a new, optional string.
2554       CodeCompletionBuilder Opt(Result.getAllocator(),
2555                                 Result.getCodeCompletionTUInfo());
2556       if (!FirstParameter)
2557         Opt.AddChunk(CodeCompletionString::CK_Comma);
2558       AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
2559                                  P - Params->begin(), true);
2560       Result.AddOptionalChunk(Opt.TakeString());
2561       break;
2562     }
2563 
2564     InDefaultArg = false;
2565 
2566     if (FirstParameter)
2567       FirstParameter = false;
2568     else
2569       Result.AddChunk(CodeCompletionString::CK_Comma);
2570 
2571     // Add the placeholder string.
2572     Result.AddPlaceholderChunk(
2573                               Result.getAllocator().CopyString(PlaceholderStr));
2574   }
2575 }
2576 
2577 /// \brief Add a qualifier to the given code-completion string, if the
2578 /// provided nested-name-specifier is non-NULL.
2579 static void
2580 AddQualifierToCompletionString(CodeCompletionBuilder &Result,
2581                                NestedNameSpecifier *Qualifier,
2582                                bool QualifierIsInformative,
2583                                ASTContext &Context,
2584                                const PrintingPolicy &Policy) {
2585   if (!Qualifier)
2586     return;
2587 
2588   std::string PrintedNNS;
2589   {
2590     llvm::raw_string_ostream OS(PrintedNNS);
2591     Qualifier->print(OS, Policy);
2592   }
2593   if (QualifierIsInformative)
2594     Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
2595   else
2596     Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
2597 }
2598 
2599 static void
2600 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2601                                        const FunctionDecl *Function) {
2602   const FunctionProtoType *Proto
2603     = Function->getType()->getAs<FunctionProtoType>();
2604   if (!Proto || !Proto->getTypeQuals())
2605     return;
2606 
2607   // FIXME: Add ref-qualifier!
2608 
2609   // Handle single qualifiers without copying
2610   if (Proto->getTypeQuals() == Qualifiers::Const) {
2611     Result.AddInformativeChunk(" const");
2612     return;
2613   }
2614 
2615   if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2616     Result.AddInformativeChunk(" volatile");
2617     return;
2618   }
2619 
2620   if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2621     Result.AddInformativeChunk(" restrict");
2622     return;
2623   }
2624 
2625   // Handle multiple qualifiers.
2626   std::string QualsStr;
2627   if (Proto->isConst())
2628     QualsStr += " const";
2629   if (Proto->isVolatile())
2630     QualsStr += " volatile";
2631   if (Proto->isRestrict())
2632     QualsStr += " restrict";
2633   Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
2634 }
2635 
2636 /// \brief Add the name of the given declaration
2637 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2638                               const NamedDecl *ND,
2639                               CodeCompletionBuilder &Result) {
2640   DeclarationName Name = ND->getDeclName();
2641   if (!Name)
2642     return;
2643 
2644   switch (Name.getNameKind()) {
2645     case DeclarationName::CXXOperatorName: {
2646       const char *OperatorName = nullptr;
2647       switch (Name.getCXXOverloadedOperator()) {
2648       case OO_None:
2649       case OO_Conditional:
2650       case NUM_OVERLOADED_OPERATORS:
2651         OperatorName = "operator";
2652         break;
2653 
2654 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2655       case OO_##Name: OperatorName = "operator" Spelling; break;
2656 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2657 #include "clang/Basic/OperatorKinds.def"
2658 
2659       case OO_New:          OperatorName = "operator new"; break;
2660       case OO_Delete:       OperatorName = "operator delete"; break;
2661       case OO_Array_New:    OperatorName = "operator new[]"; break;
2662       case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2663       case OO_Call:         OperatorName = "operator()"; break;
2664       case OO_Subscript:    OperatorName = "operator[]"; break;
2665       }
2666       Result.AddTypedTextChunk(OperatorName);
2667       break;
2668     }
2669 
2670   case DeclarationName::Identifier:
2671   case DeclarationName::CXXConversionFunctionName:
2672   case DeclarationName::CXXDestructorName:
2673   case DeclarationName::CXXLiteralOperatorName:
2674     Result.AddTypedTextChunk(
2675                       Result.getAllocator().CopyString(ND->getNameAsString()));
2676     break;
2677 
2678   case DeclarationName::CXXDeductionGuideName:
2679   case DeclarationName::CXXUsingDirective:
2680   case DeclarationName::ObjCZeroArgSelector:
2681   case DeclarationName::ObjCOneArgSelector:
2682   case DeclarationName::ObjCMultiArgSelector:
2683     break;
2684 
2685   case DeclarationName::CXXConstructorName: {
2686     CXXRecordDecl *Record = nullptr;
2687     QualType Ty = Name.getCXXNameType();
2688     if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2689       Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2690     else if (const InjectedClassNameType *InjectedTy
2691                                         = Ty->getAs<InjectedClassNameType>())
2692       Record = InjectedTy->getDecl();
2693     else {
2694       Result.AddTypedTextChunk(
2695                       Result.getAllocator().CopyString(ND->getNameAsString()));
2696       break;
2697     }
2698 
2699     Result.AddTypedTextChunk(
2700                   Result.getAllocator().CopyString(Record->getNameAsString()));
2701     if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
2702       Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2703       AddTemplateParameterChunks(Context, Policy, Template, Result);
2704       Result.AddChunk(CodeCompletionString::CK_RightAngle);
2705     }
2706     break;
2707   }
2708   }
2709 }
2710 
2711 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
2712                                          const CodeCompletionContext &CCContext,
2713                                          CodeCompletionAllocator &Allocator,
2714                                          CodeCompletionTUInfo &CCTUInfo,
2715                                          bool IncludeBriefComments) {
2716   return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
2717                                     CCTUInfo, IncludeBriefComments);
2718 }
2719 
2720 /// \brief If possible, create a new code completion string for the given
2721 /// result.
2722 ///
2723 /// \returns Either a new, heap-allocated code completion string describing
2724 /// how to use this result, or NULL to indicate that the string or name of the
2725 /// result is all that is needed.
2726 CodeCompletionString *
2727 CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2728                                                  Preprocessor &PP,
2729                                          const CodeCompletionContext &CCContext,
2730                                            CodeCompletionAllocator &Allocator,
2731                                            CodeCompletionTUInfo &CCTUInfo,
2732                                            bool IncludeBriefComments) {
2733   CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
2734 
2735   PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
2736   if (Kind == RK_Pattern) {
2737     Pattern->Priority = Priority;
2738     Pattern->Availability = Availability;
2739 
2740     if (Declaration) {
2741       Result.addParentContext(Declaration->getDeclContext());
2742       Pattern->ParentName = Result.getParentName();
2743       // Provide code completion comment for self.GetterName where
2744       // GetterName is the getter method for a property with name
2745       // different from the property name (declared via a property
2746       // getter attribute.
2747       const NamedDecl *ND = Declaration;
2748       if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2749         if (M->isPropertyAccessor())
2750           if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2751             if (PDecl->getGetterName() == M->getSelector() &&
2752                 PDecl->getIdentifier() != M->getIdentifier()) {
2753               if (const RawComment *RC =
2754                     Ctx.getRawCommentForAnyRedecl(M)) {
2755                 Result.addBriefComment(RC->getBriefText(Ctx));
2756                 Pattern->BriefComment = Result.getBriefComment();
2757               }
2758               else if (const RawComment *RC =
2759                          Ctx.getRawCommentForAnyRedecl(PDecl)) {
2760                 Result.addBriefComment(RC->getBriefText(Ctx));
2761                 Pattern->BriefComment = Result.getBriefComment();
2762               }
2763             }
2764     }
2765 
2766     return Pattern;
2767   }
2768 
2769   if (Kind == RK_Keyword) {
2770     Result.AddTypedTextChunk(Keyword);
2771     return Result.TakeString();
2772   }
2773 
2774   if (Kind == RK_Macro) {
2775     const MacroInfo *MI = PP.getMacroInfo(Macro);
2776     Result.AddTypedTextChunk(
2777                             Result.getAllocator().CopyString(Macro->getName()));
2778 
2779     if (!MI || !MI->isFunctionLike())
2780       return Result.TakeString();
2781 
2782     // Format a function-like macro with placeholders for the arguments.
2783     Result.AddChunk(CodeCompletionString::CK_LeftParen);
2784     MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
2785 
2786     // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2787     if (MI->isC99Varargs()) {
2788       --AEnd;
2789 
2790       if (A == AEnd) {
2791         Result.AddPlaceholderChunk("...");
2792       }
2793     }
2794 
2795     for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
2796       if (A != MI->param_begin())
2797         Result.AddChunk(CodeCompletionString::CK_Comma);
2798 
2799       if (MI->isVariadic() && (A+1) == AEnd) {
2800         SmallString<32> Arg = (*A)->getName();
2801         if (MI->isC99Varargs())
2802           Arg += ", ...";
2803         else
2804           Arg += "...";
2805         Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2806         break;
2807       }
2808 
2809       // Non-variadic macros are simple.
2810       Result.AddPlaceholderChunk(
2811                           Result.getAllocator().CopyString((*A)->getName()));
2812     }
2813     Result.AddChunk(CodeCompletionString::CK_RightParen);
2814     return Result.TakeString();
2815   }
2816 
2817   assert(Kind == RK_Declaration && "Missed a result kind?");
2818   const NamedDecl *ND = Declaration;
2819   Result.addParentContext(ND->getDeclContext());
2820 
2821   if (IncludeBriefComments) {
2822     // Add documentation comment, if it exists.
2823     if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
2824       Result.addBriefComment(RC->getBriefText(Ctx));
2825     }
2826     else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2827       if (OMD->isPropertyAccessor())
2828         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2829           if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2830             Result.addBriefComment(RC->getBriefText(Ctx));
2831   }
2832 
2833   if (StartsNestedNameSpecifier) {
2834     Result.AddTypedTextChunk(
2835                       Result.getAllocator().CopyString(ND->getNameAsString()));
2836     Result.AddTextChunk("::");
2837     return Result.TakeString();
2838   }
2839 
2840   for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2841     Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
2842 
2843   AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
2844 
2845   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
2846     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2847                                    Ctx, Policy);
2848     AddTypedNameChunk(Ctx, Policy, ND, Result);
2849     Result.AddChunk(CodeCompletionString::CK_LeftParen);
2850     AddFunctionParameterChunks(PP, Policy, Function, Result);
2851     Result.AddChunk(CodeCompletionString::CK_RightParen);
2852     AddFunctionTypeQualsToCompletionString(Result, Function);
2853     return Result.TakeString();
2854   }
2855 
2856   if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
2857     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2858                                    Ctx, Policy);
2859     FunctionDecl *Function = FunTmpl->getTemplatedDecl();
2860     AddTypedNameChunk(Ctx, Policy, Function, Result);
2861 
2862     // Figure out which template parameters are deduced (or have default
2863     // arguments).
2864     llvm::SmallBitVector Deduced;
2865     Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
2866     unsigned LastDeducibleArgument;
2867     for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2868          --LastDeducibleArgument) {
2869       if (!Deduced[LastDeducibleArgument - 1]) {
2870         // C++0x: Figure out if the template argument has a default. If so,
2871         // the user doesn't need to type this argument.
2872         // FIXME: We need to abstract template parameters better!
2873         bool HasDefaultArg = false;
2874         NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2875                                                     LastDeducibleArgument - 1);
2876         if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2877           HasDefaultArg = TTP->hasDefaultArgument();
2878         else if (NonTypeTemplateParmDecl *NTTP
2879                  = dyn_cast<NonTypeTemplateParmDecl>(Param))
2880           HasDefaultArg = NTTP->hasDefaultArgument();
2881         else {
2882           assert(isa<TemplateTemplateParmDecl>(Param));
2883           HasDefaultArg
2884             = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
2885         }
2886 
2887         if (!HasDefaultArg)
2888           break;
2889       }
2890     }
2891 
2892     if (LastDeducibleArgument) {
2893       // Some of the function template arguments cannot be deduced from a
2894       // function call, so we introduce an explicit template argument list
2895       // containing all of the arguments up to the first deducible argument.
2896       Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2897       AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
2898                                  LastDeducibleArgument);
2899       Result.AddChunk(CodeCompletionString::CK_RightAngle);
2900     }
2901 
2902     // Add the function parameters
2903     Result.AddChunk(CodeCompletionString::CK_LeftParen);
2904     AddFunctionParameterChunks(PP, Policy, Function, Result);
2905     Result.AddChunk(CodeCompletionString::CK_RightParen);
2906     AddFunctionTypeQualsToCompletionString(Result, Function);
2907     return Result.TakeString();
2908   }
2909 
2910   if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
2911     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2912                                    Ctx, Policy);
2913     Result.AddTypedTextChunk(
2914                 Result.getAllocator().CopyString(Template->getNameAsString()));
2915     Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2916     AddTemplateParameterChunks(Ctx, Policy, Template, Result);
2917     Result.AddChunk(CodeCompletionString::CK_RightAngle);
2918     return Result.TakeString();
2919   }
2920 
2921   if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2922     Selector Sel = Method->getSelector();
2923     if (Sel.isUnarySelector()) {
2924       Result.AddTypedTextChunk(Result.getAllocator().CopyString(
2925                                   Sel.getNameForSlot(0)));
2926       return Result.TakeString();
2927     }
2928 
2929     std::string SelName = Sel.getNameForSlot(0).str();
2930     SelName += ':';
2931     if (StartParameter == 0)
2932       Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
2933     else {
2934       Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
2935 
2936       // If there is only one parameter, and we're past it, add an empty
2937       // typed-text chunk since there is nothing to type.
2938       if (Method->param_size() == 1)
2939         Result.AddTypedTextChunk("");
2940     }
2941     unsigned Idx = 0;
2942     for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2943                                            PEnd = Method->param_end();
2944          P != PEnd; (void)++P, ++Idx) {
2945       if (Idx > 0) {
2946         std::string Keyword;
2947         if (Idx > StartParameter)
2948           Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2949         if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2950           Keyword += II->getName();
2951         Keyword += ":";
2952         if (Idx < StartParameter || AllParametersAreInformative)
2953           Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
2954         else
2955           Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
2956       }
2957 
2958       // If we're before the starting parameter, skip the placeholder.
2959       if (Idx < StartParameter)
2960         continue;
2961 
2962       std::string Arg;
2963       QualType ParamType = (*P)->getType();
2964       Optional<ArrayRef<QualType>> ObjCSubsts;
2965       if (!CCContext.getBaseType().isNull())
2966         ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
2967 
2968       if (ParamType->isBlockPointerType() && !DeclaringEntity)
2969         Arg = FormatFunctionParameter(Policy, *P, true,
2970                                       /*SuppressBlock=*/false,
2971                                       ObjCSubsts);
2972       else {
2973         if (ObjCSubsts)
2974           ParamType = ParamType.substObjCTypeArgs(Ctx, *ObjCSubsts,
2975                                             ObjCSubstitutionContext::Parameter);
2976         Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
2977                                               ParamType);
2978         Arg += ParamType.getAsString(Policy) + ")";
2979         if (IdentifierInfo *II = (*P)->getIdentifier())
2980           if (DeclaringEntity || AllParametersAreInformative)
2981             Arg += II->getName();
2982       }
2983 
2984       if (Method->isVariadic() && (P + 1) == PEnd)
2985         Arg += ", ...";
2986 
2987       if (DeclaringEntity)
2988         Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
2989       else if (AllParametersAreInformative)
2990         Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
2991       else
2992         Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2993     }
2994 
2995     if (Method->isVariadic()) {
2996       if (Method->param_size() == 0) {
2997         if (DeclaringEntity)
2998           Result.AddTextChunk(", ...");
2999         else if (AllParametersAreInformative)
3000           Result.AddInformativeChunk(", ...");
3001         else
3002           Result.AddPlaceholderChunk(", ...");
3003       }
3004 
3005       MaybeAddSentinel(PP, Method, Result);
3006     }
3007 
3008     return Result.TakeString();
3009   }
3010 
3011   if (Qualifier)
3012     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3013                                    Ctx, Policy);
3014 
3015   Result.AddTypedTextChunk(
3016                        Result.getAllocator().CopyString(ND->getNameAsString()));
3017   return Result.TakeString();
3018 }
3019 
3020 /// \brief Add function overload parameter chunks to the given code completion
3021 /// string.
3022 static void AddOverloadParameterChunks(ASTContext &Context,
3023                                        const PrintingPolicy &Policy,
3024                                        const FunctionDecl *Function,
3025                                        const FunctionProtoType *Prototype,
3026                                        CodeCompletionBuilder &Result,
3027                                        unsigned CurrentArg,
3028                                        unsigned Start = 0,
3029                                        bool InOptional = false) {
3030   bool FirstParameter = true;
3031   unsigned NumParams = Function ? Function->getNumParams()
3032                                 : Prototype->getNumParams();
3033 
3034   for (unsigned P = Start; P != NumParams; ++P) {
3035     if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
3036       // When we see an optional default argument, put that argument and
3037       // the remaining default arguments into a new, optional string.
3038       CodeCompletionBuilder Opt(Result.getAllocator(),
3039                                 Result.getCodeCompletionTUInfo());
3040       if (!FirstParameter)
3041         Opt.AddChunk(CodeCompletionString::CK_Comma);
3042       // Optional sections are nested.
3043       AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
3044                                  CurrentArg, P, /*InOptional=*/true);
3045       Result.AddOptionalChunk(Opt.TakeString());
3046       return;
3047     }
3048 
3049     if (FirstParameter)
3050       FirstParameter = false;
3051     else
3052       Result.AddChunk(CodeCompletionString::CK_Comma);
3053 
3054     InOptional = false;
3055 
3056     // Format the placeholder string.
3057     std::string Placeholder;
3058     if (Function) {
3059       const ParmVarDecl *Param = Function->getParamDecl(P);
3060       Placeholder = FormatFunctionParameter(Policy, Param);
3061       if (Param->hasDefaultArg())
3062         Placeholder += GetDefaultValueString(Param, Context.getSourceManager(), Context.getLangOpts());
3063     } else {
3064       Placeholder = Prototype->getParamType(P).getAsString(Policy);
3065     }
3066 
3067     if (P == CurrentArg)
3068       Result.AddCurrentParameterChunk(
3069         Result.getAllocator().CopyString(Placeholder));
3070     else
3071       Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3072   }
3073 
3074   if (Prototype && Prototype->isVariadic()) {
3075     CodeCompletionBuilder Opt(Result.getAllocator(),
3076                               Result.getCodeCompletionTUInfo());
3077     if (!FirstParameter)
3078       Opt.AddChunk(CodeCompletionString::CK_Comma);
3079 
3080     if (CurrentArg < NumParams)
3081       Opt.AddPlaceholderChunk("...");
3082     else
3083       Opt.AddCurrentParameterChunk("...");
3084 
3085     Result.AddOptionalChunk(Opt.TakeString());
3086   }
3087 }
3088 
3089 CodeCompletionString *
3090 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
3091                                              unsigned CurrentArg, Sema &S,
3092                                              CodeCompletionAllocator &Allocator,
3093                                              CodeCompletionTUInfo &CCTUInfo,
3094                                              bool IncludeBriefComments) const {
3095   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3096 
3097   // FIXME: Set priority, availability appropriately.
3098   CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
3099   FunctionDecl *FDecl = getFunction();
3100   const FunctionProtoType *Proto
3101     = dyn_cast<FunctionProtoType>(getFunctionType());
3102   if (!FDecl && !Proto) {
3103     // Function without a prototype. Just give the return type and a
3104     // highlighted ellipsis.
3105     const FunctionType *FT = getFunctionType();
3106     Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3107       FT->getReturnType().getAsString(Policy)));
3108     Result.AddChunk(CodeCompletionString::CK_LeftParen);
3109     Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
3110     Result.AddChunk(CodeCompletionString::CK_RightParen);
3111     return Result.TakeString();
3112   }
3113 
3114   if (FDecl) {
3115     if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
3116       if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
3117           FDecl->getParamDecl(CurrentArg)))
3118         Result.addBriefComment(RC->getBriefText(S.getASTContext()));
3119     AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
3120     Result.AddTextChunk(
3121       Result.getAllocator().CopyString(FDecl->getNameAsString()));
3122   } else {
3123     Result.AddResultTypeChunk(
3124       Result.getAllocator().CopyString(
3125         Proto->getReturnType().getAsString(Policy)));
3126   }
3127 
3128   Result.AddChunk(CodeCompletionString::CK_LeftParen);
3129   AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
3130                              CurrentArg);
3131   Result.AddChunk(CodeCompletionString::CK_RightParen);
3132 
3133   return Result.TakeString();
3134 }
3135 
3136 unsigned clang::getMacroUsagePriority(StringRef MacroName,
3137                                       const LangOptions &LangOpts,
3138                                       bool PreferredTypeIsPointer) {
3139   unsigned Priority = CCP_Macro;
3140 
3141   // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
3142   if (MacroName.equals("nil") || MacroName.equals("NULL") ||
3143       MacroName.equals("Nil")) {
3144     Priority = CCP_Constant;
3145     if (PreferredTypeIsPointer)
3146       Priority = Priority / CCF_SimilarTypeMatch;
3147   }
3148   // Treat "YES", "NO", "true", and "false" as constants.
3149   else if (MacroName.equals("YES") || MacroName.equals("NO") ||
3150            MacroName.equals("true") || MacroName.equals("false"))
3151     Priority = CCP_Constant;
3152   // Treat "bool" as a type.
3153   else if (MacroName.equals("bool"))
3154     Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
3155 
3156 
3157   return Priority;
3158 }
3159 
3160 CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
3161   if (!D)
3162     return CXCursor_UnexposedDecl;
3163 
3164   switch (D->getKind()) {
3165     case Decl::Enum:               return CXCursor_EnumDecl;
3166     case Decl::EnumConstant:       return CXCursor_EnumConstantDecl;
3167     case Decl::Field:              return CXCursor_FieldDecl;
3168     case Decl::Function:
3169       return CXCursor_FunctionDecl;
3170     case Decl::ObjCCategory:       return CXCursor_ObjCCategoryDecl;
3171     case Decl::ObjCCategoryImpl:   return CXCursor_ObjCCategoryImplDecl;
3172     case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
3173 
3174     case Decl::ObjCInterface:      return CXCursor_ObjCInterfaceDecl;
3175     case Decl::ObjCIvar:           return CXCursor_ObjCIvarDecl;
3176     case Decl::ObjCMethod:
3177       return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3178       ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
3179     case Decl::CXXMethod:          return CXCursor_CXXMethod;
3180     case Decl::CXXConstructor:     return CXCursor_Constructor;
3181     case Decl::CXXDestructor:      return CXCursor_Destructor;
3182     case Decl::CXXConversion:      return CXCursor_ConversionFunction;
3183     case Decl::ObjCProperty:       return CXCursor_ObjCPropertyDecl;
3184     case Decl::ObjCProtocol:       return CXCursor_ObjCProtocolDecl;
3185     case Decl::ParmVar:            return CXCursor_ParmDecl;
3186     case Decl::Typedef:            return CXCursor_TypedefDecl;
3187     case Decl::TypeAlias:          return CXCursor_TypeAliasDecl;
3188     case Decl::TypeAliasTemplate:  return CXCursor_TypeAliasTemplateDecl;
3189     case Decl::Var:                return CXCursor_VarDecl;
3190     case Decl::Namespace:          return CXCursor_Namespace;
3191     case Decl::NamespaceAlias:     return CXCursor_NamespaceAlias;
3192     case Decl::TemplateTypeParm:   return CXCursor_TemplateTypeParameter;
3193     case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
3194     case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
3195     case Decl::FunctionTemplate:   return CXCursor_FunctionTemplate;
3196     case Decl::ClassTemplate:      return CXCursor_ClassTemplate;
3197     case Decl::AccessSpec:         return CXCursor_CXXAccessSpecifier;
3198     case Decl::ClassTemplatePartialSpecialization:
3199       return CXCursor_ClassTemplatePartialSpecialization;
3200     case Decl::UsingDirective:     return CXCursor_UsingDirective;
3201     case Decl::StaticAssert:       return CXCursor_StaticAssert;
3202     case Decl::Friend:             return CXCursor_FriendDecl;
3203     case Decl::TranslationUnit:    return CXCursor_TranslationUnit;
3204 
3205     case Decl::Using:
3206     case Decl::UnresolvedUsingValue:
3207     case Decl::UnresolvedUsingTypename:
3208       return CXCursor_UsingDeclaration;
3209 
3210     case Decl::ObjCPropertyImpl:
3211       switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3212       case ObjCPropertyImplDecl::Dynamic:
3213         return CXCursor_ObjCDynamicDecl;
3214 
3215       case ObjCPropertyImplDecl::Synthesize:
3216         return CXCursor_ObjCSynthesizeDecl;
3217       }
3218 
3219       case Decl::Import:
3220         return CXCursor_ModuleImportDecl;
3221 
3222     case Decl::ObjCTypeParam:   return CXCursor_TemplateTypeParameter;
3223 
3224     default:
3225       if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3226         switch (TD->getTagKind()) {
3227           case TTK_Interface:  // fall through
3228           case TTK_Struct: return CXCursor_StructDecl;
3229           case TTK_Class:  return CXCursor_ClassDecl;
3230           case TTK_Union:  return CXCursor_UnionDecl;
3231           case TTK_Enum:   return CXCursor_EnumDecl;
3232         }
3233       }
3234   }
3235 
3236   return CXCursor_UnexposedDecl;
3237 }
3238 
3239 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
3240                             bool IncludeUndefined,
3241                             bool TargetTypeIsPointer = false) {
3242   typedef CodeCompletionResult Result;
3243 
3244   Results.EnterNewScope();
3245 
3246   for (Preprocessor::macro_iterator M = PP.macro_begin(),
3247                                  MEnd = PP.macro_end();
3248        M != MEnd; ++M) {
3249     auto MD = PP.getMacroDefinition(M->first);
3250     if (IncludeUndefined || MD) {
3251       if (MacroInfo *MI = MD.getMacroInfo())
3252         if (MI->isUsedForHeaderGuard())
3253           continue;
3254 
3255       Results.AddResult(Result(M->first,
3256                              getMacroUsagePriority(M->first->getName(),
3257                                                    PP.getLangOpts(),
3258                                                    TargetTypeIsPointer)));
3259     }
3260   }
3261 
3262   Results.ExitScope();
3263 
3264 }
3265 
3266 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3267                                      ResultBuilder &Results) {
3268   typedef CodeCompletionResult Result;
3269 
3270   Results.EnterNewScope();
3271 
3272   Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3273   Results.AddResult(Result("__FUNCTION__", CCP_Constant));
3274   if (LangOpts.C99 || LangOpts.CPlusPlus11)
3275     Results.AddResult(Result("__func__", CCP_Constant));
3276   Results.ExitScope();
3277 }
3278 
3279 static void HandleCodeCompleteResults(Sema *S,
3280                                       CodeCompleteConsumer *CodeCompleter,
3281                                       CodeCompletionContext Context,
3282                                       CodeCompletionResult *Results,
3283                                       unsigned NumResults) {
3284   if (CodeCompleter)
3285     CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
3286 }
3287 
3288 static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3289                                             Sema::ParserCompletionContext PCC) {
3290   switch (PCC) {
3291   case Sema::PCC_Namespace:
3292     return CodeCompletionContext::CCC_TopLevel;
3293 
3294   case Sema::PCC_Class:
3295     return CodeCompletionContext::CCC_ClassStructUnion;
3296 
3297   case Sema::PCC_ObjCInterface:
3298     return CodeCompletionContext::CCC_ObjCInterface;
3299 
3300   case Sema::PCC_ObjCImplementation:
3301     return CodeCompletionContext::CCC_ObjCImplementation;
3302 
3303   case Sema::PCC_ObjCInstanceVariableList:
3304     return CodeCompletionContext::CCC_ObjCIvarList;
3305 
3306   case Sema::PCC_Template:
3307   case Sema::PCC_MemberTemplate:
3308     if (S.CurContext->isFileContext())
3309       return CodeCompletionContext::CCC_TopLevel;
3310     if (S.CurContext->isRecord())
3311       return CodeCompletionContext::CCC_ClassStructUnion;
3312     return CodeCompletionContext::CCC_Other;
3313 
3314   case Sema::PCC_RecoveryInFunction:
3315     return CodeCompletionContext::CCC_Recovery;
3316 
3317   case Sema::PCC_ForInit:
3318     if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3319         S.getLangOpts().ObjC1)
3320       return CodeCompletionContext::CCC_ParenthesizedExpression;
3321     else
3322       return CodeCompletionContext::CCC_Expression;
3323 
3324   case Sema::PCC_Expression:
3325   case Sema::PCC_Condition:
3326     return CodeCompletionContext::CCC_Expression;
3327 
3328   case Sema::PCC_Statement:
3329     return CodeCompletionContext::CCC_Statement;
3330 
3331   case Sema::PCC_Type:
3332     return CodeCompletionContext::CCC_Type;
3333 
3334   case Sema::PCC_ParenthesizedExpression:
3335     return CodeCompletionContext::CCC_ParenthesizedExpression;
3336 
3337   case Sema::PCC_LocalDeclarationSpecifiers:
3338     return CodeCompletionContext::CCC_Type;
3339   }
3340 
3341   llvm_unreachable("Invalid ParserCompletionContext!");
3342 }
3343 
3344 /// \brief If we're in a C++ virtual member function, add completion results
3345 /// that invoke the functions we override, since it's common to invoke the
3346 /// overridden function as well as adding new functionality.
3347 ///
3348 /// \param S The semantic analysis object for which we are generating results.
3349 ///
3350 /// \param InContext This context in which the nested-name-specifier preceding
3351 /// the code-completion point
3352 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3353                                   ResultBuilder &Results) {
3354   // Look through blocks.
3355   DeclContext *CurContext = S.CurContext;
3356   while (isa<BlockDecl>(CurContext))
3357     CurContext = CurContext->getParent();
3358 
3359 
3360   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3361   if (!Method || !Method->isVirtual())
3362     return;
3363 
3364   // We need to have names for all of the parameters, if we're going to
3365   // generate a forwarding call.
3366   for (auto P : Method->parameters())
3367     if (!P->getDeclName())
3368       return;
3369 
3370   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3371   for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3372                                    MEnd = Method->end_overridden_methods();
3373        M != MEnd; ++M) {
3374     CodeCompletionBuilder Builder(Results.getAllocator(),
3375                                   Results.getCodeCompletionTUInfo());
3376     const CXXMethodDecl *Overridden = *M;
3377     if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3378       continue;
3379 
3380     // If we need a nested-name-specifier, add one now.
3381     if (!InContext) {
3382       NestedNameSpecifier *NNS
3383         = getRequiredQualification(S.Context, CurContext,
3384                                    Overridden->getDeclContext());
3385       if (NNS) {
3386         std::string Str;
3387         llvm::raw_string_ostream OS(Str);
3388         NNS->print(OS, Policy);
3389         Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
3390       }
3391     } else if (!InContext->Equals(Overridden->getDeclContext()))
3392       continue;
3393 
3394     Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
3395                                          Overridden->getNameAsString()));
3396     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3397     bool FirstParam = true;
3398     for (auto P : Method->parameters()) {
3399       if (FirstParam)
3400         FirstParam = false;
3401       else
3402         Builder.AddChunk(CodeCompletionString::CK_Comma);
3403 
3404       Builder.AddPlaceholderChunk(
3405           Results.getAllocator().CopyString(P->getIdentifier()->getName()));
3406     }
3407     Builder.AddChunk(CodeCompletionString::CK_RightParen);
3408     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
3409                                            CCP_SuperCompletion,
3410                                            CXCursor_CXXMethod,
3411                                            CXAvailability_Available,
3412                                            Overridden));
3413     Results.Ignore(Overridden);
3414   }
3415 }
3416 
3417 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3418                                     ModuleIdPath Path) {
3419   typedef CodeCompletionResult Result;
3420   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3421                         CodeCompleter->getCodeCompletionTUInfo(),
3422                         CodeCompletionContext::CCC_Other);
3423   Results.EnterNewScope();
3424 
3425   CodeCompletionAllocator &Allocator = Results.getAllocator();
3426   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
3427   typedef CodeCompletionResult Result;
3428   if (Path.empty()) {
3429     // Enumerate all top-level modules.
3430     SmallVector<Module *, 8> Modules;
3431     PP.getHeaderSearchInfo().collectAllModules(Modules);
3432     for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3433       Builder.AddTypedTextChunk(
3434         Builder.getAllocator().CopyString(Modules[I]->Name));
3435       Results.AddResult(Result(Builder.TakeString(),
3436                                CCP_Declaration,
3437                                CXCursor_ModuleImportDecl,
3438                                Modules[I]->isAvailable()
3439                                  ? CXAvailability_Available
3440                                   : CXAvailability_NotAvailable));
3441     }
3442   } else if (getLangOpts().Modules) {
3443     // Load the named module.
3444     Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3445                                                   Module::AllVisible,
3446                                                 /*IsInclusionDirective=*/false);
3447     // Enumerate submodules.
3448     if (Mod) {
3449       for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3450                                    SubEnd = Mod->submodule_end();
3451            Sub != SubEnd; ++Sub) {
3452 
3453         Builder.AddTypedTextChunk(
3454           Builder.getAllocator().CopyString((*Sub)->Name));
3455         Results.AddResult(Result(Builder.TakeString(),
3456                                  CCP_Declaration,
3457                                  CXCursor_ModuleImportDecl,
3458                                  (*Sub)->isAvailable()
3459                                    ? CXAvailability_Available
3460                                    : CXAvailability_NotAvailable));
3461       }
3462     }
3463   }
3464   Results.ExitScope();
3465   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3466                             Results.data(),Results.size());
3467 }
3468 
3469 void Sema::CodeCompleteOrdinaryName(Scope *S,
3470                                     ParserCompletionContext CompletionContext) {
3471   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3472                         CodeCompleter->getCodeCompletionTUInfo(),
3473                         mapCodeCompletionContext(*this, CompletionContext));
3474   Results.EnterNewScope();
3475 
3476   // Determine how to filter results, e.g., so that the names of
3477   // values (functions, enumerators, function templates, etc.) are
3478   // only allowed where we can have an expression.
3479   switch (CompletionContext) {
3480   case PCC_Namespace:
3481   case PCC_Class:
3482   case PCC_ObjCInterface:
3483   case PCC_ObjCImplementation:
3484   case PCC_ObjCInstanceVariableList:
3485   case PCC_Template:
3486   case PCC_MemberTemplate:
3487   case PCC_Type:
3488   case PCC_LocalDeclarationSpecifiers:
3489     Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3490     break;
3491 
3492   case PCC_Statement:
3493   case PCC_ParenthesizedExpression:
3494   case PCC_Expression:
3495   case PCC_ForInit:
3496   case PCC_Condition:
3497     if (WantTypesInContext(CompletionContext, getLangOpts()))
3498       Results.setFilter(&ResultBuilder::IsOrdinaryName);
3499     else
3500       Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3501 
3502     if (getLangOpts().CPlusPlus)
3503       MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
3504     break;
3505 
3506   case PCC_RecoveryInFunction:
3507     // Unfiltered
3508     break;
3509   }
3510 
3511   // If we are in a C++ non-static member function, check the qualifiers on
3512   // the member function to filter/prioritize the results list.
3513   if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3514     if (CurMethod->isInstance())
3515       Results.setObjectTypeQualifiers(
3516                       Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3517 
3518   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3519   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3520                      CodeCompleter->includeGlobals());
3521 
3522   AddOrdinaryNameResults(CompletionContext, S, *this, Results);
3523   Results.ExitScope();
3524 
3525   switch (CompletionContext) {
3526   case PCC_ParenthesizedExpression:
3527   case PCC_Expression:
3528   case PCC_Statement:
3529   case PCC_RecoveryInFunction:
3530     if (S->getFnParent())
3531       AddPrettyFunctionResults(getLangOpts(), Results);
3532     break;
3533 
3534   case PCC_Namespace:
3535   case PCC_Class:
3536   case PCC_ObjCInterface:
3537   case PCC_ObjCImplementation:
3538   case PCC_ObjCInstanceVariableList:
3539   case PCC_Template:
3540   case PCC_MemberTemplate:
3541   case PCC_ForInit:
3542   case PCC_Condition:
3543   case PCC_Type:
3544   case PCC_LocalDeclarationSpecifiers:
3545     break;
3546   }
3547 
3548   if (CodeCompleter->includeMacros())
3549     AddMacroResults(PP, Results, false);
3550 
3551   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3552                             Results.data(),Results.size());
3553 }
3554 
3555 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3556                                        ParsedType Receiver,
3557                                        ArrayRef<IdentifierInfo *> SelIdents,
3558                                        bool AtArgumentExpression,
3559                                        bool IsSuper,
3560                                        ResultBuilder &Results);
3561 
3562 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3563                                 bool AllowNonIdentifiers,
3564                                 bool AllowNestedNameSpecifiers) {
3565   typedef CodeCompletionResult Result;
3566   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3567                         CodeCompleter->getCodeCompletionTUInfo(),
3568                         AllowNestedNameSpecifiers
3569                           ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3570                           : CodeCompletionContext::CCC_Name);
3571   Results.EnterNewScope();
3572 
3573   // Type qualifiers can come after names.
3574   Results.AddResult(Result("const"));
3575   Results.AddResult(Result("volatile"));
3576   if (getLangOpts().C99)
3577     Results.AddResult(Result("restrict"));
3578 
3579   if (getLangOpts().CPlusPlus) {
3580     if (getLangOpts().CPlusPlus11 &&
3581         (DS.getTypeSpecType() == DeclSpec::TST_class ||
3582          DS.getTypeSpecType() == DeclSpec::TST_struct))
3583       Results.AddResult("final");
3584 
3585     if (AllowNonIdentifiers) {
3586       Results.AddResult(Result("operator"));
3587     }
3588 
3589     // Add nested-name-specifiers.
3590     if (AllowNestedNameSpecifiers) {
3591       Results.allowNestedNameSpecifiers();
3592       Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
3593       CodeCompletionDeclConsumer Consumer(Results, CurContext);
3594       LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3595                          CodeCompleter->includeGlobals());
3596       Results.setFilter(nullptr);
3597     }
3598   }
3599   Results.ExitScope();
3600 
3601   // If we're in a context where we might have an expression (rather than a
3602   // declaration), and what we've seen so far is an Objective-C type that could
3603   // be a receiver of a class message, this may be a class message send with
3604   // the initial opening bracket '[' missing. Add appropriate completions.
3605   if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3606       DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3607       DS.getTypeSpecType() == DeclSpec::TST_typename &&
3608       DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3609       DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3610       !DS.isTypeAltiVecVector() &&
3611       S &&
3612       (S->getFlags() & Scope::DeclScope) != 0 &&
3613       (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3614                         Scope::FunctionPrototypeScope |
3615                         Scope::AtCatchScope)) == 0) {
3616     ParsedType T = DS.getRepAsType();
3617     if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
3618       AddClassMessageCompletions(*this, S, T, None, false, false, Results);
3619   }
3620 
3621   // Note that we intentionally suppress macro results here, since we do not
3622   // encourage using macros to produce the names of entities.
3623 
3624   HandleCodeCompleteResults(this, CodeCompleter,
3625                             Results.getCompletionContext(),
3626                             Results.data(), Results.size());
3627 }
3628 
3629 struct Sema::CodeCompleteExpressionData {
3630   CodeCompleteExpressionData(QualType PreferredType = QualType())
3631     : PreferredType(PreferredType), IntegralConstantExpression(false),
3632       ObjCCollection(false) { }
3633 
3634   QualType PreferredType;
3635   bool IntegralConstantExpression;
3636   bool ObjCCollection;
3637   SmallVector<Decl *, 4> IgnoreDecls;
3638 };
3639 
3640 /// \brief Perform code-completion in an expression context when we know what
3641 /// type we're looking for.
3642 void Sema::CodeCompleteExpression(Scope *S,
3643                                   const CodeCompleteExpressionData &Data) {
3644   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3645                         CodeCompleter->getCodeCompletionTUInfo(),
3646                         CodeCompletionContext::CCC_Expression);
3647   if (Data.ObjCCollection)
3648     Results.setFilter(&ResultBuilder::IsObjCCollection);
3649   else if (Data.IntegralConstantExpression)
3650     Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
3651   else if (WantTypesInContext(PCC_Expression, getLangOpts()))
3652     Results.setFilter(&ResultBuilder::IsOrdinaryName);
3653   else
3654     Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3655 
3656   if (!Data.PreferredType.isNull())
3657     Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3658 
3659   // Ignore any declarations that we were told that we don't care about.
3660   for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3661     Results.Ignore(Data.IgnoreDecls[I]);
3662 
3663   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3664   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3665                      CodeCompleter->includeGlobals());
3666 
3667   Results.EnterNewScope();
3668   AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
3669   Results.ExitScope();
3670 
3671   bool PreferredTypeIsPointer = false;
3672   if (!Data.PreferredType.isNull())
3673     PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3674       || Data.PreferredType->isMemberPointerType()
3675       || Data.PreferredType->isBlockPointerType();
3676 
3677   if (S->getFnParent() &&
3678       !Data.ObjCCollection &&
3679       !Data.IntegralConstantExpression)
3680     AddPrettyFunctionResults(getLangOpts(), Results);
3681 
3682   if (CodeCompleter->includeMacros())
3683     AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
3684   HandleCodeCompleteResults(this, CodeCompleter,
3685                 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3686                                       Data.PreferredType),
3687                             Results.data(),Results.size());
3688 }
3689 
3690 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3691   if (E.isInvalid())
3692     CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3693   else if (getLangOpts().ObjC1)
3694     CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
3695 }
3696 
3697 /// \brief The set of properties that have already been added, referenced by
3698 /// property name.
3699 typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3700 
3701 /// \brief Retrieve the container definition, if any?
3702 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3703   if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3704     if (Interface->hasDefinition())
3705       return Interface->getDefinition();
3706 
3707     return Interface;
3708   }
3709 
3710   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3711     if (Protocol->hasDefinition())
3712       return Protocol->getDefinition();
3713 
3714     return Protocol;
3715   }
3716   return Container;
3717 }
3718 
3719 /// \brief Adds a block invocation code completion result for the given block
3720 /// declaration \p BD.
3721 static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
3722                              CodeCompletionBuilder &Builder,
3723                              const NamedDecl *BD,
3724                              const FunctionTypeLoc &BlockLoc,
3725                              const FunctionProtoTypeLoc &BlockProtoLoc) {
3726   Builder.AddResultTypeChunk(
3727       GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
3728                               Policy, Builder.getAllocator()));
3729 
3730   AddTypedNameChunk(Context, Policy, BD, Builder);
3731   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3732 
3733   if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
3734     Builder.AddPlaceholderChunk("...");
3735   } else {
3736     for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
3737       if (I)
3738         Builder.AddChunk(CodeCompletionString::CK_Comma);
3739 
3740       // Format the placeholder string.
3741       std::string PlaceholderStr =
3742           FormatFunctionParameter(Policy, BlockLoc.getParam(I));
3743 
3744       if (I == N - 1 && BlockProtoLoc &&
3745           BlockProtoLoc.getTypePtr()->isVariadic())
3746         PlaceholderStr += ", ...";
3747 
3748       // Add the placeholder string.
3749       Builder.AddPlaceholderChunk(
3750           Builder.getAllocator().CopyString(PlaceholderStr));
3751     }
3752   }
3753 
3754   Builder.AddChunk(CodeCompletionString::CK_RightParen);
3755 }
3756 
3757 static void AddObjCProperties(
3758     const CodeCompletionContext &CCContext, ObjCContainerDecl *Container,
3759     bool AllowCategories, bool AllowNullaryMethods, DeclContext *CurContext,
3760     AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
3761     bool IsBaseExprStatement = false, bool IsClassProperty = false) {
3762   typedef CodeCompletionResult Result;
3763 
3764   // Retrieve the definition.
3765   Container = getContainerDef(Container);
3766 
3767   // Add properties in this container.
3768   const auto AddProperty = [&](const ObjCPropertyDecl *P) {
3769     if (!AddedProperties.insert(P->getIdentifier()).second)
3770       return;
3771 
3772     // FIXME: Provide block invocation completion for non-statement
3773     // expressions.
3774     if (!P->getType().getTypePtr()->isBlockPointerType() ||
3775         !IsBaseExprStatement) {
3776       Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3777                              CurContext);
3778       return;
3779     }
3780 
3781     // Block setter and invocation completion is provided only when we are able
3782     // to find the FunctionProtoTypeLoc with parameter names for the block.
3783     FunctionTypeLoc BlockLoc;
3784     FunctionProtoTypeLoc BlockProtoLoc;
3785     findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
3786                                  BlockProtoLoc);
3787     if (!BlockLoc) {
3788       Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3789                              CurContext);
3790       return;
3791     }
3792 
3793     // The default completion result for block properties should be the block
3794     // invocation completion when the base expression is a statement.
3795     CodeCompletionBuilder Builder(Results.getAllocator(),
3796                                   Results.getCodeCompletionTUInfo());
3797     AddObjCBlockCall(Container->getASTContext(),
3798                      getCompletionPrintingPolicy(Results.getSema()), Builder, P,
3799                      BlockLoc, BlockProtoLoc);
3800     Results.MaybeAddResult(
3801         Result(Builder.TakeString(), P, Results.getBasePriority(P)),
3802         CurContext);
3803 
3804     // Provide additional block setter completion iff the base expression is a
3805     // statement and the block property is mutable.
3806     if (!P->isReadOnly()) {
3807       CodeCompletionBuilder Builder(Results.getAllocator(),
3808                                     Results.getCodeCompletionTUInfo());
3809       AddResultTypeChunk(Container->getASTContext(),
3810                          getCompletionPrintingPolicy(Results.getSema()), P,
3811                          CCContext.getBaseType(), Builder);
3812       Builder.AddTypedTextChunk(
3813           Results.getAllocator().CopyString(P->getName()));
3814       Builder.AddChunk(CodeCompletionString::CK_Equal);
3815 
3816       std::string PlaceholderStr = formatBlockPlaceholder(
3817           getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
3818           BlockProtoLoc, /*SuppressBlockName=*/true);
3819       // Add the placeholder string.
3820       Builder.AddPlaceholderChunk(
3821           Builder.getAllocator().CopyString(PlaceholderStr));
3822 
3823       // When completing blocks properties that return void the default
3824       // property completion result should show up before the setter,
3825       // otherwise the setter completion should show up before the default
3826       // property completion, as we normally want to use the result of the
3827       // call.
3828       Results.MaybeAddResult(
3829           Result(Builder.TakeString(), P,
3830                  Results.getBasePriority(P) +
3831                      (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
3832                           ? CCD_BlockPropertySetter
3833                           : -CCD_BlockPropertySetter)),
3834           CurContext);
3835     }
3836   };
3837 
3838   if (IsClassProperty) {
3839     for (const auto *P : Container->class_properties())
3840       AddProperty(P);
3841   } else {
3842     for (const auto *P : Container->instance_properties())
3843       AddProperty(P);
3844   }
3845 
3846   // Add nullary methods or implicit class properties
3847   if (AllowNullaryMethods) {
3848     ASTContext &Context = Container->getASTContext();
3849     PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
3850     // Adds a method result
3851     const auto AddMethod = [&](const ObjCMethodDecl *M) {
3852       IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
3853       if (!Name)
3854         return;
3855       if (!AddedProperties.insert(Name).second)
3856         return;
3857       CodeCompletionBuilder Builder(Results.getAllocator(),
3858                                     Results.getCodeCompletionTUInfo());
3859       AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
3860       Builder.AddTypedTextChunk(
3861           Results.getAllocator().CopyString(Name->getName()));
3862       Results.MaybeAddResult(
3863           Result(Builder.TakeString(), M,
3864                  CCP_MemberDeclaration + CCD_MethodAsProperty),
3865           CurContext);
3866     };
3867 
3868     if (IsClassProperty) {
3869       for (const auto *M : Container->methods()) {
3870         // Gather the class method that can be used as implicit property
3871         // getters. Methods with arguments or methods that return void aren't
3872         // added to the results as they can't be used as a getter.
3873         if (!M->getSelector().isUnarySelector() ||
3874             M->getReturnType()->isVoidType() || M->isInstanceMethod())
3875           continue;
3876         AddMethod(M);
3877       }
3878     } else {
3879       for (auto *M : Container->methods()) {
3880         if (M->getSelector().isUnarySelector())
3881           AddMethod(M);
3882       }
3883     }
3884   }
3885 
3886   // Add properties in referenced protocols.
3887   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3888     for (auto *P : Protocol->protocols())
3889       AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3890                         CurContext, AddedProperties, Results,
3891                         IsBaseExprStatement, IsClassProperty);
3892   } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
3893     if (AllowCategories) {
3894       // Look through categories.
3895       for (auto *Cat : IFace->known_categories())
3896         AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
3897                           CurContext, AddedProperties, Results,
3898                           IsBaseExprStatement, IsClassProperty);
3899     }
3900 
3901     // Look through protocols.
3902     for (auto *I : IFace->all_referenced_protocols())
3903       AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
3904                         CurContext, AddedProperties, Results,
3905                         IsBaseExprStatement, IsClassProperty);
3906 
3907     // Look in the superclass.
3908     if (IFace->getSuperClass())
3909       AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
3910                         AllowNullaryMethods, CurContext, AddedProperties,
3911                         Results, IsBaseExprStatement, IsClassProperty);
3912   } else if (const ObjCCategoryDecl *Category
3913                                     = dyn_cast<ObjCCategoryDecl>(Container)) {
3914     // Look through protocols.
3915     for (auto *P : Category->protocols())
3916       AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3917                         CurContext, AddedProperties, Results,
3918                         IsBaseExprStatement, IsClassProperty);
3919   }
3920 }
3921 
3922 static void AddRecordMembersCompletionResults(Sema &SemaRef,
3923                                               ResultBuilder &Results, Scope *S,
3924                                               QualType BaseType,
3925                                               RecordDecl *RD) {
3926   // Indicate that we are performing a member access, and the cv-qualifiers
3927   // for the base object type.
3928   Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3929 
3930   // Access to a C/C++ class, struct, or union.
3931   Results.allowNestedNameSpecifiers();
3932   CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
3933   SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
3934                              SemaRef.CodeCompleter->includeGlobals(),
3935                              /*IncludeDependentBases=*/true);
3936 
3937   if (SemaRef.getLangOpts().CPlusPlus) {
3938     if (!Results.empty()) {
3939       // The "template" keyword can follow "->" or "." in the grammar.
3940       // However, we only want to suggest the template keyword if something
3941       // is dependent.
3942       bool IsDependent = BaseType->isDependentType();
3943       if (!IsDependent) {
3944         for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3945           if (DeclContext *Ctx = DepScope->getEntity()) {
3946             IsDependent = Ctx->isDependentContext();
3947             break;
3948           }
3949       }
3950 
3951       if (IsDependent)
3952         Results.AddResult(CodeCompletionResult("template"));
3953     }
3954   }
3955 }
3956 
3957 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
3958                                            SourceLocation OpLoc, bool IsArrow,
3959                                            bool IsBaseExprStatement) {
3960   if (!Base || !CodeCompleter)
3961     return;
3962 
3963   ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3964   if (ConvertedBase.isInvalid())
3965     return;
3966   Base = ConvertedBase.get();
3967 
3968   QualType BaseType = Base->getType();
3969 
3970   if (IsArrow) {
3971     if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3972       BaseType = Ptr->getPointeeType();
3973     else if (BaseType->isObjCObjectPointerType())
3974       /*Do nothing*/ ;
3975     else
3976       return;
3977   }
3978 
3979   enum CodeCompletionContext::Kind contextKind;
3980 
3981   if (IsArrow) {
3982     contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3983   }
3984   else {
3985     if (BaseType->isObjCObjectPointerType() ||
3986         BaseType->isObjCObjectOrInterfaceType()) {
3987       contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3988     }
3989     else {
3990       contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3991     }
3992   }
3993 
3994   CodeCompletionContext CCContext(contextKind, BaseType);
3995   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3996                         CodeCompleter->getCodeCompletionTUInfo(),
3997                         CCContext,
3998                         &ResultBuilder::IsMember);
3999   Results.EnterNewScope();
4000   if (const RecordType *Record = BaseType->getAs<RecordType>()) {
4001     AddRecordMembersCompletionResults(*this, Results, S, BaseType,
4002                                       Record->getDecl());
4003   } else if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
4004     TemplateName TN = TST->getTemplateName();
4005     if (const auto *TD =
4006             dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) {
4007       CXXRecordDecl *RD = TD->getTemplatedDecl();
4008       AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
4009     }
4010   } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) {
4011     if (auto *RD = ICNT->getDecl())
4012       AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
4013   } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
4014     // Objective-C property reference.
4015     AddedPropertiesSet AddedProperties;
4016 
4017     if (const ObjCObjectPointerType *ObjCPtr =
4018             BaseType->getAsObjCInterfacePointerType()) {
4019       // Add property results based on our interface.
4020       assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
4021       AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
4022                         /*AllowNullaryMethods=*/true, CurContext,
4023                         AddedProperties, Results, IsBaseExprStatement);
4024     }
4025 
4026     // Add properties from the protocols in a qualified interface.
4027     for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals())
4028       AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
4029                         CurContext, AddedProperties, Results,
4030                         IsBaseExprStatement);
4031   } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
4032              (!IsArrow && BaseType->isObjCObjectType())) {
4033     // Objective-C instance variable access.
4034     ObjCInterfaceDecl *Class = nullptr;
4035     if (const ObjCObjectPointerType *ObjCPtr
4036                                     = BaseType->getAs<ObjCObjectPointerType>())
4037       Class = ObjCPtr->getInterfaceDecl();
4038     else
4039       Class = BaseType->getAs<ObjCObjectType>()->getInterface();
4040 
4041     // Add all ivars from this class and its superclasses.
4042     if (Class) {
4043       CodeCompletionDeclConsumer Consumer(Results, CurContext);
4044       Results.setFilter(&ResultBuilder::IsObjCIvar);
4045       LookupVisibleDecls(Class, LookupMemberName, Consumer,
4046                          CodeCompleter->includeGlobals());
4047     }
4048   }
4049 
4050   // FIXME: How do we cope with isa?
4051 
4052   Results.ExitScope();
4053 
4054   // Hand off the results found for code completion.
4055   HandleCodeCompleteResults(this, CodeCompleter,
4056                             Results.getCompletionContext(),
4057                             Results.data(),Results.size());
4058 }
4059 
4060 void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
4061                                                 IdentifierInfo &ClassName,
4062                                                 SourceLocation ClassNameLoc,
4063                                                 bool IsBaseExprStatement) {
4064   IdentifierInfo *ClassNamePtr = &ClassName;
4065   ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
4066   if (!IFace)
4067     return;
4068   CodeCompletionContext CCContext(
4069       CodeCompletionContext::CCC_ObjCPropertyAccess);
4070   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4071                         CodeCompleter->getCodeCompletionTUInfo(), CCContext,
4072                         &ResultBuilder::IsMember);
4073   Results.EnterNewScope();
4074   AddedPropertiesSet AddedProperties;
4075   AddObjCProperties(CCContext, IFace, true,
4076                     /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
4077                     Results, IsBaseExprStatement,
4078                     /*IsClassProperty=*/true);
4079   Results.ExitScope();
4080   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4081                             Results.data(), Results.size());
4082 }
4083 
4084 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
4085   if (!CodeCompleter)
4086     return;
4087 
4088   ResultBuilder::LookupFilter Filter = nullptr;
4089   enum CodeCompletionContext::Kind ContextKind
4090     = CodeCompletionContext::CCC_Other;
4091   switch ((DeclSpec::TST)TagSpec) {
4092   case DeclSpec::TST_enum:
4093     Filter = &ResultBuilder::IsEnum;
4094     ContextKind = CodeCompletionContext::CCC_EnumTag;
4095     break;
4096 
4097   case DeclSpec::TST_union:
4098     Filter = &ResultBuilder::IsUnion;
4099     ContextKind = CodeCompletionContext::CCC_UnionTag;
4100     break;
4101 
4102   case DeclSpec::TST_struct:
4103   case DeclSpec::TST_class:
4104   case DeclSpec::TST_interface:
4105     Filter = &ResultBuilder::IsClassOrStruct;
4106     ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
4107     break;
4108 
4109   default:
4110     llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
4111   }
4112 
4113   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4114                         CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
4115   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4116 
4117   // First pass: look for tags.
4118   Results.setFilter(Filter);
4119   LookupVisibleDecls(S, LookupTagName, Consumer,
4120                      CodeCompleter->includeGlobals());
4121 
4122   if (CodeCompleter->includeGlobals()) {
4123     // Second pass: look for nested name specifiers.
4124     Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
4125     LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
4126   }
4127 
4128   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4129                             Results.data(),Results.size());
4130 }
4131 
4132 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
4133                                     const LangOptions &LangOpts) {
4134   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
4135     Results.AddResult("const");
4136   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
4137     Results.AddResult("volatile");
4138   if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
4139     Results.AddResult("restrict");
4140   if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
4141     Results.AddResult("_Atomic");
4142   if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
4143     Results.AddResult("__unaligned");
4144 }
4145 
4146 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
4147   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4148                         CodeCompleter->getCodeCompletionTUInfo(),
4149                         CodeCompletionContext::CCC_TypeQualifiers);
4150   Results.EnterNewScope();
4151   AddTypeQualifierResults(DS, Results, LangOpts);
4152   Results.ExitScope();
4153   HandleCodeCompleteResults(this, CodeCompleter,
4154                             Results.getCompletionContext(),
4155                             Results.data(), Results.size());
4156 }
4157 
4158 void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
4159                                           const VirtSpecifiers *VS) {
4160   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4161                         CodeCompleter->getCodeCompletionTUInfo(),
4162                         CodeCompletionContext::CCC_TypeQualifiers);
4163   Results.EnterNewScope();
4164   AddTypeQualifierResults(DS, Results, LangOpts);
4165   if (LangOpts.CPlusPlus11) {
4166     Results.AddResult("noexcept");
4167     if (D.getContext() == Declarator::MemberContext && !D.isCtorOrDtor() &&
4168         !D.isStaticMember()) {
4169       if (!VS || !VS->isFinalSpecified())
4170         Results.AddResult("final");
4171       if (!VS || !VS->isOverrideSpecified())
4172         Results.AddResult("override");
4173     }
4174   }
4175   Results.ExitScope();
4176   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4177                             Results.data(), Results.size());
4178 }
4179 
4180 void Sema::CodeCompleteBracketDeclarator(Scope *S) {
4181   CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
4182 }
4183 
4184 void Sema::CodeCompleteCase(Scope *S) {
4185   if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
4186     return;
4187 
4188   SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
4189   QualType type = Switch->getCond()->IgnoreImplicit()->getType();
4190   if (!type->isEnumeralType()) {
4191     CodeCompleteExpressionData Data(type);
4192     Data.IntegralConstantExpression = true;
4193     CodeCompleteExpression(S, Data);
4194     return;
4195   }
4196 
4197   // Code-complete the cases of a switch statement over an enumeration type
4198   // by providing the list of
4199   EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
4200   if (EnumDecl *Def = Enum->getDefinition())
4201     Enum = Def;
4202 
4203   // Determine which enumerators we have already seen in the switch statement.
4204   // FIXME: Ideally, we would also be able to look *past* the code-completion
4205   // token, in case we are code-completing in the middle of the switch and not
4206   // at the end. However, we aren't able to do so at the moment.
4207   llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
4208   NestedNameSpecifier *Qualifier = nullptr;
4209   for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
4210        SC = SC->getNextSwitchCase()) {
4211     CaseStmt *Case = dyn_cast<CaseStmt>(SC);
4212     if (!Case)
4213       continue;
4214 
4215     Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
4216     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
4217       if (EnumConstantDecl *Enumerator
4218             = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4219         // We look into the AST of the case statement to determine which
4220         // enumerator was named. Alternatively, we could compute the value of
4221         // the integral constant expression, then compare it against the
4222         // values of each enumerator. However, value-based approach would not
4223         // work as well with C++ templates where enumerators declared within a
4224         // template are type- and value-dependent.
4225         EnumeratorsSeen.insert(Enumerator);
4226 
4227         // If this is a qualified-id, keep track of the nested-name-specifier
4228         // so that we can reproduce it as part of code completion, e.g.,
4229         //
4230         //   switch (TagD.getKind()) {
4231         //     case TagDecl::TK_enum:
4232         //       break;
4233         //     case XXX
4234         //
4235         // At the XXX, our completions are TagDecl::TK_union,
4236         // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
4237         // TK_struct, and TK_class.
4238         Qualifier = DRE->getQualifier();
4239       }
4240   }
4241 
4242   if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
4243     // If there are no prior enumerators in C++, check whether we have to
4244     // qualify the names of the enumerators that we suggest, because they
4245     // may not be visible in this scope.
4246     Qualifier = getRequiredQualification(Context, CurContext, Enum);
4247   }
4248 
4249   // Add any enumerators that have not yet been mentioned.
4250   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4251                         CodeCompleter->getCodeCompletionTUInfo(),
4252                         CodeCompletionContext::CCC_Expression);
4253   Results.EnterNewScope();
4254   for (auto *E : Enum->enumerators()) {
4255     if (EnumeratorsSeen.count(E))
4256       continue;
4257 
4258     CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
4259     Results.AddResult(R, CurContext, nullptr, false);
4260   }
4261   Results.ExitScope();
4262 
4263   //We need to make sure we're setting the right context,
4264   //so only say we include macros if the code completer says we do
4265   enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
4266   if (CodeCompleter->includeMacros()) {
4267     AddMacroResults(PP, Results, false);
4268     kind = CodeCompletionContext::CCC_OtherWithMacros;
4269   }
4270 
4271   HandleCodeCompleteResults(this, CodeCompleter,
4272                             kind,
4273                             Results.data(),Results.size());
4274 }
4275 
4276 static bool anyNullArguments(ArrayRef<Expr *> Args) {
4277   if (Args.size() && !Args.data())
4278     return true;
4279 
4280   for (unsigned I = 0; I != Args.size(); ++I)
4281     if (!Args[I])
4282       return true;
4283 
4284   return false;
4285 }
4286 
4287 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
4288 
4289 static void mergeCandidatesWithResults(Sema &SemaRef,
4290                                       SmallVectorImpl<ResultCandidate> &Results,
4291                                        OverloadCandidateSet &CandidateSet,
4292                                        SourceLocation Loc) {
4293   if (!CandidateSet.empty()) {
4294     // Sort the overload candidate set by placing the best overloads first.
4295     std::stable_sort(
4296         CandidateSet.begin(), CandidateSet.end(),
4297         [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
4298           return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
4299                                            CandidateSet.getKind());
4300         });
4301 
4302     // Add the remaining viable overload candidates as code-completion results.
4303     for (auto &Candidate : CandidateSet) {
4304       if (Candidate.Function && Candidate.Function->isDeleted())
4305         continue;
4306       if (Candidate.Viable)
4307         Results.push_back(ResultCandidate(Candidate.Function));
4308     }
4309   }
4310 }
4311 
4312 /// \brief Get the type of the Nth parameter from a given set of overload
4313 /// candidates.
4314 static QualType getParamType(Sema &SemaRef,
4315                              ArrayRef<ResultCandidate> Candidates,
4316                              unsigned N) {
4317 
4318   // Given the overloads 'Candidates' for a function call matching all arguments
4319   // up to N, return the type of the Nth parameter if it is the same for all
4320   // overload candidates.
4321   QualType ParamType;
4322   for (auto &Candidate : Candidates) {
4323     if (auto FType = Candidate.getFunctionType())
4324       if (auto Proto = dyn_cast<FunctionProtoType>(FType))
4325         if (N < Proto->getNumParams()) {
4326           if (ParamType.isNull())
4327             ParamType = Proto->getParamType(N);
4328           else if (!SemaRef.Context.hasSameUnqualifiedType(
4329                         ParamType.getNonReferenceType(),
4330                         Proto->getParamType(N).getNonReferenceType()))
4331             // Otherwise return a default-constructed QualType.
4332             return QualType();
4333         }
4334   }
4335 
4336   return ParamType;
4337 }
4338 
4339 static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
4340                                     MutableArrayRef<ResultCandidate> Candidates,
4341                                         unsigned CurrentArg,
4342                                  bool CompleteExpressionWithCurrentArg = true) {
4343   QualType ParamType;
4344   if (CompleteExpressionWithCurrentArg)
4345     ParamType = getParamType(SemaRef, Candidates, CurrentArg);
4346 
4347   if (ParamType.isNull())
4348     SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
4349   else
4350     SemaRef.CodeCompleteExpression(S, ParamType);
4351 
4352   if (!Candidates.empty())
4353     SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
4354                                                      Candidates.data(),
4355                                                      Candidates.size());
4356 }
4357 
4358 void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
4359   if (!CodeCompleter)
4360     return;
4361 
4362   // When we're code-completing for a call, we fall back to ordinary
4363   // name code-completion whenever we can't produce specific
4364   // results. We may want to revisit this strategy in the future,
4365   // e.g., by merging the two kinds of results.
4366 
4367   // FIXME: Provide support for variadic template functions.
4368 
4369   // Ignore type-dependent call expressions entirely.
4370   if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4371       Expr::hasAnyTypeDependentArguments(Args)) {
4372     CodeCompleteOrdinaryName(S, PCC_Expression);
4373     return;
4374   }
4375 
4376   // Build an overload candidate set based on the functions we find.
4377   SourceLocation Loc = Fn->getExprLoc();
4378   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4379 
4380   SmallVector<ResultCandidate, 8> Results;
4381 
4382   Expr *NakedFn = Fn->IgnoreParenCasts();
4383   if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
4384     AddOverloadedCallCandidates(ULE, Args, CandidateSet,
4385                                 /*PartialOverloading=*/true);
4386   else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4387     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4388     if (UME->hasExplicitTemplateArgs()) {
4389       UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4390       TemplateArgs = &TemplateArgsBuffer;
4391     }
4392 
4393     // Add the base as first argument (use a nullptr if the base is implicit).
4394     SmallVector<Expr *, 12> ArgExprs(
4395         1, UME->isImplicitAccess() ? nullptr : UME->getBase());
4396     ArgExprs.append(Args.begin(), Args.end());
4397     UnresolvedSet<8> Decls;
4398     Decls.append(UME->decls_begin(), UME->decls_end());
4399     const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase();
4400     AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4401                           /*SuppressUsedConversions=*/false,
4402                           /*PartialOverloading=*/true,
4403                           FirstArgumentIsBase);
4404   } else {
4405     FunctionDecl *FD = nullptr;
4406     if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4407       FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4408     else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4409       FD = dyn_cast<FunctionDecl>(DRE->getDecl());
4410     if (FD) { // We check whether it's a resolved function declaration.
4411       if (!getLangOpts().CPlusPlus ||
4412           !FD->getType()->getAs<FunctionProtoType>())
4413         Results.push_back(ResultCandidate(FD));
4414       else
4415         AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4416                              Args, CandidateSet,
4417                              /*SuppressUsedConversions=*/false,
4418                              /*PartialOverloading=*/true);
4419 
4420     } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4421       // If expression's type is CXXRecordDecl, it may overload the function
4422       // call operator, so we check if it does and add them as candidates.
4423       // A complete type is needed to lookup for member function call operators.
4424       if (isCompleteType(Loc, NakedFn->getType())) {
4425         DeclarationName OpName = Context.DeclarationNames
4426                                  .getCXXOperatorName(OO_Call);
4427         LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4428         LookupQualifiedName(R, DC);
4429         R.suppressDiagnostics();
4430         SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4431         ArgExprs.append(Args.begin(), Args.end());
4432         AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4433                               /*ExplicitArgs=*/nullptr,
4434                               /*SuppressUsedConversions=*/false,
4435                               /*PartialOverloading=*/true);
4436       }
4437     } else {
4438       // Lastly we check whether expression's type is function pointer or
4439       // function.
4440       QualType T = NakedFn->getType();
4441       if (!T->getPointeeType().isNull())
4442         T = T->getPointeeType();
4443 
4444       if (auto FP = T->getAs<FunctionProtoType>()) {
4445         if (!TooManyArguments(FP->getNumParams(), Args.size(),
4446                              /*PartialOverloading=*/true) ||
4447             FP->isVariadic())
4448           Results.push_back(ResultCandidate(FP));
4449       } else if (auto FT = T->getAs<FunctionType>())
4450         // No prototype and declaration, it may be a K & R style function.
4451         Results.push_back(ResultCandidate(FT));
4452     }
4453   }
4454 
4455   mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4456   CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4457                               !CandidateSet.empty());
4458 }
4459 
4460 void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4461                                    ArrayRef<Expr *> Args) {
4462   if (!CodeCompleter)
4463     return;
4464 
4465   // A complete type is needed to lookup for constructors.
4466   if (!isCompleteType(Loc, Type))
4467     return;
4468 
4469   CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4470   if (!RD) {
4471     CodeCompleteExpression(S, Type);
4472     return;
4473   }
4474 
4475   // FIXME: Provide support for member initializers.
4476   // FIXME: Provide support for variadic template constructors.
4477 
4478   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4479 
4480   for (auto C : LookupConstructors(RD)) {
4481     if (auto FD = dyn_cast<FunctionDecl>(C)) {
4482       AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4483                            Args, CandidateSet,
4484                            /*SuppressUsedConversions=*/false,
4485                            /*PartialOverloading=*/true);
4486     } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4487       AddTemplateOverloadCandidate(FTD,
4488                                    DeclAccessPair::make(FTD, C->getAccess()),
4489                                    /*ExplicitTemplateArgs=*/nullptr,
4490                                    Args, CandidateSet,
4491                                    /*SuppressUsedConversions=*/false,
4492                                    /*PartialOverloading=*/true);
4493     }
4494   }
4495 
4496   SmallVector<ResultCandidate, 8> Results;
4497   mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4498   CodeCompleteOverloadResults(*this, S, Results, Args.size());
4499 }
4500 
4501 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4502   ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
4503   if (!VD) {
4504     CodeCompleteOrdinaryName(S, PCC_Expression);
4505     return;
4506   }
4507 
4508   CodeCompleteExpression(S, VD->getType());
4509 }
4510 
4511 void Sema::CodeCompleteReturn(Scope *S) {
4512   QualType ResultType;
4513   if (isa<BlockDecl>(CurContext)) {
4514     if (BlockScopeInfo *BSI = getCurBlock())
4515       ResultType = BSI->ReturnType;
4516   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
4517     ResultType = Function->getReturnType();
4518   else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
4519     ResultType = Method->getReturnType();
4520 
4521   if (ResultType.isNull())
4522     CodeCompleteOrdinaryName(S, PCC_Expression);
4523   else
4524     CodeCompleteExpression(S, ResultType);
4525 }
4526 
4527 void Sema::CodeCompleteAfterIf(Scope *S) {
4528   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4529                         CodeCompleter->getCodeCompletionTUInfo(),
4530                         mapCodeCompletionContext(*this, PCC_Statement));
4531   Results.setFilter(&ResultBuilder::IsOrdinaryName);
4532   Results.EnterNewScope();
4533 
4534   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4535   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4536                      CodeCompleter->includeGlobals());
4537 
4538   AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4539 
4540   // "else" block
4541   CodeCompletionBuilder Builder(Results.getAllocator(),
4542                                 Results.getCodeCompletionTUInfo());
4543   Builder.AddTypedTextChunk("else");
4544   if (Results.includeCodePatterns()) {
4545     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4546     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4547     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4548     Builder.AddPlaceholderChunk("statements");
4549     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4550     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4551   }
4552   Results.AddResult(Builder.TakeString());
4553 
4554   // "else if" block
4555   Builder.AddTypedTextChunk("else");
4556   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4557   Builder.AddTextChunk("if");
4558   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4559   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4560   if (getLangOpts().CPlusPlus)
4561     Builder.AddPlaceholderChunk("condition");
4562   else
4563     Builder.AddPlaceholderChunk("expression");
4564   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4565   if (Results.includeCodePatterns()) {
4566     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4567     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4568     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4569     Builder.AddPlaceholderChunk("statements");
4570     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4571     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4572   }
4573   Results.AddResult(Builder.TakeString());
4574 
4575   Results.ExitScope();
4576 
4577   if (S->getFnParent())
4578     AddPrettyFunctionResults(getLangOpts(), Results);
4579 
4580   if (CodeCompleter->includeMacros())
4581     AddMacroResults(PP, Results, false);
4582 
4583   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4584                             Results.data(),Results.size());
4585 }
4586 
4587 void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
4588   if (LHS)
4589     CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4590   else
4591     CodeCompleteOrdinaryName(S, PCC_Expression);
4592 }
4593 
4594 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
4595                                    bool EnteringContext) {
4596   if (!SS.getScopeRep() || !CodeCompleter)
4597     return;
4598 
4599   // Always pretend to enter a context to ensure that a dependent type
4600   // resolves to a dependent record.
4601   DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true);
4602   if (!Ctx)
4603     return;
4604 
4605   // Try to instantiate any non-dependent declaration contexts before
4606   // we look in them.
4607   if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
4608     return;
4609 
4610   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4611                         CodeCompleter->getCodeCompletionTUInfo(),
4612                         CodeCompletionContext::CCC_Name);
4613   Results.EnterNewScope();
4614 
4615   // The "template" keyword can follow "::" in the grammar, but only
4616   // put it into the grammar if the nested-name-specifier is dependent.
4617   NestedNameSpecifier *NNS = SS.getScopeRep();
4618   if (!Results.empty() && NNS->isDependent())
4619     Results.AddResult("template");
4620 
4621   // Add calls to overridden virtual functions, if there are any.
4622   //
4623   // FIXME: This isn't wonderful, because we don't know whether we're actually
4624   // in a context that permits expressions. This is a general issue with
4625   // qualified-id completions.
4626   if (!EnteringContext)
4627     MaybeAddOverrideCalls(*this, Ctx, Results);
4628   Results.ExitScope();
4629 
4630   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4631   LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
4632                      /*IncludeGlobalScope=*/true,
4633                      /*IncludeDependentBases=*/true);
4634 
4635   HandleCodeCompleteResults(this, CodeCompleter,
4636                             Results.getCompletionContext(),
4637                             Results.data(),Results.size());
4638 }
4639 
4640 void Sema::CodeCompleteUsing(Scope *S) {
4641   if (!CodeCompleter)
4642     return;
4643 
4644   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4645                         CodeCompleter->getCodeCompletionTUInfo(),
4646                         CodeCompletionContext::CCC_PotentiallyQualifiedName,
4647                         &ResultBuilder::IsNestedNameSpecifier);
4648   Results.EnterNewScope();
4649 
4650   // If we aren't in class scope, we could see the "namespace" keyword.
4651   if (!S->isClassScope())
4652     Results.AddResult(CodeCompletionResult("namespace"));
4653 
4654   // After "using", we can see anything that would start a
4655   // nested-name-specifier.
4656   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4657   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4658                      CodeCompleter->includeGlobals());
4659   Results.ExitScope();
4660 
4661   HandleCodeCompleteResults(this, CodeCompleter,
4662                             CodeCompletionContext::CCC_PotentiallyQualifiedName,
4663                             Results.data(),Results.size());
4664 }
4665 
4666 void Sema::CodeCompleteUsingDirective(Scope *S) {
4667   if (!CodeCompleter)
4668     return;
4669 
4670   // After "using namespace", we expect to see a namespace name or namespace
4671   // alias.
4672   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4673                         CodeCompleter->getCodeCompletionTUInfo(),
4674                         CodeCompletionContext::CCC_Namespace,
4675                         &ResultBuilder::IsNamespaceOrAlias);
4676   Results.EnterNewScope();
4677   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4678   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4679                      CodeCompleter->includeGlobals());
4680   Results.ExitScope();
4681   HandleCodeCompleteResults(this, CodeCompleter,
4682                             CodeCompletionContext::CCC_Namespace,
4683                             Results.data(),Results.size());
4684 }
4685 
4686 void Sema::CodeCompleteNamespaceDecl(Scope *S)  {
4687   if (!CodeCompleter)
4688     return;
4689 
4690   DeclContext *Ctx = S->getEntity();
4691   if (!S->getParent())
4692     Ctx = Context.getTranslationUnitDecl();
4693 
4694   bool SuppressedGlobalResults
4695     = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4696 
4697   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4698                         CodeCompleter->getCodeCompletionTUInfo(),
4699                         SuppressedGlobalResults
4700                           ? CodeCompletionContext::CCC_Namespace
4701                           : CodeCompletionContext::CCC_Other,
4702                         &ResultBuilder::IsNamespace);
4703 
4704   if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
4705     // We only want to see those namespaces that have already been defined
4706     // within this scope, because its likely that the user is creating an
4707     // extended namespace declaration. Keep track of the most recent
4708     // definition of each namespace.
4709     std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4710     for (DeclContext::specific_decl_iterator<NamespaceDecl>
4711          NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4712          NS != NSEnd; ++NS)
4713       OrigToLatest[NS->getOriginalNamespace()] = *NS;
4714 
4715     // Add the most recent definition (or extended definition) of each
4716     // namespace to the list of results.
4717     Results.EnterNewScope();
4718     for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
4719               NS = OrigToLatest.begin(),
4720            NSEnd = OrigToLatest.end();
4721          NS != NSEnd; ++NS)
4722       Results.AddResult(CodeCompletionResult(
4723                           NS->second, Results.getBasePriority(NS->second),
4724                           nullptr),
4725                         CurContext, nullptr, false);
4726     Results.ExitScope();
4727   }
4728 
4729   HandleCodeCompleteResults(this, CodeCompleter,
4730                             Results.getCompletionContext(),
4731                             Results.data(),Results.size());
4732 }
4733 
4734 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S)  {
4735   if (!CodeCompleter)
4736     return;
4737 
4738   // After "namespace", we expect to see a namespace or alias.
4739   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4740                         CodeCompleter->getCodeCompletionTUInfo(),
4741                         CodeCompletionContext::CCC_Namespace,
4742                         &ResultBuilder::IsNamespaceOrAlias);
4743   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4744   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4745                      CodeCompleter->includeGlobals());
4746   HandleCodeCompleteResults(this, CodeCompleter,
4747                             Results.getCompletionContext(),
4748                             Results.data(),Results.size());
4749 }
4750 
4751 void Sema::CodeCompleteOperatorName(Scope *S) {
4752   if (!CodeCompleter)
4753     return;
4754 
4755   typedef CodeCompletionResult Result;
4756   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4757                         CodeCompleter->getCodeCompletionTUInfo(),
4758                         CodeCompletionContext::CCC_Type,
4759                         &ResultBuilder::IsType);
4760   Results.EnterNewScope();
4761 
4762   // Add the names of overloadable operators.
4763 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly)      \
4764   if (std::strcmp(Spelling, "?"))                                                  \
4765     Results.AddResult(Result(Spelling));
4766 #include "clang/Basic/OperatorKinds.def"
4767 
4768   // Add any type names visible from the current scope
4769   Results.allowNestedNameSpecifiers();
4770   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4771   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4772                      CodeCompleter->includeGlobals());
4773 
4774   // Add any type specifiers
4775   AddTypeSpecifierResults(getLangOpts(), Results);
4776   Results.ExitScope();
4777 
4778   HandleCodeCompleteResults(this, CodeCompleter,
4779                             CodeCompletionContext::CCC_Type,
4780                             Results.data(),Results.size());
4781 }
4782 
4783 void Sema::CodeCompleteConstructorInitializer(
4784                               Decl *ConstructorD,
4785                               ArrayRef <CXXCtorInitializer *> Initializers) {
4786   if (!ConstructorD)
4787     return;
4788 
4789   AdjustDeclIfTemplate(ConstructorD);
4790 
4791   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
4792   if (!Constructor)
4793     return;
4794 
4795   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4796                         CodeCompleter->getCodeCompletionTUInfo(),
4797                         CodeCompletionContext::CCC_PotentiallyQualifiedName);
4798   Results.EnterNewScope();
4799 
4800   // Fill in any already-initialized fields or base classes.
4801   llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4802   llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4803   for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
4804     if (Initializers[I]->isBaseInitializer())
4805       InitializedBases.insert(
4806         Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4807     else
4808       InitializedFields.insert(cast<FieldDecl>(
4809                                Initializers[I]->getAnyMember()));
4810   }
4811 
4812   // Add completions for base classes.
4813   CodeCompletionBuilder Builder(Results.getAllocator(),
4814                                 Results.getCodeCompletionTUInfo());
4815   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
4816   bool SawLastInitializer = Initializers.empty();
4817   CXXRecordDecl *ClassDecl = Constructor->getParent();
4818   for (const auto &Base : ClassDecl->bases()) {
4819     if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4820              .second) {
4821       SawLastInitializer
4822         = !Initializers.empty() &&
4823           Initializers.back()->isBaseInitializer() &&
4824           Context.hasSameUnqualifiedType(Base.getType(),
4825                QualType(Initializers.back()->getBaseClass(), 0));
4826       continue;
4827     }
4828 
4829     Builder.AddTypedTextChunk(
4830                Results.getAllocator().CopyString(
4831                           Base.getType().getAsString(Policy)));
4832     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4833     Builder.AddPlaceholderChunk("args");
4834     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4835     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4836                                    SawLastInitializer? CCP_NextInitializer
4837                                                      : CCP_MemberDeclaration));
4838     SawLastInitializer = false;
4839   }
4840 
4841   // Add completions for virtual base classes.
4842   for (const auto &Base : ClassDecl->vbases()) {
4843     if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4844              .second) {
4845       SawLastInitializer
4846         = !Initializers.empty() &&
4847           Initializers.back()->isBaseInitializer() &&
4848           Context.hasSameUnqualifiedType(Base.getType(),
4849                QualType(Initializers.back()->getBaseClass(), 0));
4850       continue;
4851     }
4852 
4853     Builder.AddTypedTextChunk(
4854                Builder.getAllocator().CopyString(
4855                           Base.getType().getAsString(Policy)));
4856     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4857     Builder.AddPlaceholderChunk("args");
4858     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4859     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4860                                    SawLastInitializer? CCP_NextInitializer
4861                                                      : CCP_MemberDeclaration));
4862     SawLastInitializer = false;
4863   }
4864 
4865   // Add completions for members.
4866   for (auto *Field : ClassDecl->fields()) {
4867     if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4868              .second) {
4869       SawLastInitializer
4870         = !Initializers.empty() &&
4871           Initializers.back()->isAnyMemberInitializer() &&
4872           Initializers.back()->getAnyMember() == Field;
4873       continue;
4874     }
4875 
4876     if (!Field->getDeclName())
4877       continue;
4878 
4879     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
4880                                          Field->getIdentifier()->getName()));
4881     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4882     Builder.AddPlaceholderChunk("args");
4883     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4884     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4885                                    SawLastInitializer? CCP_NextInitializer
4886                                                      : CCP_MemberDeclaration,
4887                                            CXCursor_MemberRef,
4888                                            CXAvailability_Available,
4889                                            Field));
4890     SawLastInitializer = false;
4891   }
4892   Results.ExitScope();
4893 
4894   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4895                             Results.data(), Results.size());
4896 }
4897 
4898 /// \brief Determine whether this scope denotes a namespace.
4899 static bool isNamespaceScope(Scope *S) {
4900   DeclContext *DC = S->getEntity();
4901   if (!DC)
4902     return false;
4903 
4904   return DC->isFileContext();
4905 }
4906 
4907 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4908                                         bool AfterAmpersand) {
4909   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4910                         CodeCompleter->getCodeCompletionTUInfo(),
4911                         CodeCompletionContext::CCC_Other);
4912   Results.EnterNewScope();
4913 
4914   // Note what has already been captured.
4915   llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4916   bool IncludedThis = false;
4917   for (const auto &C : Intro.Captures) {
4918     if (C.Kind == LCK_This) {
4919       IncludedThis = true;
4920       continue;
4921     }
4922 
4923     Known.insert(C.Id);
4924   }
4925 
4926   // Look for other capturable variables.
4927   for (; S && !isNamespaceScope(S); S = S->getParent()) {
4928     for (const auto *D : S->decls()) {
4929       const auto *Var = dyn_cast<VarDecl>(D);
4930       if (!Var ||
4931           !Var->hasLocalStorage() ||
4932           Var->hasAttr<BlocksAttr>())
4933         continue;
4934 
4935       if (Known.insert(Var->getIdentifier()).second)
4936         Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
4937                           CurContext, nullptr, false);
4938     }
4939   }
4940 
4941   // Add 'this', if it would be valid.
4942   if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4943     addThisCompletion(*this, Results);
4944 
4945   Results.ExitScope();
4946 
4947   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4948                             Results.data(), Results.size());
4949 }
4950 
4951 /// Macro that optionally prepends an "@" to the string literal passed in via
4952 /// Keyword, depending on whether NeedAt is true or false.
4953 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4954 
4955 static void AddObjCImplementationResults(const LangOptions &LangOpts,
4956                                          ResultBuilder &Results,
4957                                          bool NeedAt) {
4958   typedef CodeCompletionResult Result;
4959   // Since we have an implementation, we can end it.
4960   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
4961 
4962   CodeCompletionBuilder Builder(Results.getAllocator(),
4963                                 Results.getCodeCompletionTUInfo());
4964   if (LangOpts.ObjC2) {
4965     // @dynamic
4966     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
4967     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4968     Builder.AddPlaceholderChunk("property");
4969     Results.AddResult(Result(Builder.TakeString()));
4970 
4971     // @synthesize
4972     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
4973     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4974     Builder.AddPlaceholderChunk("property");
4975     Results.AddResult(Result(Builder.TakeString()));
4976   }
4977 }
4978 
4979 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
4980                                     ResultBuilder &Results,
4981                                     bool NeedAt) {
4982   typedef CodeCompletionResult Result;
4983 
4984   // Since we have an interface or protocol, we can end it.
4985   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
4986 
4987   if (LangOpts.ObjC2) {
4988     // @property
4989     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
4990 
4991     // @required
4992     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
4993 
4994     // @optional
4995     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
4996   }
4997 }
4998 
4999 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
5000   typedef CodeCompletionResult Result;
5001   CodeCompletionBuilder Builder(Results.getAllocator(),
5002                                 Results.getCodeCompletionTUInfo());
5003 
5004   // @class name ;
5005   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
5006   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5007   Builder.AddPlaceholderChunk("name");
5008   Results.AddResult(Result(Builder.TakeString()));
5009 
5010   if (Results.includeCodePatterns()) {
5011     // @interface name
5012     // FIXME: Could introduce the whole pattern, including superclasses and
5013     // such.
5014     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
5015     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5016     Builder.AddPlaceholderChunk("class");
5017     Results.AddResult(Result(Builder.TakeString()));
5018 
5019     // @protocol name
5020     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
5021     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5022     Builder.AddPlaceholderChunk("protocol");
5023     Results.AddResult(Result(Builder.TakeString()));
5024 
5025     // @implementation name
5026     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
5027     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5028     Builder.AddPlaceholderChunk("class");
5029     Results.AddResult(Result(Builder.TakeString()));
5030   }
5031 
5032   // @compatibility_alias name
5033   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
5034   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5035   Builder.AddPlaceholderChunk("alias");
5036   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5037   Builder.AddPlaceholderChunk("class");
5038   Results.AddResult(Result(Builder.TakeString()));
5039 
5040   if (Results.getSema().getLangOpts().Modules) {
5041     // @import name
5042     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
5043     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5044     Builder.AddPlaceholderChunk("module");
5045     Results.AddResult(Result(Builder.TakeString()));
5046   }
5047 }
5048 
5049 void Sema::CodeCompleteObjCAtDirective(Scope *S) {
5050   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5051                         CodeCompleter->getCodeCompletionTUInfo(),
5052                         CodeCompletionContext::CCC_Other);
5053   Results.EnterNewScope();
5054   if (isa<ObjCImplDecl>(CurContext))
5055     AddObjCImplementationResults(getLangOpts(), Results, false);
5056   else if (CurContext->isObjCContainer())
5057     AddObjCInterfaceResults(getLangOpts(), Results, false);
5058   else
5059     AddObjCTopLevelResults(Results, false);
5060   Results.ExitScope();
5061   HandleCodeCompleteResults(this, CodeCompleter,
5062                             CodeCompletionContext::CCC_Other,
5063                             Results.data(),Results.size());
5064 }
5065 
5066 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
5067   typedef CodeCompletionResult Result;
5068   CodeCompletionBuilder Builder(Results.getAllocator(),
5069                                 Results.getCodeCompletionTUInfo());
5070 
5071   // @encode ( type-name )
5072   const char *EncodeType = "char[]";
5073   if (Results.getSema().getLangOpts().CPlusPlus ||
5074       Results.getSema().getLangOpts().ConstStrings)
5075     EncodeType = "const char[]";
5076   Builder.AddResultTypeChunk(EncodeType);
5077   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
5078   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5079   Builder.AddPlaceholderChunk("type-name");
5080   Builder.AddChunk(CodeCompletionString::CK_RightParen);
5081   Results.AddResult(Result(Builder.TakeString()));
5082 
5083   // @protocol ( protocol-name )
5084   Builder.AddResultTypeChunk("Protocol *");
5085   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
5086   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5087   Builder.AddPlaceholderChunk("protocol-name");
5088   Builder.AddChunk(CodeCompletionString::CK_RightParen);
5089   Results.AddResult(Result(Builder.TakeString()));
5090 
5091   // @selector ( selector )
5092   Builder.AddResultTypeChunk("SEL");
5093   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
5094   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5095   Builder.AddPlaceholderChunk("selector");
5096   Builder.AddChunk(CodeCompletionString::CK_RightParen);
5097   Results.AddResult(Result(Builder.TakeString()));
5098 
5099   // @"string"
5100   Builder.AddResultTypeChunk("NSString *");
5101   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
5102   Builder.AddPlaceholderChunk("string");
5103   Builder.AddTextChunk("\"");
5104   Results.AddResult(Result(Builder.TakeString()));
5105 
5106   // @[objects, ...]
5107   Builder.AddResultTypeChunk("NSArray *");
5108   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
5109   Builder.AddPlaceholderChunk("objects, ...");
5110   Builder.AddChunk(CodeCompletionString::CK_RightBracket);
5111   Results.AddResult(Result(Builder.TakeString()));
5112 
5113   // @{key : object, ...}
5114   Builder.AddResultTypeChunk("NSDictionary *");
5115   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
5116   Builder.AddPlaceholderChunk("key");
5117   Builder.AddChunk(CodeCompletionString::CK_Colon);
5118   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5119   Builder.AddPlaceholderChunk("object, ...");
5120   Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5121   Results.AddResult(Result(Builder.TakeString()));
5122 
5123   // @(expression)
5124   Builder.AddResultTypeChunk("id");
5125   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
5126   Builder.AddPlaceholderChunk("expression");
5127   Builder.AddChunk(CodeCompletionString::CK_RightParen);
5128   Results.AddResult(Result(Builder.TakeString()));
5129 }
5130 
5131 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
5132   typedef CodeCompletionResult Result;
5133   CodeCompletionBuilder Builder(Results.getAllocator(),
5134                                 Results.getCodeCompletionTUInfo());
5135 
5136   if (Results.includeCodePatterns()) {
5137     // @try { statements } @catch ( declaration ) { statements } @finally
5138     //   { statements }
5139     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
5140     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5141     Builder.AddPlaceholderChunk("statements");
5142     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5143     Builder.AddTextChunk("@catch");
5144     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5145     Builder.AddPlaceholderChunk("parameter");
5146     Builder.AddChunk(CodeCompletionString::CK_RightParen);
5147     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5148     Builder.AddPlaceholderChunk("statements");
5149     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5150     Builder.AddTextChunk("@finally");
5151     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5152     Builder.AddPlaceholderChunk("statements");
5153     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5154     Results.AddResult(Result(Builder.TakeString()));
5155   }
5156 
5157   // @throw
5158   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
5159   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5160   Builder.AddPlaceholderChunk("expression");
5161   Results.AddResult(Result(Builder.TakeString()));
5162 
5163   if (Results.includeCodePatterns()) {
5164     // @synchronized ( expression ) { statements }
5165     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
5166     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5167     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5168     Builder.AddPlaceholderChunk("expression");
5169     Builder.AddChunk(CodeCompletionString::CK_RightParen);
5170     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5171     Builder.AddPlaceholderChunk("statements");
5172     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5173     Results.AddResult(Result(Builder.TakeString()));
5174   }
5175 }
5176 
5177 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
5178                                      ResultBuilder &Results,
5179                                      bool NeedAt) {
5180   typedef CodeCompletionResult Result;
5181   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
5182   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
5183   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
5184   if (LangOpts.ObjC2)
5185     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
5186 }
5187 
5188 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
5189   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5190                         CodeCompleter->getCodeCompletionTUInfo(),
5191                         CodeCompletionContext::CCC_Other);
5192   Results.EnterNewScope();
5193   AddObjCVisibilityResults(getLangOpts(), Results, false);
5194   Results.ExitScope();
5195   HandleCodeCompleteResults(this, CodeCompleter,
5196                             CodeCompletionContext::CCC_Other,
5197                             Results.data(),Results.size());
5198 }
5199 
5200 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
5201   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5202                         CodeCompleter->getCodeCompletionTUInfo(),
5203                         CodeCompletionContext::CCC_Other);
5204   Results.EnterNewScope();
5205   AddObjCStatementResults(Results, false);
5206   AddObjCExpressionResults(Results, false);
5207   Results.ExitScope();
5208   HandleCodeCompleteResults(this, CodeCompleter,
5209                             CodeCompletionContext::CCC_Other,
5210                             Results.data(),Results.size());
5211 }
5212 
5213 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
5214   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5215                         CodeCompleter->getCodeCompletionTUInfo(),
5216                         CodeCompletionContext::CCC_Other);
5217   Results.EnterNewScope();
5218   AddObjCExpressionResults(Results, false);
5219   Results.ExitScope();
5220   HandleCodeCompleteResults(this, CodeCompleter,
5221                             CodeCompletionContext::CCC_Other,
5222                             Results.data(),Results.size());
5223 }
5224 
5225 /// \brief Determine whether the addition of the given flag to an Objective-C
5226 /// property's attributes will cause a conflict.
5227 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
5228   // Check if we've already added this flag.
5229   if (Attributes & NewFlag)
5230     return true;
5231 
5232   Attributes |= NewFlag;
5233 
5234   // Check for collisions with "readonly".
5235   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
5236       (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
5237     return true;
5238 
5239   // Check for more than one of { assign, copy, retain, strong, weak }.
5240   unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
5241                                          ObjCDeclSpec::DQ_PR_unsafe_unretained |
5242                                              ObjCDeclSpec::DQ_PR_copy |
5243                                              ObjCDeclSpec::DQ_PR_retain |
5244                                              ObjCDeclSpec::DQ_PR_strong |
5245                                              ObjCDeclSpec::DQ_PR_weak);
5246   if (AssignCopyRetMask &&
5247       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
5248       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
5249       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
5250       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
5251       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
5252       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
5253     return true;
5254 
5255   return false;
5256 }
5257 
5258 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
5259   if (!CodeCompleter)
5260     return;
5261 
5262   unsigned Attributes = ODS.getPropertyAttributes();
5263 
5264   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5265                         CodeCompleter->getCodeCompletionTUInfo(),
5266                         CodeCompletionContext::CCC_Other);
5267   Results.EnterNewScope();
5268   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
5269     Results.AddResult(CodeCompletionResult("readonly"));
5270   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
5271     Results.AddResult(CodeCompletionResult("assign"));
5272   if (!ObjCPropertyFlagConflicts(Attributes,
5273                                  ObjCDeclSpec::DQ_PR_unsafe_unretained))
5274     Results.AddResult(CodeCompletionResult("unsafe_unretained"));
5275   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
5276     Results.AddResult(CodeCompletionResult("readwrite"));
5277   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
5278     Results.AddResult(CodeCompletionResult("retain"));
5279   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
5280     Results.AddResult(CodeCompletionResult("strong"));
5281   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
5282     Results.AddResult(CodeCompletionResult("copy"));
5283   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
5284     Results.AddResult(CodeCompletionResult("nonatomic"));
5285   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
5286     Results.AddResult(CodeCompletionResult("atomic"));
5287 
5288   // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
5289   if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
5290     if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
5291       Results.AddResult(CodeCompletionResult("weak"));
5292 
5293   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
5294     CodeCompletionBuilder Setter(Results.getAllocator(),
5295                                  Results.getCodeCompletionTUInfo());
5296     Setter.AddTypedTextChunk("setter");
5297     Setter.AddTextChunk("=");
5298     Setter.AddPlaceholderChunk("method");
5299     Results.AddResult(CodeCompletionResult(Setter.TakeString()));
5300   }
5301   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
5302     CodeCompletionBuilder Getter(Results.getAllocator(),
5303                                  Results.getCodeCompletionTUInfo());
5304     Getter.AddTypedTextChunk("getter");
5305     Getter.AddTextChunk("=");
5306     Getter.AddPlaceholderChunk("method");
5307     Results.AddResult(CodeCompletionResult(Getter.TakeString()));
5308   }
5309   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
5310     Results.AddResult(CodeCompletionResult("nonnull"));
5311     Results.AddResult(CodeCompletionResult("nullable"));
5312     Results.AddResult(CodeCompletionResult("null_unspecified"));
5313     Results.AddResult(CodeCompletionResult("null_resettable"));
5314   }
5315   Results.ExitScope();
5316   HandleCodeCompleteResults(this, CodeCompleter,
5317                             CodeCompletionContext::CCC_Other,
5318                             Results.data(),Results.size());
5319 }
5320 
5321 /// \brief Describes the kind of Objective-C method that we want to find
5322 /// via code completion.
5323 enum ObjCMethodKind {
5324   MK_Any, ///< Any kind of method, provided it means other specified criteria.
5325   MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
5326   MK_OneArgSelector ///< One-argument selector.
5327 };
5328 
5329 static bool isAcceptableObjCSelector(Selector Sel,
5330                                      ObjCMethodKind WantKind,
5331                                      ArrayRef<IdentifierInfo *> SelIdents,
5332                                      bool AllowSameLength = true) {
5333   unsigned NumSelIdents = SelIdents.size();
5334   if (NumSelIdents > Sel.getNumArgs())
5335     return false;
5336 
5337   switch (WantKind) {
5338     case MK_Any:             break;
5339     case MK_ZeroArgSelector: return Sel.isUnarySelector();
5340     case MK_OneArgSelector:  return Sel.getNumArgs() == 1;
5341   }
5342 
5343   if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
5344     return false;
5345 
5346   for (unsigned I = 0; I != NumSelIdents; ++I)
5347     if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
5348       return false;
5349 
5350   return true;
5351 }
5352 
5353 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
5354                                    ObjCMethodKind WantKind,
5355                                    ArrayRef<IdentifierInfo *> SelIdents,
5356                                    bool AllowSameLength = true) {
5357   return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
5358                                   AllowSameLength);
5359 }
5360 
5361 namespace {
5362   /// \brief A set of selectors, which is used to avoid introducing multiple
5363   /// completions with the same selector into the result set.
5364   typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
5365 }
5366 
5367 /// \brief Add all of the Objective-C methods in the given Objective-C
5368 /// container to the set of results.
5369 ///
5370 /// The container will be a class, protocol, category, or implementation of
5371 /// any of the above. This mether will recurse to include methods from
5372 /// the superclasses of classes along with their categories, protocols, and
5373 /// implementations.
5374 ///
5375 /// \param Container the container in which we'll look to find methods.
5376 ///
5377 /// \param WantInstanceMethods Whether to add instance methods (only); if
5378 /// false, this routine will add factory methods (only).
5379 ///
5380 /// \param CurContext the context in which we're performing the lookup that
5381 /// finds methods.
5382 ///
5383 /// \param AllowSameLength Whether we allow a method to be added to the list
5384 /// when it has the same number of parameters as we have selector identifiers.
5385 ///
5386 /// \param Results the structure into which we'll add results.
5387 static void AddObjCMethods(ObjCContainerDecl *Container,
5388                            bool WantInstanceMethods, ObjCMethodKind WantKind,
5389                            ArrayRef<IdentifierInfo *> SelIdents,
5390                            DeclContext *CurContext,
5391                            VisitedSelectorSet &Selectors, bool AllowSameLength,
5392                            ResultBuilder &Results, bool InOriginalClass = true,
5393                            bool IsRootClass = false) {
5394   typedef CodeCompletionResult Result;
5395   Container = getContainerDef(Container);
5396   ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
5397   IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
5398   for (auto *M : Container->methods()) {
5399     // The instance methods on the root class can be messaged via the
5400     // metaclass.
5401     if (M->isInstanceMethod() == WantInstanceMethods ||
5402         (IsRootClass && !WantInstanceMethods)) {
5403       // Check whether the selector identifiers we've been given are a
5404       // subset of the identifiers for this particular method.
5405       if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
5406         continue;
5407 
5408       if (!Selectors.insert(M->getSelector()).second)
5409         continue;
5410 
5411       Result R = Result(M, Results.getBasePriority(M), nullptr);
5412       R.StartParameter = SelIdents.size();
5413       R.AllParametersAreInformative = (WantKind != MK_Any);
5414       if (!InOriginalClass)
5415         R.Priority += CCD_InBaseClass;
5416       Results.MaybeAddResult(R, CurContext);
5417     }
5418   }
5419 
5420   // Visit the protocols of protocols.
5421   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5422     if (Protocol->hasDefinition()) {
5423       const ObjCList<ObjCProtocolDecl> &Protocols
5424         = Protocol->getReferencedProtocols();
5425       for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5426                                                 E = Protocols.end();
5427            I != E; ++I)
5428         AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5429                        Selectors, AllowSameLength, Results, false, IsRootClass);
5430     }
5431   }
5432 
5433   if (!IFace || !IFace->hasDefinition())
5434     return;
5435 
5436   // Add methods in protocols.
5437   for (auto *I : IFace->protocols())
5438     AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5439                    Selectors, AllowSameLength, Results, false, IsRootClass);
5440 
5441   // Add methods in categories.
5442   for (auto *CatDecl : IFace->known_categories()) {
5443     AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
5444                    CurContext, Selectors, AllowSameLength, Results,
5445                    InOriginalClass, IsRootClass);
5446 
5447     // Add a categories protocol methods.
5448     const ObjCList<ObjCProtocolDecl> &Protocols
5449       = CatDecl->getReferencedProtocols();
5450     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5451                                               E = Protocols.end();
5452          I != E; ++I)
5453       AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5454                      Selectors, AllowSameLength, Results, false, IsRootClass);
5455 
5456     // Add methods in category implementations.
5457     if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
5458       AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5459                      Selectors, AllowSameLength, Results, InOriginalClass,
5460                      IsRootClass);
5461   }
5462 
5463   // Add methods in superclass.
5464   // Avoid passing in IsRootClass since root classes won't have super classes.
5465   if (IFace->getSuperClass())
5466     AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
5467                    SelIdents, CurContext, Selectors, AllowSameLength, Results,
5468                    /*IsRootClass=*/false);
5469 
5470   // Add methods in our implementation, if any.
5471   if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5472     AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5473                    Selectors, AllowSameLength, Results, InOriginalClass,
5474                    IsRootClass);
5475 }
5476 
5477 
5478 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
5479   // Try to find the interface where getters might live.
5480   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
5481   if (!Class) {
5482     if (ObjCCategoryDecl *Category
5483           = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
5484       Class = Category->getClassInterface();
5485 
5486     if (!Class)
5487       return;
5488   }
5489 
5490   // Find all of the potential getters.
5491   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5492                         CodeCompleter->getCodeCompletionTUInfo(),
5493                         CodeCompletionContext::CCC_Other);
5494   Results.EnterNewScope();
5495 
5496   VisitedSelectorSet Selectors;
5497   AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
5498                  /*AllowSameLength=*/true, Results);
5499   Results.ExitScope();
5500   HandleCodeCompleteResults(this, CodeCompleter,
5501                             CodeCompletionContext::CCC_Other,
5502                             Results.data(),Results.size());
5503 }
5504 
5505 void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
5506   // Try to find the interface where setters might live.
5507   ObjCInterfaceDecl *Class
5508     = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
5509   if (!Class) {
5510     if (ObjCCategoryDecl *Category
5511           = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
5512       Class = Category->getClassInterface();
5513 
5514     if (!Class)
5515       return;
5516   }
5517 
5518   // Find all of the potential getters.
5519   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5520                         CodeCompleter->getCodeCompletionTUInfo(),
5521                         CodeCompletionContext::CCC_Other);
5522   Results.EnterNewScope();
5523 
5524   VisitedSelectorSet Selectors;
5525   AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
5526                  Selectors, /*AllowSameLength=*/true, Results);
5527 
5528   Results.ExitScope();
5529   HandleCodeCompleteResults(this, CodeCompleter,
5530                             CodeCompletionContext::CCC_Other,
5531                             Results.data(),Results.size());
5532 }
5533 
5534 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5535                                        bool IsParameter) {
5536   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5537                         CodeCompleter->getCodeCompletionTUInfo(),
5538                         CodeCompletionContext::CCC_Type);
5539   Results.EnterNewScope();
5540 
5541   // Add context-sensitive, Objective-C parameter-passing keywords.
5542   bool AddedInOut = false;
5543   if ((DS.getObjCDeclQualifier() &
5544        (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5545     Results.AddResult("in");
5546     Results.AddResult("inout");
5547     AddedInOut = true;
5548   }
5549   if ((DS.getObjCDeclQualifier() &
5550        (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5551     Results.AddResult("out");
5552     if (!AddedInOut)
5553       Results.AddResult("inout");
5554   }
5555   if ((DS.getObjCDeclQualifier() &
5556        (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5557         ObjCDeclSpec::DQ_Oneway)) == 0) {
5558      Results.AddResult("bycopy");
5559      Results.AddResult("byref");
5560      Results.AddResult("oneway");
5561   }
5562   if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
5563     Results.AddResult("nonnull");
5564     Results.AddResult("nullable");
5565     Results.AddResult("null_unspecified");
5566   }
5567 
5568   // If we're completing the return type of an Objective-C method and the
5569   // identifier IBAction refers to a macro, provide a completion item for
5570   // an action, e.g.,
5571   //   IBAction)<#selector#>:(id)sender
5572   if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
5573       PP.isMacroDefined("IBAction")) {
5574     CodeCompletionBuilder Builder(Results.getAllocator(),
5575                                   Results.getCodeCompletionTUInfo(),
5576                                   CCP_CodePattern, CXAvailability_Available);
5577     Builder.AddTypedTextChunk("IBAction");
5578     Builder.AddChunk(CodeCompletionString::CK_RightParen);
5579     Builder.AddPlaceholderChunk("selector");
5580     Builder.AddChunk(CodeCompletionString::CK_Colon);
5581     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5582     Builder.AddTextChunk("id");
5583     Builder.AddChunk(CodeCompletionString::CK_RightParen);
5584     Builder.AddTextChunk("sender");
5585     Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5586   }
5587 
5588   // If we're completing the return type, provide 'instancetype'.
5589   if (!IsParameter) {
5590     Results.AddResult(CodeCompletionResult("instancetype"));
5591   }
5592 
5593   // Add various builtin type names and specifiers.
5594   AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5595   Results.ExitScope();
5596 
5597   // Add the various type names
5598   Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5599   CodeCompletionDeclConsumer Consumer(Results, CurContext);
5600   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5601                      CodeCompleter->includeGlobals());
5602 
5603   if (CodeCompleter->includeMacros())
5604     AddMacroResults(PP, Results, false);
5605 
5606   HandleCodeCompleteResults(this, CodeCompleter,
5607                             CodeCompletionContext::CCC_Type,
5608                             Results.data(), Results.size());
5609 }
5610 
5611 /// \brief When we have an expression with type "id", we may assume
5612 /// that it has some more-specific class type based on knowledge of
5613 /// common uses of Objective-C. This routine returns that class type,
5614 /// or NULL if no better result could be determined.
5615 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
5616   ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
5617   if (!Msg)
5618     return nullptr;
5619 
5620   Selector Sel = Msg->getSelector();
5621   if (Sel.isNull())
5622     return nullptr;
5623 
5624   IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5625   if (!Id)
5626     return nullptr;
5627 
5628   ObjCMethodDecl *Method = Msg->getMethodDecl();
5629   if (!Method)
5630     return nullptr;
5631 
5632   // Determine the class that we're sending the message to.
5633   ObjCInterfaceDecl *IFace = nullptr;
5634   switch (Msg->getReceiverKind()) {
5635   case ObjCMessageExpr::Class:
5636     if (const ObjCObjectType *ObjType
5637                            = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5638       IFace = ObjType->getInterface();
5639     break;
5640 
5641   case ObjCMessageExpr::Instance: {
5642     QualType T = Msg->getInstanceReceiver()->getType();
5643     if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5644       IFace = Ptr->getInterfaceDecl();
5645     break;
5646   }
5647 
5648   case ObjCMessageExpr::SuperInstance:
5649   case ObjCMessageExpr::SuperClass:
5650     break;
5651   }
5652 
5653   if (!IFace)
5654     return nullptr;
5655 
5656   ObjCInterfaceDecl *Super = IFace->getSuperClass();
5657   if (Method->isInstanceMethod())
5658     return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5659       .Case("retain", IFace)
5660       .Case("strong", IFace)
5661       .Case("autorelease", IFace)
5662       .Case("copy", IFace)
5663       .Case("copyWithZone", IFace)
5664       .Case("mutableCopy", IFace)
5665       .Case("mutableCopyWithZone", IFace)
5666       .Case("awakeFromCoder", IFace)
5667       .Case("replacementObjectFromCoder", IFace)
5668       .Case("class", IFace)
5669       .Case("classForCoder", IFace)
5670       .Case("superclass", Super)
5671       .Default(nullptr);
5672 
5673   return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5674     .Case("new", IFace)
5675     .Case("alloc", IFace)
5676     .Case("allocWithZone", IFace)
5677     .Case("class", IFace)
5678     .Case("superclass", Super)
5679     .Default(nullptr);
5680 }
5681 
5682 // Add a special completion for a message send to "super", which fills in the
5683 // most likely case of forwarding all of our arguments to the superclass
5684 // function.
5685 ///
5686 /// \param S The semantic analysis object.
5687 ///
5688 /// \param NeedSuperKeyword Whether we need to prefix this completion with
5689 /// the "super" keyword. Otherwise, we just need to provide the arguments.
5690 ///
5691 /// \param SelIdents The identifiers in the selector that have already been
5692 /// provided as arguments for a send to "super".
5693 ///
5694 /// \param Results The set of results to augment.
5695 ///
5696 /// \returns the Objective-C method declaration that would be invoked by
5697 /// this "super" completion. If NULL, no completion was added.
5698 static ObjCMethodDecl *AddSuperSendCompletion(
5699                                           Sema &S, bool NeedSuperKeyword,
5700                                           ArrayRef<IdentifierInfo *> SelIdents,
5701                                           ResultBuilder &Results) {
5702   ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5703   if (!CurMethod)
5704     return nullptr;
5705 
5706   ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5707   if (!Class)
5708     return nullptr;
5709 
5710   // Try to find a superclass method with the same selector.
5711   ObjCMethodDecl *SuperMethod = nullptr;
5712   while ((Class = Class->getSuperClass()) && !SuperMethod) {
5713     // Check in the class
5714     SuperMethod = Class->getMethod(CurMethod->getSelector(),
5715                                    CurMethod->isInstanceMethod());
5716 
5717     // Check in categories or class extensions.
5718     if (!SuperMethod) {
5719       for (const auto *Cat : Class->known_categories()) {
5720         if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
5721                                                CurMethod->isInstanceMethod())))
5722           break;
5723       }
5724     }
5725   }
5726 
5727   if (!SuperMethod)
5728     return nullptr;
5729 
5730   // Check whether the superclass method has the same signature.
5731   if (CurMethod->param_size() != SuperMethod->param_size() ||
5732       CurMethod->isVariadic() != SuperMethod->isVariadic())
5733     return nullptr;
5734 
5735   for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5736                                    CurPEnd = CurMethod->param_end(),
5737                                     SuperP = SuperMethod->param_begin();
5738        CurP != CurPEnd; ++CurP, ++SuperP) {
5739     // Make sure the parameter types are compatible.
5740     if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5741                                           (*SuperP)->getType()))
5742       return nullptr;
5743 
5744     // Make sure we have a parameter name to forward!
5745     if (!(*CurP)->getIdentifier())
5746       return nullptr;
5747   }
5748 
5749   // We have a superclass method. Now, form the send-to-super completion.
5750   CodeCompletionBuilder Builder(Results.getAllocator(),
5751                                 Results.getCodeCompletionTUInfo());
5752 
5753   // Give this completion a return type.
5754   AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5755                      Results.getCompletionContext().getBaseType(),
5756                      Builder);
5757 
5758   // If we need the "super" keyword, add it (plus some spacing).
5759   if (NeedSuperKeyword) {
5760     Builder.AddTypedTextChunk("super");
5761     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5762   }
5763 
5764   Selector Sel = CurMethod->getSelector();
5765   if (Sel.isUnarySelector()) {
5766     if (NeedSuperKeyword)
5767       Builder.AddTextChunk(Builder.getAllocator().CopyString(
5768                                   Sel.getNameForSlot(0)));
5769     else
5770       Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
5771                                    Sel.getNameForSlot(0)));
5772   } else {
5773     ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5774     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
5775       if (I > SelIdents.size())
5776         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5777 
5778       if (I < SelIdents.size())
5779         Builder.AddInformativeChunk(
5780                    Builder.getAllocator().CopyString(
5781                                                  Sel.getNameForSlot(I) + ":"));
5782       else if (NeedSuperKeyword || I > SelIdents.size()) {
5783         Builder.AddTextChunk(
5784                  Builder.getAllocator().CopyString(
5785                                                   Sel.getNameForSlot(I) + ":"));
5786         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5787                                          (*CurP)->getIdentifier()->getName()));
5788       } else {
5789         Builder.AddTypedTextChunk(
5790                   Builder.getAllocator().CopyString(
5791                                                   Sel.getNameForSlot(I) + ":"));
5792         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5793                                          (*CurP)->getIdentifier()->getName()));
5794       }
5795     }
5796   }
5797 
5798   Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5799                                          CCP_SuperCompletion));
5800   return SuperMethod;
5801 }
5802 
5803 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
5804   typedef CodeCompletionResult Result;
5805   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5806                         CodeCompleter->getCodeCompletionTUInfo(),
5807                         CodeCompletionContext::CCC_ObjCMessageReceiver,
5808                         getLangOpts().CPlusPlus11
5809                           ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5810                           : &ResultBuilder::IsObjCMessageReceiver);
5811 
5812   CodeCompletionDeclConsumer Consumer(Results, CurContext);
5813   Results.EnterNewScope();
5814   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5815                      CodeCompleter->includeGlobals());
5816 
5817   // If we are in an Objective-C method inside a class that has a superclass,
5818   // add "super" as an option.
5819   if (ObjCMethodDecl *Method = getCurMethodDecl())
5820     if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
5821       if (Iface->getSuperClass()) {
5822         Results.AddResult(Result("super"));
5823 
5824         AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
5825       }
5826 
5827   if (getLangOpts().CPlusPlus11)
5828     addThisCompletion(*this, Results);
5829 
5830   Results.ExitScope();
5831 
5832   if (CodeCompleter->includeMacros())
5833     AddMacroResults(PP, Results, false);
5834   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5835                             Results.data(), Results.size());
5836 
5837 }
5838 
5839 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5840                                         ArrayRef<IdentifierInfo *> SelIdents,
5841                                         bool AtArgumentExpression) {
5842   ObjCInterfaceDecl *CDecl = nullptr;
5843   if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5844     // Figure out which interface we're in.
5845     CDecl = CurMethod->getClassInterface();
5846     if (!CDecl)
5847       return;
5848 
5849     // Find the superclass of this class.
5850     CDecl = CDecl->getSuperClass();
5851     if (!CDecl)
5852       return;
5853 
5854     if (CurMethod->isInstanceMethod()) {
5855       // We are inside an instance method, which means that the message
5856       // send [super ...] is actually calling an instance method on the
5857       // current object.
5858       return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
5859                                              AtArgumentExpression,
5860                                              CDecl);
5861     }
5862 
5863     // Fall through to send to the superclass in CDecl.
5864   } else {
5865     // "super" may be the name of a type or variable. Figure out which
5866     // it is.
5867     IdentifierInfo *Super = getSuperIdentifier();
5868     NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5869                                      LookupOrdinaryName);
5870     if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5871       // "super" names an interface. Use it.
5872     } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
5873       if (const ObjCObjectType *Iface
5874             = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5875         CDecl = Iface->getInterface();
5876     } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5877       // "super" names an unresolved type; we can't be more specific.
5878     } else {
5879       // Assume that "super" names some kind of value and parse that way.
5880       CXXScopeSpec SS;
5881       SourceLocation TemplateKWLoc;
5882       UnqualifiedId id;
5883       id.setIdentifier(Super, SuperLoc);
5884       ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5885                                                false, false);
5886       return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
5887                                              SelIdents,
5888                                              AtArgumentExpression);
5889     }
5890 
5891     // Fall through
5892   }
5893 
5894   ParsedType Receiver;
5895   if (CDecl)
5896     Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
5897   return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
5898                                       AtArgumentExpression,
5899                                       /*IsSuper=*/true);
5900 }
5901 
5902 /// \brief Given a set of code-completion results for the argument of a message
5903 /// send, determine the preferred type (if any) for that argument expression.
5904 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5905                                                        unsigned NumSelIdents) {
5906   typedef CodeCompletionResult Result;
5907   ASTContext &Context = Results.getSema().Context;
5908 
5909   QualType PreferredType;
5910   unsigned BestPriority = CCP_Unlikely * 2;
5911   Result *ResultsData = Results.data();
5912   for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5913     Result &R = ResultsData[I];
5914     if (R.Kind == Result::RK_Declaration &&
5915         isa<ObjCMethodDecl>(R.Declaration)) {
5916       if (R.Priority <= BestPriority) {
5917         const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5918         if (NumSelIdents <= Method->param_size()) {
5919           QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
5920                                        ->getType();
5921           if (R.Priority < BestPriority || PreferredType.isNull()) {
5922             BestPriority = R.Priority;
5923             PreferredType = MyPreferredType;
5924           } else if (!Context.hasSameUnqualifiedType(PreferredType,
5925                                                      MyPreferredType)) {
5926             PreferredType = QualType();
5927           }
5928         }
5929       }
5930     }
5931   }
5932 
5933   return PreferredType;
5934 }
5935 
5936 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5937                                        ParsedType Receiver,
5938                                        ArrayRef<IdentifierInfo *> SelIdents,
5939                                        bool AtArgumentExpression,
5940                                        bool IsSuper,
5941                                        ResultBuilder &Results) {
5942   typedef CodeCompletionResult Result;
5943   ObjCInterfaceDecl *CDecl = nullptr;
5944 
5945   // If the given name refers to an interface type, retrieve the
5946   // corresponding declaration.
5947   if (Receiver) {
5948     QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
5949     if (!T.isNull())
5950       if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5951         CDecl = Interface->getInterface();
5952   }
5953 
5954   // Add all of the factory methods in this Objective-C class, its protocols,
5955   // superclasses, categories, implementation, etc.
5956   Results.EnterNewScope();
5957 
5958   // If this is a send-to-super, try to add the special "super" send
5959   // completion.
5960   if (IsSuper) {
5961     if (ObjCMethodDecl *SuperMethod
5962         = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
5963       Results.Ignore(SuperMethod);
5964   }
5965 
5966   // If we're inside an Objective-C method definition, prefer its selector to
5967   // others.
5968   if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
5969     Results.setPreferredSelector(CurMethod->getSelector());
5970 
5971   VisitedSelectorSet Selectors;
5972   if (CDecl)
5973     AddObjCMethods(CDecl, false, MK_Any, SelIdents,
5974                    SemaRef.CurContext, Selectors, AtArgumentExpression,
5975                    Results);
5976   else {
5977     // We're messaging "id" as a type; provide all class/factory methods.
5978 
5979     // If we have an external source, load the entire class method
5980     // pool from the AST file.
5981     if (SemaRef.getExternalSource()) {
5982       for (uint32_t I = 0,
5983                     N = SemaRef.getExternalSource()->GetNumExternalSelectors();
5984            I != N; ++I) {
5985         Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
5986         if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
5987           continue;
5988 
5989         SemaRef.ReadMethodPool(Sel);
5990       }
5991     }
5992 
5993     for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5994                                        MEnd = SemaRef.MethodPool.end();
5995          M != MEnd; ++M) {
5996       for (ObjCMethodList *MethList = &M->second.second;
5997            MethList && MethList->getMethod();
5998            MethList = MethList->getNext()) {
5999         if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
6000           continue;
6001 
6002         Result R(MethList->getMethod(),
6003                  Results.getBasePriority(MethList->getMethod()), nullptr);
6004         R.StartParameter = SelIdents.size();
6005         R.AllParametersAreInformative = false;
6006         Results.MaybeAddResult(R, SemaRef.CurContext);
6007       }
6008     }
6009   }
6010 
6011   Results.ExitScope();
6012 }
6013 
6014 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
6015                                         ArrayRef<IdentifierInfo *> SelIdents,
6016                                         bool AtArgumentExpression,
6017                                         bool IsSuper) {
6018 
6019   QualType T = this->GetTypeFromParser(Receiver);
6020 
6021   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6022                         CodeCompleter->getCodeCompletionTUInfo(),
6023               CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
6024                                     T, SelIdents));
6025 
6026   AddClassMessageCompletions(*this, S, Receiver, SelIdents,
6027                              AtArgumentExpression, IsSuper, Results);
6028 
6029   // If we're actually at the argument expression (rather than prior to the
6030   // selector), we're actually performing code completion for an expression.
6031   // Determine whether we have a single, best method. If so, we can
6032   // code-complete the expression using the corresponding parameter type as
6033   // our preferred type, improving completion results.
6034   if (AtArgumentExpression) {
6035     QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
6036                                                               SelIdents.size());
6037     if (PreferredType.isNull())
6038       CodeCompleteOrdinaryName(S, PCC_Expression);
6039     else
6040       CodeCompleteExpression(S, PreferredType);
6041     return;
6042   }
6043 
6044   HandleCodeCompleteResults(this, CodeCompleter,
6045                             Results.getCompletionContext(),
6046                             Results.data(), Results.size());
6047 }
6048 
6049 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
6050                                            ArrayRef<IdentifierInfo *> SelIdents,
6051                                            bool AtArgumentExpression,
6052                                            ObjCInterfaceDecl *Super) {
6053   typedef CodeCompletionResult Result;
6054 
6055   Expr *RecExpr = static_cast<Expr *>(Receiver);
6056 
6057   // If necessary, apply function/array conversion to the receiver.
6058   // C99 6.7.5.3p[7,8].
6059   if (RecExpr) {
6060     ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
6061     if (Conv.isInvalid()) // conversion failed. bail.
6062       return;
6063     RecExpr = Conv.get();
6064   }
6065   QualType ReceiverType = RecExpr? RecExpr->getType()
6066                           : Super? Context.getObjCObjectPointerType(
6067                                             Context.getObjCInterfaceType(Super))
6068                                  : Context.getObjCIdType();
6069 
6070   // If we're messaging an expression with type "id" or "Class", check
6071   // whether we know something special about the receiver that allows
6072   // us to assume a more-specific receiver type.
6073   if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
6074     if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
6075       if (ReceiverType->isObjCClassType())
6076         return CodeCompleteObjCClassMessage(S,
6077                        ParsedType::make(Context.getObjCInterfaceType(IFace)),
6078                                             SelIdents,
6079                                             AtArgumentExpression, Super);
6080 
6081       ReceiverType = Context.getObjCObjectPointerType(
6082                                           Context.getObjCInterfaceType(IFace));
6083     }
6084   } else if (RecExpr && getLangOpts().CPlusPlus) {
6085     ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
6086     if (Conv.isUsable()) {
6087       RecExpr = Conv.get();
6088       ReceiverType = RecExpr->getType();
6089     }
6090   }
6091 
6092   // Build the set of methods we can see.
6093   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6094                         CodeCompleter->getCodeCompletionTUInfo(),
6095            CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
6096                                  ReceiverType, SelIdents));
6097 
6098   Results.EnterNewScope();
6099 
6100   // If this is a send-to-super, try to add the special "super" send
6101   // completion.
6102   if (Super) {
6103     if (ObjCMethodDecl *SuperMethod
6104           = AddSuperSendCompletion(*this, false, SelIdents, Results))
6105       Results.Ignore(SuperMethod);
6106   }
6107 
6108   // If we're inside an Objective-C method definition, prefer its selector to
6109   // others.
6110   if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
6111     Results.setPreferredSelector(CurMethod->getSelector());
6112 
6113   // Keep track of the selectors we've already added.
6114   VisitedSelectorSet Selectors;
6115 
6116   // Handle messages to Class. This really isn't a message to an instance
6117   // method, so we treat it the same way we would treat a message send to a
6118   // class method.
6119   if (ReceiverType->isObjCClassType() ||
6120       ReceiverType->isObjCQualifiedClassType()) {
6121     if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
6122       if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
6123         AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
6124                        CurContext, Selectors, AtArgumentExpression, Results);
6125     }
6126   }
6127   // Handle messages to a qualified ID ("id<foo>").
6128   else if (const ObjCObjectPointerType *QualID
6129              = ReceiverType->getAsObjCQualifiedIdType()) {
6130     // Search protocols for instance methods.
6131     for (auto *I : QualID->quals())
6132       AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
6133                      Selectors, AtArgumentExpression, Results);
6134   }
6135   // Handle messages to a pointer to interface type.
6136   else if (const ObjCObjectPointerType *IFacePtr
6137                               = ReceiverType->getAsObjCInterfacePointerType()) {
6138     // Search the class, its superclasses, etc., for instance methods.
6139     AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
6140                    CurContext, Selectors, AtArgumentExpression,
6141                    Results);
6142 
6143     // Search protocols for instance methods.
6144     for (auto *I : IFacePtr->quals())
6145       AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
6146                      Selectors, AtArgumentExpression, Results);
6147   }
6148   // Handle messages to "id".
6149   else if (ReceiverType->isObjCIdType()) {
6150     // We're messaging "id", so provide all instance methods we know
6151     // about as code-completion results.
6152 
6153     // If we have an external source, load the entire class method
6154     // pool from the AST file.
6155     if (ExternalSource) {
6156       for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6157            I != N; ++I) {
6158         Selector Sel = ExternalSource->GetExternalSelector(I);
6159         if (Sel.isNull() || MethodPool.count(Sel))
6160           continue;
6161 
6162         ReadMethodPool(Sel);
6163       }
6164     }
6165 
6166     for (GlobalMethodPool::iterator M = MethodPool.begin(),
6167                                     MEnd = MethodPool.end();
6168          M != MEnd; ++M) {
6169       for (ObjCMethodList *MethList = &M->second.first;
6170            MethList && MethList->getMethod();
6171            MethList = MethList->getNext()) {
6172         if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
6173           continue;
6174 
6175         if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
6176           continue;
6177 
6178         Result R(MethList->getMethod(),
6179                  Results.getBasePriority(MethList->getMethod()), nullptr);
6180         R.StartParameter = SelIdents.size();
6181         R.AllParametersAreInformative = false;
6182         Results.MaybeAddResult(R, CurContext);
6183       }
6184     }
6185   }
6186   Results.ExitScope();
6187 
6188 
6189   // If we're actually at the argument expression (rather than prior to the
6190   // selector), we're actually performing code completion for an expression.
6191   // Determine whether we have a single, best method. If so, we can
6192   // code-complete the expression using the corresponding parameter type as
6193   // our preferred type, improving completion results.
6194   if (AtArgumentExpression) {
6195     QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
6196                                                               SelIdents.size());
6197     if (PreferredType.isNull())
6198       CodeCompleteOrdinaryName(S, PCC_Expression);
6199     else
6200       CodeCompleteExpression(S, PreferredType);
6201     return;
6202   }
6203 
6204   HandleCodeCompleteResults(this, CodeCompleter,
6205                             Results.getCompletionContext(),
6206                             Results.data(),Results.size());
6207 }
6208 
6209 void Sema::CodeCompleteObjCForCollection(Scope *S,
6210                                          DeclGroupPtrTy IterationVar) {
6211   CodeCompleteExpressionData Data;
6212   Data.ObjCCollection = true;
6213 
6214   if (IterationVar.getAsOpaquePtr()) {
6215     DeclGroupRef DG = IterationVar.get();
6216     for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
6217       if (*I)
6218         Data.IgnoreDecls.push_back(*I);
6219     }
6220   }
6221 
6222   CodeCompleteExpression(S, Data);
6223 }
6224 
6225 void Sema::CodeCompleteObjCSelector(Scope *S,
6226                                     ArrayRef<IdentifierInfo *> SelIdents) {
6227   // If we have an external source, load the entire class method
6228   // pool from the AST file.
6229   if (ExternalSource) {
6230     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6231          I != N; ++I) {
6232       Selector Sel = ExternalSource->GetExternalSelector(I);
6233       if (Sel.isNull() || MethodPool.count(Sel))
6234         continue;
6235 
6236       ReadMethodPool(Sel);
6237     }
6238   }
6239 
6240   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6241                         CodeCompleter->getCodeCompletionTUInfo(),
6242                         CodeCompletionContext::CCC_SelectorName);
6243   Results.EnterNewScope();
6244   for (GlobalMethodPool::iterator M = MethodPool.begin(),
6245                                MEnd = MethodPool.end();
6246        M != MEnd; ++M) {
6247 
6248     Selector Sel = M->first;
6249     if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
6250       continue;
6251 
6252     CodeCompletionBuilder Builder(Results.getAllocator(),
6253                                   Results.getCodeCompletionTUInfo());
6254     if (Sel.isUnarySelector()) {
6255       Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
6256                                                        Sel.getNameForSlot(0)));
6257       Results.AddResult(Builder.TakeString());
6258       continue;
6259     }
6260 
6261     std::string Accumulator;
6262     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
6263       if (I == SelIdents.size()) {
6264         if (!Accumulator.empty()) {
6265           Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
6266                                                  Accumulator));
6267           Accumulator.clear();
6268         }
6269       }
6270 
6271       Accumulator += Sel.getNameForSlot(I);
6272       Accumulator += ':';
6273     }
6274     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
6275     Results.AddResult(Builder.TakeString());
6276   }
6277   Results.ExitScope();
6278 
6279   HandleCodeCompleteResults(this, CodeCompleter,
6280                             CodeCompletionContext::CCC_SelectorName,
6281                             Results.data(), Results.size());
6282 }
6283 
6284 /// \brief Add all of the protocol declarations that we find in the given
6285 /// (translation unit) context.
6286 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
6287                                bool OnlyForwardDeclarations,
6288                                ResultBuilder &Results) {
6289   typedef CodeCompletionResult Result;
6290 
6291   for (const auto *D : Ctx->decls()) {
6292     // Record any protocols we find.
6293     if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
6294       if (!OnlyForwardDeclarations || !Proto->hasDefinition())
6295         Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
6296                           CurContext, nullptr, false);
6297   }
6298 }
6299 
6300 void Sema::CodeCompleteObjCProtocolReferences(
6301                                         ArrayRef<IdentifierLocPair> Protocols) {
6302   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6303                         CodeCompleter->getCodeCompletionTUInfo(),
6304                         CodeCompletionContext::CCC_ObjCProtocolName);
6305 
6306   if (CodeCompleter->includeGlobals()) {
6307     Results.EnterNewScope();
6308 
6309     // Tell the result set to ignore all of the protocols we have
6310     // already seen.
6311     // FIXME: This doesn't work when caching code-completion results.
6312     for (const IdentifierLocPair &Pair : Protocols)
6313       if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first,
6314                                                       Pair.second))
6315         Results.Ignore(Protocol);
6316 
6317     // Add all protocols.
6318     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
6319                        Results);
6320 
6321     Results.ExitScope();
6322   }
6323 
6324   HandleCodeCompleteResults(this, CodeCompleter,
6325                             CodeCompletionContext::CCC_ObjCProtocolName,
6326                             Results.data(),Results.size());
6327 }
6328 
6329 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
6330   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6331                         CodeCompleter->getCodeCompletionTUInfo(),
6332                         CodeCompletionContext::CCC_ObjCProtocolName);
6333 
6334   if (CodeCompleter->includeGlobals()) {
6335     Results.EnterNewScope();
6336 
6337     // Add all protocols.
6338     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
6339                        Results);
6340 
6341     Results.ExitScope();
6342   }
6343 
6344   HandleCodeCompleteResults(this, CodeCompleter,
6345                             CodeCompletionContext::CCC_ObjCProtocolName,
6346                             Results.data(),Results.size());
6347 }
6348 
6349 /// \brief Add all of the Objective-C interface declarations that we find in
6350 /// the given (translation unit) context.
6351 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
6352                                 bool OnlyForwardDeclarations,
6353                                 bool OnlyUnimplemented,
6354                                 ResultBuilder &Results) {
6355   typedef CodeCompletionResult Result;
6356 
6357   for (const auto *D : Ctx->decls()) {
6358     // Record any interfaces we find.
6359     if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
6360       if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
6361           (!OnlyUnimplemented || !Class->getImplementation()))
6362         Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
6363                           CurContext, nullptr, false);
6364   }
6365 }
6366 
6367 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
6368   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6369                         CodeCompleter->getCodeCompletionTUInfo(),
6370                         CodeCompletionContext::CCC_Other);
6371   Results.EnterNewScope();
6372 
6373   if (CodeCompleter->includeGlobals()) {
6374     // Add all classes.
6375     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6376                         false, Results);
6377   }
6378 
6379   Results.ExitScope();
6380 
6381   HandleCodeCompleteResults(this, CodeCompleter,
6382                             CodeCompletionContext::CCC_ObjCInterfaceName,
6383                             Results.data(),Results.size());
6384 }
6385 
6386 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6387                                       SourceLocation ClassNameLoc) {
6388   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6389                         CodeCompleter->getCodeCompletionTUInfo(),
6390                         CodeCompletionContext::CCC_ObjCInterfaceName);
6391   Results.EnterNewScope();
6392 
6393   // Make sure that we ignore the class we're currently defining.
6394   NamedDecl *CurClass
6395     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6396   if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
6397     Results.Ignore(CurClass);
6398 
6399   if (CodeCompleter->includeGlobals()) {
6400     // Add all classes.
6401     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6402                         false, Results);
6403   }
6404 
6405   Results.ExitScope();
6406 
6407   HandleCodeCompleteResults(this, CodeCompleter,
6408                             CodeCompletionContext::CCC_ObjCInterfaceName,
6409                             Results.data(),Results.size());
6410 }
6411 
6412 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
6413   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6414                         CodeCompleter->getCodeCompletionTUInfo(),
6415                         CodeCompletionContext::CCC_Other);
6416   Results.EnterNewScope();
6417 
6418   if (CodeCompleter->includeGlobals()) {
6419     // Add all unimplemented classes.
6420     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6421                         true, Results);
6422   }
6423 
6424   Results.ExitScope();
6425 
6426   HandleCodeCompleteResults(this, CodeCompleter,
6427                             CodeCompletionContext::CCC_ObjCInterfaceName,
6428                             Results.data(),Results.size());
6429 }
6430 
6431 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
6432                                              IdentifierInfo *ClassName,
6433                                              SourceLocation ClassNameLoc) {
6434   typedef CodeCompletionResult Result;
6435 
6436   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6437                         CodeCompleter->getCodeCompletionTUInfo(),
6438                         CodeCompletionContext::CCC_ObjCCategoryName);
6439 
6440   // Ignore any categories we find that have already been implemented by this
6441   // interface.
6442   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6443   NamedDecl *CurClass
6444     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6445   if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
6446     for (const auto *Cat : Class->visible_categories())
6447       CategoryNames.insert(Cat->getIdentifier());
6448   }
6449 
6450   // Add all of the categories we know about.
6451   Results.EnterNewScope();
6452   TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
6453   for (const auto *D : TU->decls())
6454     if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
6455       if (CategoryNames.insert(Category->getIdentifier()).second)
6456         Results.AddResult(Result(Category, Results.getBasePriority(Category),
6457                                  nullptr),
6458                           CurContext, nullptr, false);
6459   Results.ExitScope();
6460 
6461   HandleCodeCompleteResults(this, CodeCompleter,
6462                             CodeCompletionContext::CCC_ObjCCategoryName,
6463                             Results.data(),Results.size());
6464 }
6465 
6466 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
6467                                                   IdentifierInfo *ClassName,
6468                                                   SourceLocation ClassNameLoc) {
6469   typedef CodeCompletionResult Result;
6470 
6471   // Find the corresponding interface. If we couldn't find the interface, the
6472   // program itself is ill-formed. However, we'll try to be helpful still by
6473   // providing the list of all of the categories we know about.
6474   NamedDecl *CurClass
6475     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6476   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6477   if (!Class)
6478     return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
6479 
6480   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6481                         CodeCompleter->getCodeCompletionTUInfo(),
6482                         CodeCompletionContext::CCC_ObjCCategoryName);
6483 
6484   // Add all of the categories that have have corresponding interface
6485   // declarations in this class and any of its superclasses, except for
6486   // already-implemented categories in the class itself.
6487   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6488   Results.EnterNewScope();
6489   bool IgnoreImplemented = true;
6490   while (Class) {
6491     for (const auto *Cat : Class->visible_categories()) {
6492       if ((!IgnoreImplemented || !Cat->getImplementation()) &&
6493           CategoryNames.insert(Cat->getIdentifier()).second)
6494         Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6495                           CurContext, nullptr, false);
6496     }
6497 
6498     Class = Class->getSuperClass();
6499     IgnoreImplemented = false;
6500   }
6501   Results.ExitScope();
6502 
6503   HandleCodeCompleteResults(this, CodeCompleter,
6504                             CodeCompletionContext::CCC_ObjCCategoryName,
6505                             Results.data(),Results.size());
6506 }
6507 
6508 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
6509   CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
6510   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6511                         CodeCompleter->getCodeCompletionTUInfo(),
6512                         CCContext);
6513 
6514   // Figure out where this @synthesize lives.
6515   ObjCContainerDecl *Container
6516     = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
6517   if (!Container ||
6518       (!isa<ObjCImplementationDecl>(Container) &&
6519        !isa<ObjCCategoryImplDecl>(Container)))
6520     return;
6521 
6522   // Ignore any properties that have already been implemented.
6523   Container = getContainerDef(Container);
6524   for (const auto *D : Container->decls())
6525     if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
6526       Results.Ignore(PropertyImpl->getPropertyDecl());
6527 
6528   // Add any properties that we find.
6529   AddedPropertiesSet AddedProperties;
6530   Results.EnterNewScope();
6531   if (ObjCImplementationDecl *ClassImpl
6532         = dyn_cast<ObjCImplementationDecl>(Container))
6533     AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
6534                       /*AllowNullaryMethods=*/false, CurContext,
6535                       AddedProperties, Results);
6536   else
6537     AddObjCProperties(CCContext,
6538                       cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
6539                       false, /*AllowNullaryMethods=*/false, CurContext,
6540                       AddedProperties, Results);
6541   Results.ExitScope();
6542 
6543   HandleCodeCompleteResults(this, CodeCompleter,
6544                             CodeCompletionContext::CCC_Other,
6545                             Results.data(),Results.size());
6546 }
6547 
6548 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
6549                                                   IdentifierInfo *PropertyName) {
6550   typedef CodeCompletionResult Result;
6551   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6552                         CodeCompleter->getCodeCompletionTUInfo(),
6553                         CodeCompletionContext::CCC_Other);
6554 
6555   // Figure out where this @synthesize lives.
6556   ObjCContainerDecl *Container
6557     = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
6558   if (!Container ||
6559       (!isa<ObjCImplementationDecl>(Container) &&
6560        !isa<ObjCCategoryImplDecl>(Container)))
6561     return;
6562 
6563   // Figure out which interface we're looking into.
6564   ObjCInterfaceDecl *Class = nullptr;
6565   if (ObjCImplementationDecl *ClassImpl
6566                                  = dyn_cast<ObjCImplementationDecl>(Container))
6567     Class = ClassImpl->getClassInterface();
6568   else
6569     Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6570                                                           ->getClassInterface();
6571 
6572   // Determine the type of the property we're synthesizing.
6573   QualType PropertyType = Context.getObjCIdType();
6574   if (Class) {
6575     if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
6576             PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
6577       PropertyType
6578         = Property->getType().getNonReferenceType().getUnqualifiedType();
6579 
6580       // Give preference to ivars
6581       Results.setPreferredType(PropertyType);
6582     }
6583   }
6584 
6585   // Add all of the instance variables in this class and its superclasses.
6586   Results.EnterNewScope();
6587   bool SawSimilarlyNamedIvar = false;
6588   std::string NameWithPrefix;
6589   NameWithPrefix += '_';
6590   NameWithPrefix += PropertyName->getName();
6591   std::string NameWithSuffix = PropertyName->getName().str();
6592   NameWithSuffix += '_';
6593   for(; Class; Class = Class->getSuperClass()) {
6594     for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6595          Ivar = Ivar->getNextIvar()) {
6596       Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6597                         CurContext, nullptr, false);
6598 
6599       // Determine whether we've seen an ivar with a name similar to the
6600       // property.
6601       if ((PropertyName == Ivar->getIdentifier() ||
6602            NameWithPrefix == Ivar->getName() ||
6603            NameWithSuffix == Ivar->getName())) {
6604         SawSimilarlyNamedIvar = true;
6605 
6606         // Reduce the priority of this result by one, to give it a slight
6607         // advantage over other results whose names don't match so closely.
6608         if (Results.size() &&
6609             Results.data()[Results.size() - 1].Kind
6610                                       == CodeCompletionResult::RK_Declaration &&
6611             Results.data()[Results.size() - 1].Declaration == Ivar)
6612           Results.data()[Results.size() - 1].Priority--;
6613       }
6614     }
6615   }
6616 
6617   if (!SawSimilarlyNamedIvar) {
6618     // Create ivar result _propName, that the user can use to synthesize
6619     // an ivar of the appropriate type.
6620     unsigned Priority = CCP_MemberDeclaration + 1;
6621     typedef CodeCompletionResult Result;
6622     CodeCompletionAllocator &Allocator = Results.getAllocator();
6623     CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6624                                   Priority,CXAvailability_Available);
6625 
6626     PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
6627     Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
6628                                                        Policy, Allocator));
6629     Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6630     Results.AddResult(Result(Builder.TakeString(), Priority,
6631                              CXCursor_ObjCIvarDecl));
6632   }
6633 
6634   Results.ExitScope();
6635 
6636   HandleCodeCompleteResults(this, CodeCompleter,
6637                             CodeCompletionContext::CCC_Other,
6638                             Results.data(),Results.size());
6639 }
6640 
6641 // Mapping from selectors to the methods that implement that selector, along
6642 // with the "in original class" flag.
6643 typedef llvm::DenseMap<
6644     Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
6645 
6646 /// \brief Find all of the methods that reside in the given container
6647 /// (and its superclasses, protocols, etc.) that meet the given
6648 /// criteria. Insert those methods into the map of known methods,
6649 /// indexed by selector so they can be easily found.
6650 static void FindImplementableMethods(ASTContext &Context,
6651                                      ObjCContainerDecl *Container,
6652                                      Optional<bool> WantInstanceMethods,
6653                                      QualType ReturnType,
6654                                      KnownMethodsMap &KnownMethods,
6655                                      bool InOriginalClass = true) {
6656   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
6657     // Make sure we have a definition; that's what we'll walk.
6658     if (!IFace->hasDefinition())
6659       return;
6660 
6661     IFace = IFace->getDefinition();
6662     Container = IFace;
6663 
6664     const ObjCList<ObjCProtocolDecl> &Protocols
6665       = IFace->getReferencedProtocols();
6666     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6667                                               E = Protocols.end();
6668          I != E; ++I)
6669       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6670                                KnownMethods, InOriginalClass);
6671 
6672     // Add methods from any class extensions and categories.
6673     for (auto *Cat : IFace->visible_categories()) {
6674       FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
6675                                KnownMethods, false);
6676     }
6677 
6678     // Visit the superclass.
6679     if (IFace->getSuperClass())
6680       FindImplementableMethods(Context, IFace->getSuperClass(),
6681                                WantInstanceMethods, ReturnType,
6682                                KnownMethods, false);
6683   }
6684 
6685   if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6686     // Recurse into protocols.
6687     const ObjCList<ObjCProtocolDecl> &Protocols
6688       = Category->getReferencedProtocols();
6689     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6690                                               E = Protocols.end();
6691          I != E; ++I)
6692       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6693                                KnownMethods, InOriginalClass);
6694 
6695     // If this category is the original class, jump to the interface.
6696     if (InOriginalClass && Category->getClassInterface())
6697       FindImplementableMethods(Context, Category->getClassInterface(),
6698                                WantInstanceMethods, ReturnType, KnownMethods,
6699                                false);
6700   }
6701 
6702   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
6703     // Make sure we have a definition; that's what we'll walk.
6704     if (!Protocol->hasDefinition())
6705       return;
6706     Protocol = Protocol->getDefinition();
6707     Container = Protocol;
6708 
6709     // Recurse into protocols.
6710     const ObjCList<ObjCProtocolDecl> &Protocols
6711       = Protocol->getReferencedProtocols();
6712     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6713            E = Protocols.end();
6714          I != E; ++I)
6715       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6716                                KnownMethods, false);
6717   }
6718 
6719   // Add methods in this container. This operation occurs last because
6720   // we want the methods from this container to override any methods
6721   // we've previously seen with the same selector.
6722   for (auto *M : Container->methods()) {
6723     if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) {
6724       if (!ReturnType.isNull() &&
6725           !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
6726         continue;
6727 
6728       KnownMethods[M->getSelector()] =
6729           KnownMethodsMap::mapped_type(M, InOriginalClass);
6730     }
6731   }
6732 }
6733 
6734 /// \brief Add the parenthesized return or parameter type chunk to a code
6735 /// completion string.
6736 static void AddObjCPassingTypeChunk(QualType Type,
6737                                     unsigned ObjCDeclQuals,
6738                                     ASTContext &Context,
6739                                     const PrintingPolicy &Policy,
6740                                     CodeCompletionBuilder &Builder) {
6741   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6742   std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
6743   if (!Quals.empty())
6744     Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
6745   Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
6746                                                Builder.getAllocator()));
6747   Builder.AddChunk(CodeCompletionString::CK_RightParen);
6748 }
6749 
6750 /// \brief Determine whether the given class is or inherits from a class by
6751 /// the given name.
6752 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
6753                                    StringRef Name) {
6754   if (!Class)
6755     return false;
6756 
6757   if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6758     return true;
6759 
6760   return InheritsFromClassNamed(Class->getSuperClass(), Name);
6761 }
6762 
6763 /// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6764 /// Key-Value Observing (KVO).
6765 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6766                                        bool IsInstanceMethod,
6767                                        QualType ReturnType,
6768                                        ASTContext &Context,
6769                                        VisitedSelectorSet &KnownSelectors,
6770                                        ResultBuilder &Results) {
6771   IdentifierInfo *PropName = Property->getIdentifier();
6772   if (!PropName || PropName->getLength() == 0)
6773     return;
6774 
6775   PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6776 
6777   // Builder that will create each code completion.
6778   typedef CodeCompletionResult Result;
6779   CodeCompletionAllocator &Allocator = Results.getAllocator();
6780   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
6781 
6782   // The selector table.
6783   SelectorTable &Selectors = Context.Selectors;
6784 
6785   // The property name, copied into the code completion allocation region
6786   // on demand.
6787   struct KeyHolder {
6788     CodeCompletionAllocator &Allocator;
6789     StringRef Key;
6790     const char *CopiedKey;
6791 
6792     KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
6793     : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6794 
6795     operator const char *() {
6796       if (CopiedKey)
6797         return CopiedKey;
6798 
6799       return CopiedKey = Allocator.CopyString(Key);
6800     }
6801   } Key(Allocator, PropName->getName());
6802 
6803   // The uppercased name of the property name.
6804   std::string UpperKey = PropName->getName();
6805   if (!UpperKey.empty())
6806     UpperKey[0] = toUppercase(UpperKey[0]);
6807 
6808   bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6809     Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6810                                    Property->getType());
6811   bool ReturnTypeMatchesVoid
6812     = ReturnType.isNull() || ReturnType->isVoidType();
6813 
6814   // Add the normal accessor -(type)key.
6815   if (IsInstanceMethod &&
6816       KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
6817       ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6818     if (ReturnType.isNull())
6819       AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6820                               Context, Policy, Builder);
6821 
6822     Builder.AddTypedTextChunk(Key);
6823     Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6824                              CXCursor_ObjCInstanceMethodDecl));
6825   }
6826 
6827   // If we have an integral or boolean property (or the user has provided
6828   // an integral or boolean return type), add the accessor -(type)isKey.
6829   if (IsInstanceMethod &&
6830       ((!ReturnType.isNull() &&
6831         (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6832        (ReturnType.isNull() &&
6833         (Property->getType()->isIntegerType() ||
6834          Property->getType()->isBooleanType())))) {
6835     std::string SelectorName = (Twine("is") + UpperKey).str();
6836     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6837     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6838             .second) {
6839       if (ReturnType.isNull()) {
6840         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6841         Builder.AddTextChunk("BOOL");
6842         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6843       }
6844 
6845       Builder.AddTypedTextChunk(
6846                                 Allocator.CopyString(SelectorId->getName()));
6847       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6848                                CXCursor_ObjCInstanceMethodDecl));
6849     }
6850   }
6851 
6852   // Add the normal mutator.
6853   if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6854       !Property->getSetterMethodDecl()) {
6855     std::string SelectorName = (Twine("set") + UpperKey).str();
6856     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6857     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6858       if (ReturnType.isNull()) {
6859         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6860         Builder.AddTextChunk("void");
6861         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6862       }
6863 
6864       Builder.AddTypedTextChunk(
6865                                 Allocator.CopyString(SelectorId->getName()));
6866       Builder.AddTypedTextChunk(":");
6867       AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6868                               Context, Policy, Builder);
6869       Builder.AddTextChunk(Key);
6870       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6871                                CXCursor_ObjCInstanceMethodDecl));
6872     }
6873   }
6874 
6875   // Indexed and unordered accessors
6876   unsigned IndexedGetterPriority = CCP_CodePattern;
6877   unsigned IndexedSetterPriority = CCP_CodePattern;
6878   unsigned UnorderedGetterPriority = CCP_CodePattern;
6879   unsigned UnorderedSetterPriority = CCP_CodePattern;
6880   if (const ObjCObjectPointerType *ObjCPointer
6881                     = Property->getType()->getAs<ObjCObjectPointerType>()) {
6882     if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6883       // If this interface type is not provably derived from a known
6884       // collection, penalize the corresponding completions.
6885       if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6886         IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6887         if (!InheritsFromClassNamed(IFace, "NSArray"))
6888           IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6889       }
6890 
6891       if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6892         UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6893         if (!InheritsFromClassNamed(IFace, "NSSet"))
6894           UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6895       }
6896     }
6897   } else {
6898     IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6899     IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6900     UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6901     UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6902   }
6903 
6904   // Add -(NSUInteger)countOf<key>
6905   if (IsInstanceMethod &&
6906       (ReturnType.isNull() || ReturnType->isIntegerType())) {
6907     std::string SelectorName = (Twine("countOf") + UpperKey).str();
6908     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6909     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6910             .second) {
6911       if (ReturnType.isNull()) {
6912         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6913         Builder.AddTextChunk("NSUInteger");
6914         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6915       }
6916 
6917       Builder.AddTypedTextChunk(
6918                                 Allocator.CopyString(SelectorId->getName()));
6919       Results.AddResult(Result(Builder.TakeString(),
6920                                std::min(IndexedGetterPriority,
6921                                         UnorderedGetterPriority),
6922                                CXCursor_ObjCInstanceMethodDecl));
6923     }
6924   }
6925 
6926   // Indexed getters
6927   // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6928   if (IsInstanceMethod &&
6929       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
6930     std::string SelectorName
6931       = (Twine("objectIn") + UpperKey + "AtIndex").str();
6932     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6933     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6934       if (ReturnType.isNull()) {
6935         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6936         Builder.AddTextChunk("id");
6937         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6938       }
6939 
6940       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6941       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6942       Builder.AddTextChunk("NSUInteger");
6943       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6944       Builder.AddTextChunk("index");
6945       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6946                                CXCursor_ObjCInstanceMethodDecl));
6947     }
6948   }
6949 
6950   // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6951   if (IsInstanceMethod &&
6952       (ReturnType.isNull() ||
6953        (ReturnType->isObjCObjectPointerType() &&
6954         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6955         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6956                                                 ->getName() == "NSArray"))) {
6957     std::string SelectorName
6958       = (Twine(Property->getName()) + "AtIndexes").str();
6959     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6960     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6961       if (ReturnType.isNull()) {
6962         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6963         Builder.AddTextChunk("NSArray *");
6964         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6965       }
6966 
6967       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6968       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6969       Builder.AddTextChunk("NSIndexSet *");
6970       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6971       Builder.AddTextChunk("indexes");
6972       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6973                                CXCursor_ObjCInstanceMethodDecl));
6974     }
6975   }
6976 
6977   // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6978   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6979     std::string SelectorName = (Twine("get") + UpperKey).str();
6980     IdentifierInfo *SelectorIds[2] = {
6981       &Context.Idents.get(SelectorName),
6982       &Context.Idents.get("range")
6983     };
6984 
6985     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6986       if (ReturnType.isNull()) {
6987         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6988         Builder.AddTextChunk("void");
6989         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6990       }
6991 
6992       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6993       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6994       Builder.AddPlaceholderChunk("object-type");
6995       Builder.AddTextChunk(" **");
6996       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6997       Builder.AddTextChunk("buffer");
6998       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6999       Builder.AddTypedTextChunk("range:");
7000       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7001       Builder.AddTextChunk("NSRange");
7002       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7003       Builder.AddTextChunk("inRange");
7004       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
7005                                CXCursor_ObjCInstanceMethodDecl));
7006     }
7007   }
7008 
7009   // Mutable indexed accessors
7010 
7011   // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
7012   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7013     std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
7014     IdentifierInfo *SelectorIds[2] = {
7015       &Context.Idents.get("insertObject"),
7016       &Context.Idents.get(SelectorName)
7017     };
7018 
7019     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7020       if (ReturnType.isNull()) {
7021         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7022         Builder.AddTextChunk("void");
7023         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7024       }
7025 
7026       Builder.AddTypedTextChunk("insertObject:");
7027       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7028       Builder.AddPlaceholderChunk("object-type");
7029       Builder.AddTextChunk(" *");
7030       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7031       Builder.AddTextChunk("object");
7032       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7033       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7034       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7035       Builder.AddPlaceholderChunk("NSUInteger");
7036       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7037       Builder.AddTextChunk("index");
7038       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7039                                CXCursor_ObjCInstanceMethodDecl));
7040     }
7041   }
7042 
7043   // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
7044   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7045     std::string SelectorName = (Twine("insert") + UpperKey).str();
7046     IdentifierInfo *SelectorIds[2] = {
7047       &Context.Idents.get(SelectorName),
7048       &Context.Idents.get("atIndexes")
7049     };
7050 
7051     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7052       if (ReturnType.isNull()) {
7053         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7054         Builder.AddTextChunk("void");
7055         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7056       }
7057 
7058       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7059       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7060       Builder.AddTextChunk("NSArray *");
7061       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7062       Builder.AddTextChunk("array");
7063       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7064       Builder.AddTypedTextChunk("atIndexes:");
7065       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7066       Builder.AddPlaceholderChunk("NSIndexSet *");
7067       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7068       Builder.AddTextChunk("indexes");
7069       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7070                                CXCursor_ObjCInstanceMethodDecl));
7071     }
7072   }
7073 
7074   // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
7075   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7076     std::string SelectorName
7077       = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
7078     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7079     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7080       if (ReturnType.isNull()) {
7081         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7082         Builder.AddTextChunk("void");
7083         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7084       }
7085 
7086       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7087       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7088       Builder.AddTextChunk("NSUInteger");
7089       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7090       Builder.AddTextChunk("index");
7091       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7092                                CXCursor_ObjCInstanceMethodDecl));
7093     }
7094   }
7095 
7096   // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
7097   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7098     std::string SelectorName
7099       = (Twine("remove") + UpperKey + "AtIndexes").str();
7100     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7101     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7102       if (ReturnType.isNull()) {
7103         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7104         Builder.AddTextChunk("void");
7105         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7106       }
7107 
7108       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7109       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7110       Builder.AddTextChunk("NSIndexSet *");
7111       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7112       Builder.AddTextChunk("indexes");
7113       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7114                                CXCursor_ObjCInstanceMethodDecl));
7115     }
7116   }
7117 
7118   // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
7119   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7120     std::string SelectorName
7121       = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
7122     IdentifierInfo *SelectorIds[2] = {
7123       &Context.Idents.get(SelectorName),
7124       &Context.Idents.get("withObject")
7125     };
7126 
7127     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7128       if (ReturnType.isNull()) {
7129         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7130         Builder.AddTextChunk("void");
7131         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7132       }
7133 
7134       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7135       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7136       Builder.AddPlaceholderChunk("NSUInteger");
7137       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7138       Builder.AddTextChunk("index");
7139       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7140       Builder.AddTypedTextChunk("withObject:");
7141       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7142       Builder.AddTextChunk("id");
7143       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7144       Builder.AddTextChunk("object");
7145       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7146                                CXCursor_ObjCInstanceMethodDecl));
7147     }
7148   }
7149 
7150   // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
7151   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7152     std::string SelectorName1
7153       = (Twine("replace") + UpperKey + "AtIndexes").str();
7154     std::string SelectorName2 = (Twine("with") + UpperKey).str();
7155     IdentifierInfo *SelectorIds[2] = {
7156       &Context.Idents.get(SelectorName1),
7157       &Context.Idents.get(SelectorName2)
7158     };
7159 
7160     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7161       if (ReturnType.isNull()) {
7162         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7163         Builder.AddTextChunk("void");
7164         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7165       }
7166 
7167       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
7168       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7169       Builder.AddPlaceholderChunk("NSIndexSet *");
7170       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7171       Builder.AddTextChunk("indexes");
7172       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7173       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
7174       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7175       Builder.AddTextChunk("NSArray *");
7176       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7177       Builder.AddTextChunk("array");
7178       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7179                                CXCursor_ObjCInstanceMethodDecl));
7180     }
7181   }
7182 
7183   // Unordered getters
7184   // - (NSEnumerator *)enumeratorOfKey
7185   if (IsInstanceMethod &&
7186       (ReturnType.isNull() ||
7187        (ReturnType->isObjCObjectPointerType() &&
7188         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7189         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7190           ->getName() == "NSEnumerator"))) {
7191     std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
7192     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7193     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7194             .second) {
7195       if (ReturnType.isNull()) {
7196         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7197         Builder.AddTextChunk("NSEnumerator *");
7198         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7199       }
7200 
7201       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7202       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7203                               CXCursor_ObjCInstanceMethodDecl));
7204     }
7205   }
7206 
7207   // - (type *)memberOfKey:(type *)object
7208   if (IsInstanceMethod &&
7209       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
7210     std::string SelectorName = (Twine("memberOf") + UpperKey).str();
7211     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7212     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7213       if (ReturnType.isNull()) {
7214         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7215         Builder.AddPlaceholderChunk("object-type");
7216         Builder.AddTextChunk(" *");
7217         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7218       }
7219 
7220       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7221       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7222       if (ReturnType.isNull()) {
7223         Builder.AddPlaceholderChunk("object-type");
7224         Builder.AddTextChunk(" *");
7225       } else {
7226         Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
7227                                                      Policy,
7228                                                      Builder.getAllocator()));
7229       }
7230       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7231       Builder.AddTextChunk("object");
7232       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7233                                CXCursor_ObjCInstanceMethodDecl));
7234     }
7235   }
7236 
7237   // Mutable unordered accessors
7238   // - (void)addKeyObject:(type *)object
7239   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7240     std::string SelectorName
7241       = (Twine("add") + UpperKey + Twine("Object")).str();
7242     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7243     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7244       if (ReturnType.isNull()) {
7245         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7246         Builder.AddTextChunk("void");
7247         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7248       }
7249 
7250       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7251       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7252       Builder.AddPlaceholderChunk("object-type");
7253       Builder.AddTextChunk(" *");
7254       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7255       Builder.AddTextChunk("object");
7256       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7257                                CXCursor_ObjCInstanceMethodDecl));
7258     }
7259   }
7260 
7261   // - (void)addKey:(NSSet *)objects
7262   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7263     std::string SelectorName = (Twine("add") + UpperKey).str();
7264     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7265     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7266       if (ReturnType.isNull()) {
7267         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7268         Builder.AddTextChunk("void");
7269         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7270       }
7271 
7272       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7273       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7274       Builder.AddTextChunk("NSSet *");
7275       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7276       Builder.AddTextChunk("objects");
7277       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7278                                CXCursor_ObjCInstanceMethodDecl));
7279     }
7280   }
7281 
7282   // - (void)removeKeyObject:(type *)object
7283   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7284     std::string SelectorName
7285       = (Twine("remove") + UpperKey + Twine("Object")).str();
7286     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7287     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7288       if (ReturnType.isNull()) {
7289         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7290         Builder.AddTextChunk("void");
7291         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7292       }
7293 
7294       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7295       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7296       Builder.AddPlaceholderChunk("object-type");
7297       Builder.AddTextChunk(" *");
7298       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7299       Builder.AddTextChunk("object");
7300       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7301                                CXCursor_ObjCInstanceMethodDecl));
7302     }
7303   }
7304 
7305   // - (void)removeKey:(NSSet *)objects
7306   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7307     std::string SelectorName = (Twine("remove") + UpperKey).str();
7308     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7309     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7310       if (ReturnType.isNull()) {
7311         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7312         Builder.AddTextChunk("void");
7313         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7314       }
7315 
7316       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7317       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7318       Builder.AddTextChunk("NSSet *");
7319       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7320       Builder.AddTextChunk("objects");
7321       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7322                                CXCursor_ObjCInstanceMethodDecl));
7323     }
7324   }
7325 
7326   // - (void)intersectKey:(NSSet *)objects
7327   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7328     std::string SelectorName = (Twine("intersect") + UpperKey).str();
7329     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7330     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7331       if (ReturnType.isNull()) {
7332         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7333         Builder.AddTextChunk("void");
7334         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7335       }
7336 
7337       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7338       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7339       Builder.AddTextChunk("NSSet *");
7340       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7341       Builder.AddTextChunk("objects");
7342       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7343                                CXCursor_ObjCInstanceMethodDecl));
7344     }
7345   }
7346 
7347   // Key-Value Observing
7348   // + (NSSet *)keyPathsForValuesAffectingKey
7349   if (!IsInstanceMethod &&
7350       (ReturnType.isNull() ||
7351        (ReturnType->isObjCObjectPointerType() &&
7352         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7353         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7354                                                     ->getName() == "NSSet"))) {
7355     std::string SelectorName
7356       = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
7357     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7358     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7359             .second) {
7360       if (ReturnType.isNull()) {
7361         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7362         Builder.AddTextChunk("NSSet<NSString *> *");
7363         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7364       }
7365 
7366       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7367       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7368                               CXCursor_ObjCClassMethodDecl));
7369     }
7370   }
7371 
7372   // + (BOOL)automaticallyNotifiesObserversForKey
7373   if (!IsInstanceMethod &&
7374       (ReturnType.isNull() ||
7375        ReturnType->isIntegerType() ||
7376        ReturnType->isBooleanType())) {
7377     std::string SelectorName
7378       = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
7379     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7380     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7381             .second) {
7382       if (ReturnType.isNull()) {
7383         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7384         Builder.AddTextChunk("BOOL");
7385         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7386       }
7387 
7388       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7389       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7390                               CXCursor_ObjCClassMethodDecl));
7391     }
7392   }
7393 }
7394 
7395 void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
7396                                       ParsedType ReturnTy) {
7397   // Determine the return type of the method we're declaring, if
7398   // provided.
7399   QualType ReturnType = GetTypeFromParser(ReturnTy);
7400   Decl *IDecl = nullptr;
7401   if (CurContext->isObjCContainer()) {
7402       ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7403       IDecl = cast<Decl>(OCD);
7404   }
7405   // Determine where we should start searching for methods.
7406   ObjCContainerDecl *SearchDecl = nullptr;
7407   bool IsInImplementation = false;
7408   if (Decl *D = IDecl) {
7409     if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7410       SearchDecl = Impl->getClassInterface();
7411       IsInImplementation = true;
7412     } else if (ObjCCategoryImplDecl *CatImpl
7413                                          = dyn_cast<ObjCCategoryImplDecl>(D)) {
7414       SearchDecl = CatImpl->getCategoryDecl();
7415       IsInImplementation = true;
7416     } else
7417       SearchDecl = dyn_cast<ObjCContainerDecl>(D);
7418   }
7419 
7420   if (!SearchDecl && S) {
7421     if (DeclContext *DC = S->getEntity())
7422       SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
7423   }
7424 
7425   if (!SearchDecl) {
7426     HandleCodeCompleteResults(this, CodeCompleter,
7427                               CodeCompletionContext::CCC_Other,
7428                               nullptr, 0);
7429     return;
7430   }
7431 
7432   // Find all of the methods that we could declare/implement here.
7433   KnownMethodsMap KnownMethods;
7434   FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
7435                            ReturnType, KnownMethods);
7436 
7437   // Add declarations or definitions for each of the known methods.
7438   typedef CodeCompletionResult Result;
7439   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7440                         CodeCompleter->getCodeCompletionTUInfo(),
7441                         CodeCompletionContext::CCC_Other);
7442   Results.EnterNewScope();
7443   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
7444   for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7445                               MEnd = KnownMethods.end();
7446        M != MEnd; ++M) {
7447     ObjCMethodDecl *Method = M->second.getPointer();
7448     CodeCompletionBuilder Builder(Results.getAllocator(),
7449                                   Results.getCodeCompletionTUInfo());
7450 
7451     // Add the '-'/'+' prefix if it wasn't provided yet.
7452     if (!IsInstanceMethod) {
7453       Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+");
7454       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7455     }
7456 
7457     // If the result type was not already provided, add it to the
7458     // pattern as (type).
7459     if (ReturnType.isNull()) {
7460       QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
7461       AttributedType::stripOuterNullability(ResTy);
7462       AddObjCPassingTypeChunk(ResTy,
7463                               Method->getObjCDeclQualifier(), Context, Policy,
7464                               Builder);
7465     }
7466 
7467     Selector Sel = Method->getSelector();
7468 
7469     // Add the first part of the selector to the pattern.
7470     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7471                                                        Sel.getNameForSlot(0)));
7472 
7473     // Add parameters to the pattern.
7474     unsigned I = 0;
7475     for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7476                                      PEnd = Method->param_end();
7477          P != PEnd; (void)++P, ++I) {
7478       // Add the part of the selector name.
7479       if (I == 0)
7480         Builder.AddTypedTextChunk(":");
7481       else if (I < Sel.getNumArgs()) {
7482         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7483         Builder.AddTypedTextChunk(
7484                 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7485       } else
7486         break;
7487 
7488       // Add the parameter type.
7489       QualType ParamType;
7490       if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7491         ParamType = (*P)->getType();
7492       else
7493         ParamType = (*P)->getOriginalType();
7494       ParamType = ParamType.substObjCTypeArgs(Context, {},
7495                                             ObjCSubstitutionContext::Parameter);
7496       AttributedType::stripOuterNullability(ParamType);
7497       AddObjCPassingTypeChunk(ParamType,
7498                               (*P)->getObjCDeclQualifier(),
7499                               Context, Policy,
7500                               Builder);
7501 
7502       if (IdentifierInfo *Id = (*P)->getIdentifier())
7503         Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
7504     }
7505 
7506     if (Method->isVariadic()) {
7507       if (Method->param_size() > 0)
7508         Builder.AddChunk(CodeCompletionString::CK_Comma);
7509       Builder.AddTextChunk("...");
7510     }
7511 
7512     if (IsInImplementation && Results.includeCodePatterns()) {
7513       // We will be defining the method here, so add a compound statement.
7514       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7515       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7516       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7517       if (!Method->getReturnType()->isVoidType()) {
7518         // If the result type is not void, add a return clause.
7519         Builder.AddTextChunk("return");
7520         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7521         Builder.AddPlaceholderChunk("expression");
7522         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
7523       } else
7524         Builder.AddPlaceholderChunk("statements");
7525 
7526       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7527       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7528     }
7529 
7530     unsigned Priority = CCP_CodePattern;
7531     if (!M->second.getInt())
7532       Priority += CCD_InBaseClass;
7533 
7534     Results.AddResult(Result(Builder.TakeString(), Method, Priority));
7535   }
7536 
7537   // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7538   // the properties in this class and its categories.
7539   if (Context.getLangOpts().ObjC2) {
7540     SmallVector<ObjCContainerDecl *, 4> Containers;
7541     Containers.push_back(SearchDecl);
7542 
7543     VisitedSelectorSet KnownSelectors;
7544     for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7545                                 MEnd = KnownMethods.end();
7546          M != MEnd; ++M)
7547       KnownSelectors.insert(M->first);
7548 
7549 
7550     ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7551     if (!IFace)
7552       if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7553         IFace = Category->getClassInterface();
7554 
7555     if (IFace)
7556       for (auto *Cat : IFace->visible_categories())
7557         Containers.push_back(Cat);
7558 
7559     if (IsInstanceMethod) {
7560       for (unsigned I = 0, N = Containers.size(); I != N; ++I)
7561         for (auto *P : Containers[I]->instance_properties())
7562           AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context,
7563                                      KnownSelectors, Results);
7564     }
7565   }
7566 
7567   Results.ExitScope();
7568 
7569   HandleCodeCompleteResults(this, CodeCompleter,
7570                             CodeCompletionContext::CCC_Other,
7571                             Results.data(),Results.size());
7572 }
7573 
7574 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7575                                               bool IsInstanceMethod,
7576                                               bool AtParameterName,
7577                                               ParsedType ReturnTy,
7578                                          ArrayRef<IdentifierInfo *> SelIdents) {
7579   // If we have an external source, load the entire class method
7580   // pool from the AST file.
7581   if (ExternalSource) {
7582     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7583          I != N; ++I) {
7584       Selector Sel = ExternalSource->GetExternalSelector(I);
7585       if (Sel.isNull() || MethodPool.count(Sel))
7586         continue;
7587 
7588       ReadMethodPool(Sel);
7589     }
7590   }
7591 
7592   // Build the set of methods we can see.
7593   typedef CodeCompletionResult Result;
7594   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7595                         CodeCompleter->getCodeCompletionTUInfo(),
7596                         CodeCompletionContext::CCC_Other);
7597 
7598   if (ReturnTy)
7599     Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
7600 
7601   Results.EnterNewScope();
7602   for (GlobalMethodPool::iterator M = MethodPool.begin(),
7603                                   MEnd = MethodPool.end();
7604        M != MEnd; ++M) {
7605     for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7606                                                        &M->second.second;
7607          MethList && MethList->getMethod();
7608          MethList = MethList->getNext()) {
7609       if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
7610         continue;
7611 
7612       if (AtParameterName) {
7613         // Suggest parameter names we've seen before.
7614         unsigned NumSelIdents = SelIdents.size();
7615         if (NumSelIdents &&
7616             NumSelIdents <= MethList->getMethod()->param_size()) {
7617           ParmVarDecl *Param =
7618               MethList->getMethod()->parameters()[NumSelIdents - 1];
7619           if (Param->getIdentifier()) {
7620             CodeCompletionBuilder Builder(Results.getAllocator(),
7621                                           Results.getCodeCompletionTUInfo());
7622             Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7623                                            Param->getIdentifier()->getName()));
7624             Results.AddResult(Builder.TakeString());
7625           }
7626         }
7627 
7628         continue;
7629       }
7630 
7631       Result R(MethList->getMethod(),
7632                Results.getBasePriority(MethList->getMethod()), nullptr);
7633       R.StartParameter = SelIdents.size();
7634       R.AllParametersAreInformative = false;
7635       R.DeclaringEntity = true;
7636       Results.MaybeAddResult(R, CurContext);
7637     }
7638   }
7639 
7640   Results.ExitScope();
7641 
7642   if (!AtParameterName && !SelIdents.empty() &&
7643       SelIdents.front()->getName().startswith("init")) {
7644     for (const auto &M : PP.macros()) {
7645       if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
7646         continue;
7647       Results.EnterNewScope();
7648       CodeCompletionBuilder Builder(Results.getAllocator(),
7649                                     Results.getCodeCompletionTUInfo());
7650       Builder.AddTypedTextChunk(
7651           Builder.getAllocator().CopyString(M.first->getName()));
7652       Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
7653                                              CXCursor_MacroDefinition));
7654       Results.ExitScope();
7655     }
7656   }
7657 
7658   HandleCodeCompleteResults(this, CodeCompleter,
7659                             CodeCompletionContext::CCC_Other,
7660                             Results.data(),Results.size());
7661 }
7662 
7663 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
7664   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7665                         CodeCompleter->getCodeCompletionTUInfo(),
7666                         CodeCompletionContext::CCC_PreprocessorDirective);
7667   Results.EnterNewScope();
7668 
7669   // #if <condition>
7670   CodeCompletionBuilder Builder(Results.getAllocator(),
7671                                 Results.getCodeCompletionTUInfo());
7672   Builder.AddTypedTextChunk("if");
7673   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7674   Builder.AddPlaceholderChunk("condition");
7675   Results.AddResult(Builder.TakeString());
7676 
7677   // #ifdef <macro>
7678   Builder.AddTypedTextChunk("ifdef");
7679   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7680   Builder.AddPlaceholderChunk("macro");
7681   Results.AddResult(Builder.TakeString());
7682 
7683   // #ifndef <macro>
7684   Builder.AddTypedTextChunk("ifndef");
7685   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7686   Builder.AddPlaceholderChunk("macro");
7687   Results.AddResult(Builder.TakeString());
7688 
7689   if (InConditional) {
7690     // #elif <condition>
7691     Builder.AddTypedTextChunk("elif");
7692     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7693     Builder.AddPlaceholderChunk("condition");
7694     Results.AddResult(Builder.TakeString());
7695 
7696     // #else
7697     Builder.AddTypedTextChunk("else");
7698     Results.AddResult(Builder.TakeString());
7699 
7700     // #endif
7701     Builder.AddTypedTextChunk("endif");
7702     Results.AddResult(Builder.TakeString());
7703   }
7704 
7705   // #include "header"
7706   Builder.AddTypedTextChunk("include");
7707   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7708   Builder.AddTextChunk("\"");
7709   Builder.AddPlaceholderChunk("header");
7710   Builder.AddTextChunk("\"");
7711   Results.AddResult(Builder.TakeString());
7712 
7713   // #include <header>
7714   Builder.AddTypedTextChunk("include");
7715   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7716   Builder.AddTextChunk("<");
7717   Builder.AddPlaceholderChunk("header");
7718   Builder.AddTextChunk(">");
7719   Results.AddResult(Builder.TakeString());
7720 
7721   // #define <macro>
7722   Builder.AddTypedTextChunk("define");
7723   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7724   Builder.AddPlaceholderChunk("macro");
7725   Results.AddResult(Builder.TakeString());
7726 
7727   // #define <macro>(<args>)
7728   Builder.AddTypedTextChunk("define");
7729   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7730   Builder.AddPlaceholderChunk("macro");
7731   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7732   Builder.AddPlaceholderChunk("args");
7733   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7734   Results.AddResult(Builder.TakeString());
7735 
7736   // #undef <macro>
7737   Builder.AddTypedTextChunk("undef");
7738   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7739   Builder.AddPlaceholderChunk("macro");
7740   Results.AddResult(Builder.TakeString());
7741 
7742   // #line <number>
7743   Builder.AddTypedTextChunk("line");
7744   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7745   Builder.AddPlaceholderChunk("number");
7746   Results.AddResult(Builder.TakeString());
7747 
7748   // #line <number> "filename"
7749   Builder.AddTypedTextChunk("line");
7750   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7751   Builder.AddPlaceholderChunk("number");
7752   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7753   Builder.AddTextChunk("\"");
7754   Builder.AddPlaceholderChunk("filename");
7755   Builder.AddTextChunk("\"");
7756   Results.AddResult(Builder.TakeString());
7757 
7758   // #error <message>
7759   Builder.AddTypedTextChunk("error");
7760   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7761   Builder.AddPlaceholderChunk("message");
7762   Results.AddResult(Builder.TakeString());
7763 
7764   // #pragma <arguments>
7765   Builder.AddTypedTextChunk("pragma");
7766   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7767   Builder.AddPlaceholderChunk("arguments");
7768   Results.AddResult(Builder.TakeString());
7769 
7770   if (getLangOpts().ObjC1) {
7771     // #import "header"
7772     Builder.AddTypedTextChunk("import");
7773     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7774     Builder.AddTextChunk("\"");
7775     Builder.AddPlaceholderChunk("header");
7776     Builder.AddTextChunk("\"");
7777     Results.AddResult(Builder.TakeString());
7778 
7779     // #import <header>
7780     Builder.AddTypedTextChunk("import");
7781     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7782     Builder.AddTextChunk("<");
7783     Builder.AddPlaceholderChunk("header");
7784     Builder.AddTextChunk(">");
7785     Results.AddResult(Builder.TakeString());
7786   }
7787 
7788   // #include_next "header"
7789   Builder.AddTypedTextChunk("include_next");
7790   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7791   Builder.AddTextChunk("\"");
7792   Builder.AddPlaceholderChunk("header");
7793   Builder.AddTextChunk("\"");
7794   Results.AddResult(Builder.TakeString());
7795 
7796   // #include_next <header>
7797   Builder.AddTypedTextChunk("include_next");
7798   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7799   Builder.AddTextChunk("<");
7800   Builder.AddPlaceholderChunk("header");
7801   Builder.AddTextChunk(">");
7802   Results.AddResult(Builder.TakeString());
7803 
7804   // #warning <message>
7805   Builder.AddTypedTextChunk("warning");
7806   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7807   Builder.AddPlaceholderChunk("message");
7808   Results.AddResult(Builder.TakeString());
7809 
7810   // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7811   // completions for them. And __include_macros is a Clang-internal extension
7812   // that we don't want to encourage anyone to use.
7813 
7814   // FIXME: we don't support #assert or #unassert, so don't suggest them.
7815   Results.ExitScope();
7816 
7817   HandleCodeCompleteResults(this, CodeCompleter,
7818                             CodeCompletionContext::CCC_PreprocessorDirective,
7819                             Results.data(), Results.size());
7820 }
7821 
7822 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
7823   CodeCompleteOrdinaryName(S,
7824                            S->getFnParent()? Sema::PCC_RecoveryInFunction
7825                                            : Sema::PCC_Namespace);
7826 }
7827 
7828 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
7829   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7830                         CodeCompleter->getCodeCompletionTUInfo(),
7831                         IsDefinition? CodeCompletionContext::CCC_MacroName
7832                                     : CodeCompletionContext::CCC_MacroNameUse);
7833   if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7834     // Add just the names of macros, not their arguments.
7835     CodeCompletionBuilder Builder(Results.getAllocator(),
7836                                   Results.getCodeCompletionTUInfo());
7837     Results.EnterNewScope();
7838     for (Preprocessor::macro_iterator M = PP.macro_begin(),
7839                                    MEnd = PP.macro_end();
7840          M != MEnd; ++M) {
7841       Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7842                                            M->first->getName()));
7843       Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7844                                              CCP_CodePattern,
7845                                              CXCursor_MacroDefinition));
7846     }
7847     Results.ExitScope();
7848   } else if (IsDefinition) {
7849     // FIXME: Can we detect when the user just wrote an include guard above?
7850   }
7851 
7852   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7853                             Results.data(), Results.size());
7854 }
7855 
7856 void Sema::CodeCompletePreprocessorExpression() {
7857   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7858                         CodeCompleter->getCodeCompletionTUInfo(),
7859                         CodeCompletionContext::CCC_PreprocessorExpression);
7860 
7861   if (!CodeCompleter || CodeCompleter->includeMacros())
7862     AddMacroResults(PP, Results, true);
7863 
7864     // defined (<macro>)
7865   Results.EnterNewScope();
7866   CodeCompletionBuilder Builder(Results.getAllocator(),
7867                                 Results.getCodeCompletionTUInfo());
7868   Builder.AddTypedTextChunk("defined");
7869   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7870   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7871   Builder.AddPlaceholderChunk("macro");
7872   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7873   Results.AddResult(Builder.TakeString());
7874   Results.ExitScope();
7875 
7876   HandleCodeCompleteResults(this, CodeCompleter,
7877                             CodeCompletionContext::CCC_PreprocessorExpression,
7878                             Results.data(), Results.size());
7879 }
7880 
7881 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7882                                                  IdentifierInfo *Macro,
7883                                                  MacroInfo *MacroInfo,
7884                                                  unsigned Argument) {
7885   // FIXME: In the future, we could provide "overload" results, much like we
7886   // do for function calls.
7887 
7888   // Now just ignore this. There will be another code-completion callback
7889   // for the expanded tokens.
7890 }
7891 
7892 void Sema::CodeCompleteNaturalLanguage() {
7893   HandleCodeCompleteResults(this, CodeCompleter,
7894                             CodeCompletionContext::CCC_NaturalLanguage,
7895                             nullptr, 0);
7896 }
7897 
7898 void Sema::CodeCompleteAvailabilityPlatformName() {
7899   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7900                         CodeCompleter->getCodeCompletionTUInfo(),
7901                         CodeCompletionContext::CCC_Other);
7902   Results.EnterNewScope();
7903   static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
7904   for (const char *Platform : llvm::makeArrayRef(Platforms)) {
7905     Results.AddResult(CodeCompletionResult(Platform));
7906     Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
7907         Twine(Platform) + "ApplicationExtension")));
7908   }
7909   Results.ExitScope();
7910   HandleCodeCompleteResults(this, CodeCompleter,
7911                             CodeCompletionContext::CCC_Other, Results.data(),
7912                             Results.size());
7913 }
7914 
7915 void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7916                                        CodeCompletionTUInfo &CCTUInfo,
7917                  SmallVectorImpl<CodeCompletionResult> &Results) {
7918   ResultBuilder Builder(*this, Allocator, CCTUInfo,
7919                         CodeCompletionContext::CCC_Recovery);
7920   if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7921     CodeCompletionDeclConsumer Consumer(Builder,
7922                                         Context.getTranslationUnitDecl());
7923     LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7924                        Consumer);
7925   }
7926 
7927   if (!CodeCompleter || CodeCompleter->includeMacros())
7928     AddMacroResults(PP, Builder, true);
7929 
7930   Results.clear();
7931   Results.insert(Results.end(),
7932                  Builder.data(), Builder.data() + Builder.size());
7933 }
7934