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