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