Sema.h revision ddb5a3926d715ab4354ca36117679e3f4d5d3e21
148486893f46d2e12e926682a3ecb908716bc66c4Chris Lattner//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
29769ab22265b313171d201b5928688524a01bd87Misha Brukman//
36fbcc26f1460eaee4e0eb8b426fc1ff0c7af11beJohn Criswell//                     The LLVM Compiler Infrastructure
46fbcc26f1460eaee4e0eb8b426fc1ff0c7af11beJohn Criswell//
57ed47a13356daed2a34cd2209a31f92552e3bdd8Chris Lattner// This file is distributed under the University of Illinois Open Source
67ed47a13356daed2a34cd2209a31f92552e3bdd8Chris Lattner// License. See LICENSE.TXT for details.
79769ab22265b313171d201b5928688524a01bd87Misha Brukman//
86fbcc26f1460eaee4e0eb8b426fc1ff0c7af11beJohn Criswell//===----------------------------------------------------------------------===//
9febdf58538c2510ec1c24d3a856420792c53debeChris Lattner//
10bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencer// This file defines the Sema class, which performs semantic analysis and
1102dea8b39f3acad5de1df36273444d149145e7fcDan Gohman// builds ASTs.
12009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner//
13009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner//===----------------------------------------------------------------------===//
14009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner
15009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner#ifndef LLVM_CLANG_SEMA_SEMA_H
16009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner#define LLVM_CLANG_SEMA_SEMA_H
1718961504fc2b299578dba817900a0696cf3ccc4dChris Lattner
1818961504fc2b299578dba817900a0696cf3ccc4dChris Lattner#include "clang/AST/Attr.h"
1943d1fd449f1a0ac9d9dafa0b9569bb6b2e976198Anton Korobeynikov#include "clang/AST/DeclarationName.h"
20ef547ddcdd6e49bb6f019ac5fb080d2f317e43a9Chris Lattner#include "clang/AST/Expr.h"
21009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner#include "clang/AST/ExprObjC.h"
22d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke#include "clang/AST/ExternalASTSource.h"
23d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke#include "clang/AST/LambdaMangleContext.h"
24009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner#include "clang/AST/NSAPI.h"
2512ddd409535b52a7fa5157ded9a4cedd161fedb6Benjamin Kramer#include "clang/AST/PrettyPrinter.h"
26009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner#include "clang/AST/TypeLoc.h"
2718961504fc2b299578dba817900a0696cf3ccc4dChris Lattner#include "clang/Basic/ExpressionTraits.h"
2817fcdd5e1b78b829068ca657c97357a39d6e768bChris Lattner#include "clang/Basic/LangOptions.h"
297eef1800ea8745a814b86c8610086e9f16312dcaGabor Greif#include "clang/Basic/Specifiers.h"
307eef1800ea8745a814b86c8610086e9f16312dcaGabor Greif#include "clang/Basic/TemplateKinds.h"
317eef1800ea8745a814b86c8610086e9f16312dcaGabor Greif#include "clang/Basic/TypeTraits.h"
327eef1800ea8745a814b86c8610086e9f16312dcaGabor Greif#include "clang/Lex/ModuleLoader.h"
330a0e68a7eac0513505aff3079e2d5d6864e51895Gabor Greif#include "clang/Sema/AnalysisBasedWarnings.h"
347eef1800ea8745a814b86c8610086e9f16312dcaGabor Greif#include "clang/Sema/DeclSpec.h"
357eef1800ea8745a814b86c8610086e9f16312dcaGabor Greif#include "clang/Sema/ExternalSemaSource.h"
367eef1800ea8745a814b86c8610086e9f16312dcaGabor Greif#include "clang/Sema/IdentifierResolver.h"
377eef1800ea8745a814b86c8610086e9f16312dcaGabor Greif#include "clang/Sema/LocInfoType.h"
387eef1800ea8745a814b86c8610086e9f16312dcaGabor Greif#include "clang/Sema/ObjCMethodList.h"
397eef1800ea8745a814b86c8610086e9f16312dcaGabor Greif#include "clang/Sema/Ownership.h"
401a31d09a16b0b8eaa08c8649bd8673ddb0ad1841Gabor Greif#include "clang/Sema/ScopeInfo.h"
417eef1800ea8745a814b86c8610086e9f16312dcaGabor Greif#include "clang/Sema/TypoCorrection.h"
421012919ed8b3e2cd4b421c104ce9d8f4e20ced9dGabor Greif#include "clang/Sema/Weak.h"
430a0e68a7eac0513505aff3079e2d5d6864e51895Gabor Greif#include "llvm/ADT/ArrayRef.h"
447eef1800ea8745a814b86c8610086e9f16312dcaGabor Greif#include "llvm/ADT/Optional.h"
45c23b8719ef9d6b1220e854b37d40e9e1c48a82bcGabor Greif#include "llvm/ADT/OwningPtr.h"
46c23b8719ef9d6b1220e854b37d40e9e1c48a82bcGabor Greif#include "llvm/ADT/SetVector.h"
47c23b8719ef9d6b1220e854b37d40e9e1c48a82bcGabor Greif#include "llvm/ADT/SmallPtrSet.h"
48f3841fcbd587c31aa9842b3f33bd57de40c9f443Gabor Greif#include "llvm/ADT/SmallVector.h"
490a0e68a7eac0513505aff3079e2d5d6864e51895Gabor Greif#include "llvm/MC/MCParser/MCAsmParser.h"
507309be6735666143bd9835b275dc8501617a2591Gabor Greif#include <deque>
5118961504fc2b299578dba817900a0696cf3ccc4dChris Lattner#include <string>
5218961504fc2b299578dba817900a0696cf3ccc4dChris Lattner#include <vector>
53bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencer
54bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencernamespace llvm {
55bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencer  class APSInt;
56bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencer  template <typename ValueT> struct DenseMapInfo;
57bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencer  template <typename ValueT, typename ValueInfoT> class DenseSet;
58bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencer  class SmallBitVector;
59bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencer}
60bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencer
61bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencernamespace clang {
62bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencer  class ADLResult;
63bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencer  class ASTConsumer;
64bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencer  class ASTContext;
65bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencer  class ASTMutationListener;
66bddcb9427cb36ac6609fef233eaac3c9b5e5a8f4Reid Spencer  class ASTReader;
67fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman  class ASTWriter;
68fed90b6d097d50881afb45e4d79f430db66dd741Dan Gohman  class ArrayType;
690a0e68a7eac0513505aff3079e2d5d6864e51895Gabor Greif  class AttributeList;
701fca5ff62bb2ecb5bfc8974f4dbfc56e9d3ca721Chris Lattner  class BlockDecl;
7118961504fc2b299578dba817900a0696cf3ccc4dChris Lattner  class CapturedDecl;
720a0e68a7eac0513505aff3079e2d5d6864e51895Gabor Greif  class CXXBasePath;
73009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner  class CXXBasePaths;
7417fcdd5e1b78b829068ca657c97357a39d6e768bChris Lattner  class CXXBindTemporaryExpr;
7518961504fc2b299578dba817900a0696cf3ccc4dChris Lattner  typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
76fab8c796f6754962f5732145248303e3a1f7b96bChris Lattner  class CXXConstructorDecl;
7717fcdd5e1b78b829068ca657c97357a39d6e768bChris Lattner  class CXXConversionDecl;
78009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner  class CXXDestructorDecl;
7918961504fc2b299578dba817900a0696cf3ccc4dChris Lattner  class CXXFieldCollector;
8018961504fc2b299578dba817900a0696cf3ccc4dChris Lattner  class CXXMemberCallExpr;
81009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner  class CXXMethodDecl;
82fab8c796f6754962f5732145248303e3a1f7b96bChris Lattner  class CXXScopeSpec;
833fb57b691d21e582ed18ffe6477e8f5548b4ad6aChris Lattner  class CXXTemporary;
843fb57b691d21e582ed18ffe6477e8f5548b4ad6aChris Lattner  class CXXTryStmt;
85fab8c796f6754962f5732145248303e3a1f7b96bChris Lattner  class CallExpr;
861d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson  class ClassTemplateDecl;
871d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson  class ClassTemplatePartialSpecializationDecl;
88051a950000e21935165db56695e35bade668193bGabor Greif  class ClassTemplateSpecializationDecl;
89f7e8b5c72245e2dc97539009236c651a814d909fErick Tryzelaar  class CodeCompleteConsumer;
90e922c0201916e0b980ab3cfe91e1413e68d55647Owen Anderson  class CodeCompletionAllocator;
910a205a459884ec745df1c529396dd921f029dafdOwen Anderson  class CodeCompletionTUInfo;
92051a950000e21935165db56695e35bade668193bGabor Greif  class CodeCompletionResult;
93051a950000e21935165db56695e35bade668193bGabor Greif  class Decl;
94051a950000e21935165db56695e35bade668193bGabor Greif  class DeclAccessPair;
95051a950000e21935165db56695e35bade668193bGabor Greif  class DeclContext;
96e9a393be13282f92f01d1a8f0703005e95b8c4e6Matthijs Kooijman  class DeclRefExpr;
97e9a393be13282f92f01d1a8f0703005e95b8c4e6Matthijs Kooijman  class DeclaratorDecl;
98e9a393be13282f92f01d1a8f0703005e95b8c4e6Matthijs Kooijman  class DeducedTemplateArgument;
991d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson  class DependentDiagnostic;
1001d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson  class DesignatedInitExpr;
1011d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson  class Designation;
102051a950000e21935165db56695e35bade668193bGabor Greif  class EnumConstantDecl;
103afba8fe662d65b25b4baf46bb26cc18e1f9cc0a5Gordon Henriksen  class Expr;
104009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner  class ExtVectorType;
105fab8c796f6754962f5732145248303e3a1f7b96bChris Lattner  class ExternalSemaSource;
106fab8c796f6754962f5732145248303e3a1f7b96bChris Lattner  class FormatAttr;
10717fcdd5e1b78b829068ca657c97357a39d6e768bChris Lattner  class FriendDecl;
10817fcdd5e1b78b829068ca657c97357a39d6e768bChris Lattner  class FunctionDecl;
109009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner  class FunctionProtoType;
110280a6e607d8eb7401749a92db624a82de47da777Nick Lewycky  class FunctionTemplateDecl;
11112f7cab423728180717ac94f612a561ba4fea77bDan Gohman  class ImplicitConversionSequence;
11212f7cab423728180717ac94f612a561ba4fea77bDan Gohman  class InitListExpr;
113280a6e607d8eb7401749a92db624a82de47da777Nick Lewycky  class InitializationKind;
114280a6e607d8eb7401749a92db624a82de47da777Nick Lewycky  class InitializationSequence;
115280a6e607d8eb7401749a92db624a82de47da777Nick Lewycky  class InitializedEntity;
11626199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  class IntegerLiteral;
11726199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  class LabelStmt;
11826199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  class LambdaExpr;
11926199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  class LangOptions;
120009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner  class LocalInstantiationScope;
12150cdabcfd52e88381ade61450d98a1c757195befDan Gohman  class LookupResult;
122dd49dbfe44098eb53b1ac29f017e422147572bbbVladimir Prus  class MacroInfo;
123dd49dbfe44098eb53b1ac29f017e422147572bbbVladimir Prus  class MultiLevelTemplateArgumentList;
124dd49dbfe44098eb53b1ac29f017e422147572bbbVladimir Prus  class NamedDecl;
125dd49dbfe44098eb53b1ac29f017e422147572bbbVladimir Prus  class NonNullAttr;
126dd49dbfe44098eb53b1ac29f017e422147572bbbVladimir Prus  class ObjCCategoryDecl;
127dd49dbfe44098eb53b1ac29f017e422147572bbbVladimir Prus  class ObjCCategoryImplDecl;
128dd49dbfe44098eb53b1ac29f017e422147572bbbVladimir Prus  class ObjCCompatibleAliasDecl;
12902dea8b39f3acad5de1df36273444d149145e7fcDan Gohman  class ObjCContainerDecl;
13002dea8b39f3acad5de1df36273444d149145e7fcDan Gohman  class ObjCImplDecl;
13102dea8b39f3acad5de1df36273444d149145e7fcDan Gohman  class ObjCImplementationDecl;
132dd49dbfe44098eb53b1ac29f017e422147572bbbVladimir Prus  class ObjCInterfaceDecl;
133b92f50fe6091a7a12f54f9884529b1127b1a14e5Chris Lattner  class ObjCIvarDecl;
134b92f50fe6091a7a12f54f9884529b1127b1a14e5Chris Lattner  template <class T> class ObjCList;
135b92f50fe6091a7a12f54f9884529b1127b1a14e5Chris Lattner  class ObjCMessageExpr;
136b92f50fe6091a7a12f54f9884529b1127b1a14e5Chris Lattner  class ObjCMethodDecl;
137b92f50fe6091a7a12f54f9884529b1127b1a14e5Chris Lattner  class ObjCPropertyDecl;
138b92f50fe6091a7a12f54f9884529b1127b1a14e5Chris Lattner  class ObjCProtocolDecl;
139b92f50fe6091a7a12f54f9884529b1127b1a14e5Chris Lattner  class OMPThreadPrivateDecl;
140b92f50fe6091a7a12f54f9884529b1127b1a14e5Chris Lattner  class OverloadCandidateSet;
141b92f50fe6091a7a12f54f9884529b1127b1a14e5Chris Lattner  class OverloadExpr;
14207216eabb7e749dc38f521e73485db553cefc8d4Chris Lattner  class ParenListExpr;
143a71965b1adf6bfeddfd3b38fdf7df9b4412bc6c2Chris Lattner  class ParmVarDecl;
144a71965b1adf6bfeddfd3b38fdf7df9b4412bc6c2Chris Lattner  class Preprocessor;
14507216eabb7e749dc38f521e73485db553cefc8d4Chris Lattner  class PseudoDestructorTypeStorage;
146a71965b1adf6bfeddfd3b38fdf7df9b4412bc6c2Chris Lattner  class PseudoObjectExpr;
147a71965b1adf6bfeddfd3b38fdf7df9b4412bc6c2Chris Lattner  class QualType;
148a71965b1adf6bfeddfd3b38fdf7df9b4412bc6c2Chris Lattner  class StandardConversionSequence;
149a71965b1adf6bfeddfd3b38fdf7df9b4412bc6c2Chris Lattner  class Stmt;
150a71965b1adf6bfeddfd3b38fdf7df9b4412bc6c2Chris Lattner  class StringLiteral;
151b92f50fe6091a7a12f54f9884529b1127b1a14e5Chris Lattner  class SwitchStmt;
152ad993cbb77b26b36cee938686b3377c0d92abd5eChris Lattner  class TargetAttributesSema;
153ad993cbb77b26b36cee938686b3377c0d92abd5eChris Lattner  class TemplateArgument;
154ad993cbb77b26b36cee938686b3377c0d92abd5eChris Lattner  class TemplateArgumentList;
155ad993cbb77b26b36cee938686b3377c0d92abd5eChris Lattner  class TemplateArgumentLoc;
156ad993cbb77b26b36cee938686b3377c0d92abd5eChris Lattner  class TemplateDecl;
157ad993cbb77b26b36cee938686b3377c0d92abd5eChris Lattner  class TemplateParameterList;
158b92f50fe6091a7a12f54f9884529b1127b1a14e5Chris Lattner  class TemplatePartialOrderingContext;
15987f1e7796d02ea991bdbf084f312879988732a26Torok Edwin  class TemplateTemplateParmDecl;
16087f1e7796d02ea991bdbf084f312879988732a26Torok Edwin  class Token;
16187f1e7796d02ea991bdbf084f312879988732a26Torok Edwin  class TypeAliasDecl;
1629053a739e50cb6f6b68268cc7c6b95146e66d396Torok Edwin  class TypedefDecl;
1639053a739e50cb6f6b68268cc7c6b95146e66d396Torok Edwin  class TypedefNameDecl;
16487f1e7796d02ea991bdbf084f312879988732a26Torok Edwin  class TypeLoc;
16587f1e7796d02ea991bdbf084f312879988732a26Torok Edwin  class UnqualifiedId;
16687f1e7796d02ea991bdbf084f312879988732a26Torok Edwin  class UnresolvedLookupExpr;
16787f1e7796d02ea991bdbf084f312879988732a26Torok Edwin  class UnresolvedMemberExpr;
16887f1e7796d02ea991bdbf084f312879988732a26Torok Edwin  class UnresolvedSetImpl;
1691020b3982c9eae15844c5612b0cf251917931b1dChris Lattner  class UnresolvedSetIterator;
170fab8c796f6754962f5732145248303e3a1f7b96bChris Lattner  class UsingDecl;
171fab8c796f6754962f5732145248303e3a1f7b96bChris Lattner  class UsingShadowDecl;
1721020b3982c9eae15844c5612b0cf251917931b1dChris Lattner  class ValueDecl;
1731020b3982c9eae15844c5612b0cf251917931b1dChris Lattner  class VarDecl;
1741020b3982c9eae15844c5612b0cf251917931b1dChris Lattner  class VisibilityAttr;
1751020b3982c9eae15844c5612b0cf251917931b1dChris Lattner  class VisibleDeclConsumer;
1761020b3982c9eae15844c5612b0cf251917931b1dChris Lattner  class IndirectFieldDecl;
177c063502e326fe0206942192773b263a3d88d93f5Chris Lattner
1781020b3982c9eae15844c5612b0cf251917931b1dChris Lattnernamespace sema {
17918961504fc2b299578dba817900a0696cf3ccc4dChris Lattner  class AccessedEntity;
18018961504fc2b299578dba817900a0696cf3ccc4dChris Lattner  class BlockScopeInfo;
181a4c6c522ee029e97aedccb6ee7cca912d52a5599Misha Brukman  class CapturedRegionScopeInfo;
182a4c6c522ee029e97aedccb6ee7cca912d52a5599Misha Brukman  class CapturingScopeInfo;
1831020b3982c9eae15844c5612b0cf251917931b1dChris Lattner  class CompoundScopeInfo;
18426199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  class DelayedDiagnostic;
18526199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  class DelayedDiagnosticPool;
18626199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  class FunctionScopeInfo;
1871020b3982c9eae15844c5612b0cf251917931b1dChris Lattner  class LambdaScopeInfo;
1881020b3982c9eae15844c5612b0cf251917931b1dChris Lattner  class PossiblyUnreachableDiag;
1890dd2a6a89f49438b239638ab147ac5746d6c32c3Gabor Greif  class TemplateDeductionInfo;
1900dd2a6a89f49438b239638ab147ac5746d6c32c3Gabor Greif}
191b547a181005cc255fa57c61c1c0dbafca5375fb4Gabor Greif
192b547a181005cc255fa57c61c1c0dbafca5375fb4Gabor Greif// FIXME: No way to easily map from TemplateTypeParmTypes to
193b547a181005cc255fa57c61c1c0dbafca5375fb4Gabor Greif// TemplateTypeParmDecls, so we have this horrible PointerUnion.
1941020b3982c9eae15844c5612b0cf251917931b1dChris Lattnertypedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
1950dd2a6a89f49438b239638ab147ac5746d6c32c3Gabor Greif                  SourceLocation> UnexpandedParameterPack;
1960dd2a6a89f49438b239638ab147ac5746d6c32c3Gabor Greif
1970dd2a6a89f49438b239638ab147ac5746d6c32c3Gabor Greif/// Sema - This implements semantic analysis and AST building for C.
19826199059268a05739c84ebf465fcdbf7ded861dfChris Lattnerclass Sema {
19970cfe13f19e91a595808ed6c6ff7e87ff0dccd64Chris Lattner  Sema(const Sema &) LLVM_DELETED_FUNCTION;
200b00c582b6d40e6b9ff2d1ed4f5eaf7930e792aceChris Lattner  void operator=(const Sema &) LLVM_DELETED_FUNCTION;
201a1a702cdd23221e6e3f36632be91150138958e9dDan Gohman  mutable const TargetAttributesSema* TheTargetAttributesSema;
2029636a91649f168f41b477cba705287665e054f79Chris Lattner
2039636a91649f168f41b477cba705287665e054f79Chris Lattner  ///\brief Source of additional semantic information.
20426199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  ExternalSemaSource *ExternalSource;
20526199059268a05739c84ebf465fcdbf7ded861dfChris Lattner
20626199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  ///\brief Whether Sema has generated a multiplexer and has to delete it.
20726199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  bool isMultiplexExternalSource;
20826199059268a05739c84ebf465fcdbf7ded861dfChris Lattner
2099769ab22265b313171d201b5928688524a01bd87Misha Brukman  static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
21026199059268a05739c84ebf465fcdbf7ded861dfChris Lattner
21126199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  static bool
212009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner  shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) {
213009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner    // We are about to link these. It is now safe to compute the linkage of
21426199059268a05739c84ebf465fcdbf7ded861dfChris Lattner    // the new decl. If the new decl has external linkage, we will
21526199059268a05739c84ebf465fcdbf7ded861dfChris Lattner    // link it with the hidden decl (which also has external linkage) and
2169769ab22265b313171d201b5928688524a01bd87Misha Brukman    // it will keep having external linkage. If it has internal linkage, we
21726199059268a05739c84ebf465fcdbf7ded861dfChris Lattner    // will not link it. Since it has no previous decls, it will remain
21826199059268a05739c84ebf465fcdbf7ded861dfChris Lattner    // with internal linkage.
21926199059268a05739c84ebf465fcdbf7ded861dfChris Lattner    return !Old->isHidden() || New->isExternallyVisible();
220280a6e607d8eb7401749a92db624a82de47da777Nick Lewycky  }
2217b6f5a3ee9a68d0f6206b1695f71551a467e33c4Chris Lattner
22226199059268a05739c84ebf465fcdbf7ded861dfChris Lattnerpublic:
22326199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
22426199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  typedef OpaquePtr<TemplateName> TemplateTy;
2259eb59ec548b861d6ede05b4e6dc22aabf645e665Jeff Cohen  typedef OpaquePtr<QualType> TypeTy;
22605bb8831d3cd5299ba8e0c3fecfd7cf682f0ace1Reid Spencer
22705bb8831d3cd5299ba8e0c3fecfd7cf682f0ace1Reid Spencer  OpenCLOptions OpenCLFeatures;
22826199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  FPOptions FPFeatures;
2299769ab22265b313171d201b5928688524a01bd87Misha Brukman
23026199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  const LangOptions &LangOpts;
23126199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  Preprocessor &PP;
23226199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  ASTContext &Context;
23326199059268a05739c84ebf465fcdbf7ded861dfChris Lattner  ASTConsumer &Consumer;
2346e0d1cb30957a636c53158d3089e6fb88348a57aDaniel Dunbar  DiagnosticsEngine &Diags;
235009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner  SourceManager &SourceMgr;
236009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner
237d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke  /// \brief Flag indicating whether or not to collect detailed statistics.
238d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke  bool CollectStats;
239009505452b713ed2e3a8e99c5545a6e721c65495Chris Lattner
240  /// \brief Code-completion consumer.
241  CodeCompleteConsumer *CodeCompleter;
242
243  /// CurContext - This is the current declaration context of parsing.
244  DeclContext *CurContext;
245
246  /// \brief Generally null except when we temporarily switch decl contexts,
247  /// like in \see ActOnObjCTemporaryExitContainerContext.
248  DeclContext *OriginalLexicalContext;
249
250  /// VAListTagName - The declaration name corresponding to __va_list_tag.
251  /// This is used as part of a hack to omit that class from ADL results.
252  DeclarationName VAListTagName;
253
254  /// PackContext - Manages the stack for \#pragma pack. An alignment
255  /// of 0 indicates default alignment.
256  void *PackContext; // Really a "PragmaPackStack*"
257
258  bool MSStructPragmaOn; // True when \#pragma ms_struct on
259
260  /// VisContext - Manages the stack for \#pragma GCC visibility.
261  void *VisContext; // Really a "PragmaVisStack*"
262
263  /// \brief Flag indicating if Sema is building a recovery call expression.
264  ///
265  /// This flag is used to avoid building recovery call expressions
266  /// if Sema is already doing so, which would cause infinite recursions.
267  bool IsBuildingRecoveryCallExpr;
268
269  /// ExprNeedsCleanups - True if the current evaluation context
270  /// requires cleanups to be run at its conclusion.
271  bool ExprNeedsCleanups;
272
273  /// ExprCleanupObjects - This is the stack of objects requiring
274  /// cleanup that are created by the current full expression.  The
275  /// element type here is ExprWithCleanups::Object.
276  SmallVector<BlockDecl*, 8> ExprCleanupObjects;
277
278  llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
279
280  /// \brief Stack containing information about each of the nested
281  /// function, block, and method scopes that are currently active.
282  ///
283  /// This array is never empty.  Clients should ignore the first
284  /// element, which is used to cache a single FunctionScopeInfo
285  /// that's used to parse every top-level function.
286  SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
287
288  typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
289                     &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
290    ExtVectorDeclsType;
291
292  /// ExtVectorDecls - This is a list all the extended vector types. This allows
293  /// us to associate a raw vector type with one of the ext_vector type names.
294  /// This is only necessary for issuing pretty diagnostics.
295  ExtVectorDeclsType ExtVectorDecls;
296
297  /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
298  OwningPtr<CXXFieldCollector> FieldCollector;
299
300  typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
301
302  /// \brief Set containing all declared private fields that are not used.
303  NamedDeclSetType UnusedPrivateFields;
304
305  typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
306
307  /// PureVirtualClassDiagSet - a set of class declarations which we have
308  /// emitted a list of pure virtual functions. Used to prevent emitting the
309  /// same list more than once.
310  OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet;
311
312  /// ParsingInitForAutoVars - a set of declarations with auto types for which
313  /// we are currently parsing the initializer.
314  llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
315
316  /// \brief A mapping from external names to the most recent
317  /// locally-scoped extern "C" declaration with that name.
318  ///
319  /// This map contains external declarations introduced in local
320  /// scopes, e.g.,
321  ///
322  /// \code
323  /// extern "C" void f() {
324  ///   void foo(int, int);
325  /// }
326  /// \endcode
327  ///
328  /// Here, the name "foo" will be associated with the declaration of
329  /// "foo" within f. This name is not visible outside of
330  /// "f". However, we still find it in two cases:
331  ///
332  ///   - If we are declaring another global or extern "C" entity with
333  ///     the name "foo", we can find "foo" as a previous declaration,
334  ///     so that the types of this external declaration can be checked
335  ///     for compatibility.
336  ///
337  ///   - If we would implicitly declare "foo" (e.g., due to a call to
338  ///     "foo" in C when no prototype or definition is visible), then
339  ///     we find this declaration of "foo" and complain that it is
340  ///     not visible.
341  llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternCDecls;
342
343  /// \brief Look for a locally scoped extern "C" declaration by the given name.
344  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
345  findLocallyScopedExternCDecl(DeclarationName Name);
346
347  typedef LazyVector<VarDecl *, ExternalSemaSource,
348                     &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
349    TentativeDefinitionsType;
350
351  /// \brief All the tentative definitions encountered in the TU.
352  TentativeDefinitionsType TentativeDefinitions;
353
354  typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
355                     &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
356    UnusedFileScopedDeclsType;
357
358  /// \brief The set of file scoped decls seen so far that have not been used
359  /// and must warn if not used. Only contains the first declaration.
360  UnusedFileScopedDeclsType UnusedFileScopedDecls;
361
362  typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
363                     &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
364    DelegatingCtorDeclsType;
365
366  /// \brief All the delegating constructors seen so far in the file, used for
367  /// cycle detection at the end of the TU.
368  DelegatingCtorDeclsType DelegatingCtorDecls;
369
370  /// \brief All the destructors seen during a class definition that had their
371  /// exception spec computation delayed because it depended on an unparsed
372  /// exception spec.
373  SmallVector<CXXDestructorDecl*, 2> DelayedDestructorExceptionSpecs;
374
375  /// \brief All the overriding destructors seen during a class definition
376  /// (there could be multiple due to nested classes) that had their exception
377  /// spec checks delayed, plus the overridden destructor.
378  SmallVector<std::pair<const CXXDestructorDecl*,
379                              const CXXDestructorDecl*>, 2>
380      DelayedDestructorExceptionSpecChecks;
381
382  /// \brief All the members seen during a class definition which were both
383  /// explicitly defaulted and had explicitly-specified exception
384  /// specifications, along with the function type containing their
385  /// user-specified exception specification. Those exception specifications
386  /// were overridden with the default specifications, but we still need to
387  /// check whether they are compatible with the default specification, and
388  /// we can't do that until the nesting set of class definitions is complete.
389  SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
390    DelayedDefaultedMemberExceptionSpecs;
391
392  /// \brief Callback to the parser to parse templated functions when needed.
393  typedef void LateTemplateParserCB(void *P, const FunctionDecl *FD);
394  LateTemplateParserCB *LateTemplateParser;
395  void *OpaqueParser;
396
397  void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
398    LateTemplateParser = LTP;
399    OpaqueParser = P;
400  }
401
402  class DelayedDiagnostics;
403
404  class DelayedDiagnosticsState {
405    sema::DelayedDiagnosticPool *SavedPool;
406    friend class Sema::DelayedDiagnostics;
407  };
408  typedef DelayedDiagnosticsState ParsingDeclState;
409  typedef DelayedDiagnosticsState ProcessingContextState;
410
411  /// A class which encapsulates the logic for delaying diagnostics
412  /// during parsing and other processing.
413  class DelayedDiagnostics {
414    /// \brief The current pool of diagnostics into which delayed
415    /// diagnostics should go.
416    sema::DelayedDiagnosticPool *CurPool;
417
418  public:
419    DelayedDiagnostics() : CurPool(0) {}
420
421    /// Adds a delayed diagnostic.
422    void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
423
424    /// Determines whether diagnostics should be delayed.
425    bool shouldDelayDiagnostics() { return CurPool != 0; }
426
427    /// Returns the current delayed-diagnostics pool.
428    sema::DelayedDiagnosticPool *getCurrentPool() const {
429      return CurPool;
430    }
431
432    /// Enter a new scope.  Access and deprecation diagnostics will be
433    /// collected in this pool.
434    DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
435      DelayedDiagnosticsState state;
436      state.SavedPool = CurPool;
437      CurPool = &pool;
438      return state;
439    }
440
441    /// Leave a delayed-diagnostic state that was previously pushed.
442    /// Do not emit any of the diagnostics.  This is performed as part
443    /// of the bookkeeping of popping a pool "properly".
444    void popWithoutEmitting(DelayedDiagnosticsState state) {
445      CurPool = state.SavedPool;
446    }
447
448    /// Enter a new scope where access and deprecation diagnostics are
449    /// not delayed.
450    DelayedDiagnosticsState pushUndelayed() {
451      DelayedDiagnosticsState state;
452      state.SavedPool = CurPool;
453      CurPool = 0;
454      return state;
455    }
456
457    /// Undo a previous pushUndelayed().
458    void popUndelayed(DelayedDiagnosticsState state) {
459      assert(CurPool == NULL);
460      CurPool = state.SavedPool;
461    }
462  } DelayedDiagnostics;
463
464  /// A RAII object to temporarily push a declaration context.
465  class ContextRAII {
466  private:
467    Sema &S;
468    DeclContext *SavedContext;
469    ProcessingContextState SavedContextState;
470    QualType SavedCXXThisTypeOverride;
471
472  public:
473    ContextRAII(Sema &S, DeclContext *ContextToPush)
474      : S(S), SavedContext(S.CurContext),
475        SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
476        SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
477    {
478      assert(ContextToPush && "pushing null context");
479      S.CurContext = ContextToPush;
480    }
481
482    void pop() {
483      if (!SavedContext) return;
484      S.CurContext = SavedContext;
485      S.DelayedDiagnostics.popUndelayed(SavedContextState);
486      S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
487      SavedContext = 0;
488    }
489
490    ~ContextRAII() {
491      pop();
492    }
493  };
494
495  /// \brief RAII object to handle the state changes required to synthesize
496  /// a function body.
497  class SynthesizedFunctionScope {
498    Sema &S;
499    Sema::ContextRAII SavedContext;
500
501  public:
502    SynthesizedFunctionScope(Sema &S, DeclContext *DC)
503      : S(S), SavedContext(S, DC)
504    {
505      S.PushFunctionScope();
506      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
507    }
508
509    ~SynthesizedFunctionScope() {
510      S.PopExpressionEvaluationContext();
511      S.PopFunctionScopeInfo();
512    }
513  };
514
515  /// WeakUndeclaredIdentifiers - Identifiers contained in
516  /// \#pragma weak before declared. rare. may alias another
517  /// identifier, declared or undeclared
518  llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers;
519
520  /// ExtnameUndeclaredIdentifiers - Identifiers contained in
521  /// \#pragma redefine_extname before declared.  Used in Solaris system headers
522  /// to define functions that occur in multiple standards to call the version
523  /// in the currently selected standard.
524  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
525
526
527  /// \brief Load weak undeclared identifiers from the external source.
528  void LoadExternalWeakUndeclaredIdentifiers();
529
530  /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
531  /// \#pragma weak during processing of other Decls.
532  /// I couldn't figure out a clean way to generate these in-line, so
533  /// we store them here and handle separately -- which is a hack.
534  /// It would be best to refactor this.
535  SmallVector<Decl*,2> WeakTopLevelDecl;
536
537  IdentifierResolver IdResolver;
538
539  /// Translation Unit Scope - useful to Objective-C actions that need
540  /// to lookup file scope declarations in the "ordinary" C decl namespace.
541  /// For example, user-defined classes, built-in "id" type, etc.
542  Scope *TUScope;
543
544  /// \brief The C++ "std" namespace, where the standard library resides.
545  LazyDeclPtr StdNamespace;
546
547  /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
548  /// standard library.
549  LazyDeclPtr StdBadAlloc;
550
551  /// \brief The C++ "std::initializer_list" template, which is defined in
552  /// \<initializer_list>.
553  ClassTemplateDecl *StdInitializerList;
554
555  /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
556  RecordDecl *CXXTypeInfoDecl;
557
558  /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
559  RecordDecl *MSVCGuidDecl;
560
561  /// \brief Caches identifiers/selectors for NSFoundation APIs.
562  OwningPtr<NSAPI> NSAPIObj;
563
564  /// \brief The declaration of the Objective-C NSNumber class.
565  ObjCInterfaceDecl *NSNumberDecl;
566
567  /// \brief Pointer to NSNumber type (NSNumber *).
568  QualType NSNumberPointer;
569
570  /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
571  ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
572
573  /// \brief The declaration of the Objective-C NSString class.
574  ObjCInterfaceDecl *NSStringDecl;
575
576  /// \brief Pointer to NSString type (NSString *).
577  QualType NSStringPointer;
578
579  /// \brief The declaration of the stringWithUTF8String: method.
580  ObjCMethodDecl *StringWithUTF8StringMethod;
581
582  /// \brief The declaration of the Objective-C NSArray class.
583  ObjCInterfaceDecl *NSArrayDecl;
584
585  /// \brief The declaration of the arrayWithObjects:count: method.
586  ObjCMethodDecl *ArrayWithObjectsMethod;
587
588  /// \brief The declaration of the Objective-C NSDictionary class.
589  ObjCInterfaceDecl *NSDictionaryDecl;
590
591  /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
592  ObjCMethodDecl *DictionaryWithObjectsMethod;
593
594  /// \brief id<NSCopying> type.
595  QualType QIDNSCopying;
596
597  /// \brief will hold 'respondsToSelector:'
598  Selector RespondsToSelectorSel;
599
600  /// A flag to remember whether the implicit forms of operator new and delete
601  /// have been declared.
602  bool GlobalNewDeleteDeclared;
603
604  /// A flag to indicate that we're in a context that permits abstract
605  /// references to fields.  This is really a
606  bool AllowAbstractFieldReference;
607
608  /// \brief Describes how the expressions currently being parsed are
609  /// evaluated at run-time, if at all.
610  enum ExpressionEvaluationContext {
611    /// \brief The current expression and its subexpressions occur within an
612    /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
613    /// \c sizeof, where the type of the expression may be significant but
614    /// no code will be generated to evaluate the value of the expression at
615    /// run time.
616    Unevaluated,
617
618    /// \brief The current expression occurs within an unevaluated
619    /// operand that unconditionally permits abstract references to
620    /// fields, such as a SIZE operator in MS-style inline assembly.
621    UnevaluatedAbstract,
622
623    /// \brief The current context is "potentially evaluated" in C++11 terms,
624    /// but the expression is evaluated at compile-time (like the values of
625    /// cases in a switch statment).
626    ConstantEvaluated,
627
628    /// \brief The current expression is potentially evaluated at run time,
629    /// which means that code may be generated to evaluate the value of the
630    /// expression at run time.
631    PotentiallyEvaluated,
632
633    /// \brief The current expression is potentially evaluated, but any
634    /// declarations referenced inside that expression are only used if
635    /// in fact the current expression is used.
636    ///
637    /// This value is used when parsing default function arguments, for which
638    /// we would like to provide diagnostics (e.g., passing non-POD arguments
639    /// through varargs) but do not want to mark declarations as "referenced"
640    /// until the default argument is used.
641    PotentiallyEvaluatedIfUsed
642  };
643
644  /// \brief Data structure used to record current or nested
645  /// expression evaluation contexts.
646  struct ExpressionEvaluationContextRecord {
647    /// \brief The expression evaluation context.
648    ExpressionEvaluationContext Context;
649
650    /// \brief Whether the enclosing context needed a cleanup.
651    bool ParentNeedsCleanups;
652
653    /// \brief Whether we are in a decltype expression.
654    bool IsDecltype;
655
656    /// \brief The number of active cleanup objects when we entered
657    /// this expression evaluation context.
658    unsigned NumCleanupObjects;
659
660    llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
661
662    /// \brief The lambdas that are present within this context, if it
663    /// is indeed an unevaluated context.
664    SmallVector<LambdaExpr *, 2> Lambdas;
665
666    /// \brief The declaration that provides context for the lambda expression
667    /// if the normal declaration context does not suffice, e.g., in a
668    /// default function argument.
669    Decl *LambdaContextDecl;
670
671    /// \brief The context information used to mangle lambda expressions
672    /// within this context.
673    ///
674    /// This mangling information is allocated lazily, since most contexts
675    /// do not have lambda expressions.
676    IntrusiveRefCntPtr<LambdaMangleContext> LambdaMangle;
677
678    /// \brief If we are processing a decltype type, a set of call expressions
679    /// for which we have deferred checking the completeness of the return type.
680    SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
681
682    /// \brief If we are processing a decltype type, a set of temporary binding
683    /// expressions for which we have deferred checking the destructor.
684    SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
685
686    ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
687                                      unsigned NumCleanupObjects,
688                                      bool ParentNeedsCleanups,
689                                      Decl *LambdaContextDecl,
690                                      bool IsDecltype)
691      : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
692        IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
693        LambdaContextDecl(LambdaContextDecl), LambdaMangle() { }
694
695    /// \brief Retrieve the mangling context for lambdas.
696    LambdaMangleContext &getLambdaMangleContext() {
697      assert(LambdaContextDecl && "Need to have a lambda context declaration");
698      if (!LambdaMangle)
699        LambdaMangle = new LambdaMangleContext;
700      return *LambdaMangle;
701    }
702
703    bool isUnevaluated() const {
704      return Context == Unevaluated || Context == UnevaluatedAbstract;
705    }
706  };
707
708  /// A stack of expression evaluation contexts.
709  SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
710
711  /// SpecialMemberOverloadResult - The overloading result for a special member
712  /// function.
713  ///
714  /// This is basically a wrapper around PointerIntPair. The lowest bits of the
715  /// integer are used to determine whether overload resolution succeeded.
716  class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
717  public:
718    enum Kind {
719      NoMemberOrDeleted,
720      Ambiguous,
721      Success
722    };
723
724  private:
725    llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
726
727  public:
728    SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
729      : FastFoldingSetNode(ID)
730    {}
731
732    CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
733    void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
734
735    Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
736    void setKind(Kind K) { Pair.setInt(K); }
737  };
738
739  /// \brief A cache of special member function overload resolution results
740  /// for C++ records.
741  llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
742
743  /// \brief The kind of translation unit we are processing.
744  ///
745  /// When we're processing a complete translation unit, Sema will perform
746  /// end-of-translation-unit semantic tasks (such as creating
747  /// initializers for tentative definitions in C) once parsing has
748  /// completed. Modules and precompiled headers perform different kinds of
749  /// checks.
750  TranslationUnitKind TUKind;
751
752  llvm::BumpPtrAllocator BumpAlloc;
753
754  /// \brief The number of SFINAE diagnostics that have been trapped.
755  unsigned NumSFINAEErrors;
756
757  typedef llvm::DenseMap<ParmVarDecl *, SmallVector<ParmVarDecl *, 1> >
758    UnparsedDefaultArgInstantiationsMap;
759
760  /// \brief A mapping from parameters with unparsed default arguments to the
761  /// set of instantiations of each parameter.
762  ///
763  /// This mapping is a temporary data structure used when parsing
764  /// nested class templates or nested classes of class templates,
765  /// where we might end up instantiating an inner class before the
766  /// default arguments of its methods have been parsed.
767  UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
768
769  // Contains the locations of the beginning of unparsed default
770  // argument locations.
771  llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
772
773  /// UndefinedInternals - all the used, undefined objects which require a
774  /// definition in this translation unit.
775  llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed;
776
777  /// Obtain a sorted list of functions that are undefined but ODR-used.
778  void getUndefinedButUsed(
779    llvm::SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
780
781  typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
782  typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
783
784  /// Method Pool - allows efficient lookup when typechecking messages to "id".
785  /// We need to maintain a list, since selectors can have differing signatures
786  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
787  /// of selectors are "overloaded").
788  /// At the head of the list it is recorded whether there were 0, 1, or >= 2
789  /// methods inside categories with a particular selector.
790  GlobalMethodPool MethodPool;
791
792  /// Method selectors used in a \@selector expression. Used for implementation
793  /// of -Wselector.
794  llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors;
795
796  /// Kinds of C++ special members.
797  enum CXXSpecialMember {
798    CXXDefaultConstructor,
799    CXXCopyConstructor,
800    CXXMoveConstructor,
801    CXXCopyAssignment,
802    CXXMoveAssignment,
803    CXXDestructor,
804    CXXInvalid
805  };
806
807  typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
808
809  /// The C++ special members which we are currently in the process of
810  /// declaring. If this process recursively triggers the declaration of the
811  /// same special member, we should act as if it is not yet declared.
812  llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
813
814  void ReadMethodPool(Selector Sel);
815
816  /// Private Helper predicate to check for 'self'.
817  bool isSelfExpr(Expr *RExpr);
818
819  /// \brief Cause the active diagnostic on the DiagosticsEngine to be
820  /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
821  /// should not be used elsewhere.
822  void EmitCurrentDiagnostic(unsigned DiagID);
823
824  /// Records and restores the FP_CONTRACT state on entry/exit of compound
825  /// statements.
826  class FPContractStateRAII {
827  public:
828    FPContractStateRAII(Sema& S)
829      : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
830    ~FPContractStateRAII() {
831      S.FPFeatures.fp_contract = OldFPContractState;
832    }
833  private:
834    Sema& S;
835    bool OldFPContractState : 1;
836  };
837
838  typedef llvm::MCAsmParserSemaCallback::InlineAsmIdentifierInfo
839    InlineAsmIdentifierInfo;
840
841public:
842  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
843       TranslationUnitKind TUKind = TU_Complete,
844       CodeCompleteConsumer *CompletionConsumer = 0);
845  ~Sema();
846
847  /// \brief Perform initialization that occurs after the parser has been
848  /// initialized but before it parses anything.
849  void Initialize();
850
851  const LangOptions &getLangOpts() const { return LangOpts; }
852  OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
853  FPOptions     &getFPOptions() { return FPFeatures; }
854
855  DiagnosticsEngine &getDiagnostics() const { return Diags; }
856  SourceManager &getSourceManager() const { return SourceMgr; }
857  const TargetAttributesSema &getTargetAttributesSema() const;
858  Preprocessor &getPreprocessor() const { return PP; }
859  ASTContext &getASTContext() const { return Context; }
860  ASTConsumer &getASTConsumer() const { return Consumer; }
861  ASTMutationListener *getASTMutationListener() const;
862  ExternalSemaSource* getExternalSource() const { return ExternalSource; }
863
864  ///\brief Registers an external source. If an external source already exists,
865  /// creates a multiplex external source and appends to it.
866  ///
867  ///\param[in] E - A non-null external sema source.
868  ///
869  void addExternalSource(ExternalSemaSource *E);
870
871  void PrintStats() const;
872
873  /// \brief Helper class that creates diagnostics with optional
874  /// template instantiation stacks.
875  ///
876  /// This class provides a wrapper around the basic DiagnosticBuilder
877  /// class that emits diagnostics. SemaDiagnosticBuilder is
878  /// responsible for emitting the diagnostic (as DiagnosticBuilder
879  /// does) and, if the diagnostic comes from inside a template
880  /// instantiation, printing the template instantiation stack as
881  /// well.
882  class SemaDiagnosticBuilder : public DiagnosticBuilder {
883    Sema &SemaRef;
884    unsigned DiagID;
885
886  public:
887    SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
888      : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
889
890    ~SemaDiagnosticBuilder() {
891      // If we aren't active, there is nothing to do.
892      if (!isActive()) return;
893
894      // Otherwise, we need to emit the diagnostic. First flush the underlying
895      // DiagnosticBuilder data, and clear the diagnostic builder itself so it
896      // won't emit the diagnostic in its own destructor.
897      //
898      // This seems wasteful, in that as written the DiagnosticBuilder dtor will
899      // do its own needless checks to see if the diagnostic needs to be
900      // emitted. However, because we take care to ensure that the builder
901      // objects never escape, a sufficiently smart compiler will be able to
902      // eliminate that code.
903      FlushCounts();
904      Clear();
905
906      // Dispatch to Sema to emit the diagnostic.
907      SemaRef.EmitCurrentDiagnostic(DiagID);
908    }
909
910    /// Teach operator<< to produce an object of the correct type.
911    template<typename T>
912    friend const SemaDiagnosticBuilder &operator<<(
913        const SemaDiagnosticBuilder &Diag, const T &Value) {
914      const DiagnosticBuilder &BaseDiag = Diag;
915      BaseDiag << Value;
916      return Diag;
917    }
918  };
919
920  /// \brief Emit a diagnostic.
921  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
922    DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
923    return SemaDiagnosticBuilder(DB, *this, DiagID);
924  }
925
926  /// \brief Emit a partial diagnostic.
927  SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
928
929  /// \brief Build a partial diagnostic.
930  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
931
932  bool findMacroSpelling(SourceLocation &loc, StringRef name);
933
934  /// \brief Get a string to suggest for zero-initialization of a type.
935  std::string getFixItZeroInitializerForType(QualType T) const;
936  std::string getFixItZeroLiteralForType(QualType T) const;
937
938  ExprResult Owned(Expr* E) { return E; }
939  ExprResult Owned(ExprResult R) { return R; }
940  StmtResult Owned(Stmt* S) { return S; }
941
942  void ActOnEndOfTranslationUnit();
943
944  void CheckDelegatingCtorCycles();
945
946  Scope *getScopeForContext(DeclContext *Ctx);
947
948  void PushFunctionScope();
949  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
950  void PushLambdaScope(CXXRecordDecl *Lambda, CXXMethodDecl *CallOperator);
951  void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
952                               RecordDecl *RD,
953                               CapturedRegionKind K);
954  void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP =0,
955                            const Decl *D = 0, const BlockExpr *blkExpr = 0);
956
957  sema::FunctionScopeInfo *getCurFunction() const {
958    return FunctionScopes.back();
959  }
960
961  template <typename ExprT>
962  void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
963    if (!isUnevaluatedContext())
964      getCurFunction()->recordUseOfWeak(E, IsRead);
965  }
966
967  void PushCompoundScope();
968  void PopCompoundScope();
969
970  sema::CompoundScopeInfo &getCurCompoundScope() const;
971
972  bool hasAnyUnrecoverableErrorsInThisFunction() const;
973
974  /// \brief Retrieve the current block, if any.
975  sema::BlockScopeInfo *getCurBlock();
976
977  /// \brief Retrieve the current lambda expression, if any.
978  sema::LambdaScopeInfo *getCurLambda();
979
980  /// \brief Retrieve the current captured region, if any.
981  sema::CapturedRegionScopeInfo *getCurCapturedRegion();
982
983  /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
984  SmallVector<Decl*,2> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
985
986  void ActOnComment(SourceRange Comment);
987
988  //===--------------------------------------------------------------------===//
989  // Type Analysis / Processing: SemaType.cpp.
990  //
991
992  QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
993                              const DeclSpec *DS = 0);
994  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
995                              const DeclSpec *DS = 0);
996  QualType BuildPointerType(QualType T,
997                            SourceLocation Loc, DeclarationName Entity);
998  QualType BuildReferenceType(QualType T, bool LValueRef,
999                              SourceLocation Loc, DeclarationName Entity);
1000  QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1001                          Expr *ArraySize, unsigned Quals,
1002                          SourceRange Brackets, DeclarationName Entity);
1003  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1004                              SourceLocation AttrLoc);
1005
1006  bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1007
1008  /// \brief Build a function type.
1009  ///
1010  /// This routine checks the function type according to C++ rules and
1011  /// under the assumption that the result type and parameter types have
1012  /// just been instantiated from a template. It therefore duplicates
1013  /// some of the behavior of GetTypeForDeclarator, but in a much
1014  /// simpler form that is only suitable for this narrow use case.
1015  ///
1016  /// \param T The return type of the function.
1017  ///
1018  /// \param ParamTypes The parameter types of the function. This array
1019  /// will be modified to account for adjustments to the types of the
1020  /// function parameters.
1021  ///
1022  /// \param Loc The location of the entity whose type involves this
1023  /// function type or, if there is no such entity, the location of the
1024  /// type that will have function type.
1025  ///
1026  /// \param Entity The name of the entity that involves the function
1027  /// type, if known.
1028  ///
1029  /// \param EPI Extra information about the function type. Usually this will
1030  /// be taken from an existing function with the same prototype.
1031  ///
1032  /// \returns A suitable function type, if there are no errors. The
1033  /// unqualified type will always be a FunctionProtoType.
1034  /// Otherwise, returns a NULL type.
1035  QualType BuildFunctionType(QualType T,
1036                             llvm::MutableArrayRef<QualType> ParamTypes,
1037                             SourceLocation Loc, DeclarationName Entity,
1038                             const FunctionProtoType::ExtProtoInfo &EPI);
1039
1040  QualType BuildMemberPointerType(QualType T, QualType Class,
1041                                  SourceLocation Loc,
1042                                  DeclarationName Entity);
1043  QualType BuildBlockPointerType(QualType T,
1044                                 SourceLocation Loc, DeclarationName Entity);
1045  QualType BuildParenType(QualType T);
1046  QualType BuildAtomicType(QualType T, SourceLocation Loc);
1047
1048  TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1049  TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1050  TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1051                                               TypeSourceInfo *ReturnTypeInfo);
1052
1053  /// \brief Package the given type and TSI into a ParsedType.
1054  ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1055  DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1056  DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1057  static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0);
1058  CanThrowResult canThrow(const Expr *E);
1059  const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1060                                                const FunctionProtoType *FPT);
1061  bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range);
1062  bool CheckDistantExceptionSpec(QualType T);
1063  bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1064  bool CheckEquivalentExceptionSpec(
1065      const FunctionProtoType *Old, SourceLocation OldLoc,
1066      const FunctionProtoType *New, SourceLocation NewLoc);
1067  bool CheckEquivalentExceptionSpec(
1068      const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1069      const FunctionProtoType *Old, SourceLocation OldLoc,
1070      const FunctionProtoType *New, SourceLocation NewLoc,
1071      bool *MissingExceptionSpecification = 0,
1072      bool *MissingEmptyExceptionSpecification = 0,
1073      bool AllowNoexceptAllMatchWithNoSpec = false,
1074      bool IsOperatorNew = false);
1075  bool CheckExceptionSpecSubset(
1076      const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1077      const FunctionProtoType *Superset, SourceLocation SuperLoc,
1078      const FunctionProtoType *Subset, SourceLocation SubLoc);
1079  bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
1080      const FunctionProtoType *Target, SourceLocation TargetLoc,
1081      const FunctionProtoType *Source, SourceLocation SourceLoc);
1082
1083  TypeResult ActOnTypeName(Scope *S, Declarator &D);
1084
1085  /// \brief The parser has parsed the context-sensitive type 'instancetype'
1086  /// in an Objective-C message declaration. Return the appropriate type.
1087  ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1088
1089  /// \brief Abstract class used to diagnose incomplete types.
1090  struct TypeDiagnoser {
1091    bool Suppressed;
1092
1093    TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
1094
1095    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1096    virtual ~TypeDiagnoser() {}
1097  };
1098
1099  static int getPrintable(int I) { return I; }
1100  static unsigned getPrintable(unsigned I) { return I; }
1101  static bool getPrintable(bool B) { return B; }
1102  static const char * getPrintable(const char *S) { return S; }
1103  static StringRef getPrintable(StringRef S) { return S; }
1104  static const std::string &getPrintable(const std::string &S) { return S; }
1105  static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1106    return II;
1107  }
1108  static DeclarationName getPrintable(DeclarationName N) { return N; }
1109  static QualType getPrintable(QualType T) { return T; }
1110  static SourceRange getPrintable(SourceRange R) { return R; }
1111  static SourceRange getPrintable(SourceLocation L) { return L; }
1112  static SourceRange getPrintable(Expr *E) { return E->getSourceRange(); }
1113  static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1114
1115  template<typename T1>
1116  class BoundTypeDiagnoser1 : public TypeDiagnoser {
1117    unsigned DiagID;
1118    const T1 &Arg1;
1119
1120  public:
1121    BoundTypeDiagnoser1(unsigned DiagID, const T1 &Arg1)
1122      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1) { }
1123    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
1124      if (Suppressed) return;
1125      S.Diag(Loc, DiagID) << getPrintable(Arg1) << T;
1126    }
1127
1128    virtual ~BoundTypeDiagnoser1() { }
1129  };
1130
1131  template<typename T1, typename T2>
1132  class BoundTypeDiagnoser2 : public TypeDiagnoser {
1133    unsigned DiagID;
1134    const T1 &Arg1;
1135    const T2 &Arg2;
1136
1137  public:
1138    BoundTypeDiagnoser2(unsigned DiagID, const T1 &Arg1,
1139                                  const T2 &Arg2)
1140      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
1141        Arg2(Arg2) { }
1142
1143    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
1144      if (Suppressed) return;
1145      S.Diag(Loc, DiagID) << getPrintable(Arg1) << getPrintable(Arg2) << T;
1146    }
1147
1148    virtual ~BoundTypeDiagnoser2() { }
1149  };
1150
1151  template<typename T1, typename T2, typename T3>
1152  class BoundTypeDiagnoser3 : public TypeDiagnoser {
1153    unsigned DiagID;
1154    const T1 &Arg1;
1155    const T2 &Arg2;
1156    const T3 &Arg3;
1157
1158  public:
1159    BoundTypeDiagnoser3(unsigned DiagID, const T1 &Arg1,
1160                                  const T2 &Arg2, const T3 &Arg3)
1161    : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
1162      Arg2(Arg2), Arg3(Arg3) { }
1163
1164    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
1165      if (Suppressed) return;
1166      S.Diag(Loc, DiagID)
1167        << getPrintable(Arg1) << getPrintable(Arg2) << getPrintable(Arg3) << T;
1168    }
1169
1170    virtual ~BoundTypeDiagnoser3() { }
1171  };
1172
1173  bool RequireCompleteType(SourceLocation Loc, QualType T,
1174                           TypeDiagnoser &Diagnoser);
1175  bool RequireCompleteType(SourceLocation Loc, QualType T,
1176                           unsigned DiagID);
1177
1178  template<typename T1>
1179  bool RequireCompleteType(SourceLocation Loc, QualType T,
1180                           unsigned DiagID, const T1 &Arg1) {
1181    BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1182    return RequireCompleteType(Loc, T, Diagnoser);
1183  }
1184
1185  template<typename T1, typename T2>
1186  bool RequireCompleteType(SourceLocation Loc, QualType T,
1187                           unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1188    BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1189    return RequireCompleteType(Loc, T, Diagnoser);
1190  }
1191
1192  template<typename T1, typename T2, typename T3>
1193  bool RequireCompleteType(SourceLocation Loc, QualType T,
1194                           unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1195                           const T3 &Arg3) {
1196    BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1197                                                        Arg3);
1198    return RequireCompleteType(Loc, T, Diagnoser);
1199  }
1200
1201  bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1202  bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1203
1204  template<typename T1>
1205  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1) {
1206    BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1207    return RequireCompleteExprType(E, Diagnoser);
1208  }
1209
1210  template<typename T1, typename T2>
1211  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1212                               const T2 &Arg2) {
1213    BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1214    return RequireCompleteExprType(E, Diagnoser);
1215  }
1216
1217  template<typename T1, typename T2, typename T3>
1218  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1219                               const T2 &Arg2, const T3 &Arg3) {
1220    BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1221                                                        Arg3);
1222    return RequireCompleteExprType(E, Diagnoser);
1223  }
1224
1225  bool RequireLiteralType(SourceLocation Loc, QualType T,
1226                          TypeDiagnoser &Diagnoser);
1227  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1228
1229  template<typename T1>
1230  bool RequireLiteralType(SourceLocation Loc, QualType T,
1231                          unsigned DiagID, const T1 &Arg1) {
1232    BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1233    return RequireLiteralType(Loc, T, Diagnoser);
1234  }
1235
1236  template<typename T1, typename T2>
1237  bool RequireLiteralType(SourceLocation Loc, QualType T,
1238                          unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1239    BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1240    return RequireLiteralType(Loc, T, Diagnoser);
1241  }
1242
1243  template<typename T1, typename T2, typename T3>
1244  bool RequireLiteralType(SourceLocation Loc, QualType T,
1245                          unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1246                          const T3 &Arg3) {
1247    BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1248                                                        Arg3);
1249    return RequireLiteralType(Loc, T, Diagnoser);
1250  }
1251
1252  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1253                             const CXXScopeSpec &SS, QualType T);
1254
1255  QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1256  QualType BuildDecltypeType(Expr *E, SourceLocation Loc);
1257  QualType BuildUnaryTransformType(QualType BaseType,
1258                                   UnaryTransformType::UTTKind UKind,
1259                                   SourceLocation Loc);
1260
1261  //===--------------------------------------------------------------------===//
1262  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1263  //
1264
1265  /// List of decls defined in a function prototype. This contains EnumConstants
1266  /// that incorrectly end up in translation unit scope because there is no
1267  /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
1268  /// them into the FunctionDecl.
1269  std::vector<NamedDecl*> DeclsInPrototypeScope;
1270  /// Nonzero if we are currently parsing a function declarator. This is a counter
1271  /// as opposed to a boolean so we can deal with nested function declarators
1272  /// such as:
1273  ///     void f(void (*g)(), ...)
1274  unsigned InFunctionDeclarator;
1275
1276  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = 0);
1277
1278  void DiagnoseUseOfUnimplementedSelectors();
1279
1280  bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1281
1282  ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1283                         Scope *S, CXXScopeSpec *SS = 0,
1284                         bool isClassName = false,
1285                         bool HasTrailingDot = false,
1286                         ParsedType ObjectType = ParsedType(),
1287                         bool IsCtorOrDtorName = false,
1288                         bool WantNontrivialTypeSourceInfo = false,
1289                         IdentifierInfo **CorrectedII = 0);
1290  TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1291  bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1292  bool DiagnoseUnknownTypeName(IdentifierInfo *&II,
1293                               SourceLocation IILoc,
1294                               Scope *S,
1295                               CXXScopeSpec *SS,
1296                               ParsedType &SuggestedType);
1297
1298  /// \brief Describes the result of the name lookup and resolution performed
1299  /// by \c ClassifyName().
1300  enum NameClassificationKind {
1301    NC_Unknown,
1302    NC_Error,
1303    NC_Keyword,
1304    NC_Type,
1305    NC_Expression,
1306    NC_NestedNameSpecifier,
1307    NC_TypeTemplate,
1308    NC_FunctionTemplate
1309  };
1310
1311  class NameClassification {
1312    NameClassificationKind Kind;
1313    ExprResult Expr;
1314    TemplateName Template;
1315    ParsedType Type;
1316    const IdentifierInfo *Keyword;
1317
1318    explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1319
1320  public:
1321    NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1322
1323    NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1324
1325    NameClassification(const IdentifierInfo *Keyword)
1326      : Kind(NC_Keyword), Keyword(Keyword) { }
1327
1328    static NameClassification Error() {
1329      return NameClassification(NC_Error);
1330    }
1331
1332    static NameClassification Unknown() {
1333      return NameClassification(NC_Unknown);
1334    }
1335
1336    static NameClassification NestedNameSpecifier() {
1337      return NameClassification(NC_NestedNameSpecifier);
1338    }
1339
1340    static NameClassification TypeTemplate(TemplateName Name) {
1341      NameClassification Result(NC_TypeTemplate);
1342      Result.Template = Name;
1343      return Result;
1344    }
1345
1346    static NameClassification FunctionTemplate(TemplateName Name) {
1347      NameClassification Result(NC_FunctionTemplate);
1348      Result.Template = Name;
1349      return Result;
1350    }
1351
1352    NameClassificationKind getKind() const { return Kind; }
1353
1354    ParsedType getType() const {
1355      assert(Kind == NC_Type);
1356      return Type;
1357    }
1358
1359    ExprResult getExpression() const {
1360      assert(Kind == NC_Expression);
1361      return Expr;
1362    }
1363
1364    TemplateName getTemplateName() const {
1365      assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
1366      return Template;
1367    }
1368
1369    TemplateNameKind getTemplateNameKind() const {
1370      assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
1371      return Kind == NC_TypeTemplate? TNK_Type_template : TNK_Function_template;
1372    }
1373  };
1374
1375  /// \brief Perform name lookup on the given name, classifying it based on
1376  /// the results of name lookup and the following token.
1377  ///
1378  /// This routine is used by the parser to resolve identifiers and help direct
1379  /// parsing. When the identifier cannot be found, this routine will attempt
1380  /// to correct the typo and classify based on the resulting name.
1381  ///
1382  /// \param S The scope in which we're performing name lookup.
1383  ///
1384  /// \param SS The nested-name-specifier that precedes the name.
1385  ///
1386  /// \param Name The identifier. If typo correction finds an alternative name,
1387  /// this pointer parameter will be updated accordingly.
1388  ///
1389  /// \param NameLoc The location of the identifier.
1390  ///
1391  /// \param NextToken The token following the identifier. Used to help
1392  /// disambiguate the name.
1393  ///
1394  /// \param IsAddressOfOperand True if this name is the operand of a unary
1395  ///        address of ('&') expression, assuming it is classified as an
1396  ///        expression.
1397  ///
1398  /// \param CCC The correction callback, if typo correction is desired.
1399  NameClassification ClassifyName(Scope *S,
1400                                  CXXScopeSpec &SS,
1401                                  IdentifierInfo *&Name,
1402                                  SourceLocation NameLoc,
1403                                  const Token &NextToken,
1404                                  bool IsAddressOfOperand,
1405                                  CorrectionCandidateCallback *CCC = 0);
1406
1407  Decl *ActOnDeclarator(Scope *S, Declarator &D);
1408
1409  NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1410                              MultiTemplateParamsArg TemplateParameterLists);
1411  void RegisterLocallyScopedExternCDecl(NamedDecl *ND,
1412                                        const LookupResult &Previous,
1413                                        Scope *S);
1414  bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1415  bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1416                                    DeclarationName Name,
1417                                    SourceLocation Loc);
1418  void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1419  void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1420  void CheckShadow(Scope *S, VarDecl *D);
1421  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1422  void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1423  NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1424                                    TypeSourceInfo *TInfo,
1425                                    LookupResult &Previous);
1426  NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1427                                  LookupResult &Previous, bool &Redeclaration);
1428  NamedDecl* ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1429                                     TypeSourceInfo *TInfo,
1430                                     LookupResult &Previous,
1431                                     MultiTemplateParamsArg TemplateParamLists);
1432  // Returns true if the variable declaration is a redeclaration
1433  bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1434  void CheckVariableDeclarationType(VarDecl *NewVD);
1435  void CheckCompleteVariableDeclaration(VarDecl *var);
1436  void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1437  void ActOnStartFunctionDeclarator();
1438  void ActOnEndFunctionDeclarator();
1439  NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1440                                     TypeSourceInfo *TInfo,
1441                                     LookupResult &Previous,
1442                                     MultiTemplateParamsArg TemplateParamLists,
1443                                     bool &AddToScope);
1444  bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1445  void checkVoidParamDecl(ParmVarDecl *Param);
1446
1447  bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1448  bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1449
1450  void DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1451  // Returns true if the function declaration is a redeclaration
1452  bool CheckFunctionDeclaration(Scope *S,
1453                                FunctionDecl *NewFD, LookupResult &Previous,
1454                                bool IsExplicitSpecialization);
1455  void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1456  Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1457  ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1458                                          SourceLocation Loc,
1459                                          QualType T);
1460  ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1461                              SourceLocation NameLoc, IdentifierInfo *Name,
1462                              QualType T, TypeSourceInfo *TSInfo,
1463                              StorageClass SC);
1464  void ActOnParamDefaultArgument(Decl *param,
1465                                 SourceLocation EqualLoc,
1466                                 Expr *defarg);
1467  void ActOnParamUnparsedDefaultArgument(Decl *param,
1468                                         SourceLocation EqualLoc,
1469                                         SourceLocation ArgLoc);
1470  void ActOnParamDefaultArgumentError(Decl *param);
1471  bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1472                               SourceLocation EqualLoc);
1473
1474  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1475                            bool TypeMayContainAuto);
1476  void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1477  void ActOnInitializerError(Decl *Dcl);
1478  void ActOnCXXForRangeDecl(Decl *D);
1479  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1480  void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1481  void FinalizeDeclaration(Decl *D);
1482  DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1483                                         Decl **Group,
1484                                         unsigned NumDecls);
1485  DeclGroupPtrTy BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
1486                                      bool TypeMayContainAuto = true);
1487
1488  /// Should be called on all declarations that might have attached
1489  /// documentation comments.
1490  void ActOnDocumentableDecl(Decl *D);
1491  void ActOnDocumentableDecls(Decl **Group, unsigned NumDecls);
1492
1493  void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1494                                       SourceLocation LocAfterDecls);
1495  void CheckForFunctionRedefinition(FunctionDecl *FD);
1496  Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
1497  Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
1498  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1499  bool isObjCMethodDecl(Decl *D) {
1500    return D && isa<ObjCMethodDecl>(D);
1501  }
1502
1503  /// \brief Determine whether we can skip parsing the body of a function
1504  /// definition, assuming we don't care about analyzing its body or emitting
1505  /// code for that function.
1506  ///
1507  /// This will be \c false only if we may need the body of the function in
1508  /// order to parse the rest of the program (for instance, if it is
1509  /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1510  bool canSkipFunctionBody(Decl *D);
1511
1512  void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1513  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1514  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1515  Decl *ActOnSkippedFunctionBody(Decl *Decl);
1516
1517  /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1518  /// attribute for which parsing is delayed.
1519  void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1520
1521  /// \brief Diagnose any unused parameters in the given sequence of
1522  /// ParmVarDecl pointers.
1523  void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
1524                                ParmVarDecl * const *End);
1525
1526  /// \brief Diagnose whether the size of parameters or return value of a
1527  /// function or obj-c method definition is pass-by-value and larger than a
1528  /// specified threshold.
1529  void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
1530                                              ParmVarDecl * const *End,
1531                                              QualType ReturnTy,
1532                                              NamedDecl *D);
1533
1534  void DiagnoseInvalidJumps(Stmt *Body);
1535  Decl *ActOnFileScopeAsmDecl(Expr *expr,
1536                              SourceLocation AsmLoc,
1537                              SourceLocation RParenLoc);
1538
1539  /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1540  Decl *ActOnEmptyDeclaration(Scope *S,
1541                              AttributeList *AttrList,
1542                              SourceLocation SemiLoc);
1543
1544  /// \brief The parser has processed a module import declaration.
1545  ///
1546  /// \param AtLoc The location of the '@' symbol, if any.
1547  ///
1548  /// \param ImportLoc The location of the 'import' keyword.
1549  ///
1550  /// \param Path The module access path.
1551  DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1552                               ModuleIdPath Path);
1553
1554  /// \brief Create an implicit import of the given module at the given
1555  /// source location.
1556  ///
1557  /// This routine is typically used for error recovery, when the entity found
1558  /// by name lookup is actually hidden within a module that we know about but
1559  /// the user has forgotten to import.
1560  void createImplicitModuleImport(SourceLocation Loc, Module *Mod);
1561
1562  /// \brief Retrieve a suitable printing policy.
1563  PrintingPolicy getPrintingPolicy() const {
1564    return getPrintingPolicy(Context, PP);
1565  }
1566
1567  /// \brief Retrieve a suitable printing policy.
1568  static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1569                                          const Preprocessor &PP);
1570
1571  /// Scope actions.
1572  void ActOnPopScope(SourceLocation Loc, Scope *S);
1573  void ActOnTranslationUnitScope(Scope *S);
1574
1575  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1576                                   DeclSpec &DS);
1577  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1578                                   DeclSpec &DS,
1579                                   MultiTemplateParamsArg TemplateParams,
1580                                   bool IsExplicitInstantiation = false);
1581
1582  Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1583                                    AccessSpecifier AS,
1584                                    RecordDecl *Record);
1585
1586  Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1587                                       RecordDecl *Record);
1588
1589  bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1590                                    TagTypeKind NewTag, bool isDefinition,
1591                                    SourceLocation NewTagLoc,
1592                                    const IdentifierInfo &Name);
1593
1594  enum TagUseKind {
1595    TUK_Reference,   // Reference to a tag:  'struct foo *X;'
1596    TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
1597    TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
1598    TUK_Friend       // Friend declaration:  'friend struct foo;'
1599  };
1600
1601  Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1602                 SourceLocation KWLoc, CXXScopeSpec &SS,
1603                 IdentifierInfo *Name, SourceLocation NameLoc,
1604                 AttributeList *Attr, AccessSpecifier AS,
1605                 SourceLocation ModulePrivateLoc,
1606                 MultiTemplateParamsArg TemplateParameterLists,
1607                 bool &OwnedDecl, bool &IsDependent,
1608                 SourceLocation ScopedEnumKWLoc,
1609                 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType);
1610
1611  Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1612                                unsigned TagSpec, SourceLocation TagLoc,
1613                                CXXScopeSpec &SS,
1614                                IdentifierInfo *Name, SourceLocation NameLoc,
1615                                AttributeList *Attr,
1616                                MultiTemplateParamsArg TempParamLists);
1617
1618  TypeResult ActOnDependentTag(Scope *S,
1619                               unsigned TagSpec,
1620                               TagUseKind TUK,
1621                               const CXXScopeSpec &SS,
1622                               IdentifierInfo *Name,
1623                               SourceLocation TagLoc,
1624                               SourceLocation NameLoc);
1625
1626  void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1627                 IdentifierInfo *ClassName,
1628                 SmallVectorImpl<Decl *> &Decls);
1629  Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1630                   Declarator &D, Expr *BitfieldWidth);
1631
1632  FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1633                         Declarator &D, Expr *BitfieldWidth,
1634                         InClassInitStyle InitStyle,
1635                         AccessSpecifier AS);
1636  MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
1637                                   SourceLocation DeclStart,
1638                                   Declarator &D, Expr *BitfieldWidth,
1639                                   InClassInitStyle InitStyle,
1640                                   AccessSpecifier AS,
1641                                   AttributeList *MSPropertyAttr);
1642
1643  FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1644                            TypeSourceInfo *TInfo,
1645                            RecordDecl *Record, SourceLocation Loc,
1646                            bool Mutable, Expr *BitfieldWidth,
1647                            InClassInitStyle InitStyle,
1648                            SourceLocation TSSL,
1649                            AccessSpecifier AS, NamedDecl *PrevDecl,
1650                            Declarator *D = 0);
1651
1652  bool CheckNontrivialField(FieldDecl *FD);
1653  void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
1654  bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
1655                              bool Diagnose = false);
1656  CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
1657  void ActOnLastBitfield(SourceLocation DeclStart,
1658                         SmallVectorImpl<Decl *> &AllIvarDecls);
1659  Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
1660                  Declarator &D, Expr *BitfieldWidth,
1661                  tok::ObjCKeywordKind visibility);
1662
1663  // This is used for both record definitions and ObjC interface declarations.
1664  void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
1665                   ArrayRef<Decl *> Fields,
1666                   SourceLocation LBrac, SourceLocation RBrac,
1667                   AttributeList *AttrList);
1668
1669  /// ActOnTagStartDefinition - Invoked when we have entered the
1670  /// scope of a tag's definition (e.g., for an enumeration, class,
1671  /// struct, or union).
1672  void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
1673
1674  Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
1675
1676  /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
1677  /// C++ record definition's base-specifiers clause and are starting its
1678  /// member declarations.
1679  void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
1680                                       SourceLocation FinalLoc,
1681                                       SourceLocation LBraceLoc);
1682
1683  /// ActOnTagFinishDefinition - Invoked once we have finished parsing
1684  /// the definition of a tag (enumeration, class, struct, or union).
1685  void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
1686                                SourceLocation RBraceLoc);
1687
1688  void ActOnObjCContainerFinishDefinition();
1689
1690  /// \brief Invoked when we must temporarily exit the objective-c container
1691  /// scope for parsing/looking-up C constructs.
1692  ///
1693  /// Must be followed by a call to \see ActOnObjCReenterContainerContext
1694  void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
1695  void ActOnObjCReenterContainerContext(DeclContext *DC);
1696
1697  /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
1698  /// error parsing the definition of a tag.
1699  void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
1700
1701  EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
1702                                      EnumConstantDecl *LastEnumConst,
1703                                      SourceLocation IdLoc,
1704                                      IdentifierInfo *Id,
1705                                      Expr *val);
1706  bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
1707  bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
1708                              QualType EnumUnderlyingTy, const EnumDecl *Prev);
1709
1710  Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
1711                          SourceLocation IdLoc, IdentifierInfo *Id,
1712                          AttributeList *Attrs,
1713                          SourceLocation EqualLoc, Expr *Val);
1714  void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
1715                     SourceLocation RBraceLoc, Decl *EnumDecl,
1716                     ArrayRef<Decl *> Elements,
1717                     Scope *S, AttributeList *Attr);
1718
1719  DeclContext *getContainingDC(DeclContext *DC);
1720
1721  /// Set the current declaration context until it gets popped.
1722  void PushDeclContext(Scope *S, DeclContext *DC);
1723  void PopDeclContext();
1724
1725  /// EnterDeclaratorContext - Used when we must lookup names in the context
1726  /// of a declarator's nested name specifier.
1727  void EnterDeclaratorContext(Scope *S, DeclContext *DC);
1728  void ExitDeclaratorContext(Scope *S);
1729
1730  /// Push the parameters of D, which must be a function, into scope.
1731  void ActOnReenterFunctionContext(Scope* S, Decl* D);
1732  void ActOnExitFunctionContext();
1733
1734  DeclContext *getFunctionLevelDeclContext();
1735
1736  /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1737  /// to the function decl for the function being parsed.  If we're currently
1738  /// in a 'block', this returns the containing context.
1739  FunctionDecl *getCurFunctionDecl();
1740
1741  /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1742  /// the method decl for the method being parsed.  If we're currently
1743  /// in a 'block', this returns the containing context.
1744  ObjCMethodDecl *getCurMethodDecl();
1745
1746  /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1747  /// or C function we're in, otherwise return null.  If we're currently
1748  /// in a 'block', this returns the containing context.
1749  NamedDecl *getCurFunctionOrMethodDecl();
1750
1751  /// Add this decl to the scope shadowed decl chains.
1752  void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
1753
1754  /// \brief Make the given externally-produced declaration visible at the
1755  /// top level scope.
1756  ///
1757  /// \param D The externally-produced declaration to push.
1758  ///
1759  /// \param Name The name of the externally-produced declaration.
1760  void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1761
1762  /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
1763  /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
1764  /// true if 'D' belongs to the given declaration context.
1765  ///
1766  /// \param ExplicitInstantiationOrSpecialization When true, we are checking
1767  /// whether the declaration is in scope for the purposes of explicit template
1768  /// instantiation or specialization. The default is false.
1769  bool isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S = 0,
1770                     bool ExplicitInstantiationOrSpecialization = false);
1771
1772  /// Finds the scope corresponding to the given decl context, if it
1773  /// happens to be an enclosing scope.  Otherwise return NULL.
1774  static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
1775
1776  /// Subroutines of ActOnDeclarator().
1777  TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1778                                TypeSourceInfo *TInfo);
1779  bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
1780
1781  /// Attribute merging methods. Return true if a new attribute was added.
1782  AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1783                                          IdentifierInfo *Platform,
1784                                          VersionTuple Introduced,
1785                                          VersionTuple Deprecated,
1786                                          VersionTuple Obsoleted,
1787                                          bool IsUnavailable,
1788                                          StringRef Message,
1789                                          bool Override,
1790                                          unsigned AttrSpellingListIndex);
1791  TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
1792                                       TypeVisibilityAttr::VisibilityType Vis,
1793                                              unsigned AttrSpellingListIndex);
1794  VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
1795                                      VisibilityAttr::VisibilityType Vis,
1796                                      unsigned AttrSpellingListIndex);
1797  DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
1798                                    unsigned AttrSpellingListIndex);
1799  DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
1800                                    unsigned AttrSpellingListIndex);
1801  FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range, StringRef Format,
1802                              int FormatIdx, int FirstArg,
1803                              unsigned AttrSpellingListIndex);
1804  SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
1805                                unsigned AttrSpellingListIndex);
1806
1807  /// \brief Describes the kind of merge to perform for availability
1808  /// attributes (including "deprecated", "unavailable", and "availability").
1809  enum AvailabilityMergeKind {
1810    /// \brief Don't merge availability attributes at all.
1811    AMK_None,
1812    /// \brief Merge availability attributes for a redeclaration, which requires
1813    /// an exact match.
1814    AMK_Redeclaration,
1815    /// \brief Merge availability attributes for an override, which requires
1816    /// an exact match or a weakening of constraints.
1817    AMK_Override
1818  };
1819
1820  void mergeDeclAttributes(NamedDecl *New, Decl *Old,
1821                           AvailabilityMergeKind AMK = AMK_Redeclaration);
1822  void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
1823  bool MergeFunctionDecl(FunctionDecl *New, Decl *Old, Scope *S);
1824  bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
1825                                    Scope *S);
1826  void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
1827  void MergeVarDecl(VarDecl *New, LookupResult &OldDecls,
1828                    bool OldDeclsWereHidden);
1829  void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool OldIsHidden);
1830  void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
1831  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
1832
1833  // AssignmentAction - This is used by all the assignment diagnostic functions
1834  // to represent what is actually causing the operation
1835  enum AssignmentAction {
1836    AA_Assigning,
1837    AA_Passing,
1838    AA_Returning,
1839    AA_Converting,
1840    AA_Initializing,
1841    AA_Sending,
1842    AA_Casting
1843  };
1844
1845  /// C++ Overloading.
1846  enum OverloadKind {
1847    /// This is a legitimate overload: the existing declarations are
1848    /// functions or function templates with different signatures.
1849    Ovl_Overload,
1850
1851    /// This is not an overload because the signature exactly matches
1852    /// an existing declaration.
1853    Ovl_Match,
1854
1855    /// This is not an overload because the lookup results contain a
1856    /// non-function.
1857    Ovl_NonFunction
1858  };
1859  OverloadKind CheckOverload(Scope *S,
1860                             FunctionDecl *New,
1861                             const LookupResult &OldDecls,
1862                             NamedDecl *&OldDecl,
1863                             bool IsForUsingDecl);
1864  bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
1865
1866  /// \brief Checks availability of the function depending on the current
1867  /// function context.Inside an unavailable function,unavailability is ignored.
1868  ///
1869  /// \returns true if \p FD is unavailable and current context is inside
1870  /// an available function, false otherwise.
1871  bool isFunctionConsideredUnavailable(FunctionDecl *FD);
1872
1873  ImplicitConversionSequence
1874  TryImplicitConversion(Expr *From, QualType ToType,
1875                        bool SuppressUserConversions,
1876                        bool AllowExplicit,
1877                        bool InOverloadResolution,
1878                        bool CStyle,
1879                        bool AllowObjCWritebackConversion);
1880
1881  bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
1882  bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
1883  bool IsComplexPromotion(QualType FromType, QualType ToType);
1884  bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1885                           bool InOverloadResolution,
1886                           QualType& ConvertedType, bool &IncompatibleObjC);
1887  bool isObjCPointerConversion(QualType FromType, QualType ToType,
1888                               QualType& ConvertedType, bool &IncompatibleObjC);
1889  bool isObjCWritebackConversion(QualType FromType, QualType ToType,
1890                                 QualType &ConvertedType);
1891  bool IsBlockPointerConversion(QualType FromType, QualType ToType,
1892                                QualType& ConvertedType);
1893  bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1894                                const FunctionProtoType *NewType,
1895                                unsigned *ArgPos = 0);
1896  void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
1897                                  QualType FromType, QualType ToType);
1898
1899  CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
1900  bool CheckPointerConversion(Expr *From, QualType ToType,
1901                              CastKind &Kind,
1902                              CXXCastPath& BasePath,
1903                              bool IgnoreBaseAccess);
1904  bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
1905                                 bool InOverloadResolution,
1906                                 QualType &ConvertedType);
1907  bool CheckMemberPointerConversion(Expr *From, QualType ToType,
1908                                    CastKind &Kind,
1909                                    CXXCastPath &BasePath,
1910                                    bool IgnoreBaseAccess);
1911  bool IsQualificationConversion(QualType FromType, QualType ToType,
1912                                 bool CStyle, bool &ObjCLifetimeConversion);
1913  bool IsNoReturnConversion(QualType FromType, QualType ToType,
1914                            QualType &ResultTy);
1915  bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
1916  bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
1917
1918  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1919                                             const VarDecl *NRVOCandidate,
1920                                             QualType ResultType,
1921                                             Expr *Value,
1922                                             bool AllowNRVO = true);
1923
1924  bool CanPerformCopyInitialization(const InitializedEntity &Entity,
1925                                    ExprResult Init);
1926  ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
1927                                       SourceLocation EqualLoc,
1928                                       ExprResult Init,
1929                                       bool TopLevelOfInitList = false,
1930                                       bool AllowExplicit = false);
1931  ExprResult PerformObjectArgumentInitialization(Expr *From,
1932                                                 NestedNameSpecifier *Qualifier,
1933                                                 NamedDecl *FoundDecl,
1934                                                 CXXMethodDecl *Method);
1935
1936  ExprResult PerformContextuallyConvertToBool(Expr *From);
1937  ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
1938
1939  /// Contexts in which a converted constant expression is required.
1940  enum CCEKind {
1941    CCEK_CaseValue,  ///< Expression in a case label.
1942    CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
1943    CCEK_TemplateArg ///< Value of a non-type template parameter.
1944  };
1945  ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
1946                                              llvm::APSInt &Value, CCEKind CCE);
1947
1948  /// \brief Abstract base class used to perform a contextual implicit
1949  /// conversion from an expression to any type passing a filter.
1950  class ContextualImplicitConverter {
1951  public:
1952    bool Suppress;
1953    bool SuppressConversion;
1954
1955    ContextualImplicitConverter(bool Suppress = false,
1956                                bool SuppressConversion = false)
1957        : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
1958
1959    /// \brief Determine whether the specified type is a valid destination type
1960    /// for this conversion.
1961    virtual bool match(QualType T) = 0;
1962
1963    /// \brief Emits a diagnostic complaining that the expression does not have
1964    /// integral or enumeration type.
1965    virtual SemaDiagnosticBuilder
1966    diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
1967
1968    /// \brief Emits a diagnostic when the expression has incomplete class type.
1969    virtual SemaDiagnosticBuilder
1970    diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
1971
1972    /// \brief Emits a diagnostic when the only matching conversion function
1973    /// is explicit.
1974    virtual SemaDiagnosticBuilder diagnoseExplicitConv(
1975        Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
1976
1977    /// \brief Emits a note for the explicit conversion function.
1978    virtual SemaDiagnosticBuilder
1979    noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
1980
1981    /// \brief Emits a diagnostic when there are multiple possible conversion
1982    /// functions.
1983    virtual SemaDiagnosticBuilder
1984    diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
1985
1986    /// \brief Emits a note for one of the candidate conversions.
1987    virtual SemaDiagnosticBuilder
1988    noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
1989
1990    /// \brief Emits a diagnostic when we picked a conversion function
1991    /// (for cases when we are not allowed to pick a conversion function).
1992    virtual SemaDiagnosticBuilder diagnoseConversion(
1993        Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
1994
1995    virtual ~ContextualImplicitConverter() {}
1996  };
1997
1998  class ICEConvertDiagnoser : public ContextualImplicitConverter {
1999    bool AllowScopedEnumerations;
2000
2001  public:
2002    ICEConvertDiagnoser(bool AllowScopedEnumerations,
2003                        bool Suppress, bool SuppressConversion)
2004        : ContextualImplicitConverter(Suppress, SuppressConversion),
2005          AllowScopedEnumerations(AllowScopedEnumerations) {}
2006
2007    /// Match an integral or (possibly scoped) enumeration type.
2008    bool match(QualType T);
2009
2010    SemaDiagnosticBuilder
2011    diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) {
2012      return diagnoseNotInt(S, Loc, T);
2013    }
2014
2015    /// \brief Emits a diagnostic complaining that the expression does not have
2016    /// integral or enumeration type.
2017    virtual SemaDiagnosticBuilder
2018    diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2019  };
2020
2021  /// Perform a contextual implicit conversion.
2022  ExprResult PerformContextualImplicitConversion(
2023      SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2024
2025
2026  enum ObjCSubscriptKind {
2027    OS_Array,
2028    OS_Dictionary,
2029    OS_Error
2030  };
2031  ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2032
2033  // Note that LK_String is intentionally after the other literals, as
2034  // this is used for diagnostics logic.
2035  enum ObjCLiteralKind {
2036    LK_Array,
2037    LK_Dictionary,
2038    LK_Numeric,
2039    LK_Boxed,
2040    LK_String,
2041    LK_Block,
2042    LK_None
2043  };
2044  ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2045
2046  ExprResult PerformObjectMemberConversion(Expr *From,
2047                                           NestedNameSpecifier *Qualifier,
2048                                           NamedDecl *FoundDecl,
2049                                           NamedDecl *Member);
2050
2051  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2052  // TODO: make this is a typesafe union.
2053  typedef llvm::SmallPtrSet<DeclContext   *, 16> AssociatedNamespaceSet;
2054  typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
2055
2056  void AddOverloadCandidate(FunctionDecl *Function,
2057                            DeclAccessPair FoundDecl,
2058                            ArrayRef<Expr *> Args,
2059                            OverloadCandidateSet& CandidateSet,
2060                            bool SuppressUserConversions = false,
2061                            bool PartialOverloading = false,
2062                            bool AllowExplicit = false);
2063  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2064                             ArrayRef<Expr *> Args,
2065                             OverloadCandidateSet& CandidateSet,
2066                             bool SuppressUserConversions = false,
2067                            TemplateArgumentListInfo *ExplicitTemplateArgs = 0);
2068  void AddMethodCandidate(DeclAccessPair FoundDecl,
2069                          QualType ObjectType,
2070                          Expr::Classification ObjectClassification,
2071                          ArrayRef<Expr *> Args,
2072                          OverloadCandidateSet& CandidateSet,
2073                          bool SuppressUserConversion = false);
2074  void AddMethodCandidate(CXXMethodDecl *Method,
2075                          DeclAccessPair FoundDecl,
2076                          CXXRecordDecl *ActingContext, QualType ObjectType,
2077                          Expr::Classification ObjectClassification,
2078                          ArrayRef<Expr *> Args,
2079                          OverloadCandidateSet& CandidateSet,
2080                          bool SuppressUserConversions = false);
2081  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2082                                  DeclAccessPair FoundDecl,
2083                                  CXXRecordDecl *ActingContext,
2084                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
2085                                  QualType ObjectType,
2086                                  Expr::Classification ObjectClassification,
2087                                  ArrayRef<Expr *> Args,
2088                                  OverloadCandidateSet& CandidateSet,
2089                                  bool SuppressUserConversions = false);
2090  void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2091                                    DeclAccessPair FoundDecl,
2092                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
2093                                    ArrayRef<Expr *> Args,
2094                                    OverloadCandidateSet& CandidateSet,
2095                                    bool SuppressUserConversions = false);
2096  void AddConversionCandidate(CXXConversionDecl *Conversion,
2097                              DeclAccessPair FoundDecl,
2098                              CXXRecordDecl *ActingContext,
2099                              Expr *From, QualType ToType,
2100                              OverloadCandidateSet& CandidateSet);
2101  void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2102                                      DeclAccessPair FoundDecl,
2103                                      CXXRecordDecl *ActingContext,
2104                                      Expr *From, QualType ToType,
2105                                      OverloadCandidateSet &CandidateSet);
2106  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2107                             DeclAccessPair FoundDecl,
2108                             CXXRecordDecl *ActingContext,
2109                             const FunctionProtoType *Proto,
2110                             Expr *Object, ArrayRef<Expr *> Args,
2111                             OverloadCandidateSet& CandidateSet);
2112  void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2113                                   SourceLocation OpLoc, ArrayRef<Expr *> Args,
2114                                   OverloadCandidateSet& CandidateSet,
2115                                   SourceRange OpRange = SourceRange());
2116  void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2117                           ArrayRef<Expr *> Args,
2118                           OverloadCandidateSet& CandidateSet,
2119                           bool IsAssignmentOperator = false,
2120                           unsigned NumContextualBoolArguments = 0);
2121  void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2122                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
2123                                    OverloadCandidateSet& CandidateSet);
2124  void AddArgumentDependentLookupCandidates(DeclarationName Name,
2125                                            bool Operator, SourceLocation Loc,
2126                                            ArrayRef<Expr *> Args,
2127                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2128                                            OverloadCandidateSet& CandidateSet,
2129                                            bool PartialOverloading = false);
2130
2131  // Emit as a 'note' the specific overload candidate
2132  void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType());
2133
2134  // Emit as a series of 'note's all template and non-templates
2135  // identified by the expression Expr
2136  void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType());
2137
2138  // [PossiblyAFunctionType]  -->   [Return]
2139  // NonFunctionType --> NonFunctionType
2140  // R (A) --> R(A)
2141  // R (*)(A) --> R (A)
2142  // R (&)(A) --> R (A)
2143  // R (S::*)(A) --> R (A)
2144  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2145
2146  FunctionDecl *
2147  ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2148                                     QualType TargetType,
2149                                     bool Complain,
2150                                     DeclAccessPair &Found,
2151                                     bool *pHadMultipleCandidates = 0);
2152
2153  FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2154                                                   bool Complain = false,
2155                                                   DeclAccessPair* Found = 0);
2156
2157  bool ResolveAndFixSingleFunctionTemplateSpecialization(
2158                      ExprResult &SrcExpr,
2159                      bool DoFunctionPointerConverion = false,
2160                      bool Complain = false,
2161                      const SourceRange& OpRangeForComplaining = SourceRange(),
2162                      QualType DestTypeForComplaining = QualType(),
2163                      unsigned DiagIDForComplaining = 0);
2164
2165
2166  Expr *FixOverloadedFunctionReference(Expr *E,
2167                                       DeclAccessPair FoundDecl,
2168                                       FunctionDecl *Fn);
2169  ExprResult FixOverloadedFunctionReference(ExprResult,
2170                                            DeclAccessPair FoundDecl,
2171                                            FunctionDecl *Fn);
2172
2173  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2174                                   ArrayRef<Expr *> Args,
2175                                   OverloadCandidateSet &CandidateSet,
2176                                   bool PartialOverloading = false);
2177
2178  // An enum used to represent the different possible results of building a
2179  // range-based for loop.
2180  enum ForRangeStatus {
2181    FRS_Success,
2182    FRS_NoViableFunction,
2183    FRS_DiagnosticIssued
2184  };
2185
2186  // An enum to represent whether something is dealing with a call to begin()
2187  // or a call to end() in a range-based for loop.
2188  enum BeginEndFunction {
2189    BEF_begin,
2190    BEF_end
2191  };
2192
2193  ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
2194                                           SourceLocation RangeLoc,
2195                                           VarDecl *Decl,
2196                                           BeginEndFunction BEF,
2197                                           const DeclarationNameInfo &NameInfo,
2198                                           LookupResult &MemberLookup,
2199                                           OverloadCandidateSet *CandidateSet,
2200                                           Expr *Range, ExprResult *CallExpr);
2201
2202  ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2203                                     UnresolvedLookupExpr *ULE,
2204                                     SourceLocation LParenLoc,
2205                                     MultiExprArg Args,
2206                                     SourceLocation RParenLoc,
2207                                     Expr *ExecConfig,
2208                                     bool AllowTypoCorrection=true);
2209
2210  bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2211                              MultiExprArg Args, SourceLocation RParenLoc,
2212                              OverloadCandidateSet *CandidateSet,
2213                              ExprResult *Result);
2214
2215  ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2216                                     unsigned Opc,
2217                                     const UnresolvedSetImpl &Fns,
2218                                     Expr *input);
2219
2220  ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2221                                   unsigned Opc,
2222                                   const UnresolvedSetImpl &Fns,
2223                                   Expr *LHS, Expr *RHS);
2224
2225  ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2226                                                SourceLocation RLoc,
2227                                                Expr *Base,Expr *Idx);
2228
2229  ExprResult
2230  BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2231                            SourceLocation LParenLoc,
2232                            MultiExprArg Args,
2233                            SourceLocation RParenLoc);
2234  ExprResult
2235  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2236                               MultiExprArg Args,
2237                               SourceLocation RParenLoc);
2238
2239  ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2240                                      SourceLocation OpLoc);
2241
2242  /// CheckCallReturnType - Checks that a call expression's return type is
2243  /// complete. Returns true on failure. The location passed in is the location
2244  /// that best represents the call.
2245  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2246                           CallExpr *CE, FunctionDecl *FD);
2247
2248  /// Helpers for dealing with blocks and functions.
2249  bool CheckParmsForFunctionDef(ParmVarDecl **Param, ParmVarDecl **ParamEnd,
2250                                bool CheckParameterNames);
2251  void CheckCXXDefaultArguments(FunctionDecl *FD);
2252  void CheckExtraCXXDefaultArguments(Declarator &D);
2253  Scope *getNonFieldDeclScope(Scope *S);
2254
2255  /// \name Name lookup
2256  ///
2257  /// These routines provide name lookup that is used during semantic
2258  /// analysis to resolve the various kinds of names (identifiers,
2259  /// overloaded operator names, constructor names, etc.) into zero or
2260  /// more declarations within a particular scope. The major entry
2261  /// points are LookupName, which performs unqualified name lookup,
2262  /// and LookupQualifiedName, which performs qualified name lookup.
2263  ///
2264  /// All name lookup is performed based on some specific criteria,
2265  /// which specify what names will be visible to name lookup and how
2266  /// far name lookup should work. These criteria are important both
2267  /// for capturing language semantics (certain lookups will ignore
2268  /// certain names, for example) and for performance, since name
2269  /// lookup is often a bottleneck in the compilation of C++. Name
2270  /// lookup criteria is specified via the LookupCriteria enumeration.
2271  ///
2272  /// The results of name lookup can vary based on the kind of name
2273  /// lookup performed, the current language, and the translation
2274  /// unit. In C, for example, name lookup will either return nothing
2275  /// (no entity found) or a single declaration. In C++, name lookup
2276  /// can additionally refer to a set of overloaded functions or
2277  /// result in an ambiguity. All of the possible results of name
2278  /// lookup are captured by the LookupResult class, which provides
2279  /// the ability to distinguish among them.
2280  //@{
2281
2282  /// @brief Describes the kind of name lookup to perform.
2283  enum LookupNameKind {
2284    /// Ordinary name lookup, which finds ordinary names (functions,
2285    /// variables, typedefs, etc.) in C and most kinds of names
2286    /// (functions, variables, members, types, etc.) in C++.
2287    LookupOrdinaryName = 0,
2288    /// Tag name lookup, which finds the names of enums, classes,
2289    /// structs, and unions.
2290    LookupTagName,
2291    /// Label name lookup.
2292    LookupLabel,
2293    /// Member name lookup, which finds the names of
2294    /// class/struct/union members.
2295    LookupMemberName,
2296    /// Look up of an operator name (e.g., operator+) for use with
2297    /// operator overloading. This lookup is similar to ordinary name
2298    /// lookup, but will ignore any declarations that are class members.
2299    LookupOperatorName,
2300    /// Look up of a name that precedes the '::' scope resolution
2301    /// operator in C++. This lookup completely ignores operator, object,
2302    /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2303    LookupNestedNameSpecifierName,
2304    /// Look up a namespace name within a C++ using directive or
2305    /// namespace alias definition, ignoring non-namespace names (C++
2306    /// [basic.lookup.udir]p1).
2307    LookupNamespaceName,
2308    /// Look up all declarations in a scope with the given name,
2309    /// including resolved using declarations.  This is appropriate
2310    /// for checking redeclarations for a using declaration.
2311    LookupUsingDeclName,
2312    /// Look up an ordinary name that is going to be redeclared as a
2313    /// name with linkage. This lookup ignores any declarations that
2314    /// are outside of the current scope unless they have linkage. See
2315    /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2316    LookupRedeclarationWithLinkage,
2317    /// Look up the name of an Objective-C protocol.
2318    LookupObjCProtocolName,
2319    /// Look up implicit 'self' parameter of an objective-c method.
2320    LookupObjCImplicitSelfParam,
2321    /// \brief Look up any declaration with any name.
2322    LookupAnyName
2323  };
2324
2325  /// \brief Specifies whether (or how) name lookup is being performed for a
2326  /// redeclaration (vs. a reference).
2327  enum RedeclarationKind {
2328    /// \brief The lookup is a reference to this name that is not for the
2329    /// purpose of redeclaring the name.
2330    NotForRedeclaration = 0,
2331    /// \brief The lookup results will be used for redeclaration of a name,
2332    /// if an entity by that name already exists.
2333    ForRedeclaration
2334  };
2335
2336  /// \brief The possible outcomes of name lookup for a literal operator.
2337  enum LiteralOperatorLookupResult {
2338    /// \brief The lookup resulted in an error.
2339    LOLR_Error,
2340    /// \brief The lookup found a single 'cooked' literal operator, which
2341    /// expects a normal literal to be built and passed to it.
2342    LOLR_Cooked,
2343    /// \brief The lookup found a single 'raw' literal operator, which expects
2344    /// a string literal containing the spelling of the literal token.
2345    LOLR_Raw,
2346    /// \brief The lookup found an overload set of literal operator templates,
2347    /// which expect the characters of the spelling of the literal token to be
2348    /// passed as a non-type template argument pack.
2349    LOLR_Template
2350  };
2351
2352  SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2353                                                   CXXSpecialMember SM,
2354                                                   bool ConstArg,
2355                                                   bool VolatileArg,
2356                                                   bool RValueThis,
2357                                                   bool ConstThis,
2358                                                   bool VolatileThis);
2359
2360private:
2361  bool CppLookupName(LookupResult &R, Scope *S);
2362
2363  // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2364  //
2365  // The boolean value will be true to indicate that the namespace was loaded
2366  // from an AST/PCH file, or false otherwise.
2367  llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2368
2369  /// \brief Whether we have already loaded known namespaces from an extenal
2370  /// source.
2371  bool LoadedExternalKnownNamespaces;
2372
2373public:
2374  /// \brief Look up a name, looking for a single declaration.  Return
2375  /// null if the results were absent, ambiguous, or overloaded.
2376  ///
2377  /// It is preferable to use the elaborated form and explicitly handle
2378  /// ambiguity and overloaded.
2379  NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2380                              SourceLocation Loc,
2381                              LookupNameKind NameKind,
2382                              RedeclarationKind Redecl
2383                                = NotForRedeclaration);
2384  bool LookupName(LookupResult &R, Scope *S,
2385                  bool AllowBuiltinCreation = false);
2386  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2387                           bool InUnqualifiedLookup = false);
2388  bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2389                        bool AllowBuiltinCreation = false,
2390                        bool EnteringContext = false);
2391  ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2392                                   RedeclarationKind Redecl
2393                                     = NotForRedeclaration);
2394
2395  void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2396                                    QualType T1, QualType T2,
2397                                    UnresolvedSetImpl &Functions);
2398
2399  LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2400                                 SourceLocation GnuLabelLoc = SourceLocation());
2401
2402  DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2403  CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2404  CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2405                                               unsigned Quals);
2406  CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2407                                         bool RValueThis, unsigned ThisQuals);
2408  CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2409                                              unsigned Quals);
2410  CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2411                                        bool RValueThis, unsigned ThisQuals);
2412  CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2413
2414  LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2415                                                    ArrayRef<QualType> ArgTys,
2416                                                    bool AllowRawAndTemplate);
2417  bool isKnownName(StringRef name);
2418
2419  void ArgumentDependentLookup(DeclarationName Name, bool Operator,
2420                               SourceLocation Loc,
2421                               ArrayRef<Expr *> Args,
2422                               ADLResult &Functions);
2423
2424  void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2425                          VisibleDeclConsumer &Consumer,
2426                          bool IncludeGlobalScope = true);
2427  void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2428                          VisibleDeclConsumer &Consumer,
2429                          bool IncludeGlobalScope = true);
2430
2431  TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2432                             Sema::LookupNameKind LookupKind,
2433                             Scope *S, CXXScopeSpec *SS,
2434                             CorrectionCandidateCallback &CCC,
2435                             DeclContext *MemberContext = 0,
2436                             bool EnteringContext = false,
2437                             const ObjCObjectPointerType *OPT = 0);
2438
2439  void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2440                                          ArrayRef<Expr *> Args,
2441                                   AssociatedNamespaceSet &AssociatedNamespaces,
2442                                   AssociatedClassSet &AssociatedClasses);
2443
2444  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2445                            bool ConsiderLinkage,
2446                            bool ExplicitInstantiationOrSpecialization);
2447
2448  bool DiagnoseAmbiguousLookup(LookupResult &Result);
2449  //@}
2450
2451  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2452                                          SourceLocation IdLoc,
2453                                          bool TypoCorrection = false);
2454  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2455                                 Scope *S, bool ForRedeclaration,
2456                                 SourceLocation Loc);
2457  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2458                                      Scope *S);
2459  void AddKnownFunctionAttributes(FunctionDecl *FD);
2460
2461  // More parsing and symbol table subroutines.
2462
2463  void ProcessPragmaWeak(Scope *S, Decl *D);
2464  // Decl attributes - this routine is the top level dispatcher.
2465  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
2466                             bool NonInheritable = true,
2467                             bool Inheritable = true);
2468  void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
2469                                bool NonInheritable = true,
2470                                bool Inheritable = true,
2471                                bool IncludeCXX11Attributes = true);
2472  bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
2473                                      const AttributeList *AttrList);
2474
2475  void checkUnusedDeclAttributes(Declarator &D);
2476
2477  bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
2478  bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
2479                            const FunctionDecl *FD = 0);
2480  bool CheckNoReturnAttr(const AttributeList &attr);
2481  void CheckAlignasUnderalignment(Decl *D);
2482
2483  /// \brief Stmt attributes - this routine is the top level dispatcher.
2484  StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
2485                                   SourceRange Range);
2486
2487  void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
2488                           bool &IncompleteImpl, unsigned DiagID);
2489  void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
2490                                   ObjCMethodDecl *MethodDecl,
2491                                   bool IsProtocolMethodDecl);
2492
2493  void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2494                                   ObjCMethodDecl *Overridden,
2495                                   bool IsProtocolMethodDecl);
2496
2497  /// WarnExactTypedMethods - This routine issues a warning if method
2498  /// implementation declaration matches exactly that of its declaration.
2499  void WarnExactTypedMethods(ObjCMethodDecl *Method,
2500                             ObjCMethodDecl *MethodDecl,
2501                             bool IsProtocolMethodDecl);
2502
2503  bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl,
2504                          ObjCInterfaceDecl *IDecl);
2505
2506  typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
2507  typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
2508
2509  /// CheckProtocolMethodDefs - This routine checks unimplemented
2510  /// methods declared in protocol, and those referenced by it.
2511  void CheckProtocolMethodDefs(SourceLocation ImpLoc,
2512                               ObjCProtocolDecl *PDecl,
2513                               bool& IncompleteImpl,
2514                               const SelectorSet &InsMap,
2515                               const SelectorSet &ClsMap,
2516                               ObjCContainerDecl *CDecl);
2517
2518  /// CheckImplementationIvars - This routine checks if the instance variables
2519  /// listed in the implelementation match those listed in the interface.
2520  void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2521                                ObjCIvarDecl **Fields, unsigned nIvars,
2522                                SourceLocation Loc);
2523
2524  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
2525  /// remains unimplemented in the class or category \@implementation.
2526  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2527                                 ObjCContainerDecl* IDecl,
2528                                 bool IncompleteImpl = false);
2529
2530  /// DiagnoseUnimplementedProperties - This routine warns on those properties
2531  /// which must be implemented by this implementation.
2532  void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
2533                                       ObjCContainerDecl *CDecl);
2534
2535  /// DefaultSynthesizeProperties - This routine default synthesizes all
2536  /// properties which must be synthesized in the class's \@implementation.
2537  void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
2538                                    ObjCInterfaceDecl *IDecl);
2539  void DefaultSynthesizeProperties(Scope *S, Decl *D);
2540
2541  /// CollectImmediateProperties - This routine collects all properties in
2542  /// the class and its conforming protocols; but not those it its super class.
2543  void CollectImmediateProperties(ObjCContainerDecl *CDecl,
2544            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
2545            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap);
2546
2547  /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
2548  /// an ivar synthesized for 'Method' and 'Method' is a property accessor
2549  /// declared in class 'IFace'.
2550  bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
2551                                      ObjCMethodDecl *Method, ObjCIvarDecl *IV);
2552
2553  /// Called by ActOnProperty to handle \@property declarations in
2554  /// class extensions.
2555  ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
2556                      SourceLocation AtLoc,
2557                      SourceLocation LParenLoc,
2558                      FieldDeclarator &FD,
2559                      Selector GetterSel,
2560                      Selector SetterSel,
2561                      const bool isAssign,
2562                      const bool isReadWrite,
2563                      const unsigned Attributes,
2564                      const unsigned AttributesAsWritten,
2565                      bool *isOverridingProperty,
2566                      TypeSourceInfo *T,
2567                      tok::ObjCKeywordKind MethodImplKind);
2568
2569  /// Called by ActOnProperty and HandlePropertyInClassExtension to
2570  /// handle creating the ObjcPropertyDecl for a category or \@interface.
2571  ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
2572                                       ObjCContainerDecl *CDecl,
2573                                       SourceLocation AtLoc,
2574                                       SourceLocation LParenLoc,
2575                                       FieldDeclarator &FD,
2576                                       Selector GetterSel,
2577                                       Selector SetterSel,
2578                                       const bool isAssign,
2579                                       const bool isReadWrite,
2580                                       const unsigned Attributes,
2581                                       const unsigned AttributesAsWritten,
2582                                       TypeSourceInfo *T,
2583                                       tok::ObjCKeywordKind MethodImplKind,
2584                                       DeclContext *lexicalDC = 0);
2585
2586  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
2587  /// warning) when atomic property has one but not the other user-declared
2588  /// setter or getter.
2589  void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
2590                                       ObjCContainerDecl* IDecl);
2591
2592  void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
2593
2594  void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
2595
2596  enum MethodMatchStrategy {
2597    MMS_loose,
2598    MMS_strict
2599  };
2600
2601  /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
2602  /// true, or false, accordingly.
2603  bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
2604                                  const ObjCMethodDecl *PrevMethod,
2605                                  MethodMatchStrategy strategy = MMS_strict);
2606
2607  /// MatchAllMethodDeclarations - Check methods declaraed in interface or
2608  /// or protocol against those declared in their implementations.
2609  void MatchAllMethodDeclarations(const SelectorSet &InsMap,
2610                                  const SelectorSet &ClsMap,
2611                                  SelectorSet &InsMapSeen,
2612                                  SelectorSet &ClsMapSeen,
2613                                  ObjCImplDecl* IMPDecl,
2614                                  ObjCContainerDecl* IDecl,
2615                                  bool &IncompleteImpl,
2616                                  bool ImmediateClass,
2617                                  bool WarnCategoryMethodImpl=false);
2618
2619  /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2620  /// category matches with those implemented in its primary class and
2621  /// warns each time an exact match is found.
2622  void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
2623
2624  /// \brief Add the given method to the list of globally-known methods.
2625  void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
2626
2627private:
2628  /// AddMethodToGlobalPool - Add an instance or factory method to the global
2629  /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
2630  void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
2631
2632  /// LookupMethodInGlobalPool - Returns the instance or factory method and
2633  /// optionally warns if there are multiple signatures.
2634  ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2635                                           bool receiverIdOrClass,
2636                                           bool warn, bool instance);
2637
2638public:
2639  /// AddInstanceMethodToGlobalPool - All instance methods in a translation
2640  /// unit are added to a global pool. This allows us to efficiently associate
2641  /// a selector with a method declaraation for purposes of typechecking
2642  /// messages sent to "id" (where the class of the object is unknown).
2643  void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2644    AddMethodToGlobalPool(Method, impl, /*instance*/true);
2645  }
2646
2647  /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
2648  void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2649    AddMethodToGlobalPool(Method, impl, /*instance*/false);
2650  }
2651
2652  /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
2653  /// pool.
2654  void AddAnyMethodToGlobalPool(Decl *D);
2655
2656  /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
2657  /// there are multiple signatures.
2658  ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
2659                                                   bool receiverIdOrClass=false,
2660                                                   bool warn=true) {
2661    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2662                                    warn, /*instance*/true);
2663  }
2664
2665  /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
2666  /// there are multiple signatures.
2667  ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
2668                                                  bool receiverIdOrClass=false,
2669                                                  bool warn=true) {
2670    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2671                                    warn, /*instance*/false);
2672  }
2673
2674  const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel);
2675
2676  /// DiagnoseMismatchedMethodsInGlobalPool - This routine goes through list of
2677  /// methods in global pool and issues diagnostic on identical selectors which
2678  /// have mismathched types.
2679  void DiagnoseMismatchedMethodsInGlobalPool();
2680
2681  /// LookupImplementedMethodInGlobalPool - Returns the method which has an
2682  /// implementation.
2683  ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
2684
2685  /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2686  /// initialization.
2687  void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2688                                  SmallVectorImpl<ObjCIvarDecl*> &Ivars);
2689
2690  //===--------------------------------------------------------------------===//
2691  // Statement Parsing Callbacks: SemaStmt.cpp.
2692public:
2693  class FullExprArg {
2694  public:
2695    FullExprArg(Sema &actions) : E(0) { }
2696
2697    // FIXME: The const_cast here is ugly. RValue references would make this
2698    // much nicer (or we could duplicate a bunch of the move semantics
2699    // emulation code from Ownership.h).
2700    FullExprArg(const FullExprArg& Other) : E(Other.E) {}
2701
2702    ExprResult release() {
2703      return E;
2704    }
2705
2706    Expr *get() const { return E; }
2707
2708    Expr *operator->() {
2709      return E;
2710    }
2711
2712  private:
2713    // FIXME: No need to make the entire Sema class a friend when it's just
2714    // Sema::MakeFullExpr that needs access to the constructor below.
2715    friend class Sema;
2716
2717    explicit FullExprArg(Expr *expr) : E(expr) {}
2718
2719    Expr *E;
2720  };
2721
2722  FullExprArg MakeFullExpr(Expr *Arg) {
2723    return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
2724  }
2725  FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
2726    return FullExprArg(ActOnFinishFullExpr(Arg, CC).release());
2727  }
2728  FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
2729    ExprResult FE =
2730      ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
2731                          /*DiscardedValue*/ true);
2732    return FullExprArg(FE.release());
2733  }
2734
2735  StmtResult ActOnExprStmt(ExprResult Arg);
2736  StmtResult ActOnExprStmtError();
2737
2738  StmtResult ActOnNullStmt(SourceLocation SemiLoc,
2739                           bool HasLeadingEmptyMacro = false);
2740
2741  void ActOnStartOfCompoundStmt();
2742  void ActOnFinishOfCompoundStmt();
2743  StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
2744                                       MultiStmtArg Elts,
2745                                       bool isStmtExpr);
2746
2747  /// \brief A RAII object to enter scope of a compound statement.
2748  class CompoundScopeRAII {
2749  public:
2750    CompoundScopeRAII(Sema &S): S(S) {
2751      S.ActOnStartOfCompoundStmt();
2752    }
2753
2754    ~CompoundScopeRAII() {
2755      S.ActOnFinishOfCompoundStmt();
2756    }
2757
2758  private:
2759    Sema &S;
2760  };
2761
2762  StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
2763                                   SourceLocation StartLoc,
2764                                   SourceLocation EndLoc);
2765  void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
2766  StmtResult ActOnForEachLValueExpr(Expr *E);
2767  StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
2768                                   SourceLocation DotDotDotLoc, Expr *RHSVal,
2769                                   SourceLocation ColonLoc);
2770  void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
2771
2772  StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
2773                                      SourceLocation ColonLoc,
2774                                      Stmt *SubStmt, Scope *CurScope);
2775  StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
2776                            SourceLocation ColonLoc, Stmt *SubStmt);
2777
2778  StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
2779                                 ArrayRef<const Attr*> Attrs,
2780                                 Stmt *SubStmt);
2781
2782  StmtResult ActOnIfStmt(SourceLocation IfLoc,
2783                         FullExprArg CondVal, Decl *CondVar,
2784                         Stmt *ThenVal,
2785                         SourceLocation ElseLoc, Stmt *ElseVal);
2786  StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
2787                                            Expr *Cond,
2788                                            Decl *CondVar);
2789  StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
2790                                           Stmt *Switch, Stmt *Body);
2791  StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
2792                            FullExprArg Cond,
2793                            Decl *CondVar, Stmt *Body);
2794  StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
2795                                 SourceLocation WhileLoc,
2796                                 SourceLocation CondLParen, Expr *Cond,
2797                                 SourceLocation CondRParen);
2798
2799  StmtResult ActOnForStmt(SourceLocation ForLoc,
2800                          SourceLocation LParenLoc,
2801                          Stmt *First, FullExprArg Second,
2802                          Decl *SecondVar,
2803                          FullExprArg Third,
2804                          SourceLocation RParenLoc,
2805                          Stmt *Body);
2806  ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
2807                                           Expr *collection);
2808  StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
2809                                        Stmt *First, Expr *collection,
2810                                        SourceLocation RParenLoc);
2811  StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
2812
2813  enum BuildForRangeKind {
2814    /// Initial building of a for-range statement.
2815    BFRK_Build,
2816    /// Instantiation or recovery rebuild of a for-range statement. Don't
2817    /// attempt any typo-correction.
2818    BFRK_Rebuild,
2819    /// Determining whether a for-range statement could be built. Avoid any
2820    /// unnecessary or irreversible actions.
2821    BFRK_Check
2822  };
2823
2824  StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
2825                                  SourceLocation ColonLoc, Expr *Collection,
2826                                  SourceLocation RParenLoc,
2827                                  BuildForRangeKind Kind);
2828  StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
2829                                  SourceLocation ColonLoc,
2830                                  Stmt *RangeDecl, Stmt *BeginEndDecl,
2831                                  Expr *Cond, Expr *Inc,
2832                                  Stmt *LoopVarDecl,
2833                                  SourceLocation RParenLoc,
2834                                  BuildForRangeKind Kind);
2835  StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
2836
2837  StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
2838                           SourceLocation LabelLoc,
2839                           LabelDecl *TheDecl);
2840  StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
2841                                   SourceLocation StarLoc,
2842                                   Expr *DestExp);
2843  StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
2844  StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
2845
2846  void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
2847                                CapturedRegionKind Kind, unsigned NumParams);
2848  StmtResult ActOnCapturedRegionEnd(Stmt *S);
2849  void ActOnCapturedRegionError();
2850  RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
2851                                           SourceLocation Loc,
2852                                           unsigned NumParams);
2853  const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
2854                                         bool AllowFunctionParameters);
2855
2856  StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2857  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2858
2859  StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2860                             bool IsVolatile, unsigned NumOutputs,
2861                             unsigned NumInputs, IdentifierInfo **Names,
2862                             MultiExprArg Constraints, MultiExprArg Exprs,
2863                             Expr *AsmString, MultiExprArg Clobbers,
2864                             SourceLocation RParenLoc);
2865
2866  ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
2867                                       SourceLocation TemplateKWLoc,
2868                                       UnqualifiedId &Id,
2869                                       InlineAsmIdentifierInfo &Info,
2870                                       bool IsUnevaluatedContext);
2871  bool LookupInlineAsmField(StringRef Base, StringRef Member,
2872                            unsigned &Offset, SourceLocation AsmLoc);
2873  StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
2874                            ArrayRef<Token> AsmToks,
2875                            StringRef AsmString,
2876                            unsigned NumOutputs, unsigned NumInputs,
2877                            ArrayRef<StringRef> Constraints,
2878                            ArrayRef<StringRef> Clobbers,
2879                            ArrayRef<Expr*> Exprs,
2880                            SourceLocation EndLoc);
2881
2882  VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
2883                                  SourceLocation StartLoc,
2884                                  SourceLocation IdLoc, IdentifierInfo *Id,
2885                                  bool Invalid = false);
2886
2887  Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
2888
2889  StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
2890                                  Decl *Parm, Stmt *Body);
2891
2892  StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
2893
2894  StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2895                                MultiStmtArg Catch, Stmt *Finally);
2896
2897  StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
2898  StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2899                                  Scope *CurScope);
2900  ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
2901                                            Expr *operand);
2902  StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
2903                                         Expr *SynchExpr,
2904                                         Stmt *SynchBody);
2905
2906  StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
2907
2908  VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
2909                                     SourceLocation StartLoc,
2910                                     SourceLocation IdLoc,
2911                                     IdentifierInfo *Id);
2912
2913  Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
2914
2915  StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
2916                                Decl *ExDecl, Stmt *HandlerBlock);
2917  StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
2918                              MultiStmtArg Handlers);
2919
2920  StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
2921                              SourceLocation TryLoc,
2922                              Stmt *TryBlock,
2923                              Stmt *Handler);
2924
2925  StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
2926                                 Expr *FilterExpr,
2927                                 Stmt *Block);
2928
2929  StmtResult ActOnSEHFinallyBlock(SourceLocation Loc,
2930                                  Stmt *Block);
2931
2932  void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
2933
2934  bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
2935
2936  /// \brief If it's a file scoped decl that must warn if not used, keep track
2937  /// of it.
2938  void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
2939
2940  /// DiagnoseUnusedExprResult - If the statement passed in is an expression
2941  /// whose result is unused, warn.
2942  void DiagnoseUnusedExprResult(const Stmt *S);
2943  void DiagnoseUnusedDecl(const NamedDecl *ND);
2944
2945  /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2946  /// statement as a \p Body, and it is located on the same line.
2947  ///
2948  /// This helps prevent bugs due to typos, such as:
2949  ///     if (condition);
2950  ///       do_stuff();
2951  void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
2952                             const Stmt *Body,
2953                             unsigned DiagID);
2954
2955  /// Warn if a for/while loop statement \p S, which is followed by
2956  /// \p PossibleBody, has a suspicious null statement as a body.
2957  void DiagnoseEmptyLoopBody(const Stmt *S,
2958                             const Stmt *PossibleBody);
2959
2960  ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
2961    return DelayedDiagnostics.push(pool);
2962  }
2963  void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
2964
2965  typedef ProcessingContextState ParsingClassState;
2966  ParsingClassState PushParsingClass() {
2967    return DelayedDiagnostics.pushUndelayed();
2968  }
2969  void PopParsingClass(ParsingClassState state) {
2970    DelayedDiagnostics.popUndelayed(state);
2971  }
2972
2973  void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
2974
2975  void EmitDeprecationWarning(NamedDecl *D, StringRef Message,
2976                              SourceLocation Loc,
2977                              const ObjCInterfaceDecl *UnknownObjCClass,
2978                              const ObjCPropertyDecl  *ObjCProperty);
2979
2980  void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2981
2982  bool makeUnavailableInSystemHeader(SourceLocation loc,
2983                                     StringRef message);
2984
2985  //===--------------------------------------------------------------------===//
2986  // Expression Parsing Callbacks: SemaExpr.cpp.
2987
2988  bool CanUseDecl(NamedDecl *D);
2989  bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
2990                         const ObjCInterfaceDecl *UnknownObjCClass=0);
2991  void NoteDeletedFunction(FunctionDecl *FD);
2992  std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
2993  bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
2994                                        ObjCMethodDecl *Getter,
2995                                        SourceLocation Loc);
2996  void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
2997                             ArrayRef<Expr *> Args);
2998
2999  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3000                                       Decl *LambdaContextDecl = 0,
3001                                       bool IsDecltype = false);
3002  enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3003  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3004                                       ReuseLambdaContextDecl_t,
3005                                       bool IsDecltype = false);
3006  void PopExpressionEvaluationContext();
3007
3008  void DiscardCleanupsInEvaluationContext();
3009
3010  ExprResult TransformToPotentiallyEvaluated(Expr *E);
3011  ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3012
3013  ExprResult ActOnConstantExpression(ExprResult Res);
3014
3015  // Functions for marking a declaration referenced.  These functions also
3016  // contain the relevant logic for marking if a reference to a function or
3017  // variable is an odr-use (in the C++11 sense).  There are separate variants
3018  // for expressions referring to a decl; these exist because odr-use marking
3019  // needs to be delayed for some constant variables when we build one of the
3020  // named expressions.
3021  void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
3022  void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func);
3023  void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3024  void MarkDeclRefReferenced(DeclRefExpr *E);
3025  void MarkMemberReferenced(MemberExpr *E);
3026
3027  void UpdateMarkingForLValueToRValue(Expr *E);
3028  void CleanupVarDeclMarking();
3029
3030  enum TryCaptureKind {
3031    TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3032  };
3033
3034  /// \brief Try to capture the given variable.
3035  ///
3036  /// \param Var The variable to capture.
3037  ///
3038  /// \param Loc The location at which the capture occurs.
3039  ///
3040  /// \param Kind The kind of capture, which may be implicit (for either a
3041  /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3042  ///
3043  /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3044  /// an explicit lambda capture.
3045  ///
3046  /// \param BuildAndDiagnose Whether we are actually supposed to add the
3047  /// captures or diagnose errors. If false, this routine merely check whether
3048  /// the capture can occur without performing the capture itself or complaining
3049  /// if the variable cannot be captured.
3050  ///
3051  /// \param CaptureType Will be set to the type of the field used to capture
3052  /// this variable in the innermost block or lambda. Only valid when the
3053  /// variable can be captured.
3054  ///
3055  /// \param DeclRefType Will be set to the type of a reference to the capture
3056  /// from within the current scope. Only valid when the variable can be
3057  /// captured.
3058  ///
3059  /// \returns true if an error occurred (i.e., the variable cannot be
3060  /// captured) and false if the capture succeeded.
3061  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3062                          SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3063                          QualType &CaptureType,
3064                          QualType &DeclRefType);
3065
3066  /// \brief Try to capture the given variable.
3067  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3068                          TryCaptureKind Kind = TryCapture_Implicit,
3069                          SourceLocation EllipsisLoc = SourceLocation());
3070
3071  /// \brief Given a variable, determine the type that a reference to that
3072  /// variable will have in the given scope.
3073  QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3074
3075  void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3076  void MarkDeclarationsReferencedInExpr(Expr *E,
3077                                        bool SkipLocalVariables = false);
3078
3079  /// \brief Try to recover by turning the given expression into a
3080  /// call.  Returns true if recovery was attempted or an error was
3081  /// emitted; this may also leave the ExprResult invalid.
3082  bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3083                            bool ForceComplain = false,
3084                            bool (*IsPlausibleResult)(QualType) = 0);
3085
3086  /// \brief Figure out if an expression could be turned into a call.
3087  bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy,
3088                      UnresolvedSetImpl &NonTemplateOverloads);
3089
3090  /// \brief Conditionally issue a diagnostic based on the current
3091  /// evaluation context.
3092  ///
3093  /// \param Statement If Statement is non-null, delay reporting the
3094  /// diagnostic until the function body is parsed, and then do a basic
3095  /// reachability analysis to determine if the statement is reachable.
3096  /// If it is unreachable, the diagnostic will not be emitted.
3097  bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3098                           const PartialDiagnostic &PD);
3099
3100  // Primary Expressions.
3101  SourceRange getExprRange(Expr *E) const;
3102
3103  ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
3104                               SourceLocation TemplateKWLoc,
3105                               UnqualifiedId &Id,
3106                               bool HasTrailingLParen, bool IsAddressOfOperand,
3107                               CorrectionCandidateCallback *CCC = 0,
3108                               bool IsInlineAsmIdentifier = false);
3109
3110  void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3111                              TemplateArgumentListInfo &Buffer,
3112                              DeclarationNameInfo &NameInfo,
3113                              const TemplateArgumentListInfo *&TemplateArgs);
3114
3115  bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3116                           CorrectionCandidateCallback &CCC,
3117                           TemplateArgumentListInfo *ExplicitTemplateArgs = 0,
3118                           ArrayRef<Expr *> Args = None);
3119
3120  ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3121                                IdentifierInfo *II,
3122                                bool AllowBuiltinCreation=false);
3123
3124  ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3125                                        SourceLocation TemplateKWLoc,
3126                                        const DeclarationNameInfo &NameInfo,
3127                                        bool isAddressOfOperand,
3128                                const TemplateArgumentListInfo *TemplateArgs);
3129
3130  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3131                              ExprValueKind VK,
3132                              SourceLocation Loc,
3133                              const CXXScopeSpec *SS = 0);
3134  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3135                              ExprValueKind VK,
3136                              const DeclarationNameInfo &NameInfo,
3137                              const CXXScopeSpec *SS = 0,
3138                              NamedDecl *FoundD = 0);
3139  ExprResult
3140  BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
3141                                           SourceLocation nameLoc,
3142                                           IndirectFieldDecl *indirectField,
3143                                           Expr *baseObjectExpr = 0,
3144                                      SourceLocation opLoc = SourceLocation());
3145  ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3146                                             SourceLocation TemplateKWLoc,
3147                                             LookupResult &R,
3148                                const TemplateArgumentListInfo *TemplateArgs);
3149  ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3150                                     SourceLocation TemplateKWLoc,
3151                                     LookupResult &R,
3152                                const TemplateArgumentListInfo *TemplateArgs,
3153                                     bool IsDefiniteInstance);
3154  bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3155                                  const LookupResult &R,
3156                                  bool HasTrailingLParen);
3157
3158  ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3159                                         const DeclarationNameInfo &NameInfo,
3160                                               bool IsAddressOfOperand);
3161  ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3162                                       SourceLocation TemplateKWLoc,
3163                                const DeclarationNameInfo &NameInfo,
3164                                const TemplateArgumentListInfo *TemplateArgs);
3165
3166  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3167                                      LookupResult &R,
3168                                      bool NeedsADL);
3169  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3170                                      const DeclarationNameInfo &NameInfo,
3171                                      NamedDecl *D, NamedDecl *FoundD = 0);
3172
3173  ExprResult BuildLiteralOperatorCall(LookupResult &R,
3174                                      DeclarationNameInfo &SuffixInfo,
3175                                      ArrayRef<Expr*> Args,
3176                                      SourceLocation LitEndLoc,
3177                            TemplateArgumentListInfo *ExplicitTemplateArgs = 0);
3178
3179  ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3180  ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3181  ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = 0);
3182  ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = 0);
3183  ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3184  ExprResult ActOnParenListExpr(SourceLocation L,
3185                                SourceLocation R,
3186                                MultiExprArg Val);
3187
3188  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3189  /// fragments (e.g. "foo" "bar" L"baz").
3190  ExprResult ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
3191                                Scope *UDLScope = 0);
3192
3193  ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3194                                       SourceLocation DefaultLoc,
3195                                       SourceLocation RParenLoc,
3196                                       Expr *ControllingExpr,
3197                                       ArrayRef<ParsedType> ArgTypes,
3198                                       ArrayRef<Expr *> ArgExprs);
3199  ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3200                                        SourceLocation DefaultLoc,
3201                                        SourceLocation RParenLoc,
3202                                        Expr *ControllingExpr,
3203                                        ArrayRef<TypeSourceInfo *> Types,
3204                                        ArrayRef<Expr *> Exprs);
3205
3206  // Binary/Unary Operators.  'Tok' is the token for the operator.
3207  ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3208                                  Expr *InputExpr);
3209  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3210                          UnaryOperatorKind Opc, Expr *Input);
3211  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3212                          tok::TokenKind Op, Expr *Input);
3213
3214  ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3215                                            SourceLocation OpLoc,
3216                                            UnaryExprOrTypeTrait ExprKind,
3217                                            SourceRange R);
3218  ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3219                                            UnaryExprOrTypeTrait ExprKind);
3220  ExprResult
3221    ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3222                                  UnaryExprOrTypeTrait ExprKind,
3223                                  bool IsType, void *TyOrEx,
3224                                  const SourceRange &ArgRange);
3225
3226  ExprResult CheckPlaceholderExpr(Expr *E);
3227  bool CheckVecStepExpr(Expr *E);
3228
3229  bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3230  bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3231                                        SourceRange ExprRange,
3232                                        UnaryExprOrTypeTrait ExprKind);
3233  ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3234                                          SourceLocation OpLoc,
3235                                          IdentifierInfo &Name,
3236                                          SourceLocation NameLoc,
3237                                          SourceLocation RParenLoc);
3238  ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3239                                 tok::TokenKind Kind, Expr *Input);
3240
3241  ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3242                                     Expr *Idx, SourceLocation RLoc);
3243  ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3244                                             Expr *Idx, SourceLocation RLoc);
3245
3246  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3247                                      SourceLocation OpLoc, bool IsArrow,
3248                                      CXXScopeSpec &SS,
3249                                      SourceLocation TemplateKWLoc,
3250                                      NamedDecl *FirstQualifierInScope,
3251                                const DeclarationNameInfo &NameInfo,
3252                                const TemplateArgumentListInfo *TemplateArgs);
3253
3254  // This struct is for use by ActOnMemberAccess to allow
3255  // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3256  // changing the access operator from a '.' to a '->' (to see if that is the
3257  // change needed to fix an error about an unknown member, e.g. when the class
3258  // defines a custom operator->).
3259  struct ActOnMemberAccessExtraArgs {
3260    Scope *S;
3261    UnqualifiedId &Id;
3262    Decl *ObjCImpDecl;
3263    bool HasTrailingLParen;
3264  };
3265
3266  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3267                                      SourceLocation OpLoc, bool IsArrow,
3268                                      const CXXScopeSpec &SS,
3269                                      SourceLocation TemplateKWLoc,
3270                                      NamedDecl *FirstQualifierInScope,
3271                                      LookupResult &R,
3272                                 const TemplateArgumentListInfo *TemplateArgs,
3273                                      bool SuppressQualifierCheck = false,
3274                                     ActOnMemberAccessExtraArgs *ExtraArgs = 0);
3275
3276  ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3277  ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
3278                              bool &IsArrow, SourceLocation OpLoc,
3279                              CXXScopeSpec &SS,
3280                              Decl *ObjCImpDecl,
3281                              bool HasTemplateArgs);
3282
3283  bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3284                                     const CXXScopeSpec &SS,
3285                                     const LookupResult &R);
3286
3287  ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3288                                      bool IsArrow, SourceLocation OpLoc,
3289                                      const CXXScopeSpec &SS,
3290                                      SourceLocation TemplateKWLoc,
3291                                      NamedDecl *FirstQualifierInScope,
3292                               const DeclarationNameInfo &NameInfo,
3293                               const TemplateArgumentListInfo *TemplateArgs);
3294
3295  ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3296                                   SourceLocation OpLoc,
3297                                   tok::TokenKind OpKind,
3298                                   CXXScopeSpec &SS,
3299                                   SourceLocation TemplateKWLoc,
3300                                   UnqualifiedId &Member,
3301                                   Decl *ObjCImpDecl,
3302                                   bool HasTrailingLParen);
3303
3304  void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3305  bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3306                               FunctionDecl *FDecl,
3307                               const FunctionProtoType *Proto,
3308                               ArrayRef<Expr *> Args,
3309                               SourceLocation RParenLoc,
3310                               bool ExecConfig = false);
3311  void CheckStaticArrayArgument(SourceLocation CallLoc,
3312                                ParmVarDecl *Param,
3313                                const Expr *ArgExpr);
3314
3315  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3316  /// This provides the location of the left/right parens and a list of comma
3317  /// locations.
3318  ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3319                           MultiExprArg ArgExprs, SourceLocation RParenLoc,
3320                           Expr *ExecConfig = 0, bool IsExecConfig = false);
3321  ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3322                                   SourceLocation LParenLoc,
3323                                   ArrayRef<Expr *> Arg,
3324                                   SourceLocation RParenLoc,
3325                                   Expr *Config = 0,
3326                                   bool IsExecConfig = false);
3327
3328  ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3329                                     MultiExprArg ExecConfig,
3330                                     SourceLocation GGGLoc);
3331
3332  ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
3333                           Declarator &D, ParsedType &Ty,
3334                           SourceLocation RParenLoc, Expr *CastExpr);
3335  ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
3336                                 TypeSourceInfo *Ty,
3337                                 SourceLocation RParenLoc,
3338                                 Expr *Op);
3339  CastKind PrepareScalarCast(ExprResult &src, QualType destType);
3340
3341  /// \brief Build an altivec or OpenCL literal.
3342  ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
3343                                SourceLocation RParenLoc, Expr *E,
3344                                TypeSourceInfo *TInfo);
3345
3346  ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
3347
3348  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
3349                                  ParsedType Ty,
3350                                  SourceLocation RParenLoc,
3351                                  Expr *InitExpr);
3352
3353  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
3354                                      TypeSourceInfo *TInfo,
3355                                      SourceLocation RParenLoc,
3356                                      Expr *LiteralExpr);
3357
3358  ExprResult ActOnInitList(SourceLocation LBraceLoc,
3359                           MultiExprArg InitArgList,
3360                           SourceLocation RBraceLoc);
3361
3362  ExprResult ActOnDesignatedInitializer(Designation &Desig,
3363                                        SourceLocation Loc,
3364                                        bool GNUSyntax,
3365                                        ExprResult Init);
3366
3367  ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
3368                        tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
3369  ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
3370                        BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
3371  ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
3372                                Expr *LHSExpr, Expr *RHSExpr);
3373
3374  /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
3375  /// in the case of a the GNU conditional expr extension.
3376  ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
3377                                SourceLocation ColonLoc,
3378                                Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
3379
3380  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3381  ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
3382                            LabelDecl *TheDecl);
3383
3384  void ActOnStartStmtExpr();
3385  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
3386                           SourceLocation RPLoc); // "({..})"
3387  void ActOnStmtExprError();
3388
3389  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
3390  struct OffsetOfComponent {
3391    SourceLocation LocStart, LocEnd;
3392    bool isBrackets;  // true if [expr], false if .ident
3393    union {
3394      IdentifierInfo *IdentInfo;
3395      Expr *E;
3396    } U;
3397  };
3398
3399  /// __builtin_offsetof(type, a.b[123][456].c)
3400  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
3401                                  TypeSourceInfo *TInfo,
3402                                  OffsetOfComponent *CompPtr,
3403                                  unsigned NumComponents,
3404                                  SourceLocation RParenLoc);
3405  ExprResult ActOnBuiltinOffsetOf(Scope *S,
3406                                  SourceLocation BuiltinLoc,
3407                                  SourceLocation TypeLoc,
3408                                  ParsedType ParsedArgTy,
3409                                  OffsetOfComponent *CompPtr,
3410                                  unsigned NumComponents,
3411                                  SourceLocation RParenLoc);
3412
3413  // __builtin_choose_expr(constExpr, expr1, expr2)
3414  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
3415                             Expr *CondExpr, Expr *LHSExpr,
3416                             Expr *RHSExpr, SourceLocation RPLoc);
3417
3418  // __builtin_va_arg(expr, type)
3419  ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
3420                        SourceLocation RPLoc);
3421  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
3422                            TypeSourceInfo *TInfo, SourceLocation RPLoc);
3423
3424  // __null
3425  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
3426
3427  bool CheckCaseExpression(Expr *E);
3428
3429  /// \brief Describes the result of an "if-exists" condition check.
3430  enum IfExistsResult {
3431    /// \brief The symbol exists.
3432    IER_Exists,
3433
3434    /// \brief The symbol does not exist.
3435    IER_DoesNotExist,
3436
3437    /// \brief The name is a dependent name, so the results will differ
3438    /// from one instantiation to the next.
3439    IER_Dependent,
3440
3441    /// \brief An error occurred.
3442    IER_Error
3443  };
3444
3445  IfExistsResult
3446  CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
3447                               const DeclarationNameInfo &TargetNameInfo);
3448
3449  IfExistsResult
3450  CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
3451                               bool IsIfExists, CXXScopeSpec &SS,
3452                               UnqualifiedId &Name);
3453
3454  StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3455                                        bool IsIfExists,
3456                                        NestedNameSpecifierLoc QualifierLoc,
3457                                        DeclarationNameInfo NameInfo,
3458                                        Stmt *Nested);
3459  StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3460                                        bool IsIfExists,
3461                                        CXXScopeSpec &SS, UnqualifiedId &Name,
3462                                        Stmt *Nested);
3463
3464  //===------------------------- "Block" Extension ------------------------===//
3465
3466  /// ActOnBlockStart - This callback is invoked when a block literal is
3467  /// started.
3468  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
3469
3470  /// ActOnBlockArguments - This callback allows processing of block arguments.
3471  /// If there are no arguments, this is still invoked.
3472  void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
3473                           Scope *CurScope);
3474
3475  /// ActOnBlockError - If there is an error parsing a block, this callback
3476  /// is invoked to pop the information about the block from the action impl.
3477  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
3478
3479  /// ActOnBlockStmtExpr - This is called when the body of a block statement
3480  /// literal was successfully completed.  ^(int x){...}
3481  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
3482                                Scope *CurScope);
3483
3484  //===---------------------------- OpenCL Features -----------------------===//
3485
3486  /// __builtin_astype(...)
3487  ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3488                             SourceLocation BuiltinLoc,
3489                             SourceLocation RParenLoc);
3490
3491  //===---------------------------- C++ Features --------------------------===//
3492
3493  // Act on C++ namespaces
3494  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
3495                               SourceLocation NamespaceLoc,
3496                               SourceLocation IdentLoc,
3497                               IdentifierInfo *Ident,
3498                               SourceLocation LBrace,
3499                               AttributeList *AttrList);
3500  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
3501
3502  NamespaceDecl *getStdNamespace() const;
3503  NamespaceDecl *getOrCreateStdNamespace();
3504
3505  CXXRecordDecl *getStdBadAlloc() const;
3506
3507  /// \brief Tests whether Ty is an instance of std::initializer_list and, if
3508  /// it is and Element is not NULL, assigns the element type to Element.
3509  bool isStdInitializerList(QualType Ty, QualType *Element);
3510
3511  /// \brief Looks for the std::initializer_list template and instantiates it
3512  /// with Element, or emits an error if it's not found.
3513  ///
3514  /// \returns The instantiated template, or null on error.
3515  QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
3516
3517  /// \brief Determine whether Ctor is an initializer-list constructor, as
3518  /// defined in [dcl.init.list]p2.
3519  bool isInitListConstructor(const CXXConstructorDecl *Ctor);
3520
3521  Decl *ActOnUsingDirective(Scope *CurScope,
3522                            SourceLocation UsingLoc,
3523                            SourceLocation NamespcLoc,
3524                            CXXScopeSpec &SS,
3525                            SourceLocation IdentLoc,
3526                            IdentifierInfo *NamespcName,
3527                            AttributeList *AttrList);
3528
3529  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
3530
3531  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
3532                               SourceLocation NamespaceLoc,
3533                               SourceLocation AliasLoc,
3534                               IdentifierInfo *Alias,
3535                               CXXScopeSpec &SS,
3536                               SourceLocation IdentLoc,
3537                               IdentifierInfo *Ident);
3538
3539  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
3540  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
3541                            const LookupResult &PreviousDecls);
3542  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
3543                                        NamedDecl *Target);
3544
3545  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3546                                   bool isTypeName,
3547                                   const CXXScopeSpec &SS,
3548                                   SourceLocation NameLoc,
3549                                   const LookupResult &Previous);
3550  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
3551                               const CXXScopeSpec &SS,
3552                               SourceLocation NameLoc);
3553
3554  NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3555                                   SourceLocation UsingLoc,
3556                                   CXXScopeSpec &SS,
3557                                   const DeclarationNameInfo &NameInfo,
3558                                   AttributeList *AttrList,
3559                                   bool IsInstantiation,
3560                                   bool IsTypeName,
3561                                   SourceLocation TypenameLoc);
3562
3563  bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
3564
3565  Decl *ActOnUsingDeclaration(Scope *CurScope,
3566                              AccessSpecifier AS,
3567                              bool HasUsingKeyword,
3568                              SourceLocation UsingLoc,
3569                              CXXScopeSpec &SS,
3570                              UnqualifiedId &Name,
3571                              AttributeList *AttrList,
3572                              bool IsTypeName,
3573                              SourceLocation TypenameLoc);
3574  Decl *ActOnAliasDeclaration(Scope *CurScope,
3575                              AccessSpecifier AS,
3576                              MultiTemplateParamsArg TemplateParams,
3577                              SourceLocation UsingLoc,
3578                              UnqualifiedId &Name,
3579                              AttributeList *AttrList,
3580                              TypeResult Type);
3581
3582  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
3583  /// including handling of its default argument expressions.
3584  ///
3585  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
3586  ExprResult
3587  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3588                        CXXConstructorDecl *Constructor, MultiExprArg Exprs,
3589                        bool HadMultipleCandidates, bool IsListInitialization,
3590                        bool RequiresZeroInit, unsigned ConstructKind,
3591                        SourceRange ParenRange);
3592
3593  // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
3594  // the constructor can be elidable?
3595  ExprResult
3596  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3597                        CXXConstructorDecl *Constructor, bool Elidable,
3598                        MultiExprArg Exprs, bool HadMultipleCandidates,
3599                        bool IsListInitialization, bool RequiresZeroInit,
3600                        unsigned ConstructKind, SourceRange ParenRange);
3601
3602  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
3603  /// the default expr if needed.
3604  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3605                                    FunctionDecl *FD,
3606                                    ParmVarDecl *Param);
3607
3608  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
3609  /// constructed variable.
3610  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
3611
3612  /// \brief Helper class that collects exception specifications for
3613  /// implicitly-declared special member functions.
3614  class ImplicitExceptionSpecification {
3615    // Pointer to allow copying
3616    Sema *Self;
3617    // We order exception specifications thus:
3618    // noexcept is the most restrictive, but is only used in C++11.
3619    // throw() comes next.
3620    // Then a throw(collected exceptions)
3621    // Finally no specification, which is expressed as noexcept(false).
3622    // throw(...) is used instead if any called function uses it.
3623    ExceptionSpecificationType ComputedEST;
3624    llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3625    SmallVector<QualType, 4> Exceptions;
3626
3627    void ClearExceptions() {
3628      ExceptionsSeen.clear();
3629      Exceptions.clear();
3630    }
3631
3632  public:
3633    explicit ImplicitExceptionSpecification(Sema &Self)
3634      : Self(&Self), ComputedEST(EST_BasicNoexcept) {
3635      if (!Self.getLangOpts().CPlusPlus11)
3636        ComputedEST = EST_DynamicNone;
3637    }
3638
3639    /// \brief Get the computed exception specification type.
3640    ExceptionSpecificationType getExceptionSpecType() const {
3641      assert(ComputedEST != EST_ComputedNoexcept &&
3642             "noexcept(expr) should not be a possible result");
3643      return ComputedEST;
3644    }
3645
3646    /// \brief The number of exceptions in the exception specification.
3647    unsigned size() const { return Exceptions.size(); }
3648
3649    /// \brief The set of exceptions in the exception specification.
3650    const QualType *data() const { return Exceptions.data(); }
3651
3652    /// \brief Integrate another called method into the collected data.
3653    void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
3654
3655    /// \brief Integrate an invoked expression into the collected data.
3656    void CalledExpr(Expr *E);
3657
3658    /// \brief Overwrite an EPI's exception specification with this
3659    /// computed exception specification.
3660    void getEPI(FunctionProtoType::ExtProtoInfo &EPI) const {
3661      EPI.ExceptionSpecType = getExceptionSpecType();
3662      if (EPI.ExceptionSpecType == EST_Dynamic) {
3663        EPI.NumExceptions = size();
3664        EPI.Exceptions = data();
3665      } else if (EPI.ExceptionSpecType == EST_None) {
3666        /// C++11 [except.spec]p14:
3667        ///   The exception-specification is noexcept(false) if the set of
3668        ///   potential exceptions of the special member function contains "any"
3669        EPI.ExceptionSpecType = EST_ComputedNoexcept;
3670        EPI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
3671                                                     tok::kw_false).take();
3672      }
3673    }
3674    FunctionProtoType::ExtProtoInfo getEPI() const {
3675      FunctionProtoType::ExtProtoInfo EPI;
3676      getEPI(EPI);
3677      return EPI;
3678    }
3679  };
3680
3681  /// \brief Determine what sort of exception specification a defaulted
3682  /// copy constructor of a class will have.
3683  ImplicitExceptionSpecification
3684  ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
3685                                           CXXMethodDecl *MD);
3686
3687  /// \brief Determine what sort of exception specification a defaulted
3688  /// default constructor of a class will have, and whether the parameter
3689  /// will be const.
3690  ImplicitExceptionSpecification
3691  ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
3692
3693  /// \brief Determine what sort of exception specification a defautled
3694  /// copy assignment operator of a class will have, and whether the
3695  /// parameter will be const.
3696  ImplicitExceptionSpecification
3697  ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
3698
3699  /// \brief Determine what sort of exception specification a defaulted move
3700  /// constructor of a class will have.
3701  ImplicitExceptionSpecification
3702  ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
3703
3704  /// \brief Determine what sort of exception specification a defaulted move
3705  /// assignment operator of a class will have.
3706  ImplicitExceptionSpecification
3707  ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
3708
3709  /// \brief Determine what sort of exception specification a defaulted
3710  /// destructor of a class will have.
3711  ImplicitExceptionSpecification
3712  ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
3713
3714  /// \brief Determine what sort of exception specification an inheriting
3715  /// constructor of a class will have.
3716  ImplicitExceptionSpecification
3717  ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
3718
3719  /// \brief Evaluate the implicit exception specification for a defaulted
3720  /// special member function.
3721  void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
3722
3723  /// \brief Check the given exception-specification and update the
3724  /// extended prototype information with the results.
3725  void checkExceptionSpecification(ExceptionSpecificationType EST,
3726                                   ArrayRef<ParsedType> DynamicExceptions,
3727                                   ArrayRef<SourceRange> DynamicExceptionRanges,
3728                                   Expr *NoexceptExpr,
3729                                   SmallVectorImpl<QualType> &Exceptions,
3730                                   FunctionProtoType::ExtProtoInfo &EPI);
3731
3732  /// \brief Determine if a special member function should have a deleted
3733  /// definition when it is defaulted.
3734  bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
3735                                 bool Diagnose = false);
3736
3737  /// \brief Declare the implicit default constructor for the given class.
3738  ///
3739  /// \param ClassDecl The class declaration into which the implicit
3740  /// default constructor will be added.
3741  ///
3742  /// \returns The implicitly-declared default constructor.
3743  CXXConstructorDecl *DeclareImplicitDefaultConstructor(
3744                                                     CXXRecordDecl *ClassDecl);
3745
3746  /// DefineImplicitDefaultConstructor - Checks for feasibility of
3747  /// defining this constructor as the default constructor.
3748  void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3749                                        CXXConstructorDecl *Constructor);
3750
3751  /// \brief Declare the implicit destructor for the given class.
3752  ///
3753  /// \param ClassDecl The class declaration into which the implicit
3754  /// destructor will be added.
3755  ///
3756  /// \returns The implicitly-declared destructor.
3757  CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
3758
3759  /// DefineImplicitDestructor - Checks for feasibility of
3760  /// defining this destructor as the default destructor.
3761  void DefineImplicitDestructor(SourceLocation CurrentLocation,
3762                                CXXDestructorDecl *Destructor);
3763
3764  /// \brief Build an exception spec for destructors that don't have one.
3765  ///
3766  /// C++11 says that user-defined destructors with no exception spec get one
3767  /// that looks as if the destructor was implicitly declared.
3768  void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
3769                                     CXXDestructorDecl *Destructor);
3770
3771  /// \brief Declare all inheriting constructors for the given class.
3772  ///
3773  /// \param ClassDecl The class declaration into which the inheriting
3774  /// constructors will be added.
3775  void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
3776
3777  /// \brief Define the specified inheriting constructor.
3778  void DefineInheritingConstructor(SourceLocation UseLoc,
3779                                   CXXConstructorDecl *Constructor);
3780
3781  /// \brief Declare the implicit copy constructor for the given class.
3782  ///
3783  /// \param ClassDecl The class declaration into which the implicit
3784  /// copy constructor will be added.
3785  ///
3786  /// \returns The implicitly-declared copy constructor.
3787  CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
3788
3789  /// DefineImplicitCopyConstructor - Checks for feasibility of
3790  /// defining this constructor as the copy constructor.
3791  void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3792                                     CXXConstructorDecl *Constructor);
3793
3794  /// \brief Declare the implicit move constructor for the given class.
3795  ///
3796  /// \param ClassDecl The Class declaration into which the implicit
3797  /// move constructor will be added.
3798  ///
3799  /// \returns The implicitly-declared move constructor, or NULL if it wasn't
3800  /// declared.
3801  CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
3802
3803  /// DefineImplicitMoveConstructor - Checks for feasibility of
3804  /// defining this constructor as the move constructor.
3805  void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
3806                                     CXXConstructorDecl *Constructor);
3807
3808  /// \brief Declare the implicit copy assignment operator for the given class.
3809  ///
3810  /// \param ClassDecl The class declaration into which the implicit
3811  /// copy assignment operator will be added.
3812  ///
3813  /// \returns The implicitly-declared copy assignment operator.
3814  CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
3815
3816  /// \brief Defines an implicitly-declared copy assignment operator.
3817  void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
3818                                    CXXMethodDecl *MethodDecl);
3819
3820  /// \brief Declare the implicit move assignment operator for the given class.
3821  ///
3822  /// \param ClassDecl The Class declaration into which the implicit
3823  /// move assignment operator will be added.
3824  ///
3825  /// \returns The implicitly-declared move assignment operator, or NULL if it
3826  /// wasn't declared.
3827  CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
3828
3829  /// \brief Defines an implicitly-declared move assignment operator.
3830  void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
3831                                    CXXMethodDecl *MethodDecl);
3832
3833  /// \brief Force the declaration of any implicitly-declared members of this
3834  /// class.
3835  void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
3836
3837  /// \brief Determine whether the given function is an implicitly-deleted
3838  /// special member function.
3839  bool isImplicitlyDeleted(FunctionDecl *FD);
3840
3841  /// \brief Check whether 'this' shows up in the type of a static member
3842  /// function after the (naturally empty) cv-qualifier-seq would be.
3843  ///
3844  /// \returns true if an error occurred.
3845  bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
3846
3847  /// \brief Whether this' shows up in the exception specification of a static
3848  /// member function.
3849  bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
3850
3851  /// \brief Check whether 'this' shows up in the attributes of the given
3852  /// static member function.
3853  ///
3854  /// \returns true if an error occurred.
3855  bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
3856
3857  /// MaybeBindToTemporary - If the passed in expression has a record type with
3858  /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
3859  /// it simply returns the passed in expression.
3860  ExprResult MaybeBindToTemporary(Expr *E);
3861
3862  bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
3863                               MultiExprArg ArgsPtr,
3864                               SourceLocation Loc,
3865                               SmallVectorImpl<Expr*> &ConvertedArgs,
3866                               bool AllowExplicit = false,
3867                               bool IsListInitialization = false);
3868
3869  ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
3870                                          SourceLocation NameLoc,
3871                                          IdentifierInfo &Name);
3872
3873  ParsedType getDestructorName(SourceLocation TildeLoc,
3874                               IdentifierInfo &II, SourceLocation NameLoc,
3875                               Scope *S, CXXScopeSpec &SS,
3876                               ParsedType ObjectType,
3877                               bool EnteringContext);
3878
3879  ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
3880
3881  // Checks that reinterpret casts don't have undefined behavior.
3882  void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
3883                                      bool IsDereference, SourceRange Range);
3884
3885  /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
3886  ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
3887                               tok::TokenKind Kind,
3888                               SourceLocation LAngleBracketLoc,
3889                               Declarator &D,
3890                               SourceLocation RAngleBracketLoc,
3891                               SourceLocation LParenLoc,
3892                               Expr *E,
3893                               SourceLocation RParenLoc);
3894
3895  ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
3896                               tok::TokenKind Kind,
3897                               TypeSourceInfo *Ty,
3898                               Expr *E,
3899                               SourceRange AngleBrackets,
3900                               SourceRange Parens);
3901
3902  ExprResult BuildCXXTypeId(QualType TypeInfoType,
3903                            SourceLocation TypeidLoc,
3904                            TypeSourceInfo *Operand,
3905                            SourceLocation RParenLoc);
3906  ExprResult BuildCXXTypeId(QualType TypeInfoType,
3907                            SourceLocation TypeidLoc,
3908                            Expr *Operand,
3909                            SourceLocation RParenLoc);
3910
3911  /// ActOnCXXTypeid - Parse typeid( something ).
3912  ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
3913                            SourceLocation LParenLoc, bool isType,
3914                            void *TyOrExpr,
3915                            SourceLocation RParenLoc);
3916
3917  ExprResult BuildCXXUuidof(QualType TypeInfoType,
3918                            SourceLocation TypeidLoc,
3919                            TypeSourceInfo *Operand,
3920                            SourceLocation RParenLoc);
3921  ExprResult BuildCXXUuidof(QualType TypeInfoType,
3922                            SourceLocation TypeidLoc,
3923                            Expr *Operand,
3924                            SourceLocation RParenLoc);
3925
3926  /// ActOnCXXUuidof - Parse __uuidof( something ).
3927  ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
3928                            SourceLocation LParenLoc, bool isType,
3929                            void *TyOrExpr,
3930                            SourceLocation RParenLoc);
3931
3932
3933  //// ActOnCXXThis -  Parse 'this' pointer.
3934  ExprResult ActOnCXXThis(SourceLocation loc);
3935
3936  /// \brief Try to retrieve the type of the 'this' pointer.
3937  ///
3938  /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
3939  QualType getCurrentThisType();
3940
3941  /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
3942  /// current context not being a non-static member function. In such cases,
3943  /// this provides the type used for 'this'.
3944  QualType CXXThisTypeOverride;
3945
3946  /// \brief RAII object used to temporarily allow the C++ 'this' expression
3947  /// to be used, with the given qualifiers on the current class type.
3948  class CXXThisScopeRAII {
3949    Sema &S;
3950    QualType OldCXXThisTypeOverride;
3951    bool Enabled;
3952
3953  public:
3954    /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
3955    /// using the given declaration (which is either a class template or a
3956    /// class) along with the given qualifiers.
3957    /// along with the qualifiers placed on '*this'.
3958    CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
3959                     bool Enabled = true);
3960
3961    ~CXXThisScopeRAII();
3962  };
3963
3964  /// \brief Make sure the value of 'this' is actually available in the current
3965  /// context, if it is a potentially evaluated context.
3966  ///
3967  /// \param Loc The location at which the capture of 'this' occurs.
3968  ///
3969  /// \param Explicit Whether 'this' is explicitly captured in a lambda
3970  /// capture list.
3971  void CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false);
3972
3973  /// \brief Determine whether the given type is the type of *this that is used
3974  /// outside of the body of a member function for a type that is currently
3975  /// being defined.
3976  bool isThisOutsideMemberFunctionBody(QualType BaseType);
3977
3978  /// ActOnCXXBoolLiteral - Parse {true,false} literals.
3979  ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
3980
3981
3982  /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
3983  ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
3984
3985  /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
3986  ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
3987
3988  //// ActOnCXXThrow -  Parse throw expressions.
3989  ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
3990  ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
3991                           bool IsThrownVarInScope);
3992  ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
3993                                  bool IsThrownVarInScope);
3994
3995  /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
3996  /// Can be interpreted either as function-style casting ("int(x)")
3997  /// or class type construction ("ClassType(x,y,z)")
3998  /// or creation of a value-initialized type ("int()").
3999  ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4000                                       SourceLocation LParenLoc,
4001                                       MultiExprArg Exprs,
4002                                       SourceLocation RParenLoc);
4003
4004  ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4005                                       SourceLocation LParenLoc,
4006                                       MultiExprArg Exprs,
4007                                       SourceLocation RParenLoc);
4008
4009  /// ActOnCXXNew - Parsed a C++ 'new' expression.
4010  ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4011                         SourceLocation PlacementLParen,
4012                         MultiExprArg PlacementArgs,
4013                         SourceLocation PlacementRParen,
4014                         SourceRange TypeIdParens, Declarator &D,
4015                         Expr *Initializer);
4016  ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4017                         SourceLocation PlacementLParen,
4018                         MultiExprArg PlacementArgs,
4019                         SourceLocation PlacementRParen,
4020                         SourceRange TypeIdParens,
4021                         QualType AllocType,
4022                         TypeSourceInfo *AllocTypeInfo,
4023                         Expr *ArraySize,
4024                         SourceRange DirectInitRange,
4025                         Expr *Initializer,
4026                         bool TypeMayContainAuto = true);
4027
4028  bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4029                          SourceRange R);
4030  bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4031                               bool UseGlobal, QualType AllocType, bool IsArray,
4032                               MultiExprArg PlaceArgs,
4033                               FunctionDecl *&OperatorNew,
4034                               FunctionDecl *&OperatorDelete);
4035  bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
4036                              DeclarationName Name, MultiExprArg Args,
4037                              DeclContext *Ctx,
4038                              bool AllowMissing, FunctionDecl *&Operator,
4039                              bool Diagnose = true);
4040  void DeclareGlobalNewDelete();
4041  void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4042                                       QualType Argument,
4043                                       bool addMallocAttr = false);
4044
4045  bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4046                                DeclarationName Name, FunctionDecl* &Operator,
4047                                bool Diagnose = true);
4048
4049  /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4050  ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4051                            bool UseGlobal, bool ArrayForm,
4052                            Expr *Operand);
4053
4054  DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
4055  ExprResult CheckConditionVariable(VarDecl *ConditionVar,
4056                                    SourceLocation StmtLoc,
4057                                    bool ConvertToBoolean);
4058
4059  ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4060                               Expr *Operand, SourceLocation RParen);
4061  ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4062                                  SourceLocation RParen);
4063
4064  /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
4065  /// pseudo-functions.
4066  ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
4067                                 SourceLocation KWLoc,
4068                                 ParsedType Ty,
4069                                 SourceLocation RParen);
4070
4071  ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
4072                                 SourceLocation KWLoc,
4073                                 TypeSourceInfo *T,
4074                                 SourceLocation RParen);
4075
4076  /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
4077  /// pseudo-functions.
4078  ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
4079                                  SourceLocation KWLoc,
4080                                  ParsedType LhsTy,
4081                                  ParsedType RhsTy,
4082                                  SourceLocation RParen);
4083
4084  ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
4085                                  SourceLocation KWLoc,
4086                                  TypeSourceInfo *LhsT,
4087                                  TypeSourceInfo *RhsT,
4088                                  SourceLocation RParen);
4089
4090  /// \brief Parsed one of the type trait support pseudo-functions.
4091  ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4092                            ArrayRef<ParsedType> Args,
4093                            SourceLocation RParenLoc);
4094  ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4095                            ArrayRef<TypeSourceInfo *> Args,
4096                            SourceLocation RParenLoc);
4097
4098  /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4099  /// pseudo-functions.
4100  ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4101                                 SourceLocation KWLoc,
4102                                 ParsedType LhsTy,
4103                                 Expr *DimExpr,
4104                                 SourceLocation RParen);
4105
4106  ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4107                                 SourceLocation KWLoc,
4108                                 TypeSourceInfo *TSInfo,
4109                                 Expr *DimExpr,
4110                                 SourceLocation RParen);
4111
4112  /// ActOnExpressionTrait - Parsed one of the unary type trait support
4113  /// pseudo-functions.
4114  ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4115                                  SourceLocation KWLoc,
4116                                  Expr *Queried,
4117                                  SourceLocation RParen);
4118
4119  ExprResult BuildExpressionTrait(ExpressionTrait OET,
4120                                  SourceLocation KWLoc,
4121                                  Expr *Queried,
4122                                  SourceLocation RParen);
4123
4124  ExprResult ActOnStartCXXMemberReference(Scope *S,
4125                                          Expr *Base,
4126                                          SourceLocation OpLoc,
4127                                          tok::TokenKind OpKind,
4128                                          ParsedType &ObjectType,
4129                                          bool &MayBePseudoDestructor);
4130
4131  ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
4132
4133  ExprResult BuildPseudoDestructorExpr(Expr *Base,
4134                                       SourceLocation OpLoc,
4135                                       tok::TokenKind OpKind,
4136                                       const CXXScopeSpec &SS,
4137                                       TypeSourceInfo *ScopeType,
4138                                       SourceLocation CCLoc,
4139                                       SourceLocation TildeLoc,
4140                                     PseudoDestructorTypeStorage DestroyedType,
4141                                       bool HasTrailingLParen);
4142
4143  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4144                                       SourceLocation OpLoc,
4145                                       tok::TokenKind OpKind,
4146                                       CXXScopeSpec &SS,
4147                                       UnqualifiedId &FirstTypeName,
4148                                       SourceLocation CCLoc,
4149                                       SourceLocation TildeLoc,
4150                                       UnqualifiedId &SecondTypeName,
4151                                       bool HasTrailingLParen);
4152
4153  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4154                                       SourceLocation OpLoc,
4155                                       tok::TokenKind OpKind,
4156                                       SourceLocation TildeLoc,
4157                                       const DeclSpec& DS,
4158                                       bool HasTrailingLParen);
4159
4160  /// MaybeCreateExprWithCleanups - If the current full-expression
4161  /// requires any cleanups, surround it with a ExprWithCleanups node.
4162  /// Otherwise, just returns the passed-in expression.
4163  Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4164  Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4165  ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4166
4167  ExprResult ActOnFinishFullExpr(Expr *Expr) {
4168    return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4169                                          : SourceLocation());
4170  }
4171  ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4172                                 bool DiscardedValue = false,
4173                                 bool IsConstexpr = false);
4174  StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4175
4176  // Marks SS invalid if it represents an incomplete type.
4177  bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4178
4179  DeclContext *computeDeclContext(QualType T);
4180  DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4181                                  bool EnteringContext = false);
4182  bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4183  CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4184  bool isUnknownSpecialization(const CXXScopeSpec &SS);
4185
4186  /// \brief The parser has parsed a global nested-name-specifier '::'.
4187  ///
4188  /// \param S The scope in which this nested-name-specifier occurs.
4189  ///
4190  /// \param CCLoc The location of the '::'.
4191  ///
4192  /// \param SS The nested-name-specifier, which will be updated in-place
4193  /// to reflect the parsed nested-name-specifier.
4194  ///
4195  /// \returns true if an error occurred, false otherwise.
4196  bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
4197                                    CXXScopeSpec &SS);
4198
4199  bool isAcceptableNestedNameSpecifier(const NamedDecl *SD);
4200  NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4201
4202  bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4203                                    SourceLocation IdLoc,
4204                                    IdentifierInfo &II,
4205                                    ParsedType ObjectType);
4206
4207  bool BuildCXXNestedNameSpecifier(Scope *S,
4208                                   IdentifierInfo &Identifier,
4209                                   SourceLocation IdentifierLoc,
4210                                   SourceLocation CCLoc,
4211                                   QualType ObjectType,
4212                                   bool EnteringContext,
4213                                   CXXScopeSpec &SS,
4214                                   NamedDecl *ScopeLookupResult,
4215                                   bool ErrorRecoveryLookup);
4216
4217  /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4218  ///
4219  /// \param S The scope in which this nested-name-specifier occurs.
4220  ///
4221  /// \param Identifier The identifier preceding the '::'.
4222  ///
4223  /// \param IdentifierLoc The location of the identifier.
4224  ///
4225  /// \param CCLoc The location of the '::'.
4226  ///
4227  /// \param ObjectType The type of the object, if we're parsing
4228  /// nested-name-specifier in a member access expression.
4229  ///
4230  /// \param EnteringContext Whether we're entering the context nominated by
4231  /// this nested-name-specifier.
4232  ///
4233  /// \param SS The nested-name-specifier, which is both an input
4234  /// parameter (the nested-name-specifier before this type) and an
4235  /// output parameter (containing the full nested-name-specifier,
4236  /// including this new type).
4237  ///
4238  /// \returns true if an error occurred, false otherwise.
4239  bool ActOnCXXNestedNameSpecifier(Scope *S,
4240                                   IdentifierInfo &Identifier,
4241                                   SourceLocation IdentifierLoc,
4242                                   SourceLocation CCLoc,
4243                                   ParsedType ObjectType,
4244                                   bool EnteringContext,
4245                                   CXXScopeSpec &SS);
4246
4247  ExprResult ActOnDecltypeExpression(Expr *E);
4248
4249  bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
4250                                           const DeclSpec &DS,
4251                                           SourceLocation ColonColonLoc);
4252
4253  bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
4254                                 IdentifierInfo &Identifier,
4255                                 SourceLocation IdentifierLoc,
4256                                 SourceLocation ColonLoc,
4257                                 ParsedType ObjectType,
4258                                 bool EnteringContext);
4259
4260  /// \brief The parser has parsed a nested-name-specifier
4261  /// 'template[opt] template-name < template-args >::'.
4262  ///
4263  /// \param S The scope in which this nested-name-specifier occurs.
4264  ///
4265  /// \param SS The nested-name-specifier, which is both an input
4266  /// parameter (the nested-name-specifier before this type) and an
4267  /// output parameter (containing the full nested-name-specifier,
4268  /// including this new type).
4269  ///
4270  /// \param TemplateKWLoc the location of the 'template' keyword, if any.
4271  /// \param TemplateName the template name.
4272  /// \param TemplateNameLoc The location of the template name.
4273  /// \param LAngleLoc The location of the opening angle bracket  ('<').
4274  /// \param TemplateArgs The template arguments.
4275  /// \param RAngleLoc The location of the closing angle bracket  ('>').
4276  /// \param CCLoc The location of the '::'.
4277  ///
4278  /// \param EnteringContext Whether we're entering the context of the
4279  /// nested-name-specifier.
4280  ///
4281  ///
4282  /// \returns true if an error occurred, false otherwise.
4283  bool ActOnCXXNestedNameSpecifier(Scope *S,
4284                                   CXXScopeSpec &SS,
4285                                   SourceLocation TemplateKWLoc,
4286                                   TemplateTy TemplateName,
4287                                   SourceLocation TemplateNameLoc,
4288                                   SourceLocation LAngleLoc,
4289                                   ASTTemplateArgsPtr TemplateArgs,
4290                                   SourceLocation RAngleLoc,
4291                                   SourceLocation CCLoc,
4292                                   bool EnteringContext);
4293
4294  /// \brief Given a C++ nested-name-specifier, produce an annotation value
4295  /// that the parser can use later to reconstruct the given
4296  /// nested-name-specifier.
4297  ///
4298  /// \param SS A nested-name-specifier.
4299  ///
4300  /// \returns A pointer containing all of the information in the
4301  /// nested-name-specifier \p SS.
4302  void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
4303
4304  /// \brief Given an annotation pointer for a nested-name-specifier, restore
4305  /// the nested-name-specifier structure.
4306  ///
4307  /// \param Annotation The annotation pointer, produced by
4308  /// \c SaveNestedNameSpecifierAnnotation().
4309  ///
4310  /// \param AnnotationRange The source range corresponding to the annotation.
4311  ///
4312  /// \param SS The nested-name-specifier that will be updated with the contents
4313  /// of the annotation pointer.
4314  void RestoreNestedNameSpecifierAnnotation(void *Annotation,
4315                                            SourceRange AnnotationRange,
4316                                            CXXScopeSpec &SS);
4317
4318  bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4319
4320  /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
4321  /// scope or nested-name-specifier) is parsed, part of a declarator-id.
4322  /// After this method is called, according to [C++ 3.4.3p3], names should be
4323  /// looked up in the declarator-id's scope, until the declarator is parsed and
4324  /// ActOnCXXExitDeclaratorScope is called.
4325  /// The 'SS' should be a non-empty valid CXXScopeSpec.
4326  bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
4327
4328  /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
4329  /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
4330  /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
4331  /// Used to indicate that names should revert to being looked up in the
4332  /// defining scope.
4333  void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4334
4335  /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4336  /// initializer for the declaration 'Dcl'.
4337  /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4338  /// static data member of class X, names should be looked up in the scope of
4339  /// class X.
4340  void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
4341
4342  /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4343  /// initializer for the declaration 'Dcl'.
4344  void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4345
4346  /// \brief Create a new lambda closure type.
4347  CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
4348                                         TypeSourceInfo *Info,
4349                                         bool KnownDependent);
4350
4351  /// \brief Start the definition of a lambda expression.
4352  CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
4353                                       SourceRange IntroducerRange,
4354                                       TypeSourceInfo *MethodType,
4355                                       SourceLocation EndLoc,
4356                                       ArrayRef<ParmVarDecl *> Params);
4357
4358  /// \brief Introduce the scope for a lambda expression.
4359  sema::LambdaScopeInfo *enterLambdaScope(CXXMethodDecl *CallOperator,
4360                                          SourceRange IntroducerRange,
4361                                          LambdaCaptureDefault CaptureDefault,
4362                                          bool ExplicitParams,
4363                                          bool ExplicitResultType,
4364                                          bool Mutable);
4365
4366  /// \brief Check and build an init-capture with the specified name and
4367  /// initializer.
4368  FieldDecl *checkInitCapture(SourceLocation Loc, bool ByRef,
4369                              IdentifierInfo *Id, Expr *Init);
4370
4371  /// \brief Note that we have finished the explicit captures for the
4372  /// given lambda.
4373  void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
4374
4375  /// \brief Introduce the lambda parameters into scope.
4376  void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
4377
4378  /// \brief Deduce a block or lambda's return type based on the return
4379  /// statements present in the body.
4380  void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
4381
4382  /// ActOnStartOfLambdaDefinition - This is called just before we start
4383  /// parsing the body of a lambda; it analyzes the explicit captures and
4384  /// arguments, and sets up various data-structures for the body of the
4385  /// lambda.
4386  void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4387                                    Declarator &ParamInfo, Scope *CurScope);
4388
4389  /// ActOnLambdaError - If there is an error parsing a lambda, this callback
4390  /// is invoked to pop the information about the lambda.
4391  void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
4392                        bool IsInstantiation = false);
4393
4394  /// ActOnLambdaExpr - This is called when the body of a lambda expression
4395  /// was successfully completed.
4396  ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
4397                             Scope *CurScope,
4398                             bool IsInstantiation = false);
4399
4400  /// \brief Define the "body" of the conversion from a lambda object to a
4401  /// function pointer.
4402  ///
4403  /// This routine doesn't actually define a sensible body; rather, it fills
4404  /// in the initialization expression needed to copy the lambda object into
4405  /// the block, and IR generation actually generates the real body of the
4406  /// block pointer conversion.
4407  void DefineImplicitLambdaToFunctionPointerConversion(
4408         SourceLocation CurrentLoc, CXXConversionDecl *Conv);
4409
4410  /// \brief Define the "body" of the conversion from a lambda object to a
4411  /// block pointer.
4412  ///
4413  /// This routine doesn't actually define a sensible body; rather, it fills
4414  /// in the initialization expression needed to copy the lambda object into
4415  /// the block, and IR generation actually generates the real body of the
4416  /// block pointer conversion.
4417  void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
4418                                                    CXXConversionDecl *Conv);
4419
4420  ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
4421                                           SourceLocation ConvLocation,
4422                                           CXXConversionDecl *Conv,
4423                                           Expr *Src);
4424
4425  // ParseObjCStringLiteral - Parse Objective-C string literals.
4426  ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
4427                                    Expr **Strings,
4428                                    unsigned NumStrings);
4429
4430  ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
4431
4432  /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
4433  /// numeric literal expression. Type of the expression will be "NSNumber *"
4434  /// or "id" if NSNumber is unavailable.
4435  ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
4436  ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
4437                                  bool Value);
4438  ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
4439
4440  /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
4441  /// '@' prefixed parenthesized expression. The type of the expression will
4442  /// either be "NSNumber *" or "NSString *" depending on the type of
4443  /// ValueType, which is allowed to be a built-in numeric type or
4444  /// "char *" or "const char *".
4445  ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
4446
4447  ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
4448                                          Expr *IndexExpr,
4449                                          ObjCMethodDecl *getterMethod,
4450                                          ObjCMethodDecl *setterMethod);
4451
4452  ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
4453                                        ObjCDictionaryElement *Elements,
4454                                        unsigned NumElements);
4455
4456  ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
4457                                  TypeSourceInfo *EncodedTypeInfo,
4458                                  SourceLocation RParenLoc);
4459  ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
4460                                    CXXConversionDecl *Method,
4461                                    bool HadMultipleCandidates);
4462
4463  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
4464                                       SourceLocation EncodeLoc,
4465                                       SourceLocation LParenLoc,
4466                                       ParsedType Ty,
4467                                       SourceLocation RParenLoc);
4468
4469  /// ParseObjCSelectorExpression - Build selector expression for \@selector
4470  ExprResult ParseObjCSelectorExpression(Selector Sel,
4471                                         SourceLocation AtLoc,
4472                                         SourceLocation SelLoc,
4473                                         SourceLocation LParenLoc,
4474                                         SourceLocation RParenLoc);
4475
4476  /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
4477  ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
4478                                         SourceLocation AtLoc,
4479                                         SourceLocation ProtoLoc,
4480                                         SourceLocation LParenLoc,
4481                                         SourceLocation ProtoIdLoc,
4482                                         SourceLocation RParenLoc);
4483
4484  //===--------------------------------------------------------------------===//
4485  // C++ Declarations
4486  //
4487  Decl *ActOnStartLinkageSpecification(Scope *S,
4488                                       SourceLocation ExternLoc,
4489                                       SourceLocation LangLoc,
4490                                       StringRef Lang,
4491                                       SourceLocation LBraceLoc);
4492  Decl *ActOnFinishLinkageSpecification(Scope *S,
4493                                        Decl *LinkageSpec,
4494                                        SourceLocation RBraceLoc);
4495
4496
4497  //===--------------------------------------------------------------------===//
4498  // C++ Classes
4499  //
4500  bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
4501                          const CXXScopeSpec *SS = 0);
4502
4503  bool ActOnAccessSpecifier(AccessSpecifier Access,
4504                            SourceLocation ASLoc,
4505                            SourceLocation ColonLoc,
4506                            AttributeList *Attrs = 0);
4507
4508  NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
4509                                 Declarator &D,
4510                                 MultiTemplateParamsArg TemplateParameterLists,
4511                                 Expr *BitfieldWidth, const VirtSpecifiers &VS,
4512                                 InClassInitStyle InitStyle);
4513  void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc,
4514                                        Expr *Init);
4515
4516  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4517                                    Scope *S,
4518                                    CXXScopeSpec &SS,
4519                                    IdentifierInfo *MemberOrBase,
4520                                    ParsedType TemplateTypeTy,
4521                                    const DeclSpec &DS,
4522                                    SourceLocation IdLoc,
4523                                    SourceLocation LParenLoc,
4524                                    ArrayRef<Expr *> Args,
4525                                    SourceLocation RParenLoc,
4526                                    SourceLocation EllipsisLoc);
4527
4528  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4529                                    Scope *S,
4530                                    CXXScopeSpec &SS,
4531                                    IdentifierInfo *MemberOrBase,
4532                                    ParsedType TemplateTypeTy,
4533                                    const DeclSpec &DS,
4534                                    SourceLocation IdLoc,
4535                                    Expr *InitList,
4536                                    SourceLocation EllipsisLoc);
4537
4538  MemInitResult BuildMemInitializer(Decl *ConstructorD,
4539                                    Scope *S,
4540                                    CXXScopeSpec &SS,
4541                                    IdentifierInfo *MemberOrBase,
4542                                    ParsedType TemplateTypeTy,
4543                                    const DeclSpec &DS,
4544                                    SourceLocation IdLoc,
4545                                    Expr *Init,
4546                                    SourceLocation EllipsisLoc);
4547
4548  MemInitResult BuildMemberInitializer(ValueDecl *Member,
4549                                       Expr *Init,
4550                                       SourceLocation IdLoc);
4551
4552  MemInitResult BuildBaseInitializer(QualType BaseType,
4553                                     TypeSourceInfo *BaseTInfo,
4554                                     Expr *Init,
4555                                     CXXRecordDecl *ClassDecl,
4556                                     SourceLocation EllipsisLoc);
4557
4558  MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
4559                                           Expr *Init,
4560                                           CXXRecordDecl *ClassDecl);
4561
4562  bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4563                                CXXCtorInitializer *Initializer);
4564
4565  bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4566                           ArrayRef<CXXCtorInitializer *> Initializers = None);
4567
4568  void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
4569
4570
4571  /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
4572  /// mark all the non-trivial destructors of its members and bases as
4573  /// referenced.
4574  void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
4575                                              CXXRecordDecl *Record);
4576
4577  /// \brief The list of classes whose vtables have been used within
4578  /// this translation unit, and the source locations at which the
4579  /// first use occurred.
4580  typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
4581
4582  /// \brief The list of vtables that are required but have not yet been
4583  /// materialized.
4584  SmallVector<VTableUse, 16> VTableUses;
4585
4586  /// \brief The set of classes whose vtables have been used within
4587  /// this translation unit, and a bit that will be true if the vtable is
4588  /// required to be emitted (otherwise, it should be emitted only if needed
4589  /// by code generation).
4590  llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
4591
4592  /// \brief Load any externally-stored vtable uses.
4593  void LoadExternalVTableUses();
4594
4595  typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,
4596                     &ExternalSemaSource::ReadDynamicClasses, 2, 2>
4597    DynamicClassesType;
4598
4599  /// \brief A list of all of the dynamic classes in this translation
4600  /// unit.
4601  DynamicClassesType DynamicClasses;
4602
4603  /// \brief Note that the vtable for the given class was used at the
4604  /// given location.
4605  void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
4606                      bool DefinitionRequired = false);
4607
4608  /// \brief Mark the exception specifications of all virtual member functions
4609  /// in the given class as needed.
4610  void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
4611                                             const CXXRecordDecl *RD);
4612
4613  /// MarkVirtualMembersReferenced - Will mark all members of the given
4614  /// CXXRecordDecl referenced.
4615  void MarkVirtualMembersReferenced(SourceLocation Loc,
4616                                    const CXXRecordDecl *RD);
4617
4618  /// \brief Define all of the vtables that have been used in this
4619  /// translation unit and reference any virtual members used by those
4620  /// vtables.
4621  ///
4622  /// \returns true if any work was done, false otherwise.
4623  bool DefineUsedVTables();
4624
4625  void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
4626
4627  void ActOnMemInitializers(Decl *ConstructorDecl,
4628                            SourceLocation ColonLoc,
4629                            ArrayRef<CXXCtorInitializer*> MemInits,
4630                            bool AnyErrors);
4631
4632  void CheckCompletedCXXClass(CXXRecordDecl *Record);
4633  void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4634                                         Decl *TagDecl,
4635                                         SourceLocation LBrac,
4636                                         SourceLocation RBrac,
4637                                         AttributeList *AttrList);
4638  void ActOnFinishCXXMemberDecls();
4639
4640  void ActOnReenterTemplateScope(Scope *S, Decl *Template);
4641  void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
4642  void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
4643  void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4644  void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
4645  void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
4646  void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4647  void ActOnFinishDelayedMemberInitializers(Decl *Record);
4648  void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true);
4649  bool IsInsideALocalClassWithinATemplateFunction();
4650
4651  Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4652                                     Expr *AssertExpr,
4653                                     Expr *AssertMessageExpr,
4654                                     SourceLocation RParenLoc);
4655  Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4656                                     Expr *AssertExpr,
4657                                     StringLiteral *AssertMessageExpr,
4658                                     SourceLocation RParenLoc,
4659                                     bool Failed);
4660
4661  FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
4662                                  SourceLocation FriendLoc,
4663                                  TypeSourceInfo *TSInfo);
4664  Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
4665                            MultiTemplateParamsArg TemplateParams);
4666  NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
4667                                     MultiTemplateParamsArg TemplateParams);
4668
4669  QualType CheckConstructorDeclarator(Declarator &D, QualType R,
4670                                      StorageClass& SC);
4671  void CheckConstructor(CXXConstructorDecl *Constructor);
4672  QualType CheckDestructorDeclarator(Declarator &D, QualType R,
4673                                     StorageClass& SC);
4674  bool CheckDestructor(CXXDestructorDecl *Destructor);
4675  void CheckConversionDeclarator(Declarator &D, QualType &R,
4676                                 StorageClass& SC);
4677  Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
4678
4679  void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
4680  void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
4681                                                   const FunctionProtoType *T);
4682  void CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
4683
4684  //===--------------------------------------------------------------------===//
4685  // C++ Derived Classes
4686  //
4687
4688  /// ActOnBaseSpecifier - Parsed a base specifier
4689  CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
4690                                       SourceRange SpecifierRange,
4691                                       bool Virtual, AccessSpecifier Access,
4692                                       TypeSourceInfo *TInfo,
4693                                       SourceLocation EllipsisLoc);
4694
4695  BaseResult ActOnBaseSpecifier(Decl *classdecl,
4696                                SourceRange SpecifierRange,
4697                                ParsedAttributes &Attrs,
4698                                bool Virtual, AccessSpecifier Access,
4699                                ParsedType basetype,
4700                                SourceLocation BaseLoc,
4701                                SourceLocation EllipsisLoc);
4702
4703  bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
4704                            unsigned NumBases);
4705  void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
4706                           unsigned NumBases);
4707
4708  bool IsDerivedFrom(QualType Derived, QualType Base);
4709  bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
4710
4711  // FIXME: I don't like this name.
4712  void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
4713
4714  bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
4715
4716  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4717                                    SourceLocation Loc, SourceRange Range,
4718                                    CXXCastPath *BasePath = 0,
4719                                    bool IgnoreAccess = false);
4720  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4721                                    unsigned InaccessibleBaseID,
4722                                    unsigned AmbigiousBaseConvID,
4723                                    SourceLocation Loc, SourceRange Range,
4724                                    DeclarationName Name,
4725                                    CXXCastPath *BasePath);
4726
4727  std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
4728
4729  bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
4730                                         const CXXMethodDecl *Old);
4731
4732  /// CheckOverridingFunctionReturnType - Checks whether the return types are
4733  /// covariant, according to C++ [class.virtual]p5.
4734  bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
4735                                         const CXXMethodDecl *Old);
4736
4737  /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
4738  /// spec is a subset of base spec.
4739  bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
4740                                            const CXXMethodDecl *Old);
4741
4742  bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
4743
4744  /// CheckOverrideControl - Check C++11 override control semantics.
4745  void CheckOverrideControl(Decl *D);
4746
4747  /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
4748  /// overrides a virtual member function marked 'final', according to
4749  /// C++11 [class.virtual]p4.
4750  bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
4751                                              const CXXMethodDecl *Old);
4752
4753
4754  //===--------------------------------------------------------------------===//
4755  // C++ Access Control
4756  //
4757
4758  enum AccessResult {
4759    AR_accessible,
4760    AR_inaccessible,
4761    AR_dependent,
4762    AR_delayed
4763  };
4764
4765  bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
4766                                NamedDecl *PrevMemberDecl,
4767                                AccessSpecifier LexicalAS);
4768
4769  AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
4770                                           DeclAccessPair FoundDecl);
4771  AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
4772                                           DeclAccessPair FoundDecl);
4773  AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
4774                                     SourceRange PlacementRange,
4775                                     CXXRecordDecl *NamingClass,
4776                                     DeclAccessPair FoundDecl,
4777                                     bool Diagnose = true);
4778  AccessResult CheckConstructorAccess(SourceLocation Loc,
4779                                      CXXConstructorDecl *D,
4780                                      const InitializedEntity &Entity,
4781                                      AccessSpecifier Access,
4782                                      bool IsCopyBindingRefToTemp = false);
4783  AccessResult CheckConstructorAccess(SourceLocation Loc,
4784                                      CXXConstructorDecl *D,
4785                                      const InitializedEntity &Entity,
4786                                      AccessSpecifier Access,
4787                                      const PartialDiagnostic &PDiag);
4788  AccessResult CheckDestructorAccess(SourceLocation Loc,
4789                                     CXXDestructorDecl *Dtor,
4790                                     const PartialDiagnostic &PDiag,
4791                                     QualType objectType = QualType());
4792  AccessResult CheckFriendAccess(NamedDecl *D);
4793  AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
4794                                         Expr *ObjectExpr,
4795                                         Expr *ArgExpr,
4796                                         DeclAccessPair FoundDecl);
4797  AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
4798                                          DeclAccessPair FoundDecl);
4799  AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
4800                                    QualType Base, QualType Derived,
4801                                    const CXXBasePath &Path,
4802                                    unsigned DiagID,
4803                                    bool ForceCheck = false,
4804                                    bool ForceUnprivileged = false);
4805  void CheckLookupAccess(const LookupResult &R);
4806  bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
4807  bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
4808                                            AccessSpecifier access,
4809                                            QualType objectType);
4810
4811  void HandleDependentAccessCheck(const DependentDiagnostic &DD,
4812                         const MultiLevelTemplateArgumentList &TemplateArgs);
4813  void PerformDependentDiagnostics(const DeclContext *Pattern,
4814                        const MultiLevelTemplateArgumentList &TemplateArgs);
4815
4816  void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4817
4818  /// \brief When true, access checking violations are treated as SFINAE
4819  /// failures rather than hard errors.
4820  bool AccessCheckingSFINAE;
4821
4822  enum AbstractDiagSelID {
4823    AbstractNone = -1,
4824    AbstractReturnType,
4825    AbstractParamType,
4826    AbstractVariableType,
4827    AbstractFieldType,
4828    AbstractIvarType,
4829    AbstractArrayType
4830  };
4831
4832  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4833                              TypeDiagnoser &Diagnoser);
4834  template<typename T1>
4835  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4836                              unsigned DiagID,
4837                              const T1 &Arg1) {
4838    BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
4839    return RequireNonAbstractType(Loc, T, Diagnoser);
4840  }
4841
4842  template<typename T1, typename T2>
4843  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4844                              unsigned DiagID,
4845                              const T1 &Arg1, const T2 &Arg2) {
4846    BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
4847    return RequireNonAbstractType(Loc, T, Diagnoser);
4848  }
4849
4850  template<typename T1, typename T2, typename T3>
4851  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4852                              unsigned DiagID,
4853                              const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) {
4854    BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3);
4855    return RequireNonAbstractType(Loc, T, Diagnoser);
4856  }
4857
4858  void DiagnoseAbstractType(const CXXRecordDecl *RD);
4859
4860  bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
4861                              AbstractDiagSelID SelID = AbstractNone);
4862
4863  //===--------------------------------------------------------------------===//
4864  // C++ Overloaded Operators [C++ 13.5]
4865  //
4866
4867  bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
4868
4869  bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
4870
4871  //===--------------------------------------------------------------------===//
4872  // C++ Templates [C++ 14]
4873  //
4874  void FilterAcceptableTemplateNames(LookupResult &R,
4875                                     bool AllowFunctionTemplates = true);
4876  bool hasAnyAcceptableTemplateNames(LookupResult &R,
4877                                     bool AllowFunctionTemplates = true);
4878
4879  void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
4880                          QualType ObjectType, bool EnteringContext,
4881                          bool &MemberOfUnknownSpecialization);
4882
4883  TemplateNameKind isTemplateName(Scope *S,
4884                                  CXXScopeSpec &SS,
4885                                  bool hasTemplateKeyword,
4886                                  UnqualifiedId &Name,
4887                                  ParsedType ObjectType,
4888                                  bool EnteringContext,
4889                                  TemplateTy &Template,
4890                                  bool &MemberOfUnknownSpecialization);
4891
4892  bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
4893                                   SourceLocation IILoc,
4894                                   Scope *S,
4895                                   const CXXScopeSpec *SS,
4896                                   TemplateTy &SuggestedTemplate,
4897                                   TemplateNameKind &SuggestedKind);
4898
4899  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
4900  TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
4901
4902  Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
4903                           SourceLocation EllipsisLoc,
4904                           SourceLocation KeyLoc,
4905                           IdentifierInfo *ParamName,
4906                           SourceLocation ParamNameLoc,
4907                           unsigned Depth, unsigned Position,
4908                           SourceLocation EqualLoc,
4909                           ParsedType DefaultArg);
4910
4911  QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
4912  Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
4913                                      unsigned Depth,
4914                                      unsigned Position,
4915                                      SourceLocation EqualLoc,
4916                                      Expr *DefaultArg);
4917  Decl *ActOnTemplateTemplateParameter(Scope *S,
4918                                       SourceLocation TmpLoc,
4919                                       TemplateParameterList *Params,
4920                                       SourceLocation EllipsisLoc,
4921                                       IdentifierInfo *ParamName,
4922                                       SourceLocation ParamNameLoc,
4923                                       unsigned Depth,
4924                                       unsigned Position,
4925                                       SourceLocation EqualLoc,
4926                                       ParsedTemplateArgument DefaultArg);
4927
4928  TemplateParameterList *
4929  ActOnTemplateParameterList(unsigned Depth,
4930                             SourceLocation ExportLoc,
4931                             SourceLocation TemplateLoc,
4932                             SourceLocation LAngleLoc,
4933                             Decl **Params, unsigned NumParams,
4934                             SourceLocation RAngleLoc);
4935
4936  /// \brief The context in which we are checking a template parameter
4937  /// list.
4938  enum TemplateParamListContext {
4939    TPC_ClassTemplate,
4940    TPC_FunctionTemplate,
4941    TPC_ClassTemplateMember,
4942    TPC_FriendFunctionTemplate,
4943    TPC_FriendFunctionTemplateDefinition,
4944    TPC_TypeAliasTemplate
4945  };
4946
4947  bool CheckTemplateParameterList(TemplateParameterList *NewParams,
4948                                  TemplateParameterList *OldParams,
4949                                  TemplateParamListContext TPC);
4950  TemplateParameterList *
4951  MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
4952                                          SourceLocation DeclLoc,
4953                                          const CXXScopeSpec &SS,
4954                                          TemplateParameterList **ParamLists,
4955                                          unsigned NumParamLists,
4956                                          bool IsFriend,
4957                                          bool &IsExplicitSpecialization,
4958                                          bool &Invalid);
4959
4960  DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
4961                                SourceLocation KWLoc, CXXScopeSpec &SS,
4962                                IdentifierInfo *Name, SourceLocation NameLoc,
4963                                AttributeList *Attr,
4964                                TemplateParameterList *TemplateParams,
4965                                AccessSpecifier AS,
4966                                SourceLocation ModulePrivateLoc,
4967                                unsigned NumOuterTemplateParamLists,
4968                            TemplateParameterList **OuterTemplateParamLists);
4969
4970  void translateTemplateArguments(const ASTTemplateArgsPtr &In,
4971                                  TemplateArgumentListInfo &Out);
4972
4973  void NoteAllFoundTemplates(TemplateName Name);
4974
4975  QualType CheckTemplateIdType(TemplateName Template,
4976                               SourceLocation TemplateLoc,
4977                              TemplateArgumentListInfo &TemplateArgs);
4978
4979  TypeResult
4980  ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4981                      TemplateTy Template, SourceLocation TemplateLoc,
4982                      SourceLocation LAngleLoc,
4983                      ASTTemplateArgsPtr TemplateArgs,
4984                      SourceLocation RAngleLoc,
4985                      bool IsCtorOrDtorName = false);
4986
4987  /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
4988  /// such as \c class T::template apply<U>.
4989  TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
4990                                    TypeSpecifierType TagSpec,
4991                                    SourceLocation TagLoc,
4992                                    CXXScopeSpec &SS,
4993                                    SourceLocation TemplateKWLoc,
4994                                    TemplateTy TemplateD,
4995                                    SourceLocation TemplateLoc,
4996                                    SourceLocation LAngleLoc,
4997                                    ASTTemplateArgsPtr TemplateArgsIn,
4998                                    SourceLocation RAngleLoc);
4999
5000
5001  ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5002                                 SourceLocation TemplateKWLoc,
5003                                 LookupResult &R,
5004                                 bool RequiresADL,
5005                               const TemplateArgumentListInfo *TemplateArgs);
5006
5007  ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5008                                          SourceLocation TemplateKWLoc,
5009                               const DeclarationNameInfo &NameInfo,
5010                               const TemplateArgumentListInfo *TemplateArgs);
5011
5012  TemplateNameKind ActOnDependentTemplateName(Scope *S,
5013                                              CXXScopeSpec &SS,
5014                                              SourceLocation TemplateKWLoc,
5015                                              UnqualifiedId &Name,
5016                                              ParsedType ObjectType,
5017                                              bool EnteringContext,
5018                                              TemplateTy &Template);
5019
5020  DeclResult
5021  ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5022                                   SourceLocation KWLoc,
5023                                   SourceLocation ModulePrivateLoc,
5024                                   CXXScopeSpec &SS,
5025                                   TemplateTy Template,
5026                                   SourceLocation TemplateNameLoc,
5027                                   SourceLocation LAngleLoc,
5028                                   ASTTemplateArgsPtr TemplateArgs,
5029                                   SourceLocation RAngleLoc,
5030                                   AttributeList *Attr,
5031                                 MultiTemplateParamsArg TemplateParameterLists);
5032
5033  Decl *ActOnTemplateDeclarator(Scope *S,
5034                                MultiTemplateParamsArg TemplateParameterLists,
5035                                Declarator &D);
5036
5037  Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
5038                                  MultiTemplateParamsArg TemplateParameterLists,
5039                                        Declarator &D);
5040
5041  bool
5042  CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5043                                         TemplateSpecializationKind NewTSK,
5044                                         NamedDecl *PrevDecl,
5045                                         TemplateSpecializationKind PrevTSK,
5046                                         SourceLocation PrevPtOfInstantiation,
5047                                         bool &SuppressNew);
5048
5049  bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5050                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
5051                                                    LookupResult &Previous);
5052
5053  bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5054                         TemplateArgumentListInfo *ExplicitTemplateArgs,
5055                                           LookupResult &Previous);
5056  bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5057
5058  DeclResult
5059  ActOnExplicitInstantiation(Scope *S,
5060                             SourceLocation ExternLoc,
5061                             SourceLocation TemplateLoc,
5062                             unsigned TagSpec,
5063                             SourceLocation KWLoc,
5064                             const CXXScopeSpec &SS,
5065                             TemplateTy Template,
5066                             SourceLocation TemplateNameLoc,
5067                             SourceLocation LAngleLoc,
5068                             ASTTemplateArgsPtr TemplateArgs,
5069                             SourceLocation RAngleLoc,
5070                             AttributeList *Attr);
5071
5072  DeclResult
5073  ActOnExplicitInstantiation(Scope *S,
5074                             SourceLocation ExternLoc,
5075                             SourceLocation TemplateLoc,
5076                             unsigned TagSpec,
5077                             SourceLocation KWLoc,
5078                             CXXScopeSpec &SS,
5079                             IdentifierInfo *Name,
5080                             SourceLocation NameLoc,
5081                             AttributeList *Attr);
5082
5083  DeclResult ActOnExplicitInstantiation(Scope *S,
5084                                        SourceLocation ExternLoc,
5085                                        SourceLocation TemplateLoc,
5086                                        Declarator &D);
5087
5088  TemplateArgumentLoc
5089  SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5090                                          SourceLocation TemplateLoc,
5091                                          SourceLocation RAngleLoc,
5092                                          Decl *Param,
5093                          SmallVectorImpl<TemplateArgument> &Converted);
5094
5095  /// \brief Specifies the context in which a particular template
5096  /// argument is being checked.
5097  enum CheckTemplateArgumentKind {
5098    /// \brief The template argument was specified in the code or was
5099    /// instantiated with some deduced template arguments.
5100    CTAK_Specified,
5101
5102    /// \brief The template argument was deduced via template argument
5103    /// deduction.
5104    CTAK_Deduced,
5105
5106    /// \brief The template argument was deduced from an array bound
5107    /// via template argument deduction.
5108    CTAK_DeducedFromArrayBound
5109  };
5110
5111  bool CheckTemplateArgument(NamedDecl *Param,
5112                             const TemplateArgumentLoc &Arg,
5113                             NamedDecl *Template,
5114                             SourceLocation TemplateLoc,
5115                             SourceLocation RAngleLoc,
5116                             unsigned ArgumentPackIndex,
5117                           SmallVectorImpl<TemplateArgument> &Converted,
5118                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
5119
5120  /// \brief Check that the given template arguments can be be provided to
5121  /// the given template, converting the arguments along the way.
5122  ///
5123  /// \param Template The template to which the template arguments are being
5124  /// provided.
5125  ///
5126  /// \param TemplateLoc The location of the template name in the source.
5127  ///
5128  /// \param TemplateArgs The list of template arguments. If the template is
5129  /// a template template parameter, this function may extend the set of
5130  /// template arguments to also include substituted, defaulted template
5131  /// arguments.
5132  ///
5133  /// \param PartialTemplateArgs True if the list of template arguments is
5134  /// intentionally partial, e.g., because we're checking just the initial
5135  /// set of template arguments.
5136  ///
5137  /// \param Converted Will receive the converted, canonicalized template
5138  /// arguments.
5139  ///
5140  ///
5141  /// \param ExpansionIntoFixedList If non-NULL, will be set true to indicate
5142  /// when the template arguments contain a pack expansion that is being
5143  /// expanded into a fixed parameter list.
5144  ///
5145  /// \returns True if an error occurred, false otherwise.
5146  bool CheckTemplateArgumentList(TemplateDecl *Template,
5147                                 SourceLocation TemplateLoc,
5148                                 TemplateArgumentListInfo &TemplateArgs,
5149                                 bool PartialTemplateArgs,
5150                           SmallVectorImpl<TemplateArgument> &Converted,
5151                                 bool *ExpansionIntoFixedList = 0);
5152
5153  bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5154                                 const TemplateArgumentLoc &Arg,
5155                           SmallVectorImpl<TemplateArgument> &Converted);
5156
5157  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5158                             TypeSourceInfo *Arg);
5159  ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5160                                   QualType InstantiatedParamType, Expr *Arg,
5161                                   TemplateArgument &Converted,
5162                               CheckTemplateArgumentKind CTAK = CTAK_Specified);
5163  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5164                             const TemplateArgumentLoc &Arg,
5165                             unsigned ArgumentPackIndex);
5166
5167  ExprResult
5168  BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5169                                          QualType ParamType,
5170                                          SourceLocation Loc);
5171  ExprResult
5172  BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5173                                              SourceLocation Loc);
5174
5175  /// \brief Enumeration describing how template parameter lists are compared
5176  /// for equality.
5177  enum TemplateParameterListEqualKind {
5178    /// \brief We are matching the template parameter lists of two templates
5179    /// that might be redeclarations.
5180    ///
5181    /// \code
5182    /// template<typename T> struct X;
5183    /// template<typename T> struct X;
5184    /// \endcode
5185    TPL_TemplateMatch,
5186
5187    /// \brief We are matching the template parameter lists of two template
5188    /// template parameters as part of matching the template parameter lists
5189    /// of two templates that might be redeclarations.
5190    ///
5191    /// \code
5192    /// template<template<int I> class TT> struct X;
5193    /// template<template<int Value> class Other> struct X;
5194    /// \endcode
5195    TPL_TemplateTemplateParmMatch,
5196
5197    /// \brief We are matching the template parameter lists of a template
5198    /// template argument against the template parameter lists of a template
5199    /// template parameter.
5200    ///
5201    /// \code
5202    /// template<template<int Value> class Metafun> struct X;
5203    /// template<int Value> struct integer_c;
5204    /// X<integer_c> xic;
5205    /// \endcode
5206    TPL_TemplateTemplateArgumentMatch
5207  };
5208
5209  bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5210                                      TemplateParameterList *Old,
5211                                      bool Complain,
5212                                      TemplateParameterListEqualKind Kind,
5213                                      SourceLocation TemplateArgLoc
5214                                        = SourceLocation());
5215
5216  bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
5217
5218  /// \brief Called when the parser has parsed a C++ typename
5219  /// specifier, e.g., "typename T::type".
5220  ///
5221  /// \param S The scope in which this typename type occurs.
5222  /// \param TypenameLoc the location of the 'typename' keyword
5223  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5224  /// \param II the identifier we're retrieving (e.g., 'type' in the example).
5225  /// \param IdLoc the location of the identifier.
5226  TypeResult
5227  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5228                    const CXXScopeSpec &SS, const IdentifierInfo &II,
5229                    SourceLocation IdLoc);
5230
5231  /// \brief Called when the parser has parsed a C++ typename
5232  /// specifier that ends in a template-id, e.g.,
5233  /// "typename MetaFun::template apply<T1, T2>".
5234  ///
5235  /// \param S The scope in which this typename type occurs.
5236  /// \param TypenameLoc the location of the 'typename' keyword
5237  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5238  /// \param TemplateLoc the location of the 'template' keyword, if any.
5239  /// \param TemplateName The template name.
5240  /// \param TemplateNameLoc The location of the template name.
5241  /// \param LAngleLoc The location of the opening angle bracket  ('<').
5242  /// \param TemplateArgs The template arguments.
5243  /// \param RAngleLoc The location of the closing angle bracket  ('>').
5244  TypeResult
5245  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5246                    const CXXScopeSpec &SS,
5247                    SourceLocation TemplateLoc,
5248                    TemplateTy TemplateName,
5249                    SourceLocation TemplateNameLoc,
5250                    SourceLocation LAngleLoc,
5251                    ASTTemplateArgsPtr TemplateArgs,
5252                    SourceLocation RAngleLoc);
5253
5254  QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
5255                             SourceLocation KeywordLoc,
5256                             NestedNameSpecifierLoc QualifierLoc,
5257                             const IdentifierInfo &II,
5258                             SourceLocation IILoc);
5259
5260  TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5261                                                    SourceLocation Loc,
5262                                                    DeclarationName Name);
5263  bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
5264
5265  ExprResult RebuildExprInCurrentInstantiation(Expr *E);
5266  bool RebuildTemplateParamsInCurrentInstantiation(
5267                                                TemplateParameterList *Params);
5268
5269  std::string
5270  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5271                                  const TemplateArgumentList &Args);
5272
5273  std::string
5274  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5275                                  const TemplateArgument *Args,
5276                                  unsigned NumArgs);
5277
5278  //===--------------------------------------------------------------------===//
5279  // C++ Variadic Templates (C++0x [temp.variadic])
5280  //===--------------------------------------------------------------------===//
5281
5282  /// \brief The context in which an unexpanded parameter pack is
5283  /// being diagnosed.
5284  ///
5285  /// Note that the values of this enumeration line up with the first
5286  /// argument to the \c err_unexpanded_parameter_pack diagnostic.
5287  enum UnexpandedParameterPackContext {
5288    /// \brief An arbitrary expression.
5289    UPPC_Expression = 0,
5290
5291    /// \brief The base type of a class type.
5292    UPPC_BaseType,
5293
5294    /// \brief The type of an arbitrary declaration.
5295    UPPC_DeclarationType,
5296
5297    /// \brief The type of a data member.
5298    UPPC_DataMemberType,
5299
5300    /// \brief The size of a bit-field.
5301    UPPC_BitFieldWidth,
5302
5303    /// \brief The expression in a static assertion.
5304    UPPC_StaticAssertExpression,
5305
5306    /// \brief The fixed underlying type of an enumeration.
5307    UPPC_FixedUnderlyingType,
5308
5309    /// \brief The enumerator value.
5310    UPPC_EnumeratorValue,
5311
5312    /// \brief A using declaration.
5313    UPPC_UsingDeclaration,
5314
5315    /// \brief A friend declaration.
5316    UPPC_FriendDeclaration,
5317
5318    /// \brief A declaration qualifier.
5319    UPPC_DeclarationQualifier,
5320
5321    /// \brief An initializer.
5322    UPPC_Initializer,
5323
5324    /// \brief A default argument.
5325    UPPC_DefaultArgument,
5326
5327    /// \brief The type of a non-type template parameter.
5328    UPPC_NonTypeTemplateParameterType,
5329
5330    /// \brief The type of an exception.
5331    UPPC_ExceptionType,
5332
5333    /// \brief Partial specialization.
5334    UPPC_PartialSpecialization,
5335
5336    /// \brief Microsoft __if_exists.
5337    UPPC_IfExists,
5338
5339    /// \brief Microsoft __if_not_exists.
5340    UPPC_IfNotExists,
5341
5342    /// \brief Lambda expression.
5343    UPPC_Lambda,
5344
5345    /// \brief Block expression,
5346    UPPC_Block
5347};
5348
5349  /// \brief Diagnose unexpanded parameter packs.
5350  ///
5351  /// \param Loc The location at which we should emit the diagnostic.
5352  ///
5353  /// \param UPPC The context in which we are diagnosing unexpanded
5354  /// parameter packs.
5355  ///
5356  /// \param Unexpanded the set of unexpanded parameter packs.
5357  ///
5358  /// \returns true if an error occurred, false otherwise.
5359  bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
5360                                        UnexpandedParameterPackContext UPPC,
5361                                  ArrayRef<UnexpandedParameterPack> Unexpanded);
5362
5363  /// \brief If the given type contains an unexpanded parameter pack,
5364  /// diagnose the error.
5365  ///
5366  /// \param Loc The source location where a diagnostc should be emitted.
5367  ///
5368  /// \param T The type that is being checked for unexpanded parameter
5369  /// packs.
5370  ///
5371  /// \returns true if an error occurred, false otherwise.
5372  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
5373                                       UnexpandedParameterPackContext UPPC);
5374
5375  /// \brief If the given expression contains an unexpanded parameter
5376  /// pack, diagnose the error.
5377  ///
5378  /// \param E The expression that is being checked for unexpanded
5379  /// parameter packs.
5380  ///
5381  /// \returns true if an error occurred, false otherwise.
5382  bool DiagnoseUnexpandedParameterPack(Expr *E,
5383                       UnexpandedParameterPackContext UPPC = UPPC_Expression);
5384
5385  /// \brief If the given nested-name-specifier contains an unexpanded
5386  /// parameter pack, diagnose the error.
5387  ///
5388  /// \param SS The nested-name-specifier that is being checked for
5389  /// unexpanded parameter packs.
5390  ///
5391  /// \returns true if an error occurred, false otherwise.
5392  bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
5393                                       UnexpandedParameterPackContext UPPC);
5394
5395  /// \brief If the given name contains an unexpanded parameter pack,
5396  /// diagnose the error.
5397  ///
5398  /// \param NameInfo The name (with source location information) that
5399  /// is being checked for unexpanded parameter packs.
5400  ///
5401  /// \returns true if an error occurred, false otherwise.
5402  bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
5403                                       UnexpandedParameterPackContext UPPC);
5404
5405  /// \brief If the given template name contains an unexpanded parameter pack,
5406  /// diagnose the error.
5407  ///
5408  /// \param Loc The location of the template name.
5409  ///
5410  /// \param Template The template name that is being checked for unexpanded
5411  /// parameter packs.
5412  ///
5413  /// \returns true if an error occurred, false otherwise.
5414  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
5415                                       TemplateName Template,
5416                                       UnexpandedParameterPackContext UPPC);
5417
5418  /// \brief If the given template argument contains an unexpanded parameter
5419  /// pack, diagnose the error.
5420  ///
5421  /// \param Arg The template argument that is being checked for unexpanded
5422  /// parameter packs.
5423  ///
5424  /// \returns true if an error occurred, false otherwise.
5425  bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
5426                                       UnexpandedParameterPackContext UPPC);
5427
5428  /// \brief Collect the set of unexpanded parameter packs within the given
5429  /// template argument.
5430  ///
5431  /// \param Arg The template argument that will be traversed to find
5432  /// unexpanded parameter packs.
5433  void collectUnexpandedParameterPacks(TemplateArgument Arg,
5434                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5435
5436  /// \brief Collect the set of unexpanded parameter packs within the given
5437  /// template argument.
5438  ///
5439  /// \param Arg The template argument that will be traversed to find
5440  /// unexpanded parameter packs.
5441  void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
5442                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5443
5444  /// \brief Collect the set of unexpanded parameter packs within the given
5445  /// type.
5446  ///
5447  /// \param T The type that will be traversed to find
5448  /// unexpanded parameter packs.
5449  void collectUnexpandedParameterPacks(QualType T,
5450                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5451
5452  /// \brief Collect the set of unexpanded parameter packs within the given
5453  /// type.
5454  ///
5455  /// \param TL The type that will be traversed to find
5456  /// unexpanded parameter packs.
5457  void collectUnexpandedParameterPacks(TypeLoc TL,
5458                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5459
5460  /// \brief Collect the set of unexpanded parameter packs within the given
5461  /// nested-name-specifier.
5462  ///
5463  /// \param SS The nested-name-specifier that will be traversed to find
5464  /// unexpanded parameter packs.
5465  void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
5466                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5467
5468  /// \brief Collect the set of unexpanded parameter packs within the given
5469  /// name.
5470  ///
5471  /// \param NameInfo The name that will be traversed to find
5472  /// unexpanded parameter packs.
5473  void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
5474                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5475
5476  /// \brief Invoked when parsing a template argument followed by an
5477  /// ellipsis, which creates a pack expansion.
5478  ///
5479  /// \param Arg The template argument preceding the ellipsis, which
5480  /// may already be invalid.
5481  ///
5482  /// \param EllipsisLoc The location of the ellipsis.
5483  ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
5484                                            SourceLocation EllipsisLoc);
5485
5486  /// \brief Invoked when parsing a type followed by an ellipsis, which
5487  /// creates a pack expansion.
5488  ///
5489  /// \param Type The type preceding the ellipsis, which will become
5490  /// the pattern of the pack expansion.
5491  ///
5492  /// \param EllipsisLoc The location of the ellipsis.
5493  TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
5494
5495  /// \brief Construct a pack expansion type from the pattern of the pack
5496  /// expansion.
5497  TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
5498                                     SourceLocation EllipsisLoc,
5499                                     Optional<unsigned> NumExpansions);
5500
5501  /// \brief Construct a pack expansion type from the pattern of the pack
5502  /// expansion.
5503  QualType CheckPackExpansion(QualType Pattern,
5504                              SourceRange PatternRange,
5505                              SourceLocation EllipsisLoc,
5506                              Optional<unsigned> NumExpansions);
5507
5508  /// \brief Invoked when parsing an expression followed by an ellipsis, which
5509  /// creates a pack expansion.
5510  ///
5511  /// \param Pattern The expression preceding the ellipsis, which will become
5512  /// the pattern of the pack expansion.
5513  ///
5514  /// \param EllipsisLoc The location of the ellipsis.
5515  ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
5516
5517  /// \brief Invoked when parsing an expression followed by an ellipsis, which
5518  /// creates a pack expansion.
5519  ///
5520  /// \param Pattern The expression preceding the ellipsis, which will become
5521  /// the pattern of the pack expansion.
5522  ///
5523  /// \param EllipsisLoc The location of the ellipsis.
5524  ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
5525                                Optional<unsigned> NumExpansions);
5526
5527  /// \brief Determine whether we could expand a pack expansion with the
5528  /// given set of parameter packs into separate arguments by repeatedly
5529  /// transforming the pattern.
5530  ///
5531  /// \param EllipsisLoc The location of the ellipsis that identifies the
5532  /// pack expansion.
5533  ///
5534  /// \param PatternRange The source range that covers the entire pattern of
5535  /// the pack expansion.
5536  ///
5537  /// \param Unexpanded The set of unexpanded parameter packs within the
5538  /// pattern.
5539  ///
5540  /// \param ShouldExpand Will be set to \c true if the transformer should
5541  /// expand the corresponding pack expansions into separate arguments. When
5542  /// set, \c NumExpansions must also be set.
5543  ///
5544  /// \param RetainExpansion Whether the caller should add an unexpanded
5545  /// pack expansion after all of the expanded arguments. This is used
5546  /// when extending explicitly-specified template argument packs per
5547  /// C++0x [temp.arg.explicit]p9.
5548  ///
5549  /// \param NumExpansions The number of separate arguments that will be in
5550  /// the expanded form of the corresponding pack expansion. This is both an
5551  /// input and an output parameter, which can be set by the caller if the
5552  /// number of expansions is known a priori (e.g., due to a prior substitution)
5553  /// and will be set by the callee when the number of expansions is known.
5554  /// The callee must set this value when \c ShouldExpand is \c true; it may
5555  /// set this value in other cases.
5556  ///
5557  /// \returns true if an error occurred (e.g., because the parameter packs
5558  /// are to be instantiated with arguments of different lengths), false
5559  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
5560  /// must be set.
5561  bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
5562                                       SourceRange PatternRange,
5563                             ArrayRef<UnexpandedParameterPack> Unexpanded,
5564                             const MultiLevelTemplateArgumentList &TemplateArgs,
5565                                       bool &ShouldExpand,
5566                                       bool &RetainExpansion,
5567                                       Optional<unsigned> &NumExpansions);
5568
5569  /// \brief Determine the number of arguments in the given pack expansion
5570  /// type.
5571  ///
5572  /// This routine assumes that the number of arguments in the expansion is
5573  /// consistent across all of the unexpanded parameter packs in its pattern.
5574  ///
5575  /// Returns an empty Optional if the type can't be expanded.
5576  Optional<unsigned> getNumArgumentsInExpansion(QualType T,
5577      const MultiLevelTemplateArgumentList &TemplateArgs);
5578
5579  /// \brief Determine whether the given declarator contains any unexpanded
5580  /// parameter packs.
5581  ///
5582  /// This routine is used by the parser to disambiguate function declarators
5583  /// with an ellipsis prior to the ')', e.g.,
5584  ///
5585  /// \code
5586  ///   void f(T...);
5587  /// \endcode
5588  ///
5589  /// To determine whether we have an (unnamed) function parameter pack or
5590  /// a variadic function.
5591  ///
5592  /// \returns true if the declarator contains any unexpanded parameter packs,
5593  /// false otherwise.
5594  bool containsUnexpandedParameterPacks(Declarator &D);
5595
5596  //===--------------------------------------------------------------------===//
5597  // C++ Template Argument Deduction (C++ [temp.deduct])
5598  //===--------------------------------------------------------------------===//
5599
5600  /// \brief Describes the result of template argument deduction.
5601  ///
5602  /// The TemplateDeductionResult enumeration describes the result of
5603  /// template argument deduction, as returned from
5604  /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
5605  /// structure provides additional information about the results of
5606  /// template argument deduction, e.g., the deduced template argument
5607  /// list (if successful) or the specific template parameters or
5608  /// deduced arguments that were involved in the failure.
5609  enum TemplateDeductionResult {
5610    /// \brief Template argument deduction was successful.
5611    TDK_Success = 0,
5612    /// \brief The declaration was invalid; do nothing.
5613    TDK_Invalid,
5614    /// \brief Template argument deduction exceeded the maximum template
5615    /// instantiation depth (which has already been diagnosed).
5616    TDK_InstantiationDepth,
5617    /// \brief Template argument deduction did not deduce a value
5618    /// for every template parameter.
5619    TDK_Incomplete,
5620    /// \brief Template argument deduction produced inconsistent
5621    /// deduced values for the given template parameter.
5622    TDK_Inconsistent,
5623    /// \brief Template argument deduction failed due to inconsistent
5624    /// cv-qualifiers on a template parameter type that would
5625    /// otherwise be deduced, e.g., we tried to deduce T in "const T"
5626    /// but were given a non-const "X".
5627    TDK_Underqualified,
5628    /// \brief Substitution of the deduced template argument values
5629    /// resulted in an error.
5630    TDK_SubstitutionFailure,
5631    /// \brief A non-depnedent component of the parameter did not match the
5632    /// corresponding component of the argument.
5633    TDK_NonDeducedMismatch,
5634    /// \brief When performing template argument deduction for a function
5635    /// template, there were too many call arguments.
5636    TDK_TooManyArguments,
5637    /// \brief When performing template argument deduction for a function
5638    /// template, there were too few call arguments.
5639    TDK_TooFewArguments,
5640    /// \brief The explicitly-specified template arguments were not valid
5641    /// template arguments for the given template.
5642    TDK_InvalidExplicitArguments,
5643    /// \brief The arguments included an overloaded function name that could
5644    /// not be resolved to a suitable function.
5645    TDK_FailedOverloadResolution,
5646    /// \brief Deduction failed; that's all we know.
5647    TDK_MiscellaneousDeductionFailure
5648  };
5649
5650  TemplateDeductionResult
5651  DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
5652                          const TemplateArgumentList &TemplateArgs,
5653                          sema::TemplateDeductionInfo &Info);
5654
5655  TemplateDeductionResult
5656  SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5657                              TemplateArgumentListInfo &ExplicitTemplateArgs,
5658                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5659                                 SmallVectorImpl<QualType> &ParamTypes,
5660                                      QualType *FunctionType,
5661                                      sema::TemplateDeductionInfo &Info);
5662
5663  /// brief A function argument from which we performed template argument
5664  // deduction for a call.
5665  struct OriginalCallArg {
5666    OriginalCallArg(QualType OriginalParamType,
5667                    unsigned ArgIdx,
5668                    QualType OriginalArgType)
5669      : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
5670        OriginalArgType(OriginalArgType) { }
5671
5672    QualType OriginalParamType;
5673    unsigned ArgIdx;
5674    QualType OriginalArgType;
5675  };
5676
5677  TemplateDeductionResult
5678  FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
5679                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5680                                  unsigned NumExplicitlySpecified,
5681                                  FunctionDecl *&Specialization,
5682                                  sema::TemplateDeductionInfo &Info,
5683           SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0);
5684
5685  TemplateDeductionResult
5686  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5687                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5688                          ArrayRef<Expr *> Args,
5689                          FunctionDecl *&Specialization,
5690                          sema::TemplateDeductionInfo &Info);
5691
5692  TemplateDeductionResult
5693  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5694                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5695                          QualType ArgFunctionType,
5696                          FunctionDecl *&Specialization,
5697                          sema::TemplateDeductionInfo &Info,
5698                          bool InOverloadResolution = false);
5699
5700  TemplateDeductionResult
5701  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5702                          QualType ToType,
5703                          CXXConversionDecl *&Specialization,
5704                          sema::TemplateDeductionInfo &Info);
5705
5706  TemplateDeductionResult
5707  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5708                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5709                          FunctionDecl *&Specialization,
5710                          sema::TemplateDeductionInfo &Info,
5711                          bool InOverloadResolution = false);
5712
5713  /// \brief Result type of DeduceAutoType.
5714  enum DeduceAutoResult {
5715    DAR_Succeeded,
5716    DAR_Failed,
5717    DAR_FailedAlreadyDiagnosed
5718  };
5719
5720  DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
5721                                  QualType &Result);
5722  DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
5723                                  QualType &Result);
5724  QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
5725  void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
5726  bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
5727                        bool Diagnose = true);
5728
5729  bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
5730                                        SourceLocation ReturnLoc,
5731                                        Expr *&RetExpr, AutoType *AT);
5732
5733  FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
5734                                                   FunctionTemplateDecl *FT2,
5735                                                   SourceLocation Loc,
5736                                           TemplatePartialOrderingContext TPOC,
5737                                                   unsigned NumCallArguments);
5738  UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin,
5739                                           UnresolvedSetIterator SEnd,
5740                                           TemplatePartialOrderingContext TPOC,
5741                                           unsigned NumCallArguments,
5742                                           SourceLocation Loc,
5743                                           const PartialDiagnostic &NoneDiag,
5744                                           const PartialDiagnostic &AmbigDiag,
5745                                        const PartialDiagnostic &CandidateDiag,
5746                                        bool Complain = true,
5747                                        QualType TargetType = QualType());
5748
5749  ClassTemplatePartialSpecializationDecl *
5750  getMoreSpecializedPartialSpecialization(
5751                                  ClassTemplatePartialSpecializationDecl *PS1,
5752                                  ClassTemplatePartialSpecializationDecl *PS2,
5753                                  SourceLocation Loc);
5754
5755  void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5756                                  bool OnlyDeduced,
5757                                  unsigned Depth,
5758                                  llvm::SmallBitVector &Used);
5759  void MarkDeducedTemplateParameters(
5760                                  const FunctionTemplateDecl *FunctionTemplate,
5761                                  llvm::SmallBitVector &Deduced) {
5762    return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
5763  }
5764  static void MarkDeducedTemplateParameters(ASTContext &Ctx,
5765                                  const FunctionTemplateDecl *FunctionTemplate,
5766                                  llvm::SmallBitVector &Deduced);
5767
5768  //===--------------------------------------------------------------------===//
5769  // C++ Template Instantiation
5770  //
5771
5772  MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
5773                                     const TemplateArgumentList *Innermost = 0,
5774                                                bool RelativeToPrimary = false,
5775                                               const FunctionDecl *Pattern = 0);
5776
5777  /// \brief A template instantiation that is currently in progress.
5778  struct ActiveTemplateInstantiation {
5779    /// \brief The kind of template instantiation we are performing
5780    enum InstantiationKind {
5781      /// We are instantiating a template declaration. The entity is
5782      /// the declaration we're instantiating (e.g., a CXXRecordDecl).
5783      TemplateInstantiation,
5784
5785      /// We are instantiating a default argument for a template
5786      /// parameter. The Entity is the template, and
5787      /// TemplateArgs/NumTemplateArguments provides the template
5788      /// arguments as specified.
5789      /// FIXME: Use a TemplateArgumentList
5790      DefaultTemplateArgumentInstantiation,
5791
5792      /// We are instantiating a default argument for a function.
5793      /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
5794      /// provides the template arguments as specified.
5795      DefaultFunctionArgumentInstantiation,
5796
5797      /// We are substituting explicit template arguments provided for
5798      /// a function template. The entity is a FunctionTemplateDecl.
5799      ExplicitTemplateArgumentSubstitution,
5800
5801      /// We are substituting template argument determined as part of
5802      /// template argument deduction for either a class template
5803      /// partial specialization or a function template. The
5804      /// Entity is either a ClassTemplatePartialSpecializationDecl or
5805      /// a FunctionTemplateDecl.
5806      DeducedTemplateArgumentSubstitution,
5807
5808      /// We are substituting prior template arguments into a new
5809      /// template parameter. The template parameter itself is either a
5810      /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
5811      PriorTemplateArgumentSubstitution,
5812
5813      /// We are checking the validity of a default template argument that
5814      /// has been used when naming a template-id.
5815      DefaultTemplateArgumentChecking,
5816
5817      /// We are instantiating the exception specification for a function
5818      /// template which was deferred until it was needed.
5819      ExceptionSpecInstantiation
5820    } Kind;
5821
5822    /// \brief The point of instantiation within the source code.
5823    SourceLocation PointOfInstantiation;
5824
5825    /// \brief The template (or partial specialization) in which we are
5826    /// performing the instantiation, for substitutions of prior template
5827    /// arguments.
5828    NamedDecl *Template;
5829
5830    /// \brief The entity that is being instantiated.
5831    Decl *Entity;
5832
5833    /// \brief The list of template arguments we are substituting, if they
5834    /// are not part of the entity.
5835    const TemplateArgument *TemplateArgs;
5836
5837    /// \brief The number of template arguments in TemplateArgs.
5838    unsigned NumTemplateArgs;
5839
5840    /// \brief The template deduction info object associated with the
5841    /// substitution or checking of explicit or deduced template arguments.
5842    sema::TemplateDeductionInfo *DeductionInfo;
5843
5844    /// \brief The source range that covers the construct that cause
5845    /// the instantiation, e.g., the template-id that causes a class
5846    /// template instantiation.
5847    SourceRange InstantiationRange;
5848
5849    ActiveTemplateInstantiation()
5850      : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
5851        NumTemplateArgs(0), DeductionInfo(0) {}
5852
5853    /// \brief Determines whether this template is an actual instantiation
5854    /// that should be counted toward the maximum instantiation depth.
5855    bool isInstantiationRecord() const;
5856
5857    friend bool operator==(const ActiveTemplateInstantiation &X,
5858                           const ActiveTemplateInstantiation &Y) {
5859      if (X.Kind != Y.Kind)
5860        return false;
5861
5862      if (X.Entity != Y.Entity)
5863        return false;
5864
5865      switch (X.Kind) {
5866      case TemplateInstantiation:
5867      case ExceptionSpecInstantiation:
5868        return true;
5869
5870      case PriorTemplateArgumentSubstitution:
5871      case DefaultTemplateArgumentChecking:
5872        return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
5873
5874      case DefaultTemplateArgumentInstantiation:
5875      case ExplicitTemplateArgumentSubstitution:
5876      case DeducedTemplateArgumentSubstitution:
5877      case DefaultFunctionArgumentInstantiation:
5878        return X.TemplateArgs == Y.TemplateArgs;
5879
5880      }
5881
5882      llvm_unreachable("Invalid InstantiationKind!");
5883    }
5884
5885    friend bool operator!=(const ActiveTemplateInstantiation &X,
5886                           const ActiveTemplateInstantiation &Y) {
5887      return !(X == Y);
5888    }
5889  };
5890
5891  /// \brief List of active template instantiations.
5892  ///
5893  /// This vector is treated as a stack. As one template instantiation
5894  /// requires another template instantiation, additional
5895  /// instantiations are pushed onto the stack up to a
5896  /// user-configurable limit LangOptions::InstantiationDepth.
5897  SmallVector<ActiveTemplateInstantiation, 16>
5898    ActiveTemplateInstantiations;
5899
5900  /// \brief Whether we are in a SFINAE context that is not associated with
5901  /// template instantiation.
5902  ///
5903  /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
5904  /// of a template instantiation or template argument deduction.
5905  bool InNonInstantiationSFINAEContext;
5906
5907  /// \brief The number of ActiveTemplateInstantiation entries in
5908  /// \c ActiveTemplateInstantiations that are not actual instantiations and,
5909  /// therefore, should not be counted as part of the instantiation depth.
5910  unsigned NonInstantiationEntries;
5911
5912  /// \brief The last template from which a template instantiation
5913  /// error or warning was produced.
5914  ///
5915  /// This value is used to suppress printing of redundant template
5916  /// instantiation backtraces when there are multiple errors in the
5917  /// same instantiation. FIXME: Does this belong in Sema? It's tough
5918  /// to implement it anywhere else.
5919  ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
5920
5921  /// \brief The current index into pack expansion arguments that will be
5922  /// used for substitution of parameter packs.
5923  ///
5924  /// The pack expansion index will be -1 to indicate that parameter packs
5925  /// should be instantiated as themselves. Otherwise, the index specifies
5926  /// which argument within the parameter pack will be used for substitution.
5927  int ArgumentPackSubstitutionIndex;
5928
5929  /// \brief RAII object used to change the argument pack substitution index
5930  /// within a \c Sema object.
5931  ///
5932  /// See \c ArgumentPackSubstitutionIndex for more information.
5933  class ArgumentPackSubstitutionIndexRAII {
5934    Sema &Self;
5935    int OldSubstitutionIndex;
5936
5937  public:
5938    ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
5939      : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
5940      Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
5941    }
5942
5943    ~ArgumentPackSubstitutionIndexRAII() {
5944      Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
5945    }
5946  };
5947
5948  friend class ArgumentPackSubstitutionRAII;
5949
5950  /// \brief The stack of calls expression undergoing template instantiation.
5951  ///
5952  /// The top of this stack is used by a fixit instantiating unresolved
5953  /// function calls to fix the AST to match the textual change it prints.
5954  SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
5955
5956  /// \brief For each declaration that involved template argument deduction, the
5957  /// set of diagnostics that were suppressed during that template argument
5958  /// deduction.
5959  ///
5960  /// FIXME: Serialize this structure to the AST file.
5961  llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
5962    SuppressedDiagnostics;
5963
5964  /// \brief A stack object to be created when performing template
5965  /// instantiation.
5966  ///
5967  /// Construction of an object of type \c InstantiatingTemplate
5968  /// pushes the current instantiation onto the stack of active
5969  /// instantiations. If the size of this stack exceeds the maximum
5970  /// number of recursive template instantiations, construction
5971  /// produces an error and evaluates true.
5972  ///
5973  /// Destruction of this object will pop the named instantiation off
5974  /// the stack.
5975  struct InstantiatingTemplate {
5976    /// \brief Note that we are instantiating a class template,
5977    /// function template, or a member thereof.
5978    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5979                          Decl *Entity,
5980                          SourceRange InstantiationRange = SourceRange());
5981
5982    struct ExceptionSpecification {};
5983    /// \brief Note that we are instantiating an exception specification
5984    /// of a function template.
5985    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5986                          FunctionDecl *Entity, ExceptionSpecification,
5987                          SourceRange InstantiationRange = SourceRange());
5988
5989    /// \brief Note that we are instantiating a default argument in a
5990    /// template-id.
5991    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5992                          TemplateDecl *Template,
5993                          ArrayRef<TemplateArgument> TemplateArgs,
5994                          SourceRange InstantiationRange = SourceRange());
5995
5996    /// \brief Note that we are instantiating a default argument in a
5997    /// template-id.
5998    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5999                          FunctionTemplateDecl *FunctionTemplate,
6000                          ArrayRef<TemplateArgument> TemplateArgs,
6001                          ActiveTemplateInstantiation::InstantiationKind Kind,
6002                          sema::TemplateDeductionInfo &DeductionInfo,
6003                          SourceRange InstantiationRange = SourceRange());
6004
6005    /// \brief Note that we are instantiating as part of template
6006    /// argument deduction for a class template partial
6007    /// specialization.
6008    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6009                          ClassTemplatePartialSpecializationDecl *PartialSpec,
6010                          ArrayRef<TemplateArgument> TemplateArgs,
6011                          sema::TemplateDeductionInfo &DeductionInfo,
6012                          SourceRange InstantiationRange = SourceRange());
6013
6014    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6015                          ParmVarDecl *Param,
6016                          ArrayRef<TemplateArgument> TemplateArgs,
6017                          SourceRange InstantiationRange = SourceRange());
6018
6019    /// \brief Note that we are substituting prior template arguments into a
6020    /// non-type or template template parameter.
6021    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6022                          NamedDecl *Template,
6023                          NonTypeTemplateParmDecl *Param,
6024                          ArrayRef<TemplateArgument> TemplateArgs,
6025                          SourceRange InstantiationRange);
6026
6027    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6028                          NamedDecl *Template,
6029                          TemplateTemplateParmDecl *Param,
6030                          ArrayRef<TemplateArgument> TemplateArgs,
6031                          SourceRange InstantiationRange);
6032
6033    /// \brief Note that we are checking the default template argument
6034    /// against the template parameter for a given template-id.
6035    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6036                          TemplateDecl *Template,
6037                          NamedDecl *Param,
6038                          ArrayRef<TemplateArgument> TemplateArgs,
6039                          SourceRange InstantiationRange);
6040
6041
6042    /// \brief Note that we have finished instantiating this template.
6043    void Clear();
6044
6045    ~InstantiatingTemplate() { Clear(); }
6046
6047    /// \brief Determines whether we have exceeded the maximum
6048    /// recursive template instantiations.
6049    LLVM_EXPLICIT operator bool() const { return Invalid; }
6050
6051  private:
6052    Sema &SemaRef;
6053    bool Invalid;
6054    bool SavedInNonInstantiationSFINAEContext;
6055    bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6056                                 SourceRange InstantiationRange);
6057
6058    InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6059
6060    InstantiatingTemplate&
6061    operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6062  };
6063
6064  void PrintInstantiationStack();
6065
6066  /// \brief Determines whether we are currently in a context where
6067  /// template argument substitution failures are not considered
6068  /// errors.
6069  ///
6070  /// \returns An empty \c Optional if we're not in a SFINAE context.
6071  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6072  /// template-deduction context object, which can be used to capture
6073  /// diagnostics that will be suppressed.
6074  Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6075
6076  /// \brief Determines whether we are currently in a context that
6077  /// is not evaluated as per C++ [expr] p5.
6078  bool isUnevaluatedContext() const {
6079    assert(!ExprEvalContexts.empty() &&
6080           "Must be in an expression evaluation context");
6081    return ExprEvalContexts.back().isUnevaluated();
6082  }
6083
6084  /// \brief RAII class used to determine whether SFINAE has
6085  /// trapped any errors that occur during template argument
6086  /// deduction.`
6087  class SFINAETrap {
6088    Sema &SemaRef;
6089    unsigned PrevSFINAEErrors;
6090    bool PrevInNonInstantiationSFINAEContext;
6091    bool PrevAccessCheckingSFINAE;
6092
6093  public:
6094    explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6095      : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6096        PrevInNonInstantiationSFINAEContext(
6097                                      SemaRef.InNonInstantiationSFINAEContext),
6098        PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6099    {
6100      if (!SemaRef.isSFINAEContext())
6101        SemaRef.InNonInstantiationSFINAEContext = true;
6102      SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6103    }
6104
6105    ~SFINAETrap() {
6106      SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6107      SemaRef.InNonInstantiationSFINAEContext
6108        = PrevInNonInstantiationSFINAEContext;
6109      SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6110    }
6111
6112    /// \brief Determine whether any SFINAE errors have been trapped.
6113    bool hasErrorOccurred() const {
6114      return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6115    }
6116  };
6117
6118  /// \brief The current instantiation scope used to store local
6119  /// variables.
6120  LocalInstantiationScope *CurrentInstantiationScope;
6121
6122  /// \brief The number of typos corrected by CorrectTypo.
6123  unsigned TyposCorrected;
6124
6125  typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
6126    UnqualifiedTyposCorrectedMap;
6127
6128  /// \brief A cache containing the results of typo correction for unqualified
6129  /// name lookup.
6130  ///
6131  /// The string is the string that we corrected to (which may be empty, if
6132  /// there was no correction), while the boolean will be true when the
6133  /// string represents a keyword.
6134  UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
6135
6136  /// \brief Worker object for performing CFG-based warnings.
6137  sema::AnalysisBasedWarnings AnalysisWarnings;
6138
6139  /// \brief An entity for which implicit template instantiation is required.
6140  ///
6141  /// The source location associated with the declaration is the first place in
6142  /// the source code where the declaration was "used". It is not necessarily
6143  /// the point of instantiation (which will be either before or after the
6144  /// namespace-scope declaration that triggered this implicit instantiation),
6145  /// However, it is the location that diagnostics should generally refer to,
6146  /// because users will need to know what code triggered the instantiation.
6147  typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
6148
6149  /// \brief The queue of implicit template instantiations that are required
6150  /// but have not yet been performed.
6151  std::deque<PendingImplicitInstantiation> PendingInstantiations;
6152
6153  /// \brief The queue of implicit template instantiations that are required
6154  /// and must be performed within the current local scope.
6155  ///
6156  /// This queue is only used for member functions of local classes in
6157  /// templates, which must be instantiated in the same scope as their
6158  /// enclosing function, so that they can reference function-local
6159  /// types, static variables, enumerators, etc.
6160  std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
6161
6162  void PerformPendingInstantiations(bool LocalOnly = false);
6163
6164  TypeSourceInfo *SubstType(TypeSourceInfo *T,
6165                            const MultiLevelTemplateArgumentList &TemplateArgs,
6166                            SourceLocation Loc, DeclarationName Entity);
6167
6168  QualType SubstType(QualType T,
6169                     const MultiLevelTemplateArgumentList &TemplateArgs,
6170                     SourceLocation Loc, DeclarationName Entity);
6171
6172  TypeSourceInfo *SubstType(TypeLoc TL,
6173                            const MultiLevelTemplateArgumentList &TemplateArgs,
6174                            SourceLocation Loc, DeclarationName Entity);
6175
6176  TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
6177                            const MultiLevelTemplateArgumentList &TemplateArgs,
6178                                        SourceLocation Loc,
6179                                        DeclarationName Entity,
6180                                        CXXRecordDecl *ThisContext,
6181                                        unsigned ThisTypeQuals);
6182  ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
6183                            const MultiLevelTemplateArgumentList &TemplateArgs,
6184                                int indexAdjustment,
6185                                Optional<unsigned> NumExpansions,
6186                                bool ExpectParameterPack);
6187  bool SubstParmTypes(SourceLocation Loc,
6188                      ParmVarDecl **Params, unsigned NumParams,
6189                      const MultiLevelTemplateArgumentList &TemplateArgs,
6190                      SmallVectorImpl<QualType> &ParamTypes,
6191                      SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
6192  ExprResult SubstExpr(Expr *E,
6193                       const MultiLevelTemplateArgumentList &TemplateArgs);
6194
6195  /// \brief Substitute the given template arguments into a list of
6196  /// expressions, expanding pack expansions if required.
6197  ///
6198  /// \param Exprs The list of expressions to substitute into.
6199  ///
6200  /// \param NumExprs The number of expressions in \p Exprs.
6201  ///
6202  /// \param IsCall Whether this is some form of call, in which case
6203  /// default arguments will be dropped.
6204  ///
6205  /// \param TemplateArgs The set of template arguments to substitute.
6206  ///
6207  /// \param Outputs Will receive all of the substituted arguments.
6208  ///
6209  /// \returns true if an error occurred, false otherwise.
6210  bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
6211                  const MultiLevelTemplateArgumentList &TemplateArgs,
6212                  SmallVectorImpl<Expr *> &Outputs);
6213
6214  StmtResult SubstStmt(Stmt *S,
6215                       const MultiLevelTemplateArgumentList &TemplateArgs);
6216
6217  Decl *SubstDecl(Decl *D, DeclContext *Owner,
6218                  const MultiLevelTemplateArgumentList &TemplateArgs);
6219
6220  ExprResult SubstInitializer(Expr *E,
6221                       const MultiLevelTemplateArgumentList &TemplateArgs,
6222                       bool CXXDirectInit);
6223
6224  bool
6225  SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
6226                      CXXRecordDecl *Pattern,
6227                      const MultiLevelTemplateArgumentList &TemplateArgs);
6228
6229  bool
6230  InstantiateClass(SourceLocation PointOfInstantiation,
6231                   CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
6232                   const MultiLevelTemplateArgumentList &TemplateArgs,
6233                   TemplateSpecializationKind TSK,
6234                   bool Complain = true);
6235
6236  bool InstantiateEnum(SourceLocation PointOfInstantiation,
6237                       EnumDecl *Instantiation, EnumDecl *Pattern,
6238                       const MultiLevelTemplateArgumentList &TemplateArgs,
6239                       TemplateSpecializationKind TSK);
6240
6241  struct LateInstantiatedAttribute {
6242    const Attr *TmplAttr;
6243    LocalInstantiationScope *Scope;
6244    Decl *NewDecl;
6245
6246    LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
6247                              Decl *D)
6248      : TmplAttr(A), Scope(S), NewDecl(D)
6249    { }
6250  };
6251  typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
6252
6253  void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
6254                        const Decl *Pattern, Decl *Inst,
6255                        LateInstantiatedAttrVec *LateAttrs = 0,
6256                        LocalInstantiationScope *OuterMostScope = 0);
6257
6258  bool
6259  InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
6260                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
6261                           TemplateSpecializationKind TSK,
6262                           bool Complain = true);
6263
6264  void InstantiateClassMembers(SourceLocation PointOfInstantiation,
6265                               CXXRecordDecl *Instantiation,
6266                            const MultiLevelTemplateArgumentList &TemplateArgs,
6267                               TemplateSpecializationKind TSK);
6268
6269  void InstantiateClassTemplateSpecializationMembers(
6270                                          SourceLocation PointOfInstantiation,
6271                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
6272                                                TemplateSpecializationKind TSK);
6273
6274  NestedNameSpecifierLoc
6275  SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
6276                           const MultiLevelTemplateArgumentList &TemplateArgs);
6277
6278  DeclarationNameInfo
6279  SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
6280                           const MultiLevelTemplateArgumentList &TemplateArgs);
6281  TemplateName
6282  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
6283                    SourceLocation Loc,
6284                    const MultiLevelTemplateArgumentList &TemplateArgs);
6285  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
6286             TemplateArgumentListInfo &Result,
6287             const MultiLevelTemplateArgumentList &TemplateArgs);
6288
6289  void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
6290                                FunctionDecl *Function);
6291  void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
6292                                     FunctionDecl *Function,
6293                                     bool Recursive = false,
6294                                     bool DefinitionRequired = false);
6295  void InstantiateStaticDataMemberDefinition(
6296                                     SourceLocation PointOfInstantiation,
6297                                     VarDecl *Var,
6298                                     bool Recursive = false,
6299                                     bool DefinitionRequired = false);
6300
6301  void InstantiateMemInitializers(CXXConstructorDecl *New,
6302                                  const CXXConstructorDecl *Tmpl,
6303                            const MultiLevelTemplateArgumentList &TemplateArgs);
6304
6305  NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6306                          const MultiLevelTemplateArgumentList &TemplateArgs);
6307  DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
6308                          const MultiLevelTemplateArgumentList &TemplateArgs);
6309
6310  // Objective-C declarations.
6311  enum ObjCContainerKind {
6312    OCK_None = -1,
6313    OCK_Interface = 0,
6314    OCK_Protocol,
6315    OCK_Category,
6316    OCK_ClassExtension,
6317    OCK_Implementation,
6318    OCK_CategoryImplementation
6319  };
6320  ObjCContainerKind getObjCContainerKind() const;
6321
6322  Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
6323                                 IdentifierInfo *ClassName,
6324                                 SourceLocation ClassLoc,
6325                                 IdentifierInfo *SuperName,
6326                                 SourceLocation SuperLoc,
6327                                 Decl * const *ProtoRefs,
6328                                 unsigned NumProtoRefs,
6329                                 const SourceLocation *ProtoLocs,
6330                                 SourceLocation EndProtoLoc,
6331                                 AttributeList *AttrList);
6332
6333  Decl *ActOnCompatibilityAlias(
6334                    SourceLocation AtCompatibilityAliasLoc,
6335                    IdentifierInfo *AliasName,  SourceLocation AliasLocation,
6336                    IdentifierInfo *ClassName, SourceLocation ClassLocation);
6337
6338  bool CheckForwardProtocolDeclarationForCircularDependency(
6339    IdentifierInfo *PName,
6340    SourceLocation &PLoc, SourceLocation PrevLoc,
6341    const ObjCList<ObjCProtocolDecl> &PList);
6342
6343  Decl *ActOnStartProtocolInterface(
6344                    SourceLocation AtProtoInterfaceLoc,
6345                    IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
6346                    Decl * const *ProtoRefNames, unsigned NumProtoRefs,
6347                    const SourceLocation *ProtoLocs,
6348                    SourceLocation EndProtoLoc,
6349                    AttributeList *AttrList);
6350
6351  Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
6352                                    IdentifierInfo *ClassName,
6353                                    SourceLocation ClassLoc,
6354                                    IdentifierInfo *CategoryName,
6355                                    SourceLocation CategoryLoc,
6356                                    Decl * const *ProtoRefs,
6357                                    unsigned NumProtoRefs,
6358                                    const SourceLocation *ProtoLocs,
6359                                    SourceLocation EndProtoLoc);
6360
6361  Decl *ActOnStartClassImplementation(
6362                    SourceLocation AtClassImplLoc,
6363                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
6364                    IdentifierInfo *SuperClassname,
6365                    SourceLocation SuperClassLoc);
6366
6367  Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
6368                                         IdentifierInfo *ClassName,
6369                                         SourceLocation ClassLoc,
6370                                         IdentifierInfo *CatName,
6371                                         SourceLocation CatLoc);
6372
6373  DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
6374                                               ArrayRef<Decl *> Decls);
6375
6376  DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
6377                                     IdentifierInfo **IdentList,
6378                                     SourceLocation *IdentLocs,
6379                                     unsigned NumElts);
6380
6381  DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
6382                                        const IdentifierLocPair *IdentList,
6383                                        unsigned NumElts,
6384                                        AttributeList *attrList);
6385
6386  void FindProtocolDeclaration(bool WarnOnDeclarations,
6387                               const IdentifierLocPair *ProtocolId,
6388                               unsigned NumProtocols,
6389                               SmallVectorImpl<Decl *> &Protocols);
6390
6391  /// Ensure attributes are consistent with type.
6392  /// \param [in, out] Attributes The attributes to check; they will
6393  /// be modified to be consistent with \p PropertyTy.
6394  void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
6395                                   SourceLocation Loc,
6396                                   unsigned &Attributes,
6397                                   bool propertyInPrimaryClass);
6398
6399  /// Process the specified property declaration and create decls for the
6400  /// setters and getters as needed.
6401  /// \param property The property declaration being processed
6402  /// \param CD The semantic container for the property
6403  /// \param redeclaredProperty Declaration for property if redeclared
6404  ///        in class extension.
6405  /// \param lexicalDC Container for redeclaredProperty.
6406  void ProcessPropertyDecl(ObjCPropertyDecl *property,
6407                           ObjCContainerDecl *CD,
6408                           ObjCPropertyDecl *redeclaredProperty = 0,
6409                           ObjCContainerDecl *lexicalDC = 0);
6410
6411
6412  void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
6413                                ObjCPropertyDecl *SuperProperty,
6414                                const IdentifierInfo *Name);
6415
6416  void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
6417                                        ObjCInterfaceDecl *ID);
6418
6419  void MatchOneProtocolPropertiesInClass(Decl *CDecl,
6420                                         ObjCProtocolDecl *PDecl);
6421
6422  Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
6423                   Decl **allMethods = 0, unsigned allNum = 0,
6424                   Decl **allProperties = 0, unsigned pNum = 0,
6425                   DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0);
6426
6427  Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
6428                      SourceLocation LParenLoc,
6429                      FieldDeclarator &FD, ObjCDeclSpec &ODS,
6430                      Selector GetterSel, Selector SetterSel,
6431                      bool *OverridingProperty,
6432                      tok::ObjCKeywordKind MethodImplKind,
6433                      DeclContext *lexicalDC = 0);
6434
6435  Decl *ActOnPropertyImplDecl(Scope *S,
6436                              SourceLocation AtLoc,
6437                              SourceLocation PropertyLoc,
6438                              bool ImplKind,
6439                              IdentifierInfo *PropertyId,
6440                              IdentifierInfo *PropertyIvar,
6441                              SourceLocation PropertyIvarLoc);
6442
6443  enum ObjCSpecialMethodKind {
6444    OSMK_None,
6445    OSMK_Alloc,
6446    OSMK_New,
6447    OSMK_Copy,
6448    OSMK_RetainingInit,
6449    OSMK_NonRetainingInit
6450  };
6451
6452  struct ObjCArgInfo {
6453    IdentifierInfo *Name;
6454    SourceLocation NameLoc;
6455    // The Type is null if no type was specified, and the DeclSpec is invalid
6456    // in this case.
6457    ParsedType Type;
6458    ObjCDeclSpec DeclSpec;
6459
6460    /// ArgAttrs - Attribute list for this argument.
6461    AttributeList *ArgAttrs;
6462  };
6463
6464  Decl *ActOnMethodDeclaration(
6465    Scope *S,
6466    SourceLocation BeginLoc, // location of the + or -.
6467    SourceLocation EndLoc,   // location of the ; or {.
6468    tok::TokenKind MethodType,
6469    ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
6470    ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
6471    // optional arguments. The number of types/arguments is obtained
6472    // from the Sel.getNumArgs().
6473    ObjCArgInfo *ArgInfo,
6474    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
6475    AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
6476    bool isVariadic, bool MethodDefinition);
6477
6478  ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
6479                                              const ObjCObjectPointerType *OPT,
6480                                              bool IsInstance);
6481  ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
6482                                           bool IsInstance);
6483
6484  bool CheckARCMethodDecl(ObjCMethodDecl *method);
6485  bool inferObjCARCLifetime(ValueDecl *decl);
6486
6487  ExprResult
6488  HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
6489                            Expr *BaseExpr,
6490                            SourceLocation OpLoc,
6491                            DeclarationName MemberName,
6492                            SourceLocation MemberLoc,
6493                            SourceLocation SuperLoc, QualType SuperType,
6494                            bool Super);
6495
6496  ExprResult
6497  ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
6498                            IdentifierInfo &propertyName,
6499                            SourceLocation receiverNameLoc,
6500                            SourceLocation propertyNameLoc);
6501
6502  ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
6503
6504  /// \brief Describes the kind of message expression indicated by a message
6505  /// send that starts with an identifier.
6506  enum ObjCMessageKind {
6507    /// \brief The message is sent to 'super'.
6508    ObjCSuperMessage,
6509    /// \brief The message is an instance message.
6510    ObjCInstanceMessage,
6511    /// \brief The message is a class message, and the identifier is a type
6512    /// name.
6513    ObjCClassMessage
6514  };
6515
6516  ObjCMessageKind getObjCMessageKind(Scope *S,
6517                                     IdentifierInfo *Name,
6518                                     SourceLocation NameLoc,
6519                                     bool IsSuper,
6520                                     bool HasTrailingDot,
6521                                     ParsedType &ReceiverType);
6522
6523  ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
6524                               Selector Sel,
6525                               SourceLocation LBracLoc,
6526                               ArrayRef<SourceLocation> SelectorLocs,
6527                               SourceLocation RBracLoc,
6528                               MultiExprArg Args);
6529
6530  ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
6531                               QualType ReceiverType,
6532                               SourceLocation SuperLoc,
6533                               Selector Sel,
6534                               ObjCMethodDecl *Method,
6535                               SourceLocation LBracLoc,
6536                               ArrayRef<SourceLocation> SelectorLocs,
6537                               SourceLocation RBracLoc,
6538                               MultiExprArg Args,
6539                               bool isImplicit = false);
6540
6541  ExprResult BuildClassMessageImplicit(QualType ReceiverType,
6542                                       bool isSuperReceiver,
6543                                       SourceLocation Loc,
6544                                       Selector Sel,
6545                                       ObjCMethodDecl *Method,
6546                                       MultiExprArg Args);
6547
6548  ExprResult ActOnClassMessage(Scope *S,
6549                               ParsedType Receiver,
6550                               Selector Sel,
6551                               SourceLocation LBracLoc,
6552                               ArrayRef<SourceLocation> SelectorLocs,
6553                               SourceLocation RBracLoc,
6554                               MultiExprArg Args);
6555
6556  ExprResult BuildInstanceMessage(Expr *Receiver,
6557                                  QualType ReceiverType,
6558                                  SourceLocation SuperLoc,
6559                                  Selector Sel,
6560                                  ObjCMethodDecl *Method,
6561                                  SourceLocation LBracLoc,
6562                                  ArrayRef<SourceLocation> SelectorLocs,
6563                                  SourceLocation RBracLoc,
6564                                  MultiExprArg Args,
6565                                  bool isImplicit = false);
6566
6567  ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
6568                                          QualType ReceiverType,
6569                                          SourceLocation Loc,
6570                                          Selector Sel,
6571                                          ObjCMethodDecl *Method,
6572                                          MultiExprArg Args);
6573
6574  ExprResult ActOnInstanceMessage(Scope *S,
6575                                  Expr *Receiver,
6576                                  Selector Sel,
6577                                  SourceLocation LBracLoc,
6578                                  ArrayRef<SourceLocation> SelectorLocs,
6579                                  SourceLocation RBracLoc,
6580                                  MultiExprArg Args);
6581
6582  ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
6583                                  ObjCBridgeCastKind Kind,
6584                                  SourceLocation BridgeKeywordLoc,
6585                                  TypeSourceInfo *TSInfo,
6586                                  Expr *SubExpr);
6587
6588  ExprResult ActOnObjCBridgedCast(Scope *S,
6589                                  SourceLocation LParenLoc,
6590                                  ObjCBridgeCastKind Kind,
6591                                  SourceLocation BridgeKeywordLoc,
6592                                  ParsedType Type,
6593                                  SourceLocation RParenLoc,
6594                                  Expr *SubExpr);
6595
6596  bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
6597
6598  /// \brief Check whether the given new method is a valid override of the
6599  /// given overridden method, and set any properties that should be inherited.
6600  void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
6601                               const ObjCMethodDecl *Overridden);
6602
6603  /// \brief Describes the compatibility of a result type with its method.
6604  enum ResultTypeCompatibilityKind {
6605    RTC_Compatible,
6606    RTC_Incompatible,
6607    RTC_Unknown
6608  };
6609
6610  void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
6611                                ObjCInterfaceDecl *CurrentClass,
6612                                ResultTypeCompatibilityKind RTC);
6613
6614  enum PragmaOptionsAlignKind {
6615    POAK_Native,  // #pragma options align=native
6616    POAK_Natural, // #pragma options align=natural
6617    POAK_Packed,  // #pragma options align=packed
6618    POAK_Power,   // #pragma options align=power
6619    POAK_Mac68k,  // #pragma options align=mac68k
6620    POAK_Reset    // #pragma options align=reset
6621  };
6622
6623  /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
6624  void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
6625                               SourceLocation PragmaLoc);
6626
6627  enum PragmaPackKind {
6628    PPK_Default, // #pragma pack([n])
6629    PPK_Show,    // #pragma pack(show), only supported by MSVC.
6630    PPK_Push,    // #pragma pack(push, [identifier], [n])
6631    PPK_Pop      // #pragma pack(pop, [identifier], [n])
6632  };
6633
6634  enum PragmaMSStructKind {
6635    PMSST_OFF,  // #pragms ms_struct off
6636    PMSST_ON    // #pragms ms_struct on
6637  };
6638
6639  enum PragmaMSCommentKind {
6640    PCK_Unknown,
6641    PCK_Linker,   // #pragma comment(linker, ...)
6642    PCK_Lib,      // #pragma comment(lib, ...)
6643    PCK_Compiler, // #pragma comment(compiler, ...)
6644    PCK_ExeStr,   // #pragma comment(exestr, ...)
6645    PCK_User      // #pragma comment(user, ...)
6646  };
6647
6648  /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
6649  void ActOnPragmaPack(PragmaPackKind Kind,
6650                       IdentifierInfo *Name,
6651                       Expr *Alignment,
6652                       SourceLocation PragmaLoc,
6653                       SourceLocation LParenLoc,
6654                       SourceLocation RParenLoc);
6655
6656  /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
6657  void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
6658
6659  /// ActOnPragmaMSStruct - Called on well formed \#pragma comment(kind, "arg").
6660  void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg);
6661
6662  /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
6663  void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
6664
6665  /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
6666  void ActOnPragmaUnused(const Token &Identifier,
6667                         Scope *curScope,
6668                         SourceLocation PragmaLoc);
6669
6670  /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
6671  void ActOnPragmaVisibility(const IdentifierInfo* VisType,
6672                             SourceLocation PragmaLoc);
6673
6674  NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6675                                 SourceLocation Loc);
6676  void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
6677
6678  /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
6679  void ActOnPragmaWeakID(IdentifierInfo* WeakName,
6680                         SourceLocation PragmaLoc,
6681                         SourceLocation WeakNameLoc);
6682
6683  /// ActOnPragmaRedefineExtname - Called on well formed
6684  /// \#pragma redefine_extname oldname newname.
6685  void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
6686                                  IdentifierInfo* AliasName,
6687                                  SourceLocation PragmaLoc,
6688                                  SourceLocation WeakNameLoc,
6689                                  SourceLocation AliasNameLoc);
6690
6691  /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
6692  void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
6693                            IdentifierInfo* AliasName,
6694                            SourceLocation PragmaLoc,
6695                            SourceLocation WeakNameLoc,
6696                            SourceLocation AliasNameLoc);
6697
6698  /// ActOnPragmaFPContract - Called on well formed
6699  /// \#pragma {STDC,OPENCL} FP_CONTRACT
6700  void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
6701
6702  /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
6703  /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
6704  void AddAlignmentAttributesForRecord(RecordDecl *RD);
6705
6706  /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
6707  void AddMsStructLayoutForRecord(RecordDecl *RD);
6708
6709  /// FreePackedContext - Deallocate and null out PackContext.
6710  void FreePackedContext();
6711
6712  /// PushNamespaceVisibilityAttr - Note that we've entered a
6713  /// namespace with a visibility attribute.
6714  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
6715                                   SourceLocation Loc);
6716
6717  /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
6718  /// add an appropriate visibility attribute.
6719  void AddPushedVisibilityAttribute(Decl *RD);
6720
6721  /// PopPragmaVisibility - Pop the top element of the visibility stack; used
6722  /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
6723  void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
6724
6725  /// FreeVisContext - Deallocate and null out VisContext.
6726  void FreeVisContext();
6727
6728  /// AddCFAuditedAttribute - Check whether we're currently within
6729  /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
6730  /// the appropriate attribute.
6731  void AddCFAuditedAttribute(Decl *D);
6732
6733  /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
6734  void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
6735                      unsigned SpellingListIndex, bool IsPackExpansion);
6736  void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
6737                      unsigned SpellingListIndex, bool IsPackExpansion);
6738
6739  // OpenMP directives and clauses.
6740  /// \brief Called on correct id-expression from the '#pragma omp
6741  /// threadprivate'.
6742  ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
6743                                     CXXScopeSpec &ScopeSpec,
6744                                     const DeclarationNameInfo &Id);
6745  /// \brief Called on well-formed '#pragma omp threadprivate'.
6746  DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
6747                                     SourceLocation Loc,
6748                                     ArrayRef<Expr *> VarList);
6749  // \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
6750  OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
6751                                     SourceLocation Loc,
6752                                     ArrayRef<Expr *> VarList);
6753
6754  /// \brief The kind of conversion being performed.
6755  enum CheckedConversionKind {
6756    /// \brief An implicit conversion.
6757    CCK_ImplicitConversion,
6758    /// \brief A C-style cast.
6759    CCK_CStyleCast,
6760    /// \brief A functional-style cast.
6761    CCK_FunctionalCast,
6762    /// \brief A cast other than a C-style cast.
6763    CCK_OtherCast
6764  };
6765
6766  /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
6767  /// cast.  If there is already an implicit cast, merge into the existing one.
6768  /// If isLvalue, the result of the cast is an lvalue.
6769  ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
6770                               ExprValueKind VK = VK_RValue,
6771                               const CXXCastPath *BasePath = 0,
6772                               CheckedConversionKind CCK
6773                                  = CCK_ImplicitConversion);
6774
6775  /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
6776  /// to the conversion from scalar type ScalarTy to the Boolean type.
6777  static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
6778
6779  /// IgnoredValueConversions - Given that an expression's result is
6780  /// syntactically ignored, perform any conversions that are
6781  /// required.
6782  ExprResult IgnoredValueConversions(Expr *E);
6783
6784  // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
6785  // functions and arrays to their respective pointers (C99 6.3.2.1).
6786  ExprResult UsualUnaryConversions(Expr *E);
6787
6788  // DefaultFunctionArrayConversion - converts functions and arrays
6789  // to their respective pointers (C99 6.3.2.1).
6790  ExprResult DefaultFunctionArrayConversion(Expr *E);
6791
6792  // DefaultFunctionArrayLvalueConversion - converts functions and
6793  // arrays to their respective pointers and performs the
6794  // lvalue-to-rvalue conversion.
6795  ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
6796
6797  // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
6798  // the operand.  This is DefaultFunctionArrayLvalueConversion,
6799  // except that it assumes the operand isn't of function or array
6800  // type.
6801  ExprResult DefaultLvalueConversion(Expr *E);
6802
6803  // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
6804  // do not have a prototype. Integer promotions are performed on each
6805  // argument, and arguments that have type float are promoted to double.
6806  ExprResult DefaultArgumentPromotion(Expr *E);
6807
6808  // Used for emitting the right warning by DefaultVariadicArgumentPromotion
6809  enum VariadicCallType {
6810    VariadicFunction,
6811    VariadicBlock,
6812    VariadicMethod,
6813    VariadicConstructor,
6814    VariadicDoesNotApply
6815  };
6816
6817  VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
6818                                       const FunctionProtoType *Proto,
6819                                       Expr *Fn);
6820
6821  // Used for determining in which context a type is allowed to be passed to a
6822  // vararg function.
6823  enum VarArgKind {
6824    VAK_Valid,
6825    VAK_ValidInCXX11,
6826    VAK_Invalid
6827  };
6828
6829  // Determines which VarArgKind fits an expression.
6830  VarArgKind isValidVarArgType(const QualType &Ty);
6831
6832  /// GatherArgumentsForCall - Collector argument expressions for various
6833  /// form of call prototypes.
6834  bool GatherArgumentsForCall(SourceLocation CallLoc,
6835                              FunctionDecl *FDecl,
6836                              const FunctionProtoType *Proto,
6837                              unsigned FirstProtoArg,
6838                              ArrayRef<Expr *> Args,
6839                              SmallVector<Expr *, 8> &AllArgs,
6840                              VariadicCallType CallType = VariadicDoesNotApply,
6841                              bool AllowExplicit = false,
6842                              bool IsListInitialization = false);
6843
6844  // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
6845  // will create a runtime trap if the resulting type is not a POD type.
6846  ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
6847                                              FunctionDecl *FDecl);
6848
6849  /// Checks to see if the given expression is a valid argument to a variadic
6850  /// function, issuing a diagnostic and returning NULL if not.
6851  bool variadicArgumentPODCheck(const Expr *E, VariadicCallType CT);
6852
6853  // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
6854  // operands and then handles various conversions that are common to binary
6855  // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
6856  // routine returns the first non-arithmetic type found. The client is
6857  // responsible for emitting appropriate error diagnostics.
6858  QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
6859                                      bool IsCompAssign = false);
6860
6861  /// AssignConvertType - All of the 'assignment' semantic checks return this
6862  /// enum to indicate whether the assignment was allowed.  These checks are
6863  /// done for simple assignments, as well as initialization, return from
6864  /// function, argument passing, etc.  The query is phrased in terms of a
6865  /// source and destination type.
6866  enum AssignConvertType {
6867    /// Compatible - the types are compatible according to the standard.
6868    Compatible,
6869
6870    /// PointerToInt - The assignment converts a pointer to an int, which we
6871    /// accept as an extension.
6872    PointerToInt,
6873
6874    /// IntToPointer - The assignment converts an int to a pointer, which we
6875    /// accept as an extension.
6876    IntToPointer,
6877
6878    /// FunctionVoidPointer - The assignment is between a function pointer and
6879    /// void*, which the standard doesn't allow, but we accept as an extension.
6880    FunctionVoidPointer,
6881
6882    /// IncompatiblePointer - The assignment is between two pointers types that
6883    /// are not compatible, but we accept them as an extension.
6884    IncompatiblePointer,
6885
6886    /// IncompatiblePointer - The assignment is between two pointers types which
6887    /// point to integers which have a different sign, but are otherwise
6888    /// identical. This is a subset of the above, but broken out because it's by
6889    /// far the most common case of incompatible pointers.
6890    IncompatiblePointerSign,
6891
6892    /// CompatiblePointerDiscardsQualifiers - The assignment discards
6893    /// c/v/r qualifiers, which we accept as an extension.
6894    CompatiblePointerDiscardsQualifiers,
6895
6896    /// IncompatiblePointerDiscardsQualifiers - The assignment
6897    /// discards qualifiers that we don't permit to be discarded,
6898    /// like address spaces.
6899    IncompatiblePointerDiscardsQualifiers,
6900
6901    /// IncompatibleNestedPointerQualifiers - The assignment is between two
6902    /// nested pointer types, and the qualifiers other than the first two
6903    /// levels differ e.g. char ** -> const char **, but we accept them as an
6904    /// extension.
6905    IncompatibleNestedPointerQualifiers,
6906
6907    /// IncompatibleVectors - The assignment is between two vector types that
6908    /// have the same size, which we accept as an extension.
6909    IncompatibleVectors,
6910
6911    /// IntToBlockPointer - The assignment converts an int to a block
6912    /// pointer. We disallow this.
6913    IntToBlockPointer,
6914
6915    /// IncompatibleBlockPointer - The assignment is between two block
6916    /// pointers types that are not compatible.
6917    IncompatibleBlockPointer,
6918
6919    /// IncompatibleObjCQualifiedId - The assignment is between a qualified
6920    /// id type and something else (that is incompatible with it). For example,
6921    /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
6922    IncompatibleObjCQualifiedId,
6923
6924    /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
6925    /// object with __weak qualifier.
6926    IncompatibleObjCWeakRef,
6927
6928    /// Incompatible - We reject this conversion outright, it is invalid to
6929    /// represent it in the AST.
6930    Incompatible
6931  };
6932
6933  /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
6934  /// assignment conversion type specified by ConvTy.  This returns true if the
6935  /// conversion was invalid or false if the conversion was accepted.
6936  bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
6937                                SourceLocation Loc,
6938                                QualType DstType, QualType SrcType,
6939                                Expr *SrcExpr, AssignmentAction Action,
6940                                bool *Complained = 0);
6941
6942  /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
6943  /// integer not in the range of enum values.
6944  void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
6945                              Expr *SrcExpr);
6946
6947  /// CheckAssignmentConstraints - Perform type checking for assignment,
6948  /// argument passing, variable initialization, and function return values.
6949  /// C99 6.5.16.
6950  AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
6951                                               QualType LHSType,
6952                                               QualType RHSType);
6953
6954  /// Check assignment constraints and prepare for a conversion of the
6955  /// RHS to the LHS type.
6956  AssignConvertType CheckAssignmentConstraints(QualType LHSType,
6957                                               ExprResult &RHS,
6958                                               CastKind &Kind);
6959
6960  // CheckSingleAssignmentConstraints - Currently used by
6961  // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
6962  // this routine performs the default function/array converions.
6963  AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
6964                                                     ExprResult &RHS,
6965                                                     bool Diagnose = true);
6966
6967  // \brief If the lhs type is a transparent union, check whether we
6968  // can initialize the transparent union with the given expression.
6969  AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
6970                                                             ExprResult &RHS);
6971
6972  bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
6973
6974  bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6975
6976  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6977                                       AssignmentAction Action,
6978                                       bool AllowExplicit = false);
6979  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6980                                       AssignmentAction Action,
6981                                       bool AllowExplicit,
6982                                       ImplicitConversionSequence& ICS);
6983  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6984                                       const ImplicitConversionSequence& ICS,
6985                                       AssignmentAction Action,
6986                                       CheckedConversionKind CCK
6987                                          = CCK_ImplicitConversion);
6988  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6989                                       const StandardConversionSequence& SCS,
6990                                       AssignmentAction Action,
6991                                       CheckedConversionKind CCK);
6992
6993  /// the following "Check" methods will return a valid/converted QualType
6994  /// or a null QualType (indicating an error diagnostic was issued).
6995
6996  /// type checking binary operators (subroutines of CreateBuiltinBinOp).
6997  QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6998                           ExprResult &RHS);
6999  QualType CheckPointerToMemberOperands( // C++ 5.5
7000    ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
7001    SourceLocation OpLoc, bool isIndirect);
7002  QualType CheckMultiplyDivideOperands( // C99 6.5.5
7003    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
7004    bool IsDivide);
7005  QualType CheckRemainderOperands( // C99 6.5.5
7006    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7007    bool IsCompAssign = false);
7008  QualType CheckAdditionOperands( // C99 6.5.6
7009    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7010    QualType* CompLHSTy = 0);
7011  QualType CheckSubtractionOperands( // C99 6.5.6
7012    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7013    QualType* CompLHSTy = 0);
7014  QualType CheckShiftOperands( // C99 6.5.7
7015    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7016    bool IsCompAssign = false);
7017  QualType CheckCompareOperands( // C99 6.5.8/9
7018    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
7019                                bool isRelational);
7020  QualType CheckBitwiseOperands( // C99 6.5.[10...12]
7021    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7022    bool IsCompAssign = false);
7023  QualType CheckLogicalOperands( // C99 6.5.[13,14]
7024    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
7025  // CheckAssignmentOperands is used for both simple and compound assignment.
7026  // For simple assignment, pass both expressions and a null converted type.
7027  // For compound assignment, pass both expressions and the converted type.
7028  QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
7029    Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
7030
7031  ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
7032                                     UnaryOperatorKind Opcode, Expr *Op);
7033  ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
7034                                         BinaryOperatorKind Opcode,
7035                                         Expr *LHS, Expr *RHS);
7036  ExprResult checkPseudoObjectRValue(Expr *E);
7037  Expr *recreateSyntacticForm(PseudoObjectExpr *E);
7038
7039  QualType CheckConditionalOperands( // C99 6.5.15
7040    ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
7041    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
7042  QualType CXXCheckConditionalOperands( // C++ 5.16
7043    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
7044    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
7045  QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
7046                                    bool *NonStandardCompositeType = 0);
7047  QualType FindCompositePointerType(SourceLocation Loc,
7048                                    ExprResult &E1, ExprResult &E2,
7049                                    bool *NonStandardCompositeType = 0) {
7050    Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
7051    QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
7052                                                  NonStandardCompositeType);
7053    E1 = Owned(E1Tmp);
7054    E2 = Owned(E2Tmp);
7055    return Composite;
7056  }
7057
7058  QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7059                                        SourceLocation QuestionLoc);
7060
7061  bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7062                                  SourceLocation QuestionLoc);
7063
7064  /// type checking for vector binary operators.
7065  QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7066                               SourceLocation Loc, bool IsCompAssign);
7067  QualType GetSignedVectorType(QualType V);
7068  QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7069                                      SourceLocation Loc, bool isRelational);
7070  QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7071                                      SourceLocation Loc);
7072
7073  /// type checking declaration initializers (C99 6.7.8)
7074  bool CheckForConstantInitializer(Expr *e, QualType t);
7075
7076  // type checking C++ declaration initializers (C++ [dcl.init]).
7077
7078  /// ReferenceCompareResult - Expresses the result of comparing two
7079  /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
7080  /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
7081  enum ReferenceCompareResult {
7082    /// Ref_Incompatible - The two types are incompatible, so direct
7083    /// reference binding is not possible.
7084    Ref_Incompatible = 0,
7085    /// Ref_Related - The two types are reference-related, which means
7086    /// that their unqualified forms (T1 and T2) are either the same
7087    /// or T1 is a base class of T2.
7088    Ref_Related,
7089    /// Ref_Compatible_With_Added_Qualification - The two types are
7090    /// reference-compatible with added qualification, meaning that
7091    /// they are reference-compatible and the qualifiers on T1 (cv1)
7092    /// are greater than the qualifiers on T2 (cv2).
7093    Ref_Compatible_With_Added_Qualification,
7094    /// Ref_Compatible - The two types are reference-compatible and
7095    /// have equivalent qualifiers (cv1 == cv2).
7096    Ref_Compatible
7097  };
7098
7099  ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
7100                                                      QualType T1, QualType T2,
7101                                                      bool &DerivedToBase,
7102                                                      bool &ObjCConversion,
7103                                                bool &ObjCLifetimeConversion);
7104
7105  ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
7106                                 Expr *CastExpr, CastKind &CastKind,
7107                                 ExprValueKind &VK, CXXCastPath &Path);
7108
7109  /// \brief Force an expression with unknown-type to an expression of the
7110  /// given type.
7111  ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
7112
7113  /// \brief Type-check an expression that's being passed to an
7114  /// __unknown_anytype parameter.
7115  ExprResult checkUnknownAnyArg(SourceLocation callLoc,
7116                                Expr *result, QualType &paramType);
7117
7118  // CheckVectorCast - check type constraints for vectors.
7119  // Since vectors are an extension, there are no C standard reference for this.
7120  // We allow casting between vectors and integer datatypes of the same size.
7121  // returns true if the cast is invalid
7122  bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7123                       CastKind &Kind);
7124
7125  // CheckExtVectorCast - check type constraints for extended vectors.
7126  // Since vectors are an extension, there are no C standard reference for this.
7127  // We allow casting between vectors and integer datatypes of the same size,
7128  // or vectors and the element type of that vector.
7129  // returns the cast expr
7130  ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
7131                                CastKind &Kind);
7132
7133  ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
7134                                        SourceLocation LParenLoc,
7135                                        Expr *CastExpr,
7136                                        SourceLocation RParenLoc);
7137
7138  enum ARCConversionResult { ACR_okay, ACR_unbridged };
7139
7140  /// \brief Checks for invalid conversions and casts between
7141  /// retainable pointers and other pointer kinds.
7142  ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
7143                                             QualType castType, Expr *&op,
7144                                             CheckedConversionKind CCK);
7145
7146  Expr *stripARCUnbridgedCast(Expr *e);
7147  void diagnoseARCUnbridgedCast(Expr *e);
7148
7149  bool CheckObjCARCUnavailableWeakConversion(QualType castType,
7150                                             QualType ExprType);
7151
7152  /// checkRetainCycles - Check whether an Objective-C message send
7153  /// might create an obvious retain cycle.
7154  void checkRetainCycles(ObjCMessageExpr *msg);
7155  void checkRetainCycles(Expr *receiver, Expr *argument);
7156  void checkRetainCycles(VarDecl *Var, Expr *Init);
7157
7158  /// checkUnsafeAssigns - Check whether +1 expr is being assigned
7159  /// to weak/__unsafe_unretained type.
7160  bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
7161
7162  /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
7163  /// to weak/__unsafe_unretained expression.
7164  void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
7165
7166  /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
7167  /// \param Method - May be null.
7168  /// \param [out] ReturnType - The return type of the send.
7169  /// \return true iff there were any incompatible types.
7170  bool CheckMessageArgumentTypes(QualType ReceiverType,
7171                                 MultiExprArg Args, Selector Sel,
7172                                 ArrayRef<SourceLocation> SelectorLocs,
7173                                 ObjCMethodDecl *Method, bool isClassMessage,
7174                                 bool isSuperMessage,
7175                                 SourceLocation lbrac, SourceLocation rbrac,
7176                                 QualType &ReturnType, ExprValueKind &VK);
7177
7178  /// \brief Determine the result of a message send expression based on
7179  /// the type of the receiver, the method expected to receive the message,
7180  /// and the form of the message send.
7181  QualType getMessageSendResultType(QualType ReceiverType,
7182                                    ObjCMethodDecl *Method,
7183                                    bool isClassMessage, bool isSuperMessage);
7184
7185  /// \brief If the given expression involves a message send to a method
7186  /// with a related result type, emit a note describing what happened.
7187  void EmitRelatedResultTypeNote(const Expr *E);
7188
7189  /// \brief Given that we had incompatible pointer types in a return
7190  /// statement, check whether we're in a method with a related result
7191  /// type, and if so, emit a note describing what happened.
7192  void EmitRelatedResultTypeNoteForReturn(QualType destType);
7193
7194  /// CheckBooleanCondition - Diagnose problems involving the use of
7195  /// the given expression as a boolean condition (e.g. in an if
7196  /// statement).  Also performs the standard function and array
7197  /// decays, possibly changing the input variable.
7198  ///
7199  /// \param Loc - A location associated with the condition, e.g. the
7200  /// 'if' keyword.
7201  /// \return true iff there were any errors
7202  ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
7203
7204  ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
7205                                   Expr *SubExpr);
7206
7207  /// DiagnoseAssignmentAsCondition - Given that an expression is
7208  /// being used as a boolean condition, warn if it's an assignment.
7209  void DiagnoseAssignmentAsCondition(Expr *E);
7210
7211  /// \brief Redundant parentheses over an equality comparison can indicate
7212  /// that the user intended an assignment used as condition.
7213  void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7214
7215  /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
7216  ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
7217
7218  /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
7219  /// the specified width and sign.  If an overflow occurs, detect it and emit
7220  /// the specified diagnostic.
7221  void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
7222                                          unsigned NewWidth, bool NewSign,
7223                                          SourceLocation Loc, unsigned DiagID);
7224
7225  /// Checks that the Objective-C declaration is declared in the global scope.
7226  /// Emits an error and marks the declaration as invalid if it's not declared
7227  /// in the global scope.
7228  bool CheckObjCDeclScope(Decl *D);
7229
7230  /// \brief Abstract base class used for diagnosing integer constant
7231  /// expression violations.
7232  class VerifyICEDiagnoser {
7233  public:
7234    bool Suppress;
7235
7236    VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
7237
7238    virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
7239    virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
7240    virtual ~VerifyICEDiagnoser() { }
7241  };
7242
7243  /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7244  /// and reports the appropriate diagnostics. Returns false on success.
7245  /// Can optionally return the value of the expression.
7246  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7247                                             VerifyICEDiagnoser &Diagnoser,
7248                                             bool AllowFold = true);
7249  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7250                                             unsigned DiagID,
7251                                             bool AllowFold = true);
7252  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result=0);
7253
7254  /// VerifyBitField - verifies that a bit field expression is an ICE and has
7255  /// the correct width, and that the field type is valid.
7256  /// Returns false on success.
7257  /// Can optionally return whether the bit-field is of width 0
7258  ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
7259                            QualType FieldTy, Expr *BitWidth,
7260                            bool *ZeroWidth = 0);
7261
7262  enum CUDAFunctionTarget {
7263    CFT_Device,
7264    CFT_Global,
7265    CFT_Host,
7266    CFT_HostDevice
7267  };
7268
7269  CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
7270
7271  bool CheckCUDATarget(CUDAFunctionTarget CallerTarget,
7272                       CUDAFunctionTarget CalleeTarget);
7273
7274  bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
7275    return CheckCUDATarget(IdentifyCUDATarget(Caller),
7276                           IdentifyCUDATarget(Callee));
7277  }
7278
7279  /// \name Code completion
7280  //@{
7281  /// \brief Describes the context in which code completion occurs.
7282  enum ParserCompletionContext {
7283    /// \brief Code completion occurs at top-level or namespace context.
7284    PCC_Namespace,
7285    /// \brief Code completion occurs within a class, struct, or union.
7286    PCC_Class,
7287    /// \brief Code completion occurs within an Objective-C interface, protocol,
7288    /// or category.
7289    PCC_ObjCInterface,
7290    /// \brief Code completion occurs within an Objective-C implementation or
7291    /// category implementation
7292    PCC_ObjCImplementation,
7293    /// \brief Code completion occurs within the list of instance variables
7294    /// in an Objective-C interface, protocol, category, or implementation.
7295    PCC_ObjCInstanceVariableList,
7296    /// \brief Code completion occurs following one or more template
7297    /// headers.
7298    PCC_Template,
7299    /// \brief Code completion occurs following one or more template
7300    /// headers within a class.
7301    PCC_MemberTemplate,
7302    /// \brief Code completion occurs within an expression.
7303    PCC_Expression,
7304    /// \brief Code completion occurs within a statement, which may
7305    /// also be an expression or a declaration.
7306    PCC_Statement,
7307    /// \brief Code completion occurs at the beginning of the
7308    /// initialization statement (or expression) in a for loop.
7309    PCC_ForInit,
7310    /// \brief Code completion occurs within the condition of an if,
7311    /// while, switch, or for statement.
7312    PCC_Condition,
7313    /// \brief Code completion occurs within the body of a function on a
7314    /// recovery path, where we do not have a specific handle on our position
7315    /// in the grammar.
7316    PCC_RecoveryInFunction,
7317    /// \brief Code completion occurs where only a type is permitted.
7318    PCC_Type,
7319    /// \brief Code completion occurs in a parenthesized expression, which
7320    /// might also be a type cast.
7321    PCC_ParenthesizedExpression,
7322    /// \brief Code completion occurs within a sequence of declaration
7323    /// specifiers within a function, method, or block.
7324    PCC_LocalDeclarationSpecifiers
7325  };
7326
7327  void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
7328  void CodeCompleteOrdinaryName(Scope *S,
7329                                ParserCompletionContext CompletionContext);
7330  void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
7331                            bool AllowNonIdentifiers,
7332                            bool AllowNestedNameSpecifiers);
7333
7334  struct CodeCompleteExpressionData;
7335  void CodeCompleteExpression(Scope *S,
7336                              const CodeCompleteExpressionData &Data);
7337  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
7338                                       SourceLocation OpLoc,
7339                                       bool IsArrow);
7340  void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
7341  void CodeCompleteTag(Scope *S, unsigned TagSpec);
7342  void CodeCompleteTypeQualifiers(DeclSpec &DS);
7343  void CodeCompleteCase(Scope *S);
7344  void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
7345  void CodeCompleteInitializer(Scope *S, Decl *D);
7346  void CodeCompleteReturn(Scope *S);
7347  void CodeCompleteAfterIf(Scope *S);
7348  void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
7349
7350  void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
7351                               bool EnteringContext);
7352  void CodeCompleteUsing(Scope *S);
7353  void CodeCompleteUsingDirective(Scope *S);
7354  void CodeCompleteNamespaceDecl(Scope *S);
7355  void CodeCompleteNamespaceAliasDecl(Scope *S);
7356  void CodeCompleteOperatorName(Scope *S);
7357  void CodeCompleteConstructorInitializer(Decl *Constructor,
7358                                          CXXCtorInitializer** Initializers,
7359                                          unsigned NumInitializers);
7360  void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
7361                                    bool AfterAmpersand);
7362
7363  void CodeCompleteObjCAtDirective(Scope *S);
7364  void CodeCompleteObjCAtVisibility(Scope *S);
7365  void CodeCompleteObjCAtStatement(Scope *S);
7366  void CodeCompleteObjCAtExpression(Scope *S);
7367  void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
7368  void CodeCompleteObjCPropertyGetter(Scope *S);
7369  void CodeCompleteObjCPropertySetter(Scope *S);
7370  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
7371                                   bool IsParameter);
7372  void CodeCompleteObjCMessageReceiver(Scope *S);
7373  void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
7374                                    IdentifierInfo **SelIdents,
7375                                    unsigned NumSelIdents,
7376                                    bool AtArgumentExpression);
7377  void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
7378                                    IdentifierInfo **SelIdents,
7379                                    unsigned NumSelIdents,
7380                                    bool AtArgumentExpression,
7381                                    bool IsSuper = false);
7382  void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
7383                                       IdentifierInfo **SelIdents,
7384                                       unsigned NumSelIdents,
7385                                       bool AtArgumentExpression,
7386                                       ObjCInterfaceDecl *Super = 0);
7387  void CodeCompleteObjCForCollection(Scope *S,
7388                                     DeclGroupPtrTy IterationVar);
7389  void CodeCompleteObjCSelector(Scope *S,
7390                                IdentifierInfo **SelIdents,
7391                                unsigned NumSelIdents);
7392  void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
7393                                          unsigned NumProtocols);
7394  void CodeCompleteObjCProtocolDecl(Scope *S);
7395  void CodeCompleteObjCInterfaceDecl(Scope *S);
7396  void CodeCompleteObjCSuperclass(Scope *S,
7397                                  IdentifierInfo *ClassName,
7398                                  SourceLocation ClassNameLoc);
7399  void CodeCompleteObjCImplementationDecl(Scope *S);
7400  void CodeCompleteObjCInterfaceCategory(Scope *S,
7401                                         IdentifierInfo *ClassName,
7402                                         SourceLocation ClassNameLoc);
7403  void CodeCompleteObjCImplementationCategory(Scope *S,
7404                                              IdentifierInfo *ClassName,
7405                                              SourceLocation ClassNameLoc);
7406  void CodeCompleteObjCPropertyDefinition(Scope *S);
7407  void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
7408                                              IdentifierInfo *PropertyName);
7409  void CodeCompleteObjCMethodDecl(Scope *S,
7410                                  bool IsInstanceMethod,
7411                                  ParsedType ReturnType);
7412  void CodeCompleteObjCMethodDeclSelector(Scope *S,
7413                                          bool IsInstanceMethod,
7414                                          bool AtParameterName,
7415                                          ParsedType ReturnType,
7416                                          IdentifierInfo **SelIdents,
7417                                          unsigned NumSelIdents);
7418  void CodeCompletePreprocessorDirective(bool InConditional);
7419  void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
7420  void CodeCompletePreprocessorMacroName(bool IsDefinition);
7421  void CodeCompletePreprocessorExpression();
7422  void CodeCompletePreprocessorMacroArgument(Scope *S,
7423                                             IdentifierInfo *Macro,
7424                                             MacroInfo *MacroInfo,
7425                                             unsigned Argument);
7426  void CodeCompleteNaturalLanguage();
7427  void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7428                                   CodeCompletionTUInfo &CCTUInfo,
7429                  SmallVectorImpl<CodeCompletionResult> &Results);
7430  //@}
7431
7432  //===--------------------------------------------------------------------===//
7433  // Extra semantic analysis beyond the C type system
7434
7435public:
7436  SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
7437                                                unsigned ByteNo) const;
7438
7439private:
7440  void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
7441                        const ArraySubscriptExpr *ASE=0,
7442                        bool AllowOnePastEnd=true, bool IndexNegated=false);
7443  void CheckArrayAccess(const Expr *E);
7444  // Used to grab the relevant information from a FormatAttr and a
7445  // FunctionDeclaration.
7446  struct FormatStringInfo {
7447    unsigned FormatIdx;
7448    unsigned FirstDataArg;
7449    bool HasVAListArg;
7450  };
7451
7452  bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
7453                           FormatStringInfo *FSI);
7454  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
7455                         const FunctionProtoType *Proto);
7456  bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
7457                           ArrayRef<const Expr *> Args);
7458  bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
7459                      const FunctionProtoType *Proto);
7460  void CheckConstructorCall(FunctionDecl *FDecl,
7461                            ArrayRef<const Expr *> Args,
7462                            const FunctionProtoType *Proto,
7463                            SourceLocation Loc);
7464
7465  void checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
7466                 unsigned NumProtoArgs, bool IsMemberFunction,
7467                 SourceLocation Loc, SourceRange Range,
7468                 VariadicCallType CallType);
7469
7470
7471  bool CheckObjCString(Expr *Arg);
7472
7473  ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7474  bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7475  bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7476
7477  bool SemaBuiltinVAStart(CallExpr *TheCall);
7478  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
7479  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
7480
7481public:
7482  // Used by C++ template instantiation.
7483  ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
7484
7485private:
7486  bool SemaBuiltinPrefetch(CallExpr *TheCall);
7487  bool SemaBuiltinObjectSize(CallExpr *TheCall);
7488  bool SemaBuiltinLongjmp(CallExpr *TheCall);
7489  ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
7490  ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
7491                                     AtomicExpr::AtomicOp Op);
7492  bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7493                              llvm::APSInt &Result);
7494
7495  enum FormatStringType {
7496    FST_Scanf,
7497    FST_Printf,
7498    FST_NSString,
7499    FST_Strftime,
7500    FST_Strfmon,
7501    FST_Kprintf,
7502    FST_Unknown
7503  };
7504  static FormatStringType GetFormatStringType(const FormatAttr *Format);
7505
7506  enum StringLiteralCheckType {
7507    SLCT_NotALiteral,
7508    SLCT_UncheckedLiteral,
7509    SLCT_CheckedLiteral
7510  };
7511
7512  StringLiteralCheckType checkFormatStringExpr(const Expr *E,
7513                                               ArrayRef<const Expr *> Args,
7514                                               bool HasVAListArg,
7515                                               unsigned format_idx,
7516                                               unsigned firstDataArg,
7517                                               FormatStringType Type,
7518                                               VariadicCallType CallType,
7519                                               bool inFunctionCall = true);
7520
7521  void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
7522                         ArrayRef<const Expr *> Args, bool HasVAListArg,
7523                         unsigned format_idx, unsigned firstDataArg,
7524                         FormatStringType Type, bool inFunctionCall,
7525                         VariadicCallType CallType);
7526
7527  bool CheckFormatArguments(const FormatAttr *Format,
7528                            ArrayRef<const Expr *> Args,
7529                            bool IsCXXMember,
7530                            VariadicCallType CallType,
7531                            SourceLocation Loc, SourceRange Range);
7532  bool CheckFormatArguments(ArrayRef<const Expr *> Args,
7533                            bool HasVAListArg, unsigned format_idx,
7534                            unsigned firstDataArg, FormatStringType Type,
7535                            VariadicCallType CallType,
7536                            SourceLocation Loc, SourceRange range);
7537
7538  void CheckNonNullArguments(const NonNullAttr *NonNull,
7539                             const Expr * const *ExprArgs,
7540                             SourceLocation CallSiteLoc);
7541
7542  void CheckMemaccessArguments(const CallExpr *Call,
7543                               unsigned BId,
7544                               IdentifierInfo *FnName);
7545
7546  void CheckStrlcpycatArguments(const CallExpr *Call,
7547                                IdentifierInfo *FnName);
7548
7549  void CheckStrncatArguments(const CallExpr *Call,
7550                             IdentifierInfo *FnName);
7551
7552  void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
7553                            SourceLocation ReturnLoc);
7554  void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
7555  void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
7556  void CheckForIntOverflow(Expr *E);
7557  void CheckUnsequencedOperations(Expr *E);
7558
7559  /// \brief Perform semantic checks on a completed expression. This will either
7560  /// be a full-expression or a default argument expression.
7561  void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
7562                          bool IsConstexpr = false);
7563
7564  void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
7565                                   Expr *Init);
7566
7567public:
7568  /// \brief Register a magic integral constant to be used as a type tag.
7569  void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7570                                  uint64_t MagicValue, QualType Type,
7571                                  bool LayoutCompatible, bool MustBeNull);
7572
7573  struct TypeTagData {
7574    TypeTagData() {}
7575
7576    TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
7577        Type(Type), LayoutCompatible(LayoutCompatible),
7578        MustBeNull(MustBeNull)
7579    {}
7580
7581    QualType Type;
7582
7583    /// If true, \c Type should be compared with other expression's types for
7584    /// layout-compatibility.
7585    unsigned LayoutCompatible : 1;
7586    unsigned MustBeNull : 1;
7587  };
7588
7589  /// A pair of ArgumentKind identifier and magic value.  This uniquely
7590  /// identifies the magic value.
7591  typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
7592
7593private:
7594  /// \brief A map from magic value to type information.
7595  OwningPtr<llvm::DenseMap<TypeTagMagicValue, TypeTagData> >
7596      TypeTagForDatatypeMagicValues;
7597
7598  /// \brief Peform checks on a call of a function with argument_with_type_tag
7599  /// or pointer_with_type_tag attributes.
7600  void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7601                                const Expr * const *ExprArgs);
7602
7603  /// \brief The parser's current scope.
7604  ///
7605  /// The parser maintains this state here.
7606  Scope *CurScope;
7607
7608  mutable IdentifierInfo *Ident_super;
7609
7610protected:
7611  friend class Parser;
7612  friend class InitializationSequence;
7613  friend class ASTReader;
7614  friend class ASTWriter;
7615
7616public:
7617  /// \brief Retrieve the parser's current scope.
7618  ///
7619  /// This routine must only be used when it is certain that semantic analysis
7620  /// and the parser are in precisely the same context, which is not the case
7621  /// when, e.g., we are performing any kind of template instantiation.
7622  /// Therefore, the only safe places to use this scope are in the parser
7623  /// itself and in routines directly invoked from the parser and *never* from
7624  /// template substitution or instantiation.
7625  Scope *getCurScope() const { return CurScope; }
7626
7627  IdentifierInfo *getSuperIdentifier() const;
7628
7629  Decl *getObjCDeclContext() const;
7630
7631  DeclContext *getCurLexicalContext() const {
7632    return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
7633  }
7634
7635  AvailabilityResult getCurContextAvailability() const;
7636
7637  const DeclContext *getCurObjCLexicalContext() const {
7638    const DeclContext *DC = getCurLexicalContext();
7639    // A category implicitly has the attribute of the interface.
7640    if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
7641      DC = CatD->getClassInterface();
7642    return DC;
7643  }
7644};
7645
7646/// \brief RAII object that enters a new expression evaluation context.
7647class EnterExpressionEvaluationContext {
7648  Sema &Actions;
7649
7650public:
7651  EnterExpressionEvaluationContext(Sema &Actions,
7652                                   Sema::ExpressionEvaluationContext NewContext,
7653                                   Decl *LambdaContextDecl = 0,
7654                                   bool IsDecltype = false)
7655    : Actions(Actions) {
7656    Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
7657                                            IsDecltype);
7658  }
7659  EnterExpressionEvaluationContext(Sema &Actions,
7660                                   Sema::ExpressionEvaluationContext NewContext,
7661                                   Sema::ReuseLambdaContextDecl_t,
7662                                   bool IsDecltype = false)
7663    : Actions(Actions) {
7664    Actions.PushExpressionEvaluationContext(NewContext,
7665                                            Sema::ReuseLambdaContextDecl,
7666                                            IsDecltype);
7667  }
7668
7669  ~EnterExpressionEvaluationContext() {
7670    Actions.PopExpressionEvaluationContext();
7671  }
7672};
7673
7674}  // end namespace clang
7675
7676#endif
7677