Bug Summary

File:tools/clang/include/clang/AST/Expr.h
Warning:line 4591, column 48
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ASTImporter.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/lib/AST -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp -faddrsig

/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp

1//===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTImporter class which imports AST nodes from one
11// context into another context.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/AST/ASTImporter.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTDiagnostic.h"
18#include "clang/AST/ASTStructuralEquivalence.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclAccessPair.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclFriend.h"
25#include "clang/AST/DeclGroup.h"
26#include "clang/AST/DeclObjC.h"
27#include "clang/AST/DeclTemplate.h"
28#include "clang/AST/DeclVisitor.h"
29#include "clang/AST/DeclarationName.h"
30#include "clang/AST/Expr.h"
31#include "clang/AST/ExprCXX.h"
32#include "clang/AST/ExprObjC.h"
33#include "clang/AST/ExternalASTSource.h"
34#include "clang/AST/LambdaCapture.h"
35#include "clang/AST/NestedNameSpecifier.h"
36#include "clang/AST/OperationKinds.h"
37#include "clang/AST/Stmt.h"
38#include "clang/AST/StmtCXX.h"
39#include "clang/AST/StmtObjC.h"
40#include "clang/AST/StmtVisitor.h"
41#include "clang/AST/TemplateBase.h"
42#include "clang/AST/TemplateName.h"
43#include "clang/AST/Type.h"
44#include "clang/AST/TypeLoc.h"
45#include "clang/AST/TypeVisitor.h"
46#include "clang/AST/UnresolvedSet.h"
47#include "clang/Basic/ExceptionSpecificationType.h"
48#include "clang/Basic/FileManager.h"
49#include "clang/Basic/IdentifierTable.h"
50#include "clang/Basic/LLVM.h"
51#include "clang/Basic/LangOptions.h"
52#include "clang/Basic/SourceLocation.h"
53#include "clang/Basic/SourceManager.h"
54#include "clang/Basic/Specifiers.h"
55#include "llvm/ADT/APSInt.h"
56#include "llvm/ADT/ArrayRef.h"
57#include "llvm/ADT/DenseMap.h"
58#include "llvm/ADT/None.h"
59#include "llvm/ADT/Optional.h"
60#include "llvm/ADT/STLExtras.h"
61#include "llvm/ADT/SmallVector.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/ErrorHandling.h"
64#include "llvm/Support/MemoryBuffer.h"
65#include <algorithm>
66#include <cassert>
67#include <cstddef>
68#include <memory>
69#include <type_traits>
70#include <utility>
71
72namespace clang {
73
74 template <class T>
75 SmallVector<Decl*, 2>
76 getCanonicalForwardRedeclChain(Redeclarable<T>* D) {
77 SmallVector<Decl*, 2> Redecls;
78 for (auto *R : D->getFirstDecl()->redecls()) {
79 if (R != D->getFirstDecl())
80 Redecls.push_back(R);
81 }
82 Redecls.push_back(D->getFirstDecl());
83 std::reverse(Redecls.begin(), Redecls.end());
84 return Redecls;
85 }
86
87 SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) {
88 // Currently only FunctionDecl is supported
89 auto FD = cast<FunctionDecl>(D);
90 return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
91 }
92
93 void updateFlags(const Decl *From, Decl *To) {
94 // Check if some flags or attrs are new in 'From' and copy into 'To'.
95 // FIXME: Other flags or attrs?
96 if (From->isUsed(false) && !To->isUsed(false))
97 To->setIsUsed();
98 }
99
100 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
101 public DeclVisitor<ASTNodeImporter, Decl *>,
102 public StmtVisitor<ASTNodeImporter, Stmt *> {
103 ASTImporter &Importer;
104
105 // Wrapper for an overload set.
106 template <typename ToDeclT> struct CallOverloadedCreateFun {
107 template <typename... Args>
108 auto operator()(Args &&... args)
109 -> decltype(ToDeclT::Create(std::forward<Args>(args)...)) {
110 return ToDeclT::Create(std::forward<Args>(args)...);
111 }
112 };
113
114 // Always use these functions to create a Decl during import. There are
115 // certain tasks which must be done after the Decl was created, e.g. we
116 // must immediately register that as an imported Decl. The parameter `ToD`
117 // will be set to the newly created Decl or if had been imported before
118 // then to the already imported Decl. Returns a bool value set to true if
119 // the `FromD` had been imported before.
120 template <typename ToDeclT, typename FromDeclT, typename... Args>
121 LLVM_NODISCARD[[clang::warn_unused_result]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
122 Args &&... args) {
123 // There may be several overloads of ToDeclT::Create. We must make sure
124 // to call the one which would be chosen by the arguments, thus we use a
125 // wrapper for the overload set.
126 CallOverloadedCreateFun<ToDeclT> OC;
127 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
128 std::forward<Args>(args)...);
129 }
130 // Use this overload if a special Type is needed to be created. E.g if we
131 // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
132 // then:
133 // TypedefNameDecl *ToTypedef;
134 // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
135 template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
136 typename... Args>
137 LLVM_NODISCARD[[clang::warn_unused_result]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
138 Args &&... args) {
139 CallOverloadedCreateFun<NewDeclT> OC;
140 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
141 std::forward<Args>(args)...);
142 }
143 // Use this version if a special create function must be
144 // used, e.g. CXXRecordDecl::CreateLambda .
145 template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
146 typename... Args>
147 LLVM_NODISCARD[[clang::warn_unused_result]] bool
148 GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
149 FromDeclT *FromD, Args &&... args) {
150 ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
151 if (ToD)
152 return true; // Already imported.
153 ToD = CreateFun(std::forward<Args>(args)...);
154 InitializeImportedDecl(FromD, ToD);
155 return false; // A new Decl is created.
156 }
157
158 void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
159 Importer.MapImported(FromD, ToD);
160 ToD->IdentifierNamespace = FromD->IdentifierNamespace;
161 if (FromD->hasAttrs())
162 for (const Attr *FromAttr : FromD->getAttrs())
163 ToD->addAttr(Importer.Import(FromAttr));
164 if (FromD->isUsed())
165 ToD->setIsUsed();
166 if (FromD->isImplicit())
167 ToD->setImplicit();
168 }
169
170 public:
171 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
172
173 using TypeVisitor<ASTNodeImporter, QualType>::Visit;
174 using DeclVisitor<ASTNodeImporter, Decl *>::Visit;
175 using StmtVisitor<ASTNodeImporter, Stmt *>::Visit;
176
177 // Importing types
178 QualType VisitType(const Type *T);
179 QualType VisitAtomicType(const AtomicType *T);
180 QualType VisitBuiltinType(const BuiltinType *T);
181 QualType VisitDecayedType(const DecayedType *T);
182 QualType VisitComplexType(const ComplexType *T);
183 QualType VisitPointerType(const PointerType *T);
184 QualType VisitBlockPointerType(const BlockPointerType *T);
185 QualType VisitLValueReferenceType(const LValueReferenceType *T);
186 QualType VisitRValueReferenceType(const RValueReferenceType *T);
187 QualType VisitMemberPointerType(const MemberPointerType *T);
188 QualType VisitConstantArrayType(const ConstantArrayType *T);
189 QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
190 QualType VisitVariableArrayType(const VariableArrayType *T);
191 QualType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
192 // FIXME: DependentSizedExtVectorType
193 QualType VisitVectorType(const VectorType *T);
194 QualType VisitExtVectorType(const ExtVectorType *T);
195 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
196 QualType VisitFunctionProtoType(const FunctionProtoType *T);
197 QualType VisitUnresolvedUsingType(const UnresolvedUsingType *T);
198 QualType VisitParenType(const ParenType *T);
199 QualType VisitTypedefType(const TypedefType *T);
200 QualType VisitTypeOfExprType(const TypeOfExprType *T);
201 // FIXME: DependentTypeOfExprType
202 QualType VisitTypeOfType(const TypeOfType *T);
203 QualType VisitDecltypeType(const DecltypeType *T);
204 QualType VisitUnaryTransformType(const UnaryTransformType *T);
205 QualType VisitAutoType(const AutoType *T);
206 QualType VisitInjectedClassNameType(const InjectedClassNameType *T);
207 // FIXME: DependentDecltypeType
208 QualType VisitRecordType(const RecordType *T);
209 QualType VisitEnumType(const EnumType *T);
210 QualType VisitAttributedType(const AttributedType *T);
211 QualType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
212 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T);
213 QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
214 QualType VisitElaboratedType(const ElaboratedType *T);
215 QualType VisitDependentNameType(const DependentNameType *T);
216 QualType VisitPackExpansionType(const PackExpansionType *T);
217 QualType VisitDependentTemplateSpecializationType(
218 const DependentTemplateSpecializationType *T);
219 QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
220 QualType VisitObjCObjectType(const ObjCObjectType *T);
221 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
222
223 // Importing declarations
224 bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
225 DeclContext *&LexicalDC, DeclarationName &Name,
226 NamedDecl *&ToD, SourceLocation &Loc);
227 void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
228 void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
229 DeclarationNameInfo& To);
230 void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
231 void ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
232
233 bool ImportCastPath(CastExpr *E, CXXCastPath &Path);
234
235 using Designator = DesignatedInitExpr::Designator;
236
237 Designator ImportDesignator(const Designator &D);
238
239 Optional<LambdaCapture> ImportLambdaCapture(const LambdaCapture &From);
240
241 /// What we should import from the definition.
242 enum ImportDefinitionKind {
243 /// Import the default subset of the definition, which might be
244 /// nothing (if minimal import is set) or might be everything (if minimal
245 /// import is not set).
246 IDK_Default,
247
248 /// Import everything.
249 IDK_Everything,
250
251 /// Import only the bare bones needed to establish a valid
252 /// DeclContext.
253 IDK_Basic
254 };
255
256 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
257 return IDK == IDK_Everything ||
258 (IDK == IDK_Default && !Importer.isMinimalImport());
259 }
260
261 bool ImportDefinition(RecordDecl *From, RecordDecl *To,
262 ImportDefinitionKind Kind = IDK_Default);
263 bool ImportDefinition(VarDecl *From, VarDecl *To,
264 ImportDefinitionKind Kind = IDK_Default);
265 bool ImportDefinition(EnumDecl *From, EnumDecl *To,
266 ImportDefinitionKind Kind = IDK_Default);
267 bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
268 ImportDefinitionKind Kind = IDK_Default);
269 bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
270 ImportDefinitionKind Kind = IDK_Default);
271 TemplateParameterList *ImportTemplateParameterList(
272 TemplateParameterList *Params);
273 TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
274 Optional<TemplateArgumentLoc> ImportTemplateArgumentLoc(
275 const TemplateArgumentLoc &TALoc);
276 bool ImportTemplateArguments(const TemplateArgument *FromArgs,
277 unsigned NumFromArgs,
278 SmallVectorImpl<TemplateArgument> &ToArgs);
279
280 template <typename InContainerTy>
281 bool ImportTemplateArgumentListInfo(const InContainerTy &Container,
282 TemplateArgumentListInfo &ToTAInfo);
283
284 template<typename InContainerTy>
285 bool ImportTemplateArgumentListInfo(SourceLocation FromLAngleLoc,
286 SourceLocation FromRAngleLoc,
287 const InContainerTy &Container,
288 TemplateArgumentListInfo &Result);
289
290 using TemplateArgsTy = SmallVector<TemplateArgument, 8>;
291 using OptionalTemplateArgsTy = Optional<TemplateArgsTy>;
292 std::tuple<FunctionTemplateDecl *, OptionalTemplateArgsTy>
293 ImportFunctionTemplateWithTemplateArgsFromSpecialization(
294 FunctionDecl *FromFD);
295
296 bool ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
297
298 bool IsStructuralMatch(Decl *From, Decl *To, bool Complain);
299 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
300 bool Complain = true);
301 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
302 bool Complain = true);
303 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
304 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
305 bool IsStructuralMatch(FunctionTemplateDecl *From,
306 FunctionTemplateDecl *To);
307 bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To);
308 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
309 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
310 Decl *VisitDecl(Decl *D);
311 Decl *VisitEmptyDecl(EmptyDecl *D);
312 Decl *VisitAccessSpecDecl(AccessSpecDecl *D);
313 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
314 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
315 Decl *VisitNamespaceDecl(NamespaceDecl *D);
316 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
317 Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
318 Decl *VisitTypedefDecl(TypedefDecl *D);
319 Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
320 Decl *VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
321 Decl *VisitLabelDecl(LabelDecl *D);
322 Decl *VisitEnumDecl(EnumDecl *D);
323 Decl *VisitRecordDecl(RecordDecl *D);
324 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
325 Decl *VisitFunctionDecl(FunctionDecl *D);
326 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
327 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
328 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
329 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
330 Decl *VisitFieldDecl(FieldDecl *D);
331 Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
332 Decl *VisitFriendDecl(FriendDecl *D);
333 Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
334 Decl *VisitVarDecl(VarDecl *D);
335 Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
336 Decl *VisitParmVarDecl(ParmVarDecl *D);
337 Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
338 Decl *VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
339 Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
340 Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
341 Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D);
342 Decl *VisitUsingDecl(UsingDecl *D);
343 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
344 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
345 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
346 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
347
348 ObjCTypeParamList *ImportObjCTypeParamList(ObjCTypeParamList *list);
349 Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
350 Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
351 Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
352 Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
353 Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
354 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
355 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
356 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
357 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
358 Decl *VisitClassTemplateSpecializationDecl(
359 ClassTemplateSpecializationDecl *D);
360 Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
361 Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
362 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
363
364 // Importing statements
365 DeclGroupRef ImportDeclGroup(DeclGroupRef DG);
366
367 Stmt *VisitStmt(Stmt *S);
368 Stmt *VisitGCCAsmStmt(GCCAsmStmt *S);
369 Stmt *VisitDeclStmt(DeclStmt *S);
370 Stmt *VisitNullStmt(NullStmt *S);
371 Stmt *VisitCompoundStmt(CompoundStmt *S);
372 Stmt *VisitCaseStmt(CaseStmt *S);
373 Stmt *VisitDefaultStmt(DefaultStmt *S);
374 Stmt *VisitLabelStmt(LabelStmt *S);
375 Stmt *VisitAttributedStmt(AttributedStmt *S);
376 Stmt *VisitIfStmt(IfStmt *S);
377 Stmt *VisitSwitchStmt(SwitchStmt *S);
378 Stmt *VisitWhileStmt(WhileStmt *S);
379 Stmt *VisitDoStmt(DoStmt *S);
380 Stmt *VisitForStmt(ForStmt *S);
381 Stmt *VisitGotoStmt(GotoStmt *S);
382 Stmt *VisitIndirectGotoStmt(IndirectGotoStmt *S);
383 Stmt *VisitContinueStmt(ContinueStmt *S);
384 Stmt *VisitBreakStmt(BreakStmt *S);
385 Stmt *VisitReturnStmt(ReturnStmt *S);
386 // FIXME: MSAsmStmt
387 // FIXME: SEHExceptStmt
388 // FIXME: SEHFinallyStmt
389 // FIXME: SEHTryStmt
390 // FIXME: SEHLeaveStmt
391 // FIXME: CapturedStmt
392 Stmt *VisitCXXCatchStmt(CXXCatchStmt *S);
393 Stmt *VisitCXXTryStmt(CXXTryStmt *S);
394 Stmt *VisitCXXForRangeStmt(CXXForRangeStmt *S);
395 // FIXME: MSDependentExistsStmt
396 Stmt *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
397 Stmt *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
398 Stmt *VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
399 Stmt *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
400 Stmt *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
401 Stmt *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
402 Stmt *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
403
404 // Importing expressions
405 Expr *VisitExpr(Expr *E);
406 Expr *VisitVAArgExpr(VAArgExpr *E);
407 Expr *VisitGNUNullExpr(GNUNullExpr *E);
408 Expr *VisitPredefinedExpr(PredefinedExpr *E);
409 Expr *VisitDeclRefExpr(DeclRefExpr *E);
410 Expr *VisitImplicitValueInitExpr(ImplicitValueInitExpr *ILE);
411 Expr *VisitDesignatedInitExpr(DesignatedInitExpr *E);
412 Expr *VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
413 Expr *VisitIntegerLiteral(IntegerLiteral *E);
414 Expr *VisitFloatingLiteral(FloatingLiteral *E);
415 Expr *VisitCharacterLiteral(CharacterLiteral *E);
416 Expr *VisitStringLiteral(StringLiteral *E);
417 Expr *VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
418 Expr *VisitAtomicExpr(AtomicExpr *E);
419 Expr *VisitAddrLabelExpr(AddrLabelExpr *E);
420 Expr *VisitParenExpr(ParenExpr *E);
421 Expr *VisitParenListExpr(ParenListExpr *E);
422 Expr *VisitStmtExpr(StmtExpr *E);
423 Expr *VisitUnaryOperator(UnaryOperator *E);
424 Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
425 Expr *VisitBinaryOperator(BinaryOperator *E);
426 Expr *VisitConditionalOperator(ConditionalOperator *E);
427 Expr *VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
428 Expr *VisitOpaqueValueExpr(OpaqueValueExpr *E);
429 Expr *VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
430 Expr *VisitExpressionTraitExpr(ExpressionTraitExpr *E);
431 Expr *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
432 Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
433 Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
434 Expr *VisitExplicitCastExpr(ExplicitCastExpr *E);
435 Expr *VisitOffsetOfExpr(OffsetOfExpr *OE);
436 Expr *VisitCXXThrowExpr(CXXThrowExpr *E);
437 Expr *VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
438 Expr *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
439 Expr *VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
440 Expr *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
441 Expr *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *CE);
442 Expr *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
443 Expr *VisitPackExpansionExpr(PackExpansionExpr *E);
444 Expr *VisitSizeOfPackExpr(SizeOfPackExpr *E);
445 Expr *VisitCXXNewExpr(CXXNewExpr *CE);
446 Expr *VisitCXXDeleteExpr(CXXDeleteExpr *E);
447 Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
448 Expr *VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
449 Expr *VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
450 Expr *VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
451 Expr *VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *CE);
452 Expr *VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
453 Expr *VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
454 Expr *VisitExprWithCleanups(ExprWithCleanups *EWC);
455 Expr *VisitCXXThisExpr(CXXThisExpr *E);
456 Expr *VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
457 Expr *VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
458 Expr *VisitMemberExpr(MemberExpr *E);
459 Expr *VisitCallExpr(CallExpr *E);
460 Expr *VisitLambdaExpr(LambdaExpr *LE);
461 Expr *VisitInitListExpr(InitListExpr *E);
462 Expr *VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
463 Expr *VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E);
464 Expr *VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
465 Expr *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
466 Expr *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
467 Expr *VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
468 Expr *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
469 Expr *VisitTypeTraitExpr(TypeTraitExpr *E);
470 Expr *VisitCXXTypeidExpr(CXXTypeidExpr *E);
471
472 template<typename IIter, typename OIter>
473 void ImportArray(IIter Ibegin, IIter Iend, OIter Obegin) {
474 using ItemT = typename std::remove_reference<decltype(*Obegin)>::type;
475
476 ASTImporter &ImporterRef = Importer;
477 std::transform(Ibegin, Iend, Obegin,
478 [&ImporterRef](ItemT From) -> ItemT {
479 return ImporterRef.Import(From);
480 });
481 }
482
483 template<typename IIter, typename OIter>
484 bool ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
485 using ItemT = typename std::remove_reference<decltype(**Obegin)>::type;
486
487 ASTImporter &ImporterRef = Importer;
488 bool Failed = false;
489 std::transform(Ibegin, Iend, Obegin,
490 [&ImporterRef, &Failed](ItemT *From) -> ItemT * {
491 auto *To = cast_or_null<ItemT>(ImporterRef.Import(From));
492 if (!To && From)
493 Failed = true;
494 return To;
495 });
496 return Failed;
497 }
498
499 template<typename InContainerTy, typename OutContainerTy>
500 bool ImportContainerChecked(const InContainerTy &InContainer,
501 OutContainerTy &OutContainer) {
502 return ImportArrayChecked(InContainer.begin(), InContainer.end(),
503 OutContainer.begin());
504 }
505
506 template<typename InContainerTy, typename OIter>
507 bool ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
508 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
509 }
510
511 // Importing overrides.
512 void ImportOverrides(CXXMethodDecl *ToMethod, CXXMethodDecl *FromMethod);
513
514 FunctionDecl *FindFunctionTemplateSpecialization(FunctionDecl *FromFD);
515 };
516
517template <typename InContainerTy>
518bool ASTNodeImporter::ImportTemplateArgumentListInfo(
519 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
520 const InContainerTy &Container, TemplateArgumentListInfo &Result) {
521 TemplateArgumentListInfo ToTAInfo(Importer.Import(FromLAngleLoc),
522 Importer.Import(FromRAngleLoc));
523 if (ImportTemplateArgumentListInfo(Container, ToTAInfo))
524 return true;
525 Result = ToTAInfo;
526 return false;
527}
528
529template <>
530bool ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
531 const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
532 return ImportTemplateArgumentListInfo(
533 From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
534}
535
536template <>
537bool ASTNodeImporter::ImportTemplateArgumentListInfo<
538 ASTTemplateArgumentListInfo>(const ASTTemplateArgumentListInfo &From,
539 TemplateArgumentListInfo &Result) {
540 return ImportTemplateArgumentListInfo(From.LAngleLoc, From.RAngleLoc,
541 From.arguments(), Result);
542}
543
544std::tuple<FunctionTemplateDecl *, ASTNodeImporter::OptionalTemplateArgsTy>
545ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization(
546 FunctionDecl *FromFD) {
547 assert(FromFD->getTemplatedKind() ==(static_cast <bool> (FromFD->getTemplatedKind() == FunctionDecl
::TK_FunctionTemplateSpecialization) ? void (0) : __assert_fail
("FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 548, __extension__ __PRETTY_FUNCTION__))
548 FunctionDecl::TK_FunctionTemplateSpecialization)(static_cast <bool> (FromFD->getTemplatedKind() == FunctionDecl
::TK_FunctionTemplateSpecialization) ? void (0) : __assert_fail
("FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 548, __extension__ __PRETTY_FUNCTION__))
;
549 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
550 auto *Template = cast_or_null<FunctionTemplateDecl>(
551 Importer.Import(FTSInfo->getTemplate()));
552
553 // Import template arguments.
554 auto TemplArgs = FTSInfo->TemplateArguments->asArray();
555 TemplateArgsTy ToTemplArgs;
556 if (ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(),
557 ToTemplArgs)) // Error during import.
558 return std::make_tuple(Template, OptionalTemplateArgsTy());
559
560 return std::make_tuple(Template, ToTemplArgs);
561}
562
563} // namespace clang
564
565//----------------------------------------------------------------------------
566// Import Types
567//----------------------------------------------------------------------------
568
569using namespace clang;
570
571QualType ASTNodeImporter::VisitType(const Type *T) {
572 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
573 << T->getTypeClassName();
574 return {};
575}
576
577QualType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
578 QualType UnderlyingType = Importer.Import(T->getValueType());
579 if(UnderlyingType.isNull())
580 return {};
581
582 return Importer.getToContext().getAtomicType(UnderlyingType);
583}
584
585QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
586 switch (T->getKind()) {
587#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
588 case BuiltinType::Id: \
589 return Importer.getToContext().SingletonId;
590#include "clang/Basic/OpenCLImageTypes.def"
591#define SHARED_SINGLETON_TYPE(Expansion)
592#define BUILTIN_TYPE(Id, SingletonId) \
593 case BuiltinType::Id: return Importer.getToContext().SingletonId;
594#include "clang/AST/BuiltinTypes.def"
595
596 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
597 // context supports C++.
598
599 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
600 // context supports ObjC.
601
602 case BuiltinType::Char_U:
603 // The context we're importing from has an unsigned 'char'. If we're
604 // importing into a context with a signed 'char', translate to
605 // 'unsigned char' instead.
606 if (Importer.getToContext().getLangOpts().CharIsSigned)
607 return Importer.getToContext().UnsignedCharTy;
608
609 return Importer.getToContext().CharTy;
610
611 case BuiltinType::Char_S:
612 // The context we're importing from has an unsigned 'char'. If we're
613 // importing into a context with a signed 'char', translate to
614 // 'unsigned char' instead.
615 if (!Importer.getToContext().getLangOpts().CharIsSigned)
616 return Importer.getToContext().SignedCharTy;
617
618 return Importer.getToContext().CharTy;
619
620 case BuiltinType::WChar_S:
621 case BuiltinType::WChar_U:
622 // FIXME: If not in C++, shall we translate to the C equivalent of
623 // wchar_t?
624 return Importer.getToContext().WCharTy;
625 }
626
627 llvm_unreachable("Invalid BuiltinType Kind!")::llvm::llvm_unreachable_internal("Invalid BuiltinType Kind!"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 627)
;
628}
629
630QualType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
631 QualType OrigT = Importer.Import(T->getOriginalType());
632 if (OrigT.isNull())
633 return {};
634
635 return Importer.getToContext().getDecayedType(OrigT);
636}
637
638QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
639 QualType ToElementType = Importer.Import(T->getElementType());
640 if (ToElementType.isNull())
641 return {};
642
643 return Importer.getToContext().getComplexType(ToElementType);
644}
645
646QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
647 QualType ToPointeeType = Importer.Import(T->getPointeeType());
648 if (ToPointeeType.isNull())
649 return {};
650
651 return Importer.getToContext().getPointerType(ToPointeeType);
652}
653
654QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
655 // FIXME: Check for blocks support in "to" context.
656 QualType ToPointeeType = Importer.Import(T->getPointeeType());
657 if (ToPointeeType.isNull())
658 return {};
659
660 return Importer.getToContext().getBlockPointerType(ToPointeeType);
661}
662
663QualType
664ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
665 // FIXME: Check for C++ support in "to" context.
666 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
667 if (ToPointeeType.isNull())
668 return {};
669
670 return Importer.getToContext().getLValueReferenceType(ToPointeeType);
671}
672
673QualType
674ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
675 // FIXME: Check for C++0x support in "to" context.
676 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
677 if (ToPointeeType.isNull())
678 return {};
679
680 return Importer.getToContext().getRValueReferenceType(ToPointeeType);
681}
682
683QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
684 // FIXME: Check for C++ support in "to" context.
685 QualType ToPointeeType = Importer.Import(T->getPointeeType());
686 if (ToPointeeType.isNull())
687 return {};
688
689 QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
690 return Importer.getToContext().getMemberPointerType(ToPointeeType,
691 ClassType.getTypePtr());
692}
693
694QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
695 QualType ToElementType = Importer.Import(T->getElementType());
696 if (ToElementType.isNull())
697 return {};
698
699 return Importer.getToContext().getConstantArrayType(ToElementType,
700 T->getSize(),
701 T->getSizeModifier(),
702 T->getIndexTypeCVRQualifiers());
703}
704
705QualType
706ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
707 QualType ToElementType = Importer.Import(T->getElementType());
708 if (ToElementType.isNull())
709 return {};
710
711 return Importer.getToContext().getIncompleteArrayType(ToElementType,
712 T->getSizeModifier(),
713 T->getIndexTypeCVRQualifiers());
714}
715
716QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
717 QualType ToElementType = Importer.Import(T->getElementType());
718 if (ToElementType.isNull())
719 return {};
720
721 Expr *Size = Importer.Import(T->getSizeExpr());
722 if (!Size)
723 return {};
724
725 SourceRange Brackets = Importer.Import(T->getBracketsRange());
726 return Importer.getToContext().getVariableArrayType(ToElementType, Size,
727 T->getSizeModifier(),
728 T->getIndexTypeCVRQualifiers(),
729 Brackets);
730}
731
732QualType ASTNodeImporter::VisitDependentSizedArrayType(
733 const DependentSizedArrayType *T) {
734 QualType ToElementType = Importer.Import(T->getElementType());
735 if (ToElementType.isNull())
736 return {};
737
738 // SizeExpr may be null if size is not specified directly.
739 // For example, 'int a[]'.
740 Expr *Size = Importer.Import(T->getSizeExpr());
741 if (!Size && T->getSizeExpr())
742 return {};
743
744 SourceRange Brackets = Importer.Import(T->getBracketsRange());
745 return Importer.getToContext().getDependentSizedArrayType(
746 ToElementType, Size, T->getSizeModifier(), T->getIndexTypeCVRQualifiers(),
747 Brackets);
748}
749
750QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
751 QualType ToElementType = Importer.Import(T->getElementType());
752 if (ToElementType.isNull())
753 return {};
754
755 return Importer.getToContext().getVectorType(ToElementType,
756 T->getNumElements(),
757 T->getVectorKind());
758}
759
760QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
761 QualType ToElementType = Importer.Import(T->getElementType());
762 if (ToElementType.isNull())
763 return {};
764
765 return Importer.getToContext().getExtVectorType(ToElementType,
766 T->getNumElements());
767}
768
769QualType
770ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
771 // FIXME: What happens if we're importing a function without a prototype
772 // into C++? Should we make it variadic?
773 QualType ToResultType = Importer.Import(T->getReturnType());
774 if (ToResultType.isNull())
775 return {};
776
777 return Importer.getToContext().getFunctionNoProtoType(ToResultType,
778 T->getExtInfo());
779}
780
781QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
782 QualType ToResultType = Importer.Import(T->getReturnType());
783 if (ToResultType.isNull())
784 return {};
785
786 // Import argument types
787 SmallVector<QualType, 4> ArgTypes;
788 for (const auto &A : T->param_types()) {
789 QualType ArgType = Importer.Import(A);
790 if (ArgType.isNull())
791 return {};
792 ArgTypes.push_back(ArgType);
793 }
794
795 // Import exception types
796 SmallVector<QualType, 4> ExceptionTypes;
797 for (const auto &E : T->exceptions()) {
798 QualType ExceptionType = Importer.Import(E);
799 if (ExceptionType.isNull())
800 return {};
801 ExceptionTypes.push_back(ExceptionType);
802 }
803
804 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
805 FunctionProtoType::ExtProtoInfo ToEPI;
806
807 ToEPI.ExtInfo = FromEPI.ExtInfo;
808 ToEPI.Variadic = FromEPI.Variadic;
809 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
810 ToEPI.TypeQuals = FromEPI.TypeQuals;
811 ToEPI.RefQualifier = FromEPI.RefQualifier;
812 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
813 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
814 ToEPI.ExceptionSpec.NoexceptExpr =
815 Importer.Import(FromEPI.ExceptionSpec.NoexceptExpr);
816 ToEPI.ExceptionSpec.SourceDecl = cast_or_null<FunctionDecl>(
817 Importer.Import(FromEPI.ExceptionSpec.SourceDecl));
818 ToEPI.ExceptionSpec.SourceTemplate = cast_or_null<FunctionDecl>(
819 Importer.Import(FromEPI.ExceptionSpec.SourceTemplate));
820
821 return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
822}
823
824QualType ASTNodeImporter::VisitUnresolvedUsingType(
825 const UnresolvedUsingType *T) {
826 const auto *ToD =
827 cast_or_null<UnresolvedUsingTypenameDecl>(Importer.Import(T->getDecl()));
828 if (!ToD)
829 return {};
830
831 auto *ToPrevD =
832 cast_or_null<UnresolvedUsingTypenameDecl>(
833 Importer.Import(T->getDecl()->getPreviousDecl()));
834 if (!ToPrevD && T->getDecl()->getPreviousDecl())
835 return {};
836
837 return Importer.getToContext().getTypeDeclType(ToD, ToPrevD);
838}
839
840QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
841 QualType ToInnerType = Importer.Import(T->getInnerType());
842 if (ToInnerType.isNull())
843 return {};
844
845 return Importer.getToContext().getParenType(ToInnerType);
846}
847
848QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
849 auto *ToDecl =
850 dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
851 if (!ToDecl)
852 return {};
853
854 return Importer.getToContext().getTypeDeclType(ToDecl);
855}
856
857QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
858 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
859 if (!ToExpr)
860 return {};
861
862 return Importer.getToContext().getTypeOfExprType(ToExpr);
863}
864
865QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
866 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
867 if (ToUnderlyingType.isNull())
868 return {};
869
870 return Importer.getToContext().getTypeOfType(ToUnderlyingType);
871}
872
873QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
874 // FIXME: Make sure that the "to" context supports C++0x!
875 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
876 if (!ToExpr)
877 return {};
878
879 QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
880 if (UnderlyingType.isNull())
881 return {};
882
883 return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
884}
885
886QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
887 QualType ToBaseType = Importer.Import(T->getBaseType());
888 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
889 if (ToBaseType.isNull() || ToUnderlyingType.isNull())
890 return {};
891
892 return Importer.getToContext().getUnaryTransformType(ToBaseType,
893 ToUnderlyingType,
894 T->getUTTKind());
895}
896
897QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
898 // FIXME: Make sure that the "to" context supports C++11!
899 QualType FromDeduced = T->getDeducedType();
900 QualType ToDeduced;
901 if (!FromDeduced.isNull()) {
902 ToDeduced = Importer.Import(FromDeduced);
903 if (ToDeduced.isNull())
904 return {};
905 }
906
907 return Importer.getToContext().getAutoType(ToDeduced, T->getKeyword(),
908 /*IsDependent*/false);
909}
910
911QualType ASTNodeImporter::VisitInjectedClassNameType(
912 const InjectedClassNameType *T) {
913 auto *D = cast_or_null<CXXRecordDecl>(Importer.Import(T->getDecl()));
914 if (!D)
915 return {};
916
917 QualType InjType = Importer.Import(T->getInjectedSpecializationType());
918 if (InjType.isNull())
919 return {};
920
921 // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
922 // See comments in InjectedClassNameType definition for details
923 // return Importer.getToContext().getInjectedClassNameType(D, InjType);
924 enum {
925 TypeAlignmentInBits = 4,
926 TypeAlignment = 1 << TypeAlignmentInBits
927 };
928
929 return QualType(new (Importer.getToContext(), TypeAlignment)
930 InjectedClassNameType(D, InjType), 0);
931}
932
933QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
934 auto *ToDecl = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
935 if (!ToDecl)
936 return {};
937
938 return Importer.getToContext().getTagDeclType(ToDecl);
939}
940
941QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
942 auto *ToDecl = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
943 if (!ToDecl)
944 return {};
945
946 return Importer.getToContext().getTagDeclType(ToDecl);
947}
948
949QualType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
950 QualType FromModifiedType = T->getModifiedType();
951 QualType FromEquivalentType = T->getEquivalentType();
952 QualType ToModifiedType;
953 QualType ToEquivalentType;
954
955 if (!FromModifiedType.isNull()) {
956 ToModifiedType = Importer.Import(FromModifiedType);
957 if (ToModifiedType.isNull())
958 return {};
959 }
960 if (!FromEquivalentType.isNull()) {
961 ToEquivalentType = Importer.Import(FromEquivalentType);
962 if (ToEquivalentType.isNull())
963 return {};
964 }
965
966 return Importer.getToContext().getAttributedType(T->getAttrKind(),
967 ToModifiedType, ToEquivalentType);
968}
969
970QualType ASTNodeImporter::VisitTemplateTypeParmType(
971 const TemplateTypeParmType *T) {
972 auto *ParmDecl =
973 cast_or_null<TemplateTypeParmDecl>(Importer.Import(T->getDecl()));
974 if (!ParmDecl && T->getDecl())
975 return {};
976
977 return Importer.getToContext().getTemplateTypeParmType(
978 T->getDepth(), T->getIndex(), T->isParameterPack(), ParmDecl);
979}
980
981QualType ASTNodeImporter::VisitSubstTemplateTypeParmType(
982 const SubstTemplateTypeParmType *T) {
983 const auto *Replaced =
984 cast_or_null<TemplateTypeParmType>(Importer.Import(
985 QualType(T->getReplacedParameter(), 0)).getTypePtr());
986 if (!Replaced)
987 return {};
988
989 QualType Replacement = Importer.Import(T->getReplacementType());
990 if (Replacement.isNull())
991 return {};
992 Replacement = Replacement.getCanonicalType();
993
994 return Importer.getToContext().getSubstTemplateTypeParmType(
995 Replaced, Replacement);
996}
997
998QualType ASTNodeImporter::VisitTemplateSpecializationType(
999 const TemplateSpecializationType *T) {
1000 TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1001 if (ToTemplate.isNull())
1002 return {};
1003
1004 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1005 if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1006 return {};
1007
1008 QualType ToCanonType;
1009 if (!QualType(T, 0).isCanonical()) {
1010 QualType FromCanonType
1011 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1012 ToCanonType =Importer.Import(FromCanonType);
1013 if (ToCanonType.isNull())
1014 return {};
1015 }
1016 return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
1017 ToTemplateArgs,
1018 ToCanonType);
1019}
1020
1021QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1022 NestedNameSpecifier *ToQualifier = nullptr;
1023 // Note: the qualifier in an ElaboratedType is optional.
1024 if (T->getQualifier()) {
1025 ToQualifier = Importer.Import(T->getQualifier());
1026 if (!ToQualifier)
1027 return {};
1028 }
1029
1030 QualType ToNamedType = Importer.Import(T->getNamedType());
1031 if (ToNamedType.isNull())
1032 return {};
1033
1034 TagDecl *OwnedTagDecl =
1035 cast_or_null<TagDecl>(Importer.Import(T->getOwnedTagDecl()));
1036 if (!OwnedTagDecl && T->getOwnedTagDecl())
1037 return {};
1038
1039 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1040 ToQualifier, ToNamedType,
1041 OwnedTagDecl);
1042}
1043
1044QualType ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
1045 QualType Pattern = Importer.Import(T->getPattern());
1046 if (Pattern.isNull())
1047 return {};
1048
1049 return Importer.getToContext().getPackExpansionType(Pattern,
1050 T->getNumExpansions());
1051}
1052
1053QualType ASTNodeImporter::VisitDependentTemplateSpecializationType(
1054 const DependentTemplateSpecializationType *T) {
1055 NestedNameSpecifier *Qualifier = Importer.Import(T->getQualifier());
1056 if (!Qualifier && T->getQualifier())
1057 return {};
1058
1059 IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1060 if (!Name && T->getIdentifier())
1061 return {};
1062
1063 SmallVector<TemplateArgument, 2> ToPack;
1064 ToPack.reserve(T->getNumArgs());
1065 if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToPack))
1066 return {};
1067
1068 return Importer.getToContext().getDependentTemplateSpecializationType(
1069 T->getKeyword(), Qualifier, Name, ToPack);
1070}
1071
1072QualType ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) {
1073 NestedNameSpecifier *NNS = Importer.Import(T->getQualifier());
1074 if (!NNS && T->getQualifier())
1075 return QualType();
1076
1077 IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1078 if (!Name && T->getIdentifier())
1079 return QualType();
1080
1081 QualType Canon = (T == T->getCanonicalTypeInternal().getTypePtr())
1082 ? QualType()
1083 : Importer.Import(T->getCanonicalTypeInternal());
1084 if (!Canon.isNull())
1085 Canon = Canon.getCanonicalType();
1086
1087 return Importer.getToContext().getDependentNameType(T->getKeyword(), NNS,
1088 Name, Canon);
1089}
1090
1091QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1092 auto *Class =
1093 dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1094 if (!Class)
1095 return {};
1096
1097 return Importer.getToContext().getObjCInterfaceType(Class);
1098}
1099
1100QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1101 QualType ToBaseType = Importer.Import(T->getBaseType());
1102 if (ToBaseType.isNull())
1103 return {};
1104
1105 SmallVector<QualType, 4> TypeArgs;
1106 for (auto TypeArg : T->getTypeArgsAsWritten()) {
1107 QualType ImportedTypeArg = Importer.Import(TypeArg);
1108 if (ImportedTypeArg.isNull())
1109 return {};
1110
1111 TypeArgs.push_back(ImportedTypeArg);
1112 }
1113
1114 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1115 for (auto *P : T->quals()) {
1116 auto *Protocol = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(P));
1117 if (!Protocol)
1118 return {};
1119 Protocols.push_back(Protocol);
1120 }
1121
1122 return Importer.getToContext().getObjCObjectType(ToBaseType, TypeArgs,
1123 Protocols,
1124 T->isKindOfTypeAsWritten());
1125}
1126
1127QualType
1128ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1129 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1130 if (ToPointeeType.isNull())
1131 return {};
1132
1133 return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
1134}
1135
1136//----------------------------------------------------------------------------
1137// Import Declarations
1138//----------------------------------------------------------------------------
1139bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
1140 DeclContext *&LexicalDC,
1141 DeclarationName &Name,
1142 NamedDecl *&ToD,
1143 SourceLocation &Loc) {
1144 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1145 // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1146 DeclContext *OrigDC = D->getDeclContext();
1147 FunctionDecl *FunDecl;
1148 if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1149 FunDecl->hasBody()) {
1150 SourceRange RecR = D->getSourceRange();
1151 SourceRange BodyR = FunDecl->getBody()->getSourceRange();
1152 // If RecordDecl is not in Body (it is a param), we bail out.
1153 if (RecR.isValid() && BodyR.isValid() &&
1154 (RecR.getBegin() < BodyR.getBegin() ||
1155 BodyR.getEnd() < RecR.getEnd())) {
1156 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1157 << D->getDeclKindName();
1158 return true;
1159 }
1160 }
1161
1162 // Import the context of this declaration.
1163 DC = Importer.ImportContext(OrigDC);
1164 if (!DC)
1165 return true;
1166
1167 LexicalDC = DC;
1168 if (D->getDeclContext() != D->getLexicalDeclContext()) {
1169 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1170 if (!LexicalDC)
1171 return true;
1172 }
1173
1174 // Import the name of this declaration.
1175 Name = Importer.Import(D->getDeclName());
1176 if (D->getDeclName() && !Name)
1177 return true;
1178
1179 // Import the location of this declaration.
1180 Loc = Importer.Import(D->getLocation());
1181 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1182 return false;
1183}
1184
1185void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1186 if (!FromD)
1187 return;
1188
1189 if (!ToD) {
1190 ToD = Importer.Import(FromD);
1191 if (!ToD)
1192 return;
1193 }
1194
1195 if (auto *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1196 if (auto *ToRecord = cast_or_null<RecordDecl>(ToD)) {
1197 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
1198 ImportDefinition(FromRecord, ToRecord);
1199 }
1200 }
1201 return;
1202 }
1203
1204 if (auto *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1205 if (auto *ToEnum = cast_or_null<EnumDecl>(ToD)) {
1206 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1207 ImportDefinition(FromEnum, ToEnum);
1208 }
1209 }
1210 return;
1211 }
1212}
1213
1214void
1215ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
1216 DeclarationNameInfo& To) {
1217 // NOTE: To.Name and To.Loc are already imported.
1218 // We only have to import To.LocInfo.
1219 switch (To.getName().getNameKind()) {
1220 case DeclarationName::Identifier:
1221 case DeclarationName::ObjCZeroArgSelector:
1222 case DeclarationName::ObjCOneArgSelector:
1223 case DeclarationName::ObjCMultiArgSelector:
1224 case DeclarationName::CXXUsingDirective:
1225 case DeclarationName::CXXDeductionGuideName:
1226 return;
1227
1228 case DeclarationName::CXXOperatorName: {
1229 SourceRange Range = From.getCXXOperatorNameRange();
1230 To.setCXXOperatorNameRange(Importer.Import(Range));
1231 return;
1232 }
1233 case DeclarationName::CXXLiteralOperatorName: {
1234 SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
1235 To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
1236 return;
1237 }
1238 case DeclarationName::CXXConstructorName:
1239 case DeclarationName::CXXDestructorName:
1240 case DeclarationName::CXXConversionFunctionName: {
1241 TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
1242 To.setNamedTypeInfo(Importer.Import(FromTInfo));
1243 return;
1244 }
1245 }
1246 llvm_unreachable("Unknown name kind.")::llvm::llvm_unreachable_internal("Unknown name kind.", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 1246)
;
1247}
1248
1249void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1250 if (Importer.isMinimalImport() && !ForceImport) {
1251 Importer.ImportContext(FromDC);
1252 return;
1253 }
1254
1255 for (auto *From : FromDC->decls())
1256 Importer.Import(From);
1257}
1258
1259void ASTNodeImporter::ImportImplicitMethods(
1260 const CXXRecordDecl *From, CXXRecordDecl *To) {
1261 assert(From->isCompleteDefinition() && To->getDefinition() == To &&(static_cast <bool> (From->isCompleteDefinition() &&
To->getDefinition() == To && "Import implicit methods to or from non-definition"
) ? void (0) : __assert_fail ("From->isCompleteDefinition() && To->getDefinition() == To && \"Import implicit methods to or from non-definition\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 1262, __extension__ __PRETTY_FUNCTION__))
1262 "Import implicit methods to or from non-definition")(static_cast <bool> (From->isCompleteDefinition() &&
To->getDefinition() == To && "Import implicit methods to or from non-definition"
) ? void (0) : __assert_fail ("From->isCompleteDefinition() && To->getDefinition() == To && \"Import implicit methods to or from non-definition\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 1262, __extension__ __PRETTY_FUNCTION__))
;
1263
1264 for (CXXMethodDecl *FromM : From->methods())
1265 if (FromM->isImplicit())
1266 Importer.Import(FromM);
1267}
1268
1269static void setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To,
1270 ASTImporter &Importer) {
1271 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
1272 auto *ToTypedef =
1273 cast_or_null<TypedefNameDecl>(Importer.Import(FromTypedef));
1274 assert (ToTypedef && "Failed to import typedef of an anonymous structure")(static_cast <bool> (ToTypedef && "Failed to import typedef of an anonymous structure"
) ? void (0) : __assert_fail ("ToTypedef && \"Failed to import typedef of an anonymous structure\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 1274, __extension__ __PRETTY_FUNCTION__))
;
1275
1276 To->setTypedefNameForAnonDecl(ToTypedef);
1277 }
1278}
1279
1280bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To,
1281 ImportDefinitionKind Kind) {
1282 if (To->getDefinition() || To->isBeingDefined()) {
1283 if (Kind == IDK_Everything)
1284 ImportDeclContext(From, /*ForceImport=*/true);
1285
1286 return false;
1287 }
1288
1289 To->startDefinition();
1290
1291 setTypedefNameForAnonDecl(From, To, Importer);
1292
1293 // Add base classes.
1294 if (auto *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
1295 auto *FromCXX = cast<CXXRecordDecl>(From);
1296
1297 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1298 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1299 ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
1300 ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
1301 ToData.Aggregate = FromData.Aggregate;
1302 ToData.PlainOldData = FromData.PlainOldData;
1303 ToData.Empty = FromData.Empty;
1304 ToData.Polymorphic = FromData.Polymorphic;
1305 ToData.Abstract = FromData.Abstract;
1306 ToData.IsStandardLayout = FromData.IsStandardLayout;
1307 ToData.IsCXX11StandardLayout = FromData.IsCXX11StandardLayout;
1308 ToData.HasBasesWithFields = FromData.HasBasesWithFields;
1309 ToData.HasBasesWithNonStaticDataMembers =
1310 FromData.HasBasesWithNonStaticDataMembers;
1311 ToData.HasPrivateFields = FromData.HasPrivateFields;
1312 ToData.HasProtectedFields = FromData.HasProtectedFields;
1313 ToData.HasPublicFields = FromData.HasPublicFields;
1314 ToData.HasMutableFields = FromData.HasMutableFields;
1315 ToData.HasVariantMembers = FromData.HasVariantMembers;
1316 ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
1317 ToData.HasInClassInitializer = FromData.HasInClassInitializer;
1318 ToData.HasUninitializedReferenceMember
1319 = FromData.HasUninitializedReferenceMember;
1320 ToData.HasUninitializedFields = FromData.HasUninitializedFields;
1321 ToData.HasInheritedConstructor = FromData.HasInheritedConstructor;
1322 ToData.HasInheritedAssignment = FromData.HasInheritedAssignment;
1323 ToData.NeedOverloadResolutionForCopyConstructor
1324 = FromData.NeedOverloadResolutionForCopyConstructor;
1325 ToData.NeedOverloadResolutionForMoveConstructor
1326 = FromData.NeedOverloadResolutionForMoveConstructor;
1327 ToData.NeedOverloadResolutionForMoveAssignment
1328 = FromData.NeedOverloadResolutionForMoveAssignment;
1329 ToData.NeedOverloadResolutionForDestructor
1330 = FromData.NeedOverloadResolutionForDestructor;
1331 ToData.DefaultedCopyConstructorIsDeleted
1332 = FromData.DefaultedCopyConstructorIsDeleted;
1333 ToData.DefaultedMoveConstructorIsDeleted
1334 = FromData.DefaultedMoveConstructorIsDeleted;
1335 ToData.DefaultedMoveAssignmentIsDeleted
1336 = FromData.DefaultedMoveAssignmentIsDeleted;
1337 ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
1338 ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
1339 ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
1340 ToData.HasConstexprNonCopyMoveConstructor
1341 = FromData.HasConstexprNonCopyMoveConstructor;
1342 ToData.HasDefaultedDefaultConstructor
1343 = FromData.HasDefaultedDefaultConstructor;
1344 ToData.DefaultedDefaultConstructorIsConstexpr
1345 = FromData.DefaultedDefaultConstructorIsConstexpr;
1346 ToData.HasConstexprDefaultConstructor
1347 = FromData.HasConstexprDefaultConstructor;
1348 ToData.HasNonLiteralTypeFieldsOrBases
1349 = FromData.HasNonLiteralTypeFieldsOrBases;
1350 // ComputedVisibleConversions not imported.
1351 ToData.UserProvidedDefaultConstructor
1352 = FromData.UserProvidedDefaultConstructor;
1353 ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
1354 ToData.ImplicitCopyConstructorCanHaveConstParamForVBase
1355 = FromData.ImplicitCopyConstructorCanHaveConstParamForVBase;
1356 ToData.ImplicitCopyConstructorCanHaveConstParamForNonVBase
1357 = FromData.ImplicitCopyConstructorCanHaveConstParamForNonVBase;
1358 ToData.ImplicitCopyAssignmentHasConstParam
1359 = FromData.ImplicitCopyAssignmentHasConstParam;
1360 ToData.HasDeclaredCopyConstructorWithConstParam
1361 = FromData.HasDeclaredCopyConstructorWithConstParam;
1362 ToData.HasDeclaredCopyAssignmentWithConstParam
1363 = FromData.HasDeclaredCopyAssignmentWithConstParam;
1364
1365 SmallVector<CXXBaseSpecifier *, 4> Bases;
1366 for (const auto &Base1 : FromCXX->bases()) {
1367 QualType T = Importer.Import(Base1.getType());
1368 if (T.isNull())
1369 return true;
1370
1371 SourceLocation EllipsisLoc;
1372 if (Base1.isPackExpansion())
1373 EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
1374
1375 // Ensure that we have a definition for the base.
1376 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
1377
1378 Bases.push_back(
1379 new (Importer.getToContext())
1380 CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
1381 Base1.isVirtual(),
1382 Base1.isBaseOfClass(),
1383 Base1.getAccessSpecifierAsWritten(),
1384 Importer.Import(Base1.getTypeSourceInfo()),
1385 EllipsisLoc));
1386 }
1387 if (!Bases.empty())
1388 ToCXX->setBases(Bases.data(), Bases.size());
1389 }
1390
1391 if (shouldForceImportDeclContext(Kind))
1392 ImportDeclContext(From, /*ForceImport=*/true);
1393
1394 To->completeDefinition();
1395 return false;
1396}
1397
1398bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
1399 ImportDefinitionKind Kind) {
1400 if (To->getAnyInitializer())
1401 return false;
1402
1403 // FIXME: Can we really import any initializer? Alternatively, we could force
1404 // ourselves to import every declaration of a variable and then only use
1405 // getInit() here.
1406 To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
1407
1408 // FIXME: Other bits to merge?
1409
1410 return false;
1411}
1412
1413bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To,
1414 ImportDefinitionKind Kind) {
1415 if (To->getDefinition() || To->isBeingDefined()) {
1416 if (Kind == IDK_Everything)
1417 ImportDeclContext(From, /*ForceImport=*/true);
1418 return false;
1419 }
1420
1421 To->startDefinition();
1422
1423 setTypedefNameForAnonDecl(From, To, Importer);
1424
1425 QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
1426 if (T.isNull())
1427 return true;
1428
1429 QualType ToPromotionType = Importer.Import(From->getPromotionType());
1430 if (ToPromotionType.isNull())
1431 return true;
1432
1433 if (shouldForceImportDeclContext(Kind))
1434 ImportDeclContext(From, /*ForceImport=*/true);
1435
1436 // FIXME: we might need to merge the number of positive or negative bits
1437 // if the enumerator lists don't match.
1438 To->completeDefinition(T, ToPromotionType,
1439 From->getNumPositiveBits(),
1440 From->getNumNegativeBits());
1441 return false;
1442}
1443
1444TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
1445 TemplateParameterList *Params) {
1446 SmallVector<NamedDecl *, 4> ToParams(Params->size());
1447 if (ImportContainerChecked(*Params, ToParams))
1448 return nullptr;
1449
1450 Expr *ToRequiresClause;
1451 if (Expr *const R = Params->getRequiresClause()) {
1452 ToRequiresClause = Importer.Import(R);
1453 if (!ToRequiresClause)
1454 return nullptr;
1455 } else {
1456 ToRequiresClause = nullptr;
1457 }
1458
1459 return TemplateParameterList::Create(Importer.getToContext(),
1460 Importer.Import(Params->getTemplateLoc()),
1461 Importer.Import(Params->getLAngleLoc()),
1462 ToParams,
1463 Importer.Import(Params->getRAngleLoc()),
1464 ToRequiresClause);
1465}
1466
1467TemplateArgument
1468ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
1469 switch (From.getKind()) {
1470 case TemplateArgument::Null:
1471 return TemplateArgument();
1472
1473 case TemplateArgument::Type: {
1474 QualType ToType = Importer.Import(From.getAsType());
1475 if (ToType.isNull())
1476 return {};
1477 return TemplateArgument(ToType);
1478 }
1479
1480 case TemplateArgument::Integral: {
1481 QualType ToType = Importer.Import(From.getIntegralType());
1482 if (ToType.isNull())
1483 return {};
1484 return TemplateArgument(From, ToType);
1485 }
1486
1487 case TemplateArgument::Declaration: {
1488 auto *To = cast_or_null<ValueDecl>(Importer.Import(From.getAsDecl()));
1489 QualType ToType = Importer.Import(From.getParamTypeForDecl());
1490 if (!To || ToType.isNull())
1491 return {};
1492 return TemplateArgument(To, ToType);
1493 }
1494
1495 case TemplateArgument::NullPtr: {
1496 QualType ToType = Importer.Import(From.getNullPtrType());
1497 if (ToType.isNull())
1498 return {};
1499 return TemplateArgument(ToType, /*isNullPtr*/true);
1500 }
1501
1502 case TemplateArgument::Template: {
1503 TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
1504 if (ToTemplate.isNull())
1505 return {};
1506
1507 return TemplateArgument(ToTemplate);
1508 }
1509
1510 case TemplateArgument::TemplateExpansion: {
1511 TemplateName ToTemplate
1512 = Importer.Import(From.getAsTemplateOrTemplatePattern());
1513 if (ToTemplate.isNull())
1514 return {};
1515
1516 return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
1517 }
1518
1519 case TemplateArgument::Expression:
1520 if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
1521 return TemplateArgument(ToExpr);
1522 return TemplateArgument();
1523
1524 case TemplateArgument::Pack: {
1525 SmallVector<TemplateArgument, 2> ToPack;
1526 ToPack.reserve(From.pack_size());
1527 if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
1528 return {};
1529
1530 return TemplateArgument(
1531 llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
1532 }
1533 }
1534
1535 llvm_unreachable("Invalid template argument kind")::llvm::llvm_unreachable_internal("Invalid template argument kind"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 1535)
;
1536}
1537
1538Optional<TemplateArgumentLoc>
1539ASTNodeImporter::ImportTemplateArgumentLoc(const TemplateArgumentLoc &TALoc) {
1540 TemplateArgument Arg = ImportTemplateArgument(TALoc.getArgument());
1541 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
1542 TemplateArgumentLocInfo ToInfo;
1543 if (Arg.getKind() == TemplateArgument::Expression) {
1544 Expr *E = Importer.Import(FromInfo.getAsExpr());
1545 ToInfo = TemplateArgumentLocInfo(E);
1546 if (!E)
1547 return None;
1548 } else if (Arg.getKind() == TemplateArgument::Type) {
1549 if (TypeSourceInfo *TSI = Importer.Import(FromInfo.getAsTypeSourceInfo()))
1550 ToInfo = TemplateArgumentLocInfo(TSI);
1551 else
1552 return None;
1553 } else {
1554 ToInfo = TemplateArgumentLocInfo(
1555 Importer.Import(FromInfo.getTemplateQualifierLoc()),
1556 Importer.Import(FromInfo.getTemplateNameLoc()),
1557 Importer.Import(FromInfo.getTemplateEllipsisLoc()));
1558 }
1559 return TemplateArgumentLoc(Arg, ToInfo);
1560}
1561
1562bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
1563 unsigned NumFromArgs,
1564 SmallVectorImpl<TemplateArgument> &ToArgs) {
1565 for (unsigned I = 0; I != NumFromArgs; ++I) {
1566 TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
1567 if (To.isNull() && !FromArgs[I].isNull())
1568 return true;
1569
1570 ToArgs.push_back(To);
1571 }
1572
1573 return false;
1574}
1575
1576// We cannot use Optional<> pattern here and below because
1577// TemplateArgumentListInfo's operator new is declared as deleted so it cannot
1578// be stored in Optional.
1579template <typename InContainerTy>
1580bool ASTNodeImporter::ImportTemplateArgumentListInfo(
1581 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
1582 for (const auto &FromLoc : Container) {
1583 if (auto ToLoc = ImportTemplateArgumentLoc(FromLoc))
1584 ToTAInfo.addArgument(*ToLoc);
1585 else
1586 return true;
1587 }
1588 return false;
1589}
1590
1591static StructuralEquivalenceKind
1592getStructuralEquivalenceKind(const ASTImporter &Importer) {
1593 return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal
1594 : StructuralEquivalenceKind::Default;
1595}
1596
1597bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
1598 StructuralEquivalenceContext Ctx(
1599 Importer.getFromContext(), Importer.getToContext(),
1600 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1601 false, Complain);
1602 return Ctx.IsEquivalent(From, To);
1603}
1604
1605bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
1606 RecordDecl *ToRecord, bool Complain) {
1607 // Eliminate a potential failure point where we attempt to re-import
1608 // something we're trying to import while completing ToRecord.
1609 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
1610 if (ToOrigin) {
1611 auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
1612 if (ToOriginRecord)
1613 ToRecord = ToOriginRecord;
1614 }
1615
1616 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1617 ToRecord->getASTContext(),
1618 Importer.getNonEquivalentDecls(),
1619 getStructuralEquivalenceKind(Importer),
1620 false, Complain);
1621 return Ctx.IsEquivalent(FromRecord, ToRecord);
1622}
1623
1624bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
1625 bool Complain) {
1626 StructuralEquivalenceContext Ctx(
1627 Importer.getFromContext(), Importer.getToContext(),
1628 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1629 false, Complain);
1630 return Ctx.IsEquivalent(FromVar, ToVar);
1631}
1632
1633bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
1634 StructuralEquivalenceContext Ctx(
1635 Importer.getFromContext(), Importer.getToContext(),
1636 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer));
1637 return Ctx.IsEquivalent(FromEnum, ToEnum);
1638}
1639
1640bool ASTNodeImporter::IsStructuralMatch(FunctionTemplateDecl *From,
1641 FunctionTemplateDecl *To) {
1642 StructuralEquivalenceContext Ctx(
1643 Importer.getFromContext(), Importer.getToContext(),
1644 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1645 false, false);
1646 return Ctx.IsEquivalent(From, To);
1647}
1648
1649bool ASTNodeImporter::IsStructuralMatch(FunctionDecl *From, FunctionDecl *To) {
1650 StructuralEquivalenceContext Ctx(
1651 Importer.getFromContext(), Importer.getToContext(),
1652 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1653 false, false);
1654 return Ctx.IsEquivalent(From, To);
1655}
1656
1657bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
1658 EnumConstantDecl *ToEC) {
1659 const llvm::APSInt &FromVal = FromEC->getInitVal();
1660 const llvm::APSInt &ToVal = ToEC->getInitVal();
1661
1662 return FromVal.isSigned() == ToVal.isSigned() &&
1663 FromVal.getBitWidth() == ToVal.getBitWidth() &&
1664 FromVal == ToVal;
1665}
1666
1667bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
1668 ClassTemplateDecl *To) {
1669 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1670 Importer.getToContext(),
1671 Importer.getNonEquivalentDecls(),
1672 getStructuralEquivalenceKind(Importer));
1673 return Ctx.IsEquivalent(From, To);
1674}
1675
1676bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
1677 VarTemplateDecl *To) {
1678 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1679 Importer.getToContext(),
1680 Importer.getNonEquivalentDecls(),
1681 getStructuralEquivalenceKind(Importer));
1682 return Ctx.IsEquivalent(From, To);
1683}
1684
1685Decl *ASTNodeImporter::VisitDecl(Decl *D) {
1686 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1687 << D->getDeclKindName();
1688 return nullptr;
1689}
1690
1691Decl *ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) {
1692 // Import the context of this declaration.
1693 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
1694 if (!DC)
1695 return nullptr;
1696
1697 DeclContext *LexicalDC = DC;
1698 if (D->getDeclContext() != D->getLexicalDeclContext()) {
1699 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1700 if (!LexicalDC)
1701 return nullptr;
1702 }
1703
1704 // Import the location of this declaration.
1705 SourceLocation Loc = Importer.Import(D->getLocation());
1706
1707 EmptyDecl *ToD;
1708 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, Loc))
1709 return ToD;
1710
1711 ToD->setLexicalDeclContext(LexicalDC);
1712 LexicalDC->addDeclInternal(ToD);
1713 return ToD;
1714}
1715
1716Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
1717 TranslationUnitDecl *ToD =
1718 Importer.getToContext().getTranslationUnitDecl();
1719
1720 Importer.MapImported(D, ToD);
1721
1722 return ToD;
1723}
1724
1725Decl *ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
1726 SourceLocation Loc = Importer.Import(D->getLocation());
1727 SourceLocation ColonLoc = Importer.Import(D->getColonLoc());
1728
1729 // Import the context of this declaration.
1730 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
1731 if (!DC)
1732 return nullptr;
1733
1734 AccessSpecDecl *ToD;
1735 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
1736 DC, Loc, ColonLoc))
1737 return ToD;
1738
1739 // Lexical DeclContext and Semantic DeclContext
1740 // is always the same for the accessSpec.
1741 ToD->setLexicalDeclContext(DC);
1742 DC->addDeclInternal(ToD);
1743
1744 return ToD;
1745}
1746
1747Decl *ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
1748 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
1749 if (!DC)
1750 return nullptr;
1751
1752 DeclContext *LexicalDC = DC;
1753
1754 // Import the location of this declaration.
1755 SourceLocation Loc = Importer.Import(D->getLocation());
1756
1757 Expr *AssertExpr = Importer.Import(D->getAssertExpr());
1758 if (!AssertExpr)
1759 return nullptr;
1760
1761 StringLiteral *FromMsg = D->getMessage();
1762 auto *ToMsg = cast_or_null<StringLiteral>(Importer.Import(FromMsg));
1763 if (!ToMsg && FromMsg)
1764 return nullptr;
1765
1766 StaticAssertDecl *ToD;
1767 if (GetImportedOrCreateDecl(
1768 ToD, D, Importer.getToContext(), DC, Loc, AssertExpr, ToMsg,
1769 Importer.Import(D->getRParenLoc()), D->isFailed()))
1770 return ToD;
1771
1772 ToD->setLexicalDeclContext(LexicalDC);
1773 LexicalDC->addDeclInternal(ToD);
1774 return ToD;
1775}
1776
1777Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
1778 // Import the major distinguishing characteristics of this namespace.
1779 DeclContext *DC, *LexicalDC;
1780 DeclarationName Name;
1781 SourceLocation Loc;
1782 NamedDecl *ToD;
1783 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1784 return nullptr;
1785 if (ToD)
1786 return ToD;
1787
1788 NamespaceDecl *MergeWithNamespace = nullptr;
1789 if (!Name) {
1790 // This is an anonymous namespace. Adopt an existing anonymous
1791 // namespace if we can.
1792 // FIXME: Not testable.
1793 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
1794 MergeWithNamespace = TU->getAnonymousNamespace();
1795 else
1796 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
1797 } else {
1798 SmallVector<NamedDecl *, 4> ConflictingDecls;
1799 SmallVector<NamedDecl *, 2> FoundDecls;
1800 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
1801 for (auto *FoundDecl : FoundDecls) {
1802 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace))
1803 continue;
1804
1805 if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
1806 MergeWithNamespace = FoundNS;
1807 ConflictingDecls.clear();
1808 break;
1809 }
1810
1811 ConflictingDecls.push_back(FoundDecl);
1812 }
1813
1814 if (!ConflictingDecls.empty()) {
1815 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
1816 ConflictingDecls.data(),
1817 ConflictingDecls.size());
1818 }
1819 }
1820
1821 // Create the "to" namespace, if needed.
1822 NamespaceDecl *ToNamespace = MergeWithNamespace;
1823 if (!ToNamespace) {
1824 if (GetImportedOrCreateDecl(
1825 ToNamespace, D, Importer.getToContext(), DC, D->isInline(),
1826 Importer.Import(D->getLocStart()), Loc, Name.getAsIdentifierInfo(),
1827 /*PrevDecl=*/nullptr))
1828 return ToNamespace;
1829 ToNamespace->setLexicalDeclContext(LexicalDC);
1830 LexicalDC->addDeclInternal(ToNamespace);
1831
1832 // If this is an anonymous namespace, register it as the anonymous
1833 // namespace within its context.
1834 if (!Name) {
1835 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
1836 TU->setAnonymousNamespace(ToNamespace);
1837 else
1838 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
1839 }
1840 }
1841 Importer.MapImported(D, ToNamespace);
1842
1843 ImportDeclContext(D);
1844
1845 return ToNamespace;
1846}
1847
1848Decl *ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1849 // Import the major distinguishing characteristics of this namespace.
1850 DeclContext *DC, *LexicalDC;
1851 DeclarationName Name;
1852 SourceLocation Loc;
1853 NamedDecl *LookupD;
1854 if (ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
1855 return nullptr;
1856 if (LookupD)
1857 return LookupD;
1858
1859 // NOTE: No conflict resolution is done for namespace aliases now.
1860
1861 auto *TargetDecl = cast_or_null<NamespaceDecl>(
1862 Importer.Import(D->getNamespace()));
1863 if (!TargetDecl)
1864 return nullptr;
1865
1866 IdentifierInfo *ToII = Importer.Import(D->getIdentifier());
1867 if (!ToII)
1868 return nullptr;
1869
1870 NestedNameSpecifierLoc ToQLoc = Importer.Import(D->getQualifierLoc());
1871 if (D->getQualifierLoc() && !ToQLoc)
1872 return nullptr;
1873
1874 NamespaceAliasDecl *ToD;
1875 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC,
1876 Importer.Import(D->getNamespaceLoc()),
1877 Importer.Import(D->getAliasLoc()), ToII, ToQLoc,
1878 Importer.Import(D->getTargetNameLoc()),
1879 TargetDecl))
1880 return ToD;
1881
1882 ToD->setLexicalDeclContext(LexicalDC);
1883 LexicalDC->addDeclInternal(ToD);
1884
1885 return ToD;
1886}
1887
1888Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
1889 // Import the major distinguishing characteristics of this typedef.
1890 DeclContext *DC, *LexicalDC;
1891 DeclarationName Name;
1892 SourceLocation Loc;
1893 NamedDecl *ToD;
1894 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1895 return nullptr;
1896 if (ToD)
1897 return ToD;
1898
1899 // If this typedef is not in block scope, determine whether we've
1900 // seen a typedef with the same name (that we can merge with) or any
1901 // other entity by that name (which name lookup could conflict with).
1902 if (!DC->isFunctionOrMethod()) {
1903 SmallVector<NamedDecl *, 4> ConflictingDecls;
1904 unsigned IDNS = Decl::IDNS_Ordinary;
1905 SmallVector<NamedDecl *, 2> FoundDecls;
1906 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
1907 for (auto *FoundDecl : FoundDecls) {
1908 if (!FoundDecl->isInIdentifierNamespace(IDNS))
1909 continue;
1910 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
1911 if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
1912 FoundTypedef->getUnderlyingType()))
1913 return Importer.MapImported(D, FoundTypedef);
1914 }
1915
1916 ConflictingDecls.push_back(FoundDecl);
1917 }
1918
1919 if (!ConflictingDecls.empty()) {
1920 Name = Importer.HandleNameConflict(Name, DC, IDNS,
1921 ConflictingDecls.data(),
1922 ConflictingDecls.size());
1923 if (!Name)
1924 return nullptr;
1925 }
1926 }
1927
1928 // Import the underlying type of this typedef;
1929 QualType T = Importer.Import(D->getUnderlyingType());
1930 if (T.isNull())
1931 return nullptr;
1932
1933 // Create the new typedef node.
1934 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
1935 SourceLocation StartL = Importer.Import(D->getLocStart());
1936
1937 TypedefNameDecl *ToTypedef;
1938 if (IsAlias) {
1939 if (GetImportedOrCreateDecl<TypeAliasDecl>(
1940 ToTypedef, D, Importer.getToContext(), DC, StartL, Loc,
1941 Name.getAsIdentifierInfo(), TInfo))
1942 return ToTypedef;
1943 } else if (GetImportedOrCreateDecl<TypedefDecl>(
1944 ToTypedef, D, Importer.getToContext(), DC, StartL, Loc,
1945 Name.getAsIdentifierInfo(), TInfo))
1946 return ToTypedef;
1947
1948 ToTypedef->setAccess(D->getAccess());
1949 ToTypedef->setLexicalDeclContext(LexicalDC);
1950
1951 // Templated declarations should not appear in DeclContext.
1952 TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
1953 if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
1954 LexicalDC->addDeclInternal(ToTypedef);
1955
1956 return ToTypedef;
1957}
1958
1959Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
1960 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
1961}
1962
1963Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
1964 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
1965}
1966
1967Decl *ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1968 // Import the major distinguishing characteristics of this typedef.
1969 DeclContext *DC, *LexicalDC;
1970 DeclarationName Name;
1971 SourceLocation Loc;
1972 NamedDecl *FoundD;
1973 if (ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
1974 return nullptr;
1975 if (FoundD)
1976 return FoundD;
1977
1978 // If this typedef is not in block scope, determine whether we've
1979 // seen a typedef with the same name (that we can merge with) or any
1980 // other entity by that name (which name lookup could conflict with).
1981 if (!DC->isFunctionOrMethod()) {
1982 SmallVector<NamedDecl *, 4> ConflictingDecls;
1983 unsigned IDNS = Decl::IDNS_Ordinary;
1984 SmallVector<NamedDecl *, 2> FoundDecls;
1985 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
1986 for (auto *FoundDecl : FoundDecls) {
1987 if (!FoundDecl->isInIdentifierNamespace(IDNS))
1988 continue;
1989 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
1990 return Importer.MapImported(D, FoundAlias);
1991 ConflictingDecls.push_back(FoundDecl);
1992 }
1993
1994 if (!ConflictingDecls.empty()) {
1995 Name = Importer.HandleNameConflict(Name, DC, IDNS,
1996 ConflictingDecls.data(),
1997 ConflictingDecls.size());
1998 if (!Name)
1999 return nullptr;
2000 }
2001 }
2002
2003 TemplateParameterList *Params = ImportTemplateParameterList(
2004 D->getTemplateParameters());
2005 if (!Params)
2006 return nullptr;
2007
2008 auto *TemplDecl = cast_or_null<TypeAliasDecl>(
2009 Importer.Import(D->getTemplatedDecl()));
2010 if (!TemplDecl)
2011 return nullptr;
2012
2013 TypeAliasTemplateDecl *ToAlias;
2014 if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2015 Name, Params, TemplDecl))
2016 return ToAlias;
2017
2018 TemplDecl->setDescribedAliasTemplate(ToAlias);
2019
2020 ToAlias->setAccess(D->getAccess());
2021 ToAlias->setLexicalDeclContext(LexicalDC);
2022 LexicalDC->addDeclInternal(ToAlias);
2023 return ToAlias;
2024}
2025
2026Decl *ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
2027 // Import the major distinguishing characteristics of this label.
2028 DeclContext *DC, *LexicalDC;
2029 DeclarationName Name;
2030 SourceLocation Loc;
2031 NamedDecl *ToD;
2032 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2033 return nullptr;
2034 if (ToD)
2035 return ToD;
2036
2037 assert(LexicalDC->isFunctionOrMethod())(static_cast <bool> (LexicalDC->isFunctionOrMethod()
) ? void (0) : __assert_fail ("LexicalDC->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 2037, __extension__ __PRETTY_FUNCTION__))
;
2038
2039 LabelDecl *ToLabel;
2040 if (D->isGnuLocal()
2041 ? GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC,
2042 Importer.Import(D->getLocation()),
2043 Name.getAsIdentifierInfo(),
2044 Importer.Import(D->getLocStart()))
2045 : GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC,
2046 Importer.Import(D->getLocation()),
2047 Name.getAsIdentifierInfo()))
2048 return ToLabel;
2049
2050 auto *Label = cast_or_null<LabelStmt>(Importer.Import(D->getStmt()));
2051 if (!Label)
2052 return nullptr;
2053
2054 ToLabel->setStmt(Label);
2055 ToLabel->setLexicalDeclContext(LexicalDC);
2056 LexicalDC->addDeclInternal(ToLabel);
2057 return ToLabel;
2058}
2059
2060Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2061 // Import the major distinguishing characteristics of this enum.
2062 DeclContext *DC, *LexicalDC;
2063 DeclarationName Name;
2064 SourceLocation Loc;
2065 NamedDecl *ToD;
2066 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2067 return nullptr;
2068 if (ToD)
2069 return ToD;
2070
2071 // Figure out what enum name we're looking for.
2072 unsigned IDNS = Decl::IDNS_Tag;
2073 DeclarationName SearchName = Name;
2074 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2075 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2076 IDNS = Decl::IDNS_Ordinary;
2077 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2078 IDNS |= Decl::IDNS_Ordinary;
2079
2080 // We may already have an enum of the same name; try to find and match it.
2081 if (!DC->isFunctionOrMethod() && SearchName) {
2082 SmallVector<NamedDecl *, 4> ConflictingDecls;
2083 SmallVector<NamedDecl *, 2> FoundDecls;
2084 DC->getRedeclContext()->localUncachedLookup(SearchName, FoundDecls);
2085 for (auto *FoundDecl : FoundDecls) {
2086 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2087 continue;
2088
2089 Decl *Found = FoundDecl;
2090 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2091 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2092 Found = Tag->getDecl();
2093 }
2094
2095 if (auto *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2096 if (IsStructuralMatch(D, FoundEnum))
2097 return Importer.MapImported(D, FoundEnum);
2098 }
2099
2100 ConflictingDecls.push_back(FoundDecl);
2101 }
2102
2103 if (!ConflictingDecls.empty()) {
2104 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2105 ConflictingDecls.data(),
2106 ConflictingDecls.size());
2107 }
2108 }
2109
2110 // Create the enum declaration.
2111 EnumDecl *D2;
2112 if (GetImportedOrCreateDecl(
2113 D2, D, Importer.getToContext(), DC, Importer.Import(D->getLocStart()),
2114 Loc, Name.getAsIdentifierInfo(), nullptr, D->isScoped(),
2115 D->isScopedUsingClassTag(), D->isFixed()))
2116 return D2;
2117
2118 // Import the qualifier, if any.
2119 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2120 D2->setAccess(D->getAccess());
2121 D2->setLexicalDeclContext(LexicalDC);
2122 LexicalDC->addDeclInternal(D2);
2123
2124 // Import the integer type.
2125 QualType ToIntegerType = Importer.Import(D->getIntegerType());
2126 if (ToIntegerType.isNull())
2127 return nullptr;
2128 D2->setIntegerType(ToIntegerType);
2129
2130 // Import the definition
2131 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
2132 return nullptr;
2133
2134 return D2;
2135}
2136
2137Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2138 // If this record has a definition in the translation unit we're coming from,
2139 // but this particular declaration is not that definition, import the
2140 // definition and map to that.
2141 TagDecl *Definition = D->getDefinition();
2142 if (Definition && Definition != D &&
2143 // In contrast to a normal CXXRecordDecl, the implicit
2144 // CXXRecordDecl of ClassTemplateSpecializationDecl is its redeclaration.
2145 // The definition of the implicit CXXRecordDecl in this case is the
2146 // ClassTemplateSpecializationDecl itself. Thus, we start with an extra
2147 // condition in order to be able to import the implict Decl.
2148 !D->isImplicit()) {
2149 Decl *ImportedDef = Importer.Import(Definition);
2150 if (!ImportedDef)
2151 return nullptr;
2152
2153 return Importer.MapImported(D, ImportedDef);
2154 }
2155
2156 // Import the major distinguishing characteristics of this record.
2157 DeclContext *DC, *LexicalDC;
2158 DeclarationName Name;
2159 SourceLocation Loc;
2160 NamedDecl *ToD;
2161 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2162 return nullptr;
2163 if (ToD)
2164 return ToD;
2165
2166 // Figure out what structure name we're looking for.
2167 unsigned IDNS = Decl::IDNS_Tag;
2168 DeclarationName SearchName = Name;
2169 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2170 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2171 IDNS = Decl::IDNS_Ordinary;
2172 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2173 IDNS |= Decl::IDNS_Ordinary;
2174
2175 // We may already have a record of the same name; try to find and match it.
2176 RecordDecl *AdoptDecl = nullptr;
2177 RecordDecl *PrevDecl = nullptr;
2178 if (!DC->isFunctionOrMethod()) {
2179 SmallVector<NamedDecl *, 4> ConflictingDecls;
2180 SmallVector<NamedDecl *, 2> FoundDecls;
2181 DC->getRedeclContext()->localUncachedLookup(SearchName, FoundDecls);
2182
2183 if (!FoundDecls.empty()) {
2184 // We're going to have to compare D against potentially conflicting Decls, so complete it.
2185 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
2186 D->getASTContext().getExternalSource()->CompleteType(D);
2187 }
2188
2189 for (auto *FoundDecl : FoundDecls) {
2190 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2191 continue;
2192
2193 Decl *Found = FoundDecl;
2194 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2195 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2196 Found = Tag->getDecl();
2197 }
2198
2199 if (D->getDescribedTemplate()) {
2200 if (auto *Template = dyn_cast<ClassTemplateDecl>(Found))
2201 Found = Template->getTemplatedDecl();
2202 else
2203 continue;
2204 }
2205
2206 if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2207 if (!SearchName) {
2208 if (!IsStructuralMatch(D, FoundRecord, false))
2209 continue;
2210 }
2211
2212 PrevDecl = FoundRecord;
2213
2214 if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2215 if ((SearchName && !D->isCompleteDefinition())
2216 || (D->isCompleteDefinition() &&
2217 D->isAnonymousStructOrUnion()
2218 == FoundDef->isAnonymousStructOrUnion() &&
2219 IsStructuralMatch(D, FoundDef))) {
2220 // The record types structurally match, or the "from" translation
2221 // unit only had a forward declaration anyway; call it the same
2222 // function.
2223 // FIXME: Structural equivalence check should check for same
2224 // user-defined methods.
2225 Importer.MapImported(D, FoundDef);
2226 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2227 auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
2228 assert(FoundCXX && "Record type mismatch")(static_cast <bool> (FoundCXX && "Record type mismatch"
) ? void (0) : __assert_fail ("FoundCXX && \"Record type mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 2228, __extension__ __PRETTY_FUNCTION__))
;
2229
2230 if (D->isCompleteDefinition() && !Importer.isMinimalImport())
2231 // FoundDef may not have every implicit method that D has
2232 // because implicit methods are created only if they are used.
2233 ImportImplicitMethods(DCXX, FoundCXX);
2234 }
2235 return FoundDef;
2236 }
2237 } else if (!D->isCompleteDefinition()) {
2238 // We have a forward declaration of this type, so adopt that forward
2239 // declaration rather than building a new one.
2240
2241 // If one or both can be completed from external storage then try one
2242 // last time to complete and compare them before doing this.
2243
2244 if (FoundRecord->hasExternalLexicalStorage() &&
2245 !FoundRecord->isCompleteDefinition())
2246 FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
2247 if (D->hasExternalLexicalStorage())
2248 D->getASTContext().getExternalSource()->CompleteType(D);
2249
2250 if (FoundRecord->isCompleteDefinition() &&
2251 D->isCompleteDefinition() &&
2252 !IsStructuralMatch(D, FoundRecord))
2253 continue;
2254
2255 AdoptDecl = FoundRecord;
2256 continue;
2257 } else if (!SearchName) {
2258 continue;
2259 }
2260 }
2261
2262 ConflictingDecls.push_back(FoundDecl);
2263 }
2264
2265 if (!ConflictingDecls.empty() && SearchName) {
2266 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2267 ConflictingDecls.data(),
2268 ConflictingDecls.size());
2269 }
2270 }
2271
2272 // Create the record declaration.
2273 RecordDecl *D2 = AdoptDecl;
2274 SourceLocation StartLoc = Importer.Import(D->getLocStart());
2275 if (!D2) {
2276 CXXRecordDecl *D2CXX = nullptr;
2277 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2278 if (DCXX->isLambda()) {
2279 TypeSourceInfo *TInfo = Importer.Import(DCXX->getLambdaTypeInfo());
2280 if (GetImportedOrCreateSpecialDecl(
2281 D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
2282 DC, TInfo, Loc, DCXX->isDependentLambda(),
2283 DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
2284 return D2CXX;
2285 Decl *CDecl = Importer.Import(DCXX->getLambdaContextDecl());
2286 if (DCXX->getLambdaContextDecl() && !CDecl)
2287 return nullptr;
2288 D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), CDecl);
2289 } else if (DCXX->isInjectedClassName()) {
2290 // We have to be careful to do a similar dance to the one in
2291 // Sema::ActOnStartCXXMemberDeclarations
2292 CXXRecordDecl *const PrevDecl = nullptr;
2293 const bool DelayTypeCreation = true;
2294 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2295 D->getTagKind(), DC, StartLoc, Loc,
2296 Name.getAsIdentifierInfo(), PrevDecl,
2297 DelayTypeCreation))
2298 return D2CXX;
2299 Importer.getToContext().getTypeDeclType(
2300 D2CXX, dyn_cast<CXXRecordDecl>(DC));
2301 } else {
2302 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2303 D->getTagKind(), DC, StartLoc, Loc,
2304 Name.getAsIdentifierInfo(),
2305 cast_or_null<CXXRecordDecl>(PrevDecl)))
2306 return D2CXX;
2307 }
2308
2309 D2 = D2CXX;
2310 D2->setAccess(D->getAccess());
2311 D2->setLexicalDeclContext(LexicalDC);
2312 if (!DCXX->getDescribedClassTemplate() || DCXX->isImplicit())
2313 LexicalDC->addDeclInternal(D2);
2314
2315 if (ClassTemplateDecl *FromDescribed =
2316 DCXX->getDescribedClassTemplate()) {
2317 auto *ToDescribed = cast_or_null<ClassTemplateDecl>(
2318 Importer.Import(FromDescribed));
2319 if (!ToDescribed)
2320 return nullptr;
2321 D2CXX->setDescribedClassTemplate(ToDescribed);
2322 if (!DCXX->isInjectedClassName()) {
2323 // In a record describing a template the type should be an
2324 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
2325 // previously set type to the correct value here (ToDescribed is not
2326 // available at record create).
2327 // FIXME: The previous type is cleared but not removed from
2328 // ASTContext's internal storage.
2329 CXXRecordDecl *Injected = nullptr;
2330 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
2331 auto *Record = dyn_cast<CXXRecordDecl>(Found);
2332 if (Record && Record->isInjectedClassName()) {
2333 Injected = Record;
2334 break;
2335 }
2336 }
2337 D2CXX->setTypeForDecl(nullptr);
2338 Importer.getToContext().getInjectedClassNameType(D2CXX,
2339 ToDescribed->getInjectedClassNameSpecialization());
2340 if (Injected) {
2341 Injected->setTypeForDecl(nullptr);
2342 Importer.getToContext().getTypeDeclType(Injected, D2CXX);
2343 }
2344 }
2345 } else if (MemberSpecializationInfo *MemberInfo =
2346 DCXX->getMemberSpecializationInfo()) {
2347 TemplateSpecializationKind SK =
2348 MemberInfo->getTemplateSpecializationKind();
2349 CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
2350 auto *ToInst =
2351 cast_or_null<CXXRecordDecl>(Importer.Import(FromInst));
2352 if (FromInst && !ToInst)
2353 return nullptr;
2354 D2CXX->setInstantiationOfMemberClass(ToInst, SK);
2355 D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation(
2356 Importer.Import(MemberInfo->getPointOfInstantiation()));
2357 }
2358 } else {
2359 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
2360 D->getTagKind(), DC, StartLoc, Loc,
2361 Name.getAsIdentifierInfo(), PrevDecl))
2362 return D2;
2363 D2->setLexicalDeclContext(LexicalDC);
2364 LexicalDC->addDeclInternal(D2);
2365 }
2366
2367 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2368 if (D->isAnonymousStructOrUnion())
2369 D2->setAnonymousStructOrUnion(true);
2370 }
2371
2372 Importer.MapImported(D, D2);
2373
2374 if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
2375 return nullptr;
2376
2377 return D2;
2378}
2379
2380Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2381 // Import the major distinguishing characteristics of this enumerator.
2382 DeclContext *DC, *LexicalDC;
2383 DeclarationName Name;
2384 SourceLocation Loc;
2385 NamedDecl *ToD;
2386 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2387 return nullptr;
2388 if (ToD)
2389 return ToD;
2390
2391 QualType T = Importer.Import(D->getType());
2392 if (T.isNull())
2393 return nullptr;
2394
2395 // Determine whether there are any other declarations with the same name and
2396 // in the same context.
2397 if (!LexicalDC->isFunctionOrMethod()) {
2398 SmallVector<NamedDecl *, 4> ConflictingDecls;
2399 unsigned IDNS = Decl::IDNS_Ordinary;
2400 SmallVector<NamedDecl *, 2> FoundDecls;
2401 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2402 for (auto *FoundDecl : FoundDecls) {
2403 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2404 continue;
2405
2406 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
2407 if (IsStructuralMatch(D, FoundEnumConstant))
2408 return Importer.MapImported(D, FoundEnumConstant);
2409 }
2410
2411 ConflictingDecls.push_back(FoundDecl);
2412 }
2413
2414 if (!ConflictingDecls.empty()) {
2415 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2416 ConflictingDecls.data(),
2417 ConflictingDecls.size());
2418 if (!Name)
2419 return nullptr;
2420 }
2421 }
2422
2423 Expr *Init = Importer.Import(D->getInitExpr());
2424 if (D->getInitExpr() && !Init)
2425 return nullptr;
2426
2427 EnumConstantDecl *ToEnumerator;
2428 if (GetImportedOrCreateDecl(
2429 ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2430 Name.getAsIdentifierInfo(), T, Init, D->getInitVal()))
2431 return ToEnumerator;
2432
2433 ToEnumerator->setAccess(D->getAccess());
2434 ToEnumerator->setLexicalDeclContext(LexicalDC);
2435 LexicalDC->addDeclInternal(ToEnumerator);
2436 return ToEnumerator;
2437}
2438
2439bool ASTNodeImporter::ImportTemplateInformation(FunctionDecl *FromFD,
2440 FunctionDecl *ToFD) {
2441 switch (FromFD->getTemplatedKind()) {
2442 case FunctionDecl::TK_NonTemplate:
2443 case FunctionDecl::TK_FunctionTemplate:
2444 return false;
2445
2446 case FunctionDecl::TK_MemberSpecialization: {
2447 auto *InstFD = cast_or_null<FunctionDecl>(
2448 Importer.Import(FromFD->getInstantiatedFromMemberFunction()));
2449 if (!InstFD)
2450 return true;
2451
2452 TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind();
2453 SourceLocation POI = Importer.Import(
2454 FromFD->getMemberSpecializationInfo()->getPointOfInstantiation());
2455 ToFD->setInstantiationOfMemberFunction(InstFD, TSK);
2456 ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
2457 return false;
2458 }
2459
2460 case FunctionDecl::TK_FunctionTemplateSpecialization: {
2461 FunctionTemplateDecl* Template;
2462 OptionalTemplateArgsTy ToTemplArgs;
2463 std::tie(Template, ToTemplArgs) =
2464 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
2465 if (!Template || !ToTemplArgs)
2466 return true;
2467
2468 TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy(
2469 Importer.getToContext(), *ToTemplArgs);
2470
2471 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
2472 TemplateArgumentListInfo ToTAInfo;
2473 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
2474 if (FromTAArgsAsWritten)
2475 if (ImportTemplateArgumentListInfo(*FromTAArgsAsWritten, ToTAInfo))
2476 return true;
2477
2478 SourceLocation POI = Importer.Import(FTSInfo->getPointOfInstantiation());
2479
2480 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
2481 ToFD->setFunctionTemplateSpecialization(
2482 Template, ToTAList, /* InsertPos= */ nullptr,
2483 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, POI);
2484 return false;
2485 }
2486
2487 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
2488 auto *FromInfo = FromFD->getDependentSpecializationInfo();
2489 UnresolvedSet<8> TemplDecls;
2490 unsigned NumTemplates = FromInfo->getNumTemplates();
2491 for (unsigned I = 0; I < NumTemplates; I++) {
2492 if (auto *ToFTD = cast_or_null<FunctionTemplateDecl>(
2493 Importer.Import(FromInfo->getTemplate(I))))
2494 TemplDecls.addDecl(ToFTD);
2495 else
2496 return true;
2497 }
2498
2499 // Import TemplateArgumentListInfo.
2500 TemplateArgumentListInfo ToTAInfo;
2501 if (ImportTemplateArgumentListInfo(
2502 FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
2503 llvm::makeArrayRef(FromInfo->getTemplateArgs(),
2504 FromInfo->getNumTemplateArgs()),
2505 ToTAInfo))
2506 return true;
2507
2508 ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
2509 TemplDecls, ToTAInfo);
2510 return false;
2511 }
2512 }
2513 llvm_unreachable("All cases should be covered!")::llvm::llvm_unreachable_internal("All cases should be covered!"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 2513)
;
2514}
2515
2516FunctionDecl *
2517ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) {
2518 FunctionTemplateDecl* Template;
2519 OptionalTemplateArgsTy ToTemplArgs;
2520 std::tie(Template, ToTemplArgs) =
2521 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
2522 if (!Template || !ToTemplArgs)
2523 return nullptr;
2524
2525 void *InsertPos = nullptr;
2526 auto *FoundSpec = Template->findSpecialization(*ToTemplArgs, InsertPos);
2527 return FoundSpec;
2528}
2529
2530Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2531
2532 SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D);
2533 auto RedeclIt = Redecls.begin();
2534 // Import the first part of the decl chain. I.e. import all previous
2535 // declarations starting from the canonical decl.
2536 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt)
2537 if (!Importer.Import(*RedeclIt))
2538 return nullptr;
2539 assert(*RedeclIt == D)(static_cast <bool> (*RedeclIt == D) ? void (0) : __assert_fail
("*RedeclIt == D", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 2539, __extension__ __PRETTY_FUNCTION__))
;
2540
2541 // Import the major distinguishing characteristics of this function.
2542 DeclContext *DC, *LexicalDC;
2543 DeclarationName Name;
2544 SourceLocation Loc;
2545 NamedDecl *ToD;
2546 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2547 return nullptr;
2548 if (ToD)
2549 return ToD;
2550
2551 const FunctionDecl *FoundByLookup = nullptr;
2552 FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate();
2553
2554 // If this is a function template specialization, then try to find the same
2555 // existing specialization in the "to" context. The localUncachedLookup
2556 // below will not find any specialization, but would find the primary
2557 // template; thus, we have to skip normal lookup in case of specializations.
2558 // FIXME handle member function templates (TK_MemberSpecialization) similarly?
2559 if (D->getTemplatedKind() ==
2560 FunctionDecl::TK_FunctionTemplateSpecialization) {
2561 if (FunctionDecl *FoundFunction = FindFunctionTemplateSpecialization(D)) {
2562 if (D->doesThisDeclarationHaveABody() &&
2563 FoundFunction->hasBody())
2564 return Importer.Imported(D, FoundFunction);
2565 FoundByLookup = FoundFunction;
2566 }
2567 }
2568 // Try to find a function in our own ("to") context with the same name, same
2569 // type, and in the same context as the function we're importing.
2570 else if (!LexicalDC->isFunctionOrMethod()) {
2571 SmallVector<NamedDecl *, 4> ConflictingDecls;
2572 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
2573 SmallVector<NamedDecl *, 2> FoundDecls;
2574 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2575 for (auto *FoundDecl : FoundDecls) {
2576 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2577 continue;
2578
2579 // If template was found, look at the templated function.
2580 if (FromFT) {
2581 if (auto *Template = dyn_cast<FunctionTemplateDecl>(FoundDecl))
2582 FoundDecl = Template->getTemplatedDecl();
2583 else
2584 continue;
2585 }
2586
2587 if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
2588 if (FoundFunction->hasExternalFormalLinkage() &&
2589 D->hasExternalFormalLinkage()) {
2590 if (IsStructuralMatch(D, FoundFunction)) {
2591 const FunctionDecl *Definition = nullptr;
2592 if (D->doesThisDeclarationHaveABody() &&
2593 FoundFunction->hasBody(Definition)) {
2594 return Importer.MapImported(
2595 D, const_cast<FunctionDecl *>(Definition));
2596 }
2597 FoundByLookup = FoundFunction;
2598 break;
2599 }
2600
2601 // FIXME: Check for overloading more carefully, e.g., by boosting
2602 // Sema::IsOverload out to the AST library.
2603
2604 // Function overloading is okay in C++.
2605 if (Importer.getToContext().getLangOpts().CPlusPlus)
2606 continue;
2607
2608 // Complain about inconsistent function types.
2609 Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2610 << Name << D->getType() << FoundFunction->getType();
2611 Importer.ToDiag(FoundFunction->getLocation(),
2612 diag::note_odr_value_here)
2613 << FoundFunction->getType();
2614 }
2615 }
2616
2617 ConflictingDecls.push_back(FoundDecl);
2618 }
2619
2620 if (!ConflictingDecls.empty()) {
2621 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2622 ConflictingDecls.data(),
2623 ConflictingDecls.size());
2624 if (!Name)
2625 return nullptr;
2626 }
2627 }
2628
2629 DeclarationNameInfo NameInfo(Name, Loc);
2630 // Import additional name location/type info.
2631 ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
2632
2633 QualType FromTy = D->getType();
2634 bool usedDifferentExceptionSpec = false;
2635
2636 if (const auto *FromFPT = D->getType()->getAs<FunctionProtoType>()) {
2637 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
2638 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
2639 // FunctionDecl that we are importing the FunctionProtoType for.
2640 // To avoid an infinite recursion when importing, create the FunctionDecl
2641 // with a simplified function type and update it afterwards.
2642 if (FromEPI.ExceptionSpec.SourceDecl ||
2643 FromEPI.ExceptionSpec.SourceTemplate ||
2644 FromEPI.ExceptionSpec.NoexceptExpr) {
2645 FunctionProtoType::ExtProtoInfo DefaultEPI;
2646 FromTy = Importer.getFromContext().getFunctionType(
2647 FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
2648 usedDifferentExceptionSpec = true;
2649 }
2650 }
2651
2652 // Import the type.
2653 QualType T = Importer.Import(FromTy);
2654 if (T.isNull())
2655 return nullptr;
2656
2657 // Import the function parameters.
2658 SmallVector<ParmVarDecl *, 8> Parameters;
2659 for (auto P : D->parameters()) {
2660 auto *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
2661 if (!ToP)
2662 return nullptr;
2663
2664 Parameters.push_back(ToP);
2665 }
2666
2667 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2668 if (D->getTypeSourceInfo() && !TInfo)
2669 return nullptr;
2670
2671 // Create the imported function.
2672 FunctionDecl *ToFunction = nullptr;
2673 SourceLocation InnerLocStart = Importer.Import(D->getInnerLocStart());
2674 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
2675 if (GetImportedOrCreateDecl<CXXConstructorDecl>(
2676 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
2677 InnerLocStart, NameInfo, T, TInfo, FromConstructor->isExplicit(),
2678 D->isInlineSpecified(), D->isImplicit(), D->isConstexpr()))
2679 return ToFunction;
2680 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
2681 SmallVector<CXXCtorInitializer *, 4> CtorInitializers;
2682 for (auto *I : FromConstructor->inits()) {
2683 auto *ToI = cast_or_null<CXXCtorInitializer>(Importer.Import(I));
2684 if (!ToI && I)
2685 return nullptr;
2686 CtorInitializers.push_back(ToI);
2687 }
2688 auto **Memory =
2689 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
2690 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
2691 auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
2692 ToCtor->setCtorInitializers(Memory);
2693 ToCtor->setNumCtorInitializers(NumInitializers);
2694 }
2695 } else if (isa<CXXDestructorDecl>(D)) {
2696 if (GetImportedOrCreateDecl<CXXDestructorDecl>(
2697 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
2698 InnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
2699 D->isImplicit()))
2700 return ToFunction;
2701 } else if (CXXConversionDecl *FromConversion =
2702 dyn_cast<CXXConversionDecl>(D)) {
2703 if (GetImportedOrCreateDecl<CXXConversionDecl>(
2704 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
2705 InnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
2706 FromConversion->isExplicit(), D->isConstexpr(), SourceLocation()))
2707 return ToFunction;
2708 } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2709 if (GetImportedOrCreateDecl<CXXMethodDecl>(
2710 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
2711 InnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
2712 Method->isInlineSpecified(), D->isConstexpr(), SourceLocation()))
2713 return ToFunction;
2714 } else {
2715 if (GetImportedOrCreateDecl(ToFunction, D, Importer.getToContext(), DC,
2716 InnerLocStart, NameInfo, T, TInfo,
2717 D->getStorageClass(), D->isInlineSpecified(),
2718 D->hasWrittenPrototype(), D->isConstexpr()))
2719 return ToFunction;
2720 }
2721
2722 // Import the qualifier, if any.
2723 ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2724 ToFunction->setAccess(D->getAccess());
2725 ToFunction->setLexicalDeclContext(LexicalDC);
2726 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
2727 ToFunction->setTrivial(D->isTrivial());
2728 ToFunction->setPure(D->isPure());
2729 ToFunction->setRangeEnd(Importer.Import(D->getLocEnd()));
2730
2731 // Set the parameters.
2732 for (auto *Param : Parameters) {
2733 Param->setOwningFunction(ToFunction);
2734 ToFunction->addDeclInternal(Param);
2735 }
2736 ToFunction->setParams(Parameters);
2737
2738 if (FoundByLookup) {
2739 auto *Recent = const_cast<FunctionDecl *>(
2740 FoundByLookup->getMostRecentDecl());
2741 ToFunction->setPreviousDecl(Recent);
2742 }
2743
2744 // We need to complete creation of FunctionProtoTypeLoc manually with setting
2745 // params it refers to.
2746 if (TInfo) {
2747 if (auto ProtoLoc =
2748 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
2749 for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
2750 ProtoLoc.setParam(I, Parameters[I]);
2751 }
2752 }
2753
2754 if (usedDifferentExceptionSpec) {
2755 // Update FunctionProtoType::ExtProtoInfo.
2756 QualType T = Importer.Import(D->getType());
2757 if (T.isNull())
2758 return nullptr;
2759 ToFunction->setType(T);
2760 }
2761
2762 // Import the describing template function, if any.
2763 if (FromFT)
2764 if (!Importer.Import(FromFT))
2765 return nullptr;
2766
2767 if (D->doesThisDeclarationHaveABody()) {
2768 if (Stmt *FromBody = D->getBody()) {
2769 if (Stmt *ToBody = Importer.Import(FromBody)) {
2770 ToFunction->setBody(ToBody);
2771 }
2772 }
2773 }
2774
2775 // FIXME: Other bits to merge?
2776
2777 // If it is a template, import all related things.
2778 if (ImportTemplateInformation(D, ToFunction))
2779 return nullptr;
2780
2781 bool IsFriend = D->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend);
2782
2783 // TODO Can we generalize this approach to other AST nodes as well?
2784 if (D->getDeclContext()->containsDeclAndLoad(D))
2785 DC->addDeclInternal(ToFunction);
2786 if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
2787 LexicalDC->addDeclInternal(ToFunction);
2788
2789 // Friend declaration's lexical context is the befriending class, but the
2790 // semantic context is the enclosing scope of the befriending class.
2791 // We want the friend functions to be found in the semantic context by lookup.
2792 // FIXME should we handle this generically in VisitFriendDecl?
2793 // In Other cases when LexicalDC != DC we don't want it to be added,
2794 // e.g out-of-class definitions like void B::f() {} .
2795 if (LexicalDC != DC && IsFriend) {
2796 DC->makeDeclVisibleInContext(ToFunction);
2797 }
2798
2799 // Import the rest of the chain. I.e. import all subsequent declarations.
2800 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt)
2801 if (!Importer.Import(*RedeclIt))
2802 return nullptr;
2803
2804 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
2805 ImportOverrides(cast<CXXMethodDecl>(ToFunction), FromCXXMethod);
2806
2807 return ToFunction;
2808}
2809
2810Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
2811 return VisitFunctionDecl(D);
2812}
2813
2814Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2815 return VisitCXXMethodDecl(D);
2816}
2817
2818Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2819 return VisitCXXMethodDecl(D);
2820}
2821
2822Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
2823 return VisitCXXMethodDecl(D);
2824}
2825
2826static unsigned getFieldIndex(Decl *F) {
2827 auto *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
2828 if (!Owner)
2829 return 0;
2830
2831 unsigned Index = 1;
2832 for (const auto *D : Owner->noload_decls()) {
2833 if (D == F)
2834 return Index;
2835
2836 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
2837 ++Index;
2838 }
2839
2840 return Index;
2841}
2842
2843Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
2844 // Import the major distinguishing characteristics of a variable.
2845 DeclContext *DC, *LexicalDC;
2846 DeclarationName Name;
2847 SourceLocation Loc;
2848 NamedDecl *ToD;
2849 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2850 return nullptr;
2851 if (ToD)
2852 return ToD;
2853
2854 // Determine whether we've already imported this field.
2855 SmallVector<NamedDecl *, 2> FoundDecls;
2856 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2857 for (auto *FoundDecl : FoundDecls) {
2858 if (auto *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
2859 // For anonymous fields, match up by index.
2860 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2861 continue;
2862
2863 if (Importer.IsStructurallyEquivalent(D->getType(),
2864 FoundField->getType())) {
2865 Importer.MapImported(D, FoundField);
2866 return FoundField;
2867 }
2868
2869 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2870 << Name << D->getType() << FoundField->getType();
2871 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2872 << FoundField->getType();
2873 return nullptr;
2874 }
2875 }
2876
2877 // Import the type.
2878 QualType T = Importer.Import(D->getType());
2879 if (T.isNull())
2880 return nullptr;
2881
2882 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2883 Expr *BitWidth = Importer.Import(D->getBitWidth());
2884 if (!BitWidth && D->getBitWidth())
2885 return nullptr;
2886
2887 FieldDecl *ToField;
2888 if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
2889 Importer.Import(D->getInnerLocStart()), Loc,
2890 Name.getAsIdentifierInfo(), T, TInfo, BitWidth,
2891 D->isMutable(), D->getInClassInitStyle()))
2892 return ToField;
2893
2894 ToField->setAccess(D->getAccess());
2895 ToField->setLexicalDeclContext(LexicalDC);
2896 if (Expr *FromInitializer = D->getInClassInitializer()) {
2897 Expr *ToInitializer = Importer.Import(FromInitializer);
2898 if (ToInitializer)
2899 ToField->setInClassInitializer(ToInitializer);
2900 else
2901 return nullptr;
2902 }
2903 ToField->setImplicit(D->isImplicit());
2904 LexicalDC->addDeclInternal(ToField);
2905 return ToField;
2906}
2907
2908Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
2909 // Import the major distinguishing characteristics of a variable.
2910 DeclContext *DC, *LexicalDC;
2911 DeclarationName Name;
2912 SourceLocation Loc;
2913 NamedDecl *ToD;
2914 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2915 return nullptr;
2916 if (ToD)
2917 return ToD;
2918
2919 // Determine whether we've already imported this field.
2920 SmallVector<NamedDecl *, 2> FoundDecls;
2921 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2922 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2923 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
2924 // For anonymous indirect fields, match up by index.
2925 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2926 continue;
2927
2928 if (Importer.IsStructurallyEquivalent(D->getType(),
2929 FoundField->getType(),
2930 !Name.isEmpty())) {
2931 Importer.MapImported(D, FoundField);
2932 return FoundField;
2933 }
2934
2935 // If there are more anonymous fields to check, continue.
2936 if (!Name && I < N-1)
2937 continue;
2938
2939 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2940 << Name << D->getType() << FoundField->getType();
2941 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2942 << FoundField->getType();
2943 return nullptr;
2944 }
2945 }
2946
2947 // Import the type.
2948 QualType T = Importer.Import(D->getType());
2949 if (T.isNull())
2950 return nullptr;
2951
2952 auto **NamedChain =
2953 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
2954
2955 unsigned i = 0;
2956 for (auto *PI : D->chain()) {
2957 Decl *D = Importer.Import(PI);
2958 if (!D)
2959 return nullptr;
2960 NamedChain[i++] = cast<NamedDecl>(D);
2961 }
2962
2963 llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
2964 IndirectFieldDecl *ToIndirectField;
2965 if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
2966 Loc, Name.getAsIdentifierInfo(), T, CH))
2967 // FIXME here we leak `NamedChain` which is allocated before
2968 return ToIndirectField;
2969
2970 for (const auto *A : D->attrs())
2971 ToIndirectField->addAttr(Importer.Import(A));
2972
2973 ToIndirectField->setAccess(D->getAccess());
2974 ToIndirectField->setLexicalDeclContext(LexicalDC);
2975 LexicalDC->addDeclInternal(ToIndirectField);
2976 return ToIndirectField;
2977}
2978
2979Decl *ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
2980 // Import the major distinguishing characteristics of a declaration.
2981 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
2982 DeclContext *LexicalDC = D->getDeclContext() == D->getLexicalDeclContext()
2983 ? DC : Importer.ImportContext(D->getLexicalDeclContext());
2984 if (!DC || !LexicalDC)
2985 return nullptr;
2986
2987 // Determine whether we've already imported this decl.
2988 // FriendDecl is not a NamedDecl so we cannot use localUncachedLookup.
2989 auto *RD = cast<CXXRecordDecl>(DC);
2990 FriendDecl *ImportedFriend = RD->getFirstFriend();
2991
2992 while (ImportedFriend) {
2993 if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
2994 if (IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
2995 /*Complain=*/false))
2996 return Importer.MapImported(D, ImportedFriend);
2997
2998 } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
2999 if (Importer.IsStructurallyEquivalent(
3000 D->getFriendType()->getType(),
3001 ImportedFriend->getFriendType()->getType(), true))
3002 return Importer.MapImported(D, ImportedFriend);
3003 }
3004 ImportedFriend = ImportedFriend->getNextFriend();
3005 }
3006
3007 // Not found. Create it.
3008 FriendDecl::FriendUnion ToFU;
3009 if (NamedDecl *FriendD = D->getFriendDecl()) {
3010 auto *ToFriendD = cast_or_null<NamedDecl>(Importer.Import(FriendD));
3011 if (ToFriendD && FriendD->getFriendObjectKind() != Decl::FOK_None &&
3012 !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
3013 ToFriendD->setObjectOfFriendDecl(false);
3014
3015 ToFU = ToFriendD;
3016 } else // The friend is a type, not a decl.
3017 ToFU = Importer.Import(D->getFriendType());
3018 if (!ToFU)
3019 return nullptr;
3020
3021 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
3022 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
3023 for (unsigned I = 0; I < D->NumTPLists; I++) {
3024 TemplateParameterList *List = ImportTemplateParameterList(FromTPLists[I]);
3025 if (!List)
3026 return nullptr;
3027 ToTPLists[I] = List;
3028 }
3029
3030 FriendDecl *FrD;
3031 if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
3032 Importer.Import(D->getLocation()), ToFU,
3033 Importer.Import(D->getFriendLoc()), ToTPLists))
3034 return FrD;
3035
3036 FrD->setAccess(D->getAccess());
3037 FrD->setLexicalDeclContext(LexicalDC);
3038 LexicalDC->addDeclInternal(FrD);
3039 return FrD;
3040}
3041
3042Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
3043 // Import the major distinguishing characteristics of an ivar.
3044 DeclContext *DC, *LexicalDC;
3045 DeclarationName Name;
3046 SourceLocation Loc;
3047 NamedDecl *ToD;
3048 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3049 return nullptr;
3050 if (ToD)
3051 return ToD;
3052
3053 // Determine whether we've already imported this ivar
3054 SmallVector<NamedDecl *, 2> FoundDecls;
3055 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3056 for (auto *FoundDecl : FoundDecls) {
3057 if (auto *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
3058 if (Importer.IsStructurallyEquivalent(D->getType(),
3059 FoundIvar->getType())) {
3060 Importer.MapImported(D, FoundIvar);
3061 return FoundIvar;
3062 }
3063
3064 Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
3065 << Name << D->getType() << FoundIvar->getType();
3066 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3067 << FoundIvar->getType();
3068 return nullptr;
3069 }
3070 }
3071
3072 // Import the type.
3073 QualType T = Importer.Import(D->getType());
3074 if (T.isNull())
3075 return nullptr;
3076
3077 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3078 Expr *BitWidth = Importer.Import(D->getBitWidth());
3079 if (!BitWidth && D->getBitWidth())
3080 return nullptr;
3081
3082 ObjCIvarDecl *ToIvar;
3083 if (GetImportedOrCreateDecl(
3084 ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
3085 Importer.Import(D->getInnerLocStart()), Loc,
3086 Name.getAsIdentifierInfo(), T, TInfo, D->getAccessControl(), BitWidth,
3087 D->getSynthesize()))
3088 return ToIvar;
3089
3090 ToIvar->setLexicalDeclContext(LexicalDC);
3091 LexicalDC->addDeclInternal(ToIvar);
3092 return ToIvar;
3093}
3094
3095Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3096 // Import the major distinguishing characteristics of a variable.
3097 DeclContext *DC, *LexicalDC;
3098 DeclarationName Name;
3099 SourceLocation Loc;
3100 NamedDecl *ToD;
3101 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3102 return nullptr;
3103 if (ToD)
3104 return ToD;
3105
3106 // Try to find a variable in our own ("to") context with the same name and
3107 // in the same context as the variable we're importing.
3108 if (D->isFileVarDecl()) {
3109 VarDecl *MergeWithVar = nullptr;
3110 SmallVector<NamedDecl *, 4> ConflictingDecls;
3111 unsigned IDNS = Decl::IDNS_Ordinary;
3112 SmallVector<NamedDecl *, 2> FoundDecls;
3113 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3114 for (auto *FoundDecl : FoundDecls) {
3115 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3116 continue;
3117
3118 if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
3119 // We have found a variable that we may need to merge with. Check it.
3120 if (FoundVar->hasExternalFormalLinkage() &&
3121 D->hasExternalFormalLinkage()) {
3122 if (Importer.IsStructurallyEquivalent(D->getType(),
3123 FoundVar->getType())) {
3124 MergeWithVar = FoundVar;
3125 break;
3126 }
3127
3128 const ArrayType *FoundArray
3129 = Importer.getToContext().getAsArrayType(FoundVar->getType());
3130 const ArrayType *TArray
3131 = Importer.getToContext().getAsArrayType(D->getType());
3132 if (FoundArray && TArray) {
3133 if (isa<IncompleteArrayType>(FoundArray) &&
3134 isa<ConstantArrayType>(TArray)) {
3135 // Import the type.
3136 QualType T = Importer.Import(D->getType());
3137 if (T.isNull())
3138 return nullptr;
3139
3140 FoundVar->setType(T);
3141 MergeWithVar = FoundVar;
3142 break;
3143 } else if (isa<IncompleteArrayType>(TArray) &&
3144 isa<ConstantArrayType>(FoundArray)) {
3145 MergeWithVar = FoundVar;
3146 break;
3147 }
3148 }
3149
3150 Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
3151 << Name << D->getType() << FoundVar->getType();
3152 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3153 << FoundVar->getType();
3154 }
3155 }
3156
3157 ConflictingDecls.push_back(FoundDecl);
3158 }
3159
3160 if (MergeWithVar) {
3161 // An equivalent variable with external linkage has been found. Link
3162 // the two declarations, then merge them.
3163 Importer.MapImported(D, MergeWithVar);
3164 updateFlags(D, MergeWithVar);
3165
3166 if (VarDecl *DDef = D->getDefinition()) {
3167 if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
3168 Importer.ToDiag(ExistingDef->getLocation(),
3169 diag::err_odr_variable_multiple_def)
3170 << Name;
3171 Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
3172 } else {
3173 Expr *Init = Importer.Import(DDef->getInit());
3174 MergeWithVar->setInit(Init);
3175 if (DDef->isInitKnownICE()) {
3176 EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
3177 Eval->CheckedICE = true;
3178 Eval->IsICE = DDef->isInitICE();
3179 }
3180 }
3181 }
3182
3183 return MergeWithVar;
3184 }
3185
3186 if (!ConflictingDecls.empty()) {
3187 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3188 ConflictingDecls.data(),
3189 ConflictingDecls.size());
3190 if (!Name)
3191 return nullptr;
3192 }
3193 }
3194
3195 // Import the type.
3196 QualType T = Importer.Import(D->getType());
3197 if (T.isNull())
3198 return nullptr;
3199
3200 // Create the imported variable.
3201 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3202 VarDecl *ToVar;
3203 if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
3204 Importer.Import(D->getInnerLocStart()), Loc,
3205 Name.getAsIdentifierInfo(), T, TInfo,
3206 D->getStorageClass()))
3207 return ToVar;
3208
3209 ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3210 ToVar->setAccess(D->getAccess());
3211 ToVar->setLexicalDeclContext(LexicalDC);
3212
3213 // Templated declarations should never appear in the enclosing DeclContext.
3214 if (!D->getDescribedVarTemplate())
3215 LexicalDC->addDeclInternal(ToVar);
3216
3217 // Merge the initializer.
3218 if (ImportDefinition(D, ToVar))
3219 return nullptr;
3220
3221 if (D->isConstexpr())
3222 ToVar->setConstexpr(true);
3223
3224 return ToVar;
3225}
3226
3227Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
3228 // Parameters are created in the translation unit's context, then moved
3229 // into the function declaration's context afterward.
3230 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3231
3232 // Import the name of this declaration.
3233 DeclarationName Name = Importer.Import(D->getDeclName());
3234 if (D->getDeclName() && !Name)
3235 return nullptr;
3236
3237 // Import the location of this declaration.
3238 SourceLocation Loc = Importer.Import(D->getLocation());
3239
3240 // Import the parameter's type.
3241 QualType T = Importer.Import(D->getType());
3242 if (T.isNull())
3243 return nullptr;
3244
3245 // Create the imported parameter.
3246 ImplicitParamDecl *ToParm = nullptr;
3247 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC, Loc,
3248 Name.getAsIdentifierInfo(), T,
3249 D->getParameterKind()))
3250 return ToParm;
3251 return ToParm;
3252}
3253
3254Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
3255 // Parameters are created in the translation unit's context, then moved
3256 // into the function declaration's context afterward.
3257 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3258
3259 // Import the name of this declaration.
3260 DeclarationName Name = Importer.Import(D->getDeclName());
3261 if (D->getDeclName() && !Name)
3262 return nullptr;
3263
3264 // Import the location of this declaration.
3265 SourceLocation Loc = Importer.Import(D->getLocation());
3266
3267 // Import the parameter's type.
3268 QualType T = Importer.Import(D->getType());
3269 if (T.isNull())
3270 return nullptr;
3271
3272 // Create the imported parameter.
3273 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3274 ParmVarDecl *ToParm;
3275 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
3276 Importer.Import(D->getInnerLocStart()), Loc,
3277 Name.getAsIdentifierInfo(), T, TInfo,
3278 D->getStorageClass(),
3279 /*DefaultArg*/ nullptr))
3280 return ToParm;
3281
3282 // Set the default argument.
3283 ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
3284 ToParm->setKNRPromoted(D->isKNRPromoted());
3285
3286 Expr *ToDefArg = nullptr;
3287 Expr *FromDefArg = nullptr;
3288 if (D->hasUninstantiatedDefaultArg()) {
3289 FromDefArg = D->getUninstantiatedDefaultArg();
3290 ToDefArg = Importer.Import(FromDefArg);
3291 ToParm->setUninstantiatedDefaultArg(ToDefArg);
3292 } else if (D->hasUnparsedDefaultArg()) {
3293 ToParm->setUnparsedDefaultArg();
3294 } else if (D->hasDefaultArg()) {
3295 FromDefArg = D->getDefaultArg();
3296 ToDefArg = Importer.Import(FromDefArg);
3297 ToParm->setDefaultArg(ToDefArg);
3298 }
3299 if (FromDefArg && !ToDefArg)
3300 return nullptr;
3301
3302 if (D->isObjCMethodParameter()) {
3303 ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex());
3304 ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier());
3305 } else {
3306 ToParm->setScopeInfo(D->getFunctionScopeDepth(),
3307 D->getFunctionScopeIndex());
3308 }
3309
3310 return ToParm;
3311}
3312
3313Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
3314 // Import the major distinguishing characteristics of a method.
3315 DeclContext *DC, *LexicalDC;
3316 DeclarationName Name;
3317 SourceLocation Loc;
3318 NamedDecl *ToD;
3319 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3320 return nullptr;
3321 if (ToD)
3322 return ToD;
3323
3324 SmallVector<NamedDecl *, 2> FoundDecls;
3325 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3326 for (auto *FoundDecl : FoundDecls) {
3327 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
3328 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3329 continue;
3330
3331 // Check return types.
3332 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3333 FoundMethod->getReturnType())) {
3334 Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
3335 << D->isInstanceMethod() << Name << D->getReturnType()
3336 << FoundMethod->getReturnType();
3337 Importer.ToDiag(FoundMethod->getLocation(),
3338 diag::note_odr_objc_method_here)
3339 << D->isInstanceMethod() << Name;
3340 return nullptr;
3341 }
3342
3343 // Check the number of parameters.
3344 if (D->param_size() != FoundMethod->param_size()) {
3345 Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
3346 << D->isInstanceMethod() << Name
3347 << D->param_size() << FoundMethod->param_size();
3348 Importer.ToDiag(FoundMethod->getLocation(),
3349 diag::note_odr_objc_method_here)
3350 << D->isInstanceMethod() << Name;
3351 return nullptr;
3352 }
3353
3354 // Check parameter types.
3355 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
3356 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3357 P != PEnd; ++P, ++FoundP) {
3358 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3359 (*FoundP)->getType())) {
3360 Importer.FromDiag((*P)->getLocation(),
3361 diag::err_odr_objc_method_param_type_inconsistent)
3362 << D->isInstanceMethod() << Name
3363 << (*P)->getType() << (*FoundP)->getType();
3364 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3365 << (*FoundP)->getType();
3366 return nullptr;
3367 }
3368 }
3369
3370 // Check variadic/non-variadic.
3371 // Check the number of parameters.
3372 if (D->isVariadic() != FoundMethod->isVariadic()) {
3373 Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3374 << D->isInstanceMethod() << Name;
3375 Importer.ToDiag(FoundMethod->getLocation(),
3376 diag::note_odr_objc_method_here)
3377 << D->isInstanceMethod() << Name;
3378 return nullptr;
3379 }
3380
3381 // FIXME: Any other bits we need to merge?
3382 return Importer.MapImported(D, FoundMethod);
3383 }
3384 }
3385
3386 // Import the result type.
3387 QualType ResultTy = Importer.Import(D->getReturnType());
3388 if (ResultTy.isNull())
3389 return nullptr;
3390
3391 TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
3392
3393 ObjCMethodDecl *ToMethod;
3394 if (GetImportedOrCreateDecl(
3395 ToMethod, D, Importer.getToContext(), Loc,
3396 Importer.Import(D->getLocEnd()), Name.getObjCSelector(), ResultTy,
3397 ReturnTInfo, DC, D->isInstanceMethod(), D->isVariadic(),
3398 D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3399 D->getImplementationControl(), D->hasRelatedResultType()))
3400 return ToMethod;
3401
3402 // FIXME: When we decide to merge method definitions, we'll need to
3403 // deal with implicit parameters.
3404
3405 // Import the parameters
3406 SmallVector<ParmVarDecl *, 5> ToParams;
3407 for (auto *FromP : D->parameters()) {
3408 auto *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
3409 if (!ToP)
3410 return nullptr;
3411
3412 ToParams.push_back(ToP);
3413 }
3414
3415 // Set the parameters.
3416 for (auto *ToParam : ToParams) {
3417 ToParam->setOwningFunction(ToMethod);
3418 ToMethod->addDeclInternal(ToParam);
3419 }
3420
3421 SmallVector<SourceLocation, 12> SelLocs;
3422 D->getSelectorLocs(SelLocs);
3423 for (auto &Loc : SelLocs)
3424 Loc = Importer.Import(Loc);
3425
3426 ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs);
3427
3428 ToMethod->setLexicalDeclContext(LexicalDC);
3429 LexicalDC->addDeclInternal(ToMethod);
3430 return ToMethod;
3431}
3432
3433Decl *ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
3434 // Import the major distinguishing characteristics of a category.
3435 DeclContext *DC, *LexicalDC;
3436 DeclarationName Name;
3437 SourceLocation Loc;
3438 NamedDecl *ToD;
3439 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3440 return nullptr;
3441 if (ToD)
3442 return ToD;
3443
3444 TypeSourceInfo *BoundInfo = Importer.Import(D->getTypeSourceInfo());
3445 if (!BoundInfo)
3446 return nullptr;
3447
3448 ObjCTypeParamDecl *Result;
3449 if (GetImportedOrCreateDecl(
3450 Result, D, Importer.getToContext(), DC, D->getVariance(),
3451 Importer.Import(D->getVarianceLoc()), D->getIndex(),
3452 Importer.Import(D->getLocation()), Name.getAsIdentifierInfo(),
3453 Importer.Import(D->getColonLoc()), BoundInfo))
3454 return Result;
3455
3456 Result->setLexicalDeclContext(LexicalDC);
3457 return Result;
3458}
3459
3460Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3461 // Import the major distinguishing characteristics of a category.
3462 DeclContext *DC, *LexicalDC;
3463 DeclarationName Name;
3464 SourceLocation Loc;
3465 NamedDecl *ToD;
3466 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3467 return nullptr;
3468 if (ToD)
3469 return ToD;
3470
3471 auto *ToInterface =
3472 cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3473 if (!ToInterface)
3474 return nullptr;
3475
3476 // Determine if we've already encountered this category.
3477 ObjCCategoryDecl *MergeWithCategory
3478 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3479 ObjCCategoryDecl *ToCategory = MergeWithCategory;
3480 if (!ToCategory) {
3481
3482 if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
3483 Importer.Import(D->getAtStartLoc()), Loc,
3484 Importer.Import(D->getCategoryNameLoc()),
3485 Name.getAsIdentifierInfo(), ToInterface,
3486 /*TypeParamList=*/nullptr,
3487 Importer.Import(D->getIvarLBraceLoc()),
3488 Importer.Import(D->getIvarRBraceLoc())))
3489 return ToCategory;
3490
3491 ToCategory->setLexicalDeclContext(LexicalDC);
3492 LexicalDC->addDeclInternal(ToCategory);
3493 // Import the type parameter list after calling Imported, to avoid
3494 // loops when bringing in their DeclContext.
3495 ToCategory->setTypeParamList(ImportObjCTypeParamList(
3496 D->getTypeParamList()));
3497
3498 // Import protocols
3499 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3500 SmallVector<SourceLocation, 4> ProtocolLocs;
3501 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3502 = D->protocol_loc_begin();
3503 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3504 FromProtoEnd = D->protocol_end();
3505 FromProto != FromProtoEnd;
3506 ++FromProto, ++FromProtoLoc) {
3507 auto *ToProto =
3508 cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3509 if (!ToProto)
3510 return nullptr;
3511 Protocols.push_back(ToProto);
3512 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3513 }
3514
3515 // FIXME: If we're merging, make sure that the protocol list is the same.
3516 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3517 ProtocolLocs.data(), Importer.getToContext());
3518 } else {
3519 Importer.MapImported(D, ToCategory);
3520 }
3521
3522 // Import all of the members of this category.
3523 ImportDeclContext(D);
3524
3525 // If we have an implementation, import it as well.
3526 if (D->getImplementation()) {
3527 auto *Impl =
3528 cast_or_null<ObjCCategoryImplDecl>(
3529 Importer.Import(D->getImplementation()));
3530 if (!Impl)
3531 return nullptr;
3532
3533 ToCategory->setImplementation(Impl);
3534 }
3535
3536 return ToCategory;
3537}
3538
3539bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From,
3540 ObjCProtocolDecl *To,
3541 ImportDefinitionKind Kind) {
3542 if (To->getDefinition()) {
3543 if (shouldForceImportDeclContext(Kind))
3544 ImportDeclContext(From);
3545 return false;
3546 }
3547
3548 // Start the protocol definition
3549 To->startDefinition();
3550
3551 // Import protocols
3552 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3553 SmallVector<SourceLocation, 4> ProtocolLocs;
3554 ObjCProtocolDecl::protocol_loc_iterator
3555 FromProtoLoc = From->protocol_loc_begin();
3556 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3557 FromProtoEnd = From->protocol_end();
3558 FromProto != FromProtoEnd;
3559 ++FromProto, ++FromProtoLoc) {
3560 auto *ToProto = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3561 if (!ToProto)
3562 return true;
3563 Protocols.push_back(ToProto);
3564 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3565 }
3566
3567 // FIXME: If we're merging, make sure that the protocol list is the same.
3568 To->setProtocolList(Protocols.data(), Protocols.size(),
3569 ProtocolLocs.data(), Importer.getToContext());
3570
3571 if (shouldForceImportDeclContext(Kind)) {
3572 // Import all of the members of this protocol.
3573 ImportDeclContext(From, /*ForceImport=*/true);
3574 }
3575 return false;
3576}
3577
3578Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
3579 // If this protocol has a definition in the translation unit we're coming
3580 // from, but this particular declaration is not that definition, import the
3581 // definition and map to that.
3582 ObjCProtocolDecl *Definition = D->getDefinition();
3583 if (Definition && Definition != D) {
3584 Decl *ImportedDef = Importer.Import(Definition);
3585 if (!ImportedDef)
3586 return nullptr;
3587
3588 return Importer.MapImported(D, ImportedDef);
3589 }
3590
3591 // Import the major distinguishing characteristics of a protocol.
3592 DeclContext *DC, *LexicalDC;
3593 DeclarationName Name;
3594 SourceLocation Loc;
3595 NamedDecl *ToD;
3596 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3597 return nullptr;
3598 if (ToD)
3599 return ToD;
3600
3601 ObjCProtocolDecl *MergeWithProtocol = nullptr;
3602 SmallVector<NamedDecl *, 2> FoundDecls;
3603 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3604 for (auto *FoundDecl : FoundDecls) {
3605 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
3606 continue;
3607
3608 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
3609 break;
3610 }
3611
3612 ObjCProtocolDecl *ToProto = MergeWithProtocol;
3613 if (!ToProto) {
3614 if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
3615 Name.getAsIdentifierInfo(), Loc,
3616 Importer.Import(D->getAtStartLoc()),
3617 /*PrevDecl=*/nullptr))
3618 return ToProto;
3619 ToProto->setLexicalDeclContext(LexicalDC);
3620 LexicalDC->addDeclInternal(ToProto);
3621 }
3622
3623 Importer.MapImported(D, ToProto);
3624
3625 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
3626 return nullptr;
3627
3628 return ToProto;
3629}
3630
3631Decl *ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
3632 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3633 DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3634
3635 SourceLocation ExternLoc = Importer.Import(D->getExternLoc());
3636 SourceLocation LangLoc = Importer.Import(D->getLocation());
3637
3638 bool HasBraces = D->hasBraces();
3639
3640 LinkageSpecDecl *ToLinkageSpec;
3641 if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
3642 ExternLoc, LangLoc, D->getLanguage(), HasBraces))
3643 return ToLinkageSpec;
3644
3645 if (HasBraces) {
3646 SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc());
3647 ToLinkageSpec->setRBraceLoc(RBraceLoc);
3648 }
3649
3650 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
3651 LexicalDC->addDeclInternal(ToLinkageSpec);
3652
3653 return ToLinkageSpec;
3654}
3655
3656Decl *ASTNodeImporter::VisitUsingDecl(UsingDecl *D) {
3657 DeclContext *DC, *LexicalDC;
3658 DeclarationName Name;
3659 SourceLocation Loc;
3660 NamedDecl *ToD = nullptr;
3661 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3662 return nullptr;
3663 if (ToD)
3664 return ToD;
3665
3666 DeclarationNameInfo NameInfo(Name,
3667 Importer.Import(D->getNameInfo().getLoc()));
3668 ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
3669
3670 UsingDecl *ToUsing;
3671 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
3672 Importer.Import(D->getUsingLoc()),
3673 Importer.Import(D->getQualifierLoc()), NameInfo,
3674 D->hasTypename()))
3675 return ToUsing;
3676
3677 ToUsing->setLexicalDeclContext(LexicalDC);
3678 LexicalDC->addDeclInternal(ToUsing);
3679
3680 if (NamedDecl *FromPattern =
3681 Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
3682 if (auto *ToPattern =
3683 dyn_cast_or_null<NamedDecl>(Importer.Import(FromPattern)))
3684 Importer.getToContext().setInstantiatedFromUsingDecl(ToUsing, ToPattern);
3685 else
3686 return nullptr;
3687 }
3688
3689 for (auto *FromShadow : D->shadows()) {
3690 if (auto *ToShadow =
3691 dyn_cast_or_null<UsingShadowDecl>(Importer.Import(FromShadow)))
3692 ToUsing->addShadowDecl(ToShadow);
3693 else
3694 // FIXME: We return a nullptr here but the definition is already created
3695 // and available with lookups. How to fix this?..
3696 return nullptr;
3697 }
3698 return ToUsing;
3699}
3700
3701Decl *ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) {
3702 DeclContext *DC, *LexicalDC;
3703 DeclarationName Name;
3704 SourceLocation Loc;
3705 NamedDecl *ToD = nullptr;
3706 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3707 return nullptr;
3708 if (ToD)
3709 return ToD;
3710
3711 auto *ToUsing = dyn_cast_or_null<UsingDecl>(
3712 Importer.Import(D->getUsingDecl()));
3713 if (!ToUsing)
3714 return nullptr;
3715
3716 auto *ToTarget = dyn_cast_or_null<NamedDecl>(
3717 Importer.Import(D->getTargetDecl()));
3718 if (!ToTarget)
3719 return nullptr;
3720
3721 UsingShadowDecl *ToShadow;
3722 if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
3723 ToUsing, ToTarget))
3724 return ToShadow;
3725
3726 ToShadow->setLexicalDeclContext(LexicalDC);
3727 ToShadow->setAccess(D->getAccess());
3728
3729 if (UsingShadowDecl *FromPattern =
3730 Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
3731 if (auto *ToPattern =
3732 dyn_cast_or_null<UsingShadowDecl>(Importer.Import(FromPattern)))
3733 Importer.getToContext().setInstantiatedFromUsingShadowDecl(ToShadow,
3734 ToPattern);
3735 else
3736 // FIXME: We return a nullptr here but the definition is already created
3737 // and available with lookups. How to fix this?..
3738 return nullptr;
3739 }
3740
3741 LexicalDC->addDeclInternal(ToShadow);
3742
3743 return ToShadow;
3744}
3745
3746Decl *ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3747 DeclContext *DC, *LexicalDC;
3748 DeclarationName Name;
3749 SourceLocation Loc;
3750 NamedDecl *ToD = nullptr;
3751 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3752 return nullptr;
3753 if (ToD)
3754 return ToD;
3755
3756 DeclContext *ToComAncestor = Importer.ImportContext(D->getCommonAncestor());
3757 if (!ToComAncestor)
3758 return nullptr;
3759
3760 auto *ToNominated = cast_or_null<NamespaceDecl>(
3761 Importer.Import(D->getNominatedNamespace()));
3762 if (!ToNominated)
3763 return nullptr;
3764
3765 UsingDirectiveDecl *ToUsingDir;
3766 if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
3767 Importer.Import(D->getUsingLoc()),
3768 Importer.Import(D->getNamespaceKeyLocation()),
3769 Importer.Import(D->getQualifierLoc()),
3770 Importer.Import(D->getIdentLocation()),
3771 ToNominated, ToComAncestor))
3772 return ToUsingDir;
3773
3774 ToUsingDir->setLexicalDeclContext(LexicalDC);
3775 LexicalDC->addDeclInternal(ToUsingDir);
3776
3777 return ToUsingDir;
3778}
3779
3780Decl *ASTNodeImporter::VisitUnresolvedUsingValueDecl(
3781 UnresolvedUsingValueDecl *D) {
3782 DeclContext *DC, *LexicalDC;
3783 DeclarationName Name;
3784 SourceLocation Loc;
3785 NamedDecl *ToD = nullptr;
3786 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3787 return nullptr;
3788 if (ToD)
3789 return ToD;
3790
3791 DeclarationNameInfo NameInfo(Name, Importer.Import(D->getNameInfo().getLoc()));
3792 ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
3793
3794 UnresolvedUsingValueDecl *ToUsingValue;
3795 if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
3796 Importer.Import(D->getUsingLoc()),
3797 Importer.Import(D->getQualifierLoc()), NameInfo,
3798 Importer.Import(D->getEllipsisLoc())))
3799 return ToUsingValue;
3800
3801 ToUsingValue->setAccess(D->getAccess());
3802 ToUsingValue->setLexicalDeclContext(LexicalDC);
3803 LexicalDC->addDeclInternal(ToUsingValue);
3804
3805 return ToUsingValue;
3806}
3807
3808Decl *ASTNodeImporter::VisitUnresolvedUsingTypenameDecl(
3809 UnresolvedUsingTypenameDecl *D) {
3810 DeclContext *DC, *LexicalDC;
3811 DeclarationName Name;
3812 SourceLocation Loc;
3813 NamedDecl *ToD = nullptr;
3814 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3815 return nullptr;
3816 if (ToD)
3817 return ToD;
3818
3819 UnresolvedUsingTypenameDecl *ToUsing;
3820 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
3821 Importer.Import(D->getUsingLoc()),
3822 Importer.Import(D->getTypenameLoc()),
3823 Importer.Import(D->getQualifierLoc()), Loc, Name,
3824 Importer.Import(D->getEllipsisLoc())))
3825 return ToUsing;
3826
3827 ToUsing->setAccess(D->getAccess());
3828 ToUsing->setLexicalDeclContext(LexicalDC);
3829 LexicalDC->addDeclInternal(ToUsing);
3830
3831 return ToUsing;
3832}
3833
3834bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From,
3835 ObjCInterfaceDecl *To,
3836 ImportDefinitionKind Kind) {
3837 if (To->getDefinition()) {
3838 // Check consistency of superclass.
3839 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
3840 if (FromSuper) {
3841 FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
3842 if (!FromSuper)
3843 return true;
3844 }
3845
3846 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
3847 if ((bool)FromSuper != (bool)ToSuper ||
3848 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
3849 Importer.ToDiag(To->getLocation(),
3850 diag::err_odr_objc_superclass_inconsistent)
3851 << To->getDeclName();
3852 if (ToSuper)
3853 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
3854 << To->getSuperClass()->getDeclName();
3855 else
3856 Importer.ToDiag(To->getLocation(),
3857 diag::note_odr_objc_missing_superclass);
3858 if (From->getSuperClass())
3859 Importer.FromDiag(From->getSuperClassLoc(),
3860 diag::note_odr_objc_superclass)
3861 << From->getSuperClass()->getDeclName();
3862 else
3863 Importer.FromDiag(From->getLocation(),
3864 diag::note_odr_objc_missing_superclass);
3865 }
3866
3867 if (shouldForceImportDeclContext(Kind))
3868 ImportDeclContext(From);
3869 return false;
3870 }
3871
3872 // Start the definition.
3873 To->startDefinition();
3874
3875 // If this class has a superclass, import it.
3876 if (From->getSuperClass()) {
3877 TypeSourceInfo *SuperTInfo = Importer.Import(From->getSuperClassTInfo());
3878 if (!SuperTInfo)
3879 return true;
3880
3881 To->setSuperClass(SuperTInfo);
3882 }
3883
3884 // Import protocols
3885 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3886 SmallVector<SourceLocation, 4> ProtocolLocs;
3887 ObjCInterfaceDecl::protocol_loc_iterator
3888 FromProtoLoc = From->protocol_loc_begin();
3889
3890 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
3891 FromProtoEnd = From->protocol_end();
3892 FromProto != FromProtoEnd;
3893 ++FromProto, ++FromProtoLoc) {
3894 auto *ToProto = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3895 if (!ToProto)
3896 return true;
3897 Protocols.push_back(ToProto);
3898 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3899 }
3900
3901 // FIXME: If we're merging, make sure that the protocol list is the same.
3902 To->setProtocolList(Protocols.data(), Protocols.size(),
3903 ProtocolLocs.data(), Importer.getToContext());
3904
3905 // Import categories. When the categories themselves are imported, they'll
3906 // hook themselves into this interface.
3907 for (auto *Cat : From->known_categories())
3908 Importer.Import(Cat);
3909
3910 // If we have an @implementation, import it as well.
3911 if (From->getImplementation()) {
3912 auto *Impl = cast_or_null<ObjCImplementationDecl>(
3913 Importer.Import(From->getImplementation()));
3914 if (!Impl)
3915 return true;
3916
3917 To->setImplementation(Impl);
3918 }
3919
3920 if (shouldForceImportDeclContext(Kind)) {
3921 // Import all of the members of this class.
3922 ImportDeclContext(From, /*ForceImport=*/true);
3923 }
3924 return false;
3925}
3926
3927ObjCTypeParamList *
3928ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
3929 if (!list)
3930 return nullptr;
3931
3932 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
3933 for (auto fromTypeParam : *list) {
3934 auto *toTypeParam = cast_or_null<ObjCTypeParamDecl>(
3935 Importer.Import(fromTypeParam));
3936 if (!toTypeParam)
3937 return nullptr;
3938
3939 toTypeParams.push_back(toTypeParam);
3940 }
3941
3942 return ObjCTypeParamList::create(Importer.getToContext(),
3943 Importer.Import(list->getLAngleLoc()),
3944 toTypeParams,
3945 Importer.Import(list->getRAngleLoc()));
3946}
3947
3948Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
3949 // If this class has a definition in the translation unit we're coming from,
3950 // but this particular declaration is not that definition, import the
3951 // definition and map to that.
3952 ObjCInterfaceDecl *Definition = D->getDefinition();
3953 if (Definition && Definition != D) {
3954 Decl *ImportedDef = Importer.Import(Definition);
3955 if (!ImportedDef)
3956 return nullptr;
3957
3958 return Importer.MapImported(D, ImportedDef);
3959 }
3960
3961 // Import the major distinguishing characteristics of an @interface.
3962 DeclContext *DC, *LexicalDC;
3963 DeclarationName Name;
3964 SourceLocation Loc;
3965 NamedDecl *ToD;
3966 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3967 return nullptr;
3968 if (ToD)
3969 return ToD;
3970
3971 // Look for an existing interface with the same name.
3972 ObjCInterfaceDecl *MergeWithIface = nullptr;
3973 SmallVector<NamedDecl *, 2> FoundDecls;
3974 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3975 for (auto *FoundDecl : FoundDecls) {
3976 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3977 continue;
3978
3979 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
3980 break;
3981 }
3982
3983 // Create an interface declaration, if one does not already exist.
3984 ObjCInterfaceDecl *ToIface = MergeWithIface;
3985 if (!ToIface) {
3986 if (GetImportedOrCreateDecl(
3987 ToIface, D, Importer.getToContext(), DC,
3988 Importer.Import(D->getAtStartLoc()), Name.getAsIdentifierInfo(),
3989 /*TypeParamList=*/nullptr,
3990 /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
3991 return ToIface;
3992 ToIface->setLexicalDeclContext(LexicalDC);
3993 LexicalDC->addDeclInternal(ToIface);
3994 }
3995 Importer.MapImported(D, ToIface);
3996 // Import the type parameter list after calling Imported, to avoid
3997 // loops when bringing in their DeclContext.
3998 ToIface->setTypeParamList(ImportObjCTypeParamList(
3999 D->getTypeParamListAsWritten()));
4000
4001 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
4002 return nullptr;
4003
4004 return ToIface;
4005}
4006
4007Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
4008 auto *Category = cast_or_null<ObjCCategoryDecl>(
4009 Importer.Import(D->getCategoryDecl()));
4010 if (!Category)
4011 return nullptr;
4012
4013 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
4014 if (!ToImpl) {
4015 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4016 if (!DC)
4017 return nullptr;
4018
4019 SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
4020 if (GetImportedOrCreateDecl(
4021 ToImpl, D, Importer.getToContext(), DC,
4022 Importer.Import(D->getIdentifier()), Category->getClassInterface(),
4023 Importer.Import(D->getLocation()),
4024 Importer.Import(D->getAtStartLoc()), CategoryNameLoc))
4025 return ToImpl;
4026
4027 DeclContext *LexicalDC = DC;
4028 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4029 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4030 if (!LexicalDC)
4031 return nullptr;
4032
4033 ToImpl->setLexicalDeclContext(LexicalDC);
4034 }
4035
4036 LexicalDC->addDeclInternal(ToImpl);
4037 Category->setImplementation(ToImpl);
4038 }
4039
4040 Importer.MapImported(D, ToImpl);
4041 ImportDeclContext(D);
4042 return ToImpl;
4043}
4044
4045Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
4046 // Find the corresponding interface.
4047 auto *Iface = cast_or_null<ObjCInterfaceDecl>(
4048 Importer.Import(D->getClassInterface()));
4049 if (!Iface)
4050 return nullptr;
4051
4052 // Import the superclass, if any.
4053 ObjCInterfaceDecl *Super = nullptr;
4054 if (D->getSuperClass()) {
4055 Super = cast_or_null<ObjCInterfaceDecl>(
4056 Importer.Import(D->getSuperClass()));
4057 if (!Super)
4058 return nullptr;
4059 }
4060
4061 ObjCImplementationDecl *Impl = Iface->getImplementation();
4062 if (!Impl) {
4063 // We haven't imported an implementation yet. Create a new @implementation
4064 // now.
4065 if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
4066 Importer.ImportContext(D->getDeclContext()),
4067 Iface, Super, Importer.Import(D->getLocation()),
4068 Importer.Import(D->getAtStartLoc()),
4069 Importer.Import(D->getSuperClassLoc()),
4070 Importer.Import(D->getIvarLBraceLoc()),
4071 Importer.Import(D->getIvarRBraceLoc())))
4072 return Impl;
4073
4074 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4075 DeclContext *LexicalDC
4076 = Importer.ImportContext(D->getLexicalDeclContext());
4077 if (!LexicalDC)
4078 return nullptr;
4079 Impl->setLexicalDeclContext(LexicalDC);
4080 }
4081
4082 // Associate the implementation with the class it implements.
4083 Iface->setImplementation(Impl);
4084 Importer.MapImported(D, Iface->getImplementation());
4085 } else {
4086 Importer.MapImported(D, Iface->getImplementation());
4087
4088 // Verify that the existing @implementation has the same superclass.
4089 if ((Super && !Impl->getSuperClass()) ||
4090 (!Super && Impl->getSuperClass()) ||
4091 (Super && Impl->getSuperClass() &&
4092 !declaresSameEntity(Super->getCanonicalDecl(),
4093 Impl->getSuperClass()))) {
4094 Importer.ToDiag(Impl->getLocation(),
4095 diag::err_odr_objc_superclass_inconsistent)
4096 << Iface->getDeclName();
4097 // FIXME: It would be nice to have the location of the superclass
4098 // below.
4099 if (Impl->getSuperClass())
4100 Importer.ToDiag(Impl->getLocation(),
4101 diag::note_odr_objc_superclass)
4102 << Impl->getSuperClass()->getDeclName();
4103 else
4104 Importer.ToDiag(Impl->getLocation(),
4105 diag::note_odr_objc_missing_superclass);
4106 if (D->getSuperClass())
4107 Importer.FromDiag(D->getLocation(),
4108 diag::note_odr_objc_superclass)
4109 << D->getSuperClass()->getDeclName();
4110 else
4111 Importer.FromDiag(D->getLocation(),
4112 diag::note_odr_objc_missing_superclass);
4113 return nullptr;
4114 }
4115 }
4116
4117 // Import all of the members of this @implementation.
4118 ImportDeclContext(D);
4119
4120 return Impl;
4121}
4122
4123Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
4124 // Import the major distinguishing characteristics of an @property.
4125 DeclContext *DC, *LexicalDC;
4126 DeclarationName Name;
4127 SourceLocation Loc;
4128 NamedDecl *ToD;
4129 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4130 return nullptr;
4131 if (ToD)
4132 return ToD;
4133
4134 // Check whether we have already imported this property.
4135 SmallVector<NamedDecl *, 2> FoundDecls;
4136 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4137 for (auto *FoundDecl : FoundDecls) {
4138 if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
4139 // Check property types.
4140 if (!Importer.IsStructurallyEquivalent(D->getType(),
4141 FoundProp->getType())) {
4142 Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
4143 << Name << D->getType() << FoundProp->getType();
4144 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
4145 << FoundProp->getType();
4146 return nullptr;
4147 }
4148
4149 // FIXME: Check property attributes, getters, setters, etc.?
4150
4151 // Consider these properties to be equivalent.
4152 Importer.MapImported(D, FoundProp);
4153 return FoundProp;
4154 }
4155 }
4156
4157 // Import the type.
4158 TypeSourceInfo *TSI = Importer.Import(D->getTypeSourceInfo());
4159 if (!TSI)
4160 return nullptr;
4161
4162 // Create the new property.
4163 ObjCPropertyDecl *ToProperty;
4164 if (GetImportedOrCreateDecl(
4165 ToProperty, D, Importer.getToContext(), DC, Loc,
4166 Name.getAsIdentifierInfo(), Importer.Import(D->getAtLoc()),
4167 Importer.Import(D->getLParenLoc()), Importer.Import(D->getType()),
4168 TSI, D->getPropertyImplementation()))
4169 return ToProperty;
4170
4171 ToProperty->setLexicalDeclContext(LexicalDC);
4172 LexicalDC->addDeclInternal(ToProperty);
4173
4174 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
4175 ToProperty->setPropertyAttributesAsWritten(
4176 D->getPropertyAttributesAsWritten());
4177 ToProperty->setGetterName(Importer.Import(D->getGetterName()),
4178 Importer.Import(D->getGetterNameLoc()));
4179 ToProperty->setSetterName(Importer.Import(D->getSetterName()),
4180 Importer.Import(D->getSetterNameLoc()));
4181 ToProperty->setGetterMethodDecl(
4182 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
4183 ToProperty->setSetterMethodDecl(
4184 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
4185 ToProperty->setPropertyIvarDecl(
4186 cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
4187 return ToProperty;
4188}
4189
4190Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
4191 auto *Property = cast_or_null<ObjCPropertyDecl>(
4192 Importer.Import(D->getPropertyDecl()));
4193 if (!Property)
4194 return nullptr;
4195
4196 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4197 if (!DC)
4198 return nullptr;
4199
4200 // Import the lexical declaration context.
4201 DeclContext *LexicalDC = DC;
4202 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4203 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4204 if (!LexicalDC)
4205 return nullptr;
4206 }
4207
4208 auto *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
4209 if (!InImpl)
4210 return nullptr;
4211
4212 // Import the ivar (for an @synthesize).
4213 ObjCIvarDecl *Ivar = nullptr;
4214 if (D->getPropertyIvarDecl()) {
4215 Ivar = cast_or_null<ObjCIvarDecl>(
4216 Importer.Import(D->getPropertyIvarDecl()));
4217 if (!Ivar)
4218 return nullptr;
4219 }
4220
4221 ObjCPropertyImplDecl *ToImpl
4222 = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
4223 Property->getQueryKind());
4224 if (!ToImpl) {
4225 if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
4226 Importer.Import(D->getLocStart()),
4227 Importer.Import(D->getLocation()), Property,
4228 D->getPropertyImplementation(), Ivar,
4229 Importer.Import(D->getPropertyIvarDeclLoc())))
4230 return ToImpl;
4231
4232 ToImpl->setLexicalDeclContext(LexicalDC);
4233 LexicalDC->addDeclInternal(ToImpl);
4234 } else {
4235 // Check that we have the same kind of property implementation (@synthesize
4236 // vs. @dynamic).
4237 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4238 Importer.ToDiag(ToImpl->getLocation(),
4239 diag::err_odr_objc_property_impl_kind_inconsistent)
4240 << Property->getDeclName()
4241 << (ToImpl->getPropertyImplementation()
4242 == ObjCPropertyImplDecl::Dynamic);
4243 Importer.FromDiag(D->getLocation(),
4244 diag::note_odr_objc_property_impl_kind)
4245 << D->getPropertyDecl()->getDeclName()
4246 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
4247 return nullptr;
4248 }
4249
4250 // For @synthesize, check that we have the same
4251 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
4252 Ivar != ToImpl->getPropertyIvarDecl()) {
4253 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
4254 diag::err_odr_objc_synthesize_ivar_inconsistent)
4255 << Property->getDeclName()
4256 << ToImpl->getPropertyIvarDecl()->getDeclName()
4257 << Ivar->getDeclName();
4258 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
4259 diag::note_odr_objc_synthesize_ivar_here)
4260 << D->getPropertyIvarDecl()->getDeclName();
4261 return nullptr;
4262 }
4263
4264 // Merge the existing implementation with the new implementation.
4265 Importer.MapImported(D, ToImpl);
4266 }
4267
4268 return ToImpl;
4269}
4270
4271Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
4272 // For template arguments, we adopt the translation unit as our declaration
4273 // context. This context will be fixed when the actual template declaration
4274 // is created.
4275
4276 // FIXME: Import default argument.
4277 TemplateTypeParmDecl *ToD = nullptr;
4278 (void)GetImportedOrCreateDecl(
4279 ToD, D, Importer.getToContext(),
4280 Importer.getToContext().getTranslationUnitDecl(),
4281 Importer.Import(D->getLocStart()), Importer.Import(D->getLocation()),
4282 D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
4283 D->wasDeclaredWithTypename(), D->isParameterPack());
4284 return ToD;
4285}
4286
4287Decl *
4288ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
4289 // Import the name of this declaration.
4290 DeclarationName Name = Importer.Import(D->getDeclName());
4291 if (D->getDeclName() && !Name)
4292 return nullptr;
4293
4294 // Import the location of this declaration.
4295 SourceLocation Loc = Importer.Import(D->getLocation());
4296
4297 // Import the type of this declaration.
4298 QualType T = Importer.Import(D->getType());
4299 if (T.isNull())
4300 return nullptr;
4301
4302 // Import type-source information.
4303 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4304 if (D->getTypeSourceInfo() && !TInfo)
4305 return nullptr;
4306
4307 // FIXME: Import default argument.
4308
4309 NonTypeTemplateParmDecl *ToD = nullptr;
4310 (void)GetImportedOrCreateDecl(
4311 ToD, D, Importer.getToContext(),
4312 Importer.getToContext().getTranslationUnitDecl(),
4313 Importer.Import(D->getInnerLocStart()), Loc, D->getDepth(),
4314 D->getPosition(), Name.getAsIdentifierInfo(), T, D->isParameterPack(),
4315 TInfo);
4316 return ToD;
4317}
4318
4319Decl *
4320ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
4321 // Import the name of this declaration.
4322 DeclarationName Name = Importer.Import(D->getDeclName());
4323 if (D->getDeclName() && !Name)
4324 return nullptr;
4325
4326 // Import the location of this declaration.
4327 SourceLocation Loc = Importer.Import(D->getLocation());
4328
4329 // Import template parameters.
4330 TemplateParameterList *TemplateParams
4331 = ImportTemplateParameterList(D->getTemplateParameters());
4332 if (!TemplateParams)
4333 return nullptr;
4334
4335 // FIXME: Import default argument.
4336
4337 TemplateTemplateParmDecl *ToD = nullptr;
4338 (void)GetImportedOrCreateDecl(
4339 ToD, D, Importer.getToContext(),
4340 Importer.getToContext().getTranslationUnitDecl(), Loc, D->getDepth(),
4341 D->getPosition(), D->isParameterPack(), Name.getAsIdentifierInfo(),
4342 TemplateParams);
4343 return ToD;
4344}
4345
4346// Returns the definition for a (forward) declaration of a ClassTemplateDecl, if
4347// it has any definition in the redecl chain.
4348static ClassTemplateDecl *getDefinition(ClassTemplateDecl *D) {
4349 CXXRecordDecl *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
4350 if (!ToTemplatedDef)
4351 return nullptr;
4352 ClassTemplateDecl *TemplateWithDef =
4353 ToTemplatedDef->getDescribedClassTemplate();
4354 return TemplateWithDef;
4355}
4356
4357Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
4358 // If this record has a definition in the translation unit we're coming from,
4359 // but this particular declaration is not that definition, import the
4360 // definition and map to that.
4361 auto *Definition =
4362 cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
4363 if (Definition && Definition != D->getTemplatedDecl()) {
4364 Decl *ImportedDef
4365 = Importer.Import(Definition->getDescribedClassTemplate());
4366 if (!ImportedDef)
4367 return nullptr;
4368
4369 return Importer.MapImported(D, ImportedDef);
4370 }
4371
4372 // Import the major distinguishing characteristics of this class template.
4373 DeclContext *DC, *LexicalDC;
4374 DeclarationName Name;
4375 SourceLocation Loc;
4376 NamedDecl *ToD;
4377 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4378 return nullptr;
4379 if (ToD)
4380 return ToD;
4381
4382 // We may already have a template of the same name; try to find and match it.
4383 if (!DC->isFunctionOrMethod()) {
4384 SmallVector<NamedDecl *, 4> ConflictingDecls;
4385 SmallVector<NamedDecl *, 2> FoundDecls;
4386 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4387 for (auto *FoundDecl : FoundDecls) {
4388 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4389 continue;
4390
4391 Decl *Found = FoundDecl;
4392 if (auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found)) {
4393
4394 // The class to be imported is a definition.
4395 if (D->isThisDeclarationADefinition()) {
4396 // Lookup will find the fwd decl only if that is more recent than the
4397 // definition. So, try to get the definition if that is available in
4398 // the redecl chain.
4399 ClassTemplateDecl *TemplateWithDef = getDefinition(FoundTemplate);
4400 if (!TemplateWithDef)
4401 continue;
4402 FoundTemplate = TemplateWithDef; // Continue with the definition.
4403 }
4404
4405 if (IsStructuralMatch(D, FoundTemplate)) {
4406 // The class templates structurally match; call it the same template.
4407
4408 Importer.MapImported(D->getTemplatedDecl(),
4409 FoundTemplate->getTemplatedDecl());
4410 return Importer.MapImported(D, FoundTemplate);
4411 }
4412 }
4413
4414 ConflictingDecls.push_back(FoundDecl);
4415 }
4416
4417 if (!ConflictingDecls.empty()) {
4418 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4419 ConflictingDecls.data(),
4420 ConflictingDecls.size());
4421 }
4422
4423 if (!Name)
4424 return nullptr;
4425 }
4426
4427 CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
4428
4429 // Create the declaration that is being templated.
4430 auto *ToTemplated = cast_or_null<CXXRecordDecl>(
4431 Importer.Import(FromTemplated));
4432 if (!ToTemplated)
4433 return nullptr;
4434
4435 // Create the class template declaration itself.
4436 TemplateParameterList *TemplateParams =
4437 ImportTemplateParameterList(D->getTemplateParameters());
4438 if (!TemplateParams)
4439 return nullptr;
4440
4441 ClassTemplateDecl *D2;
4442 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
4443 TemplateParams, ToTemplated))
4444 return D2;
4445
4446 ToTemplated->setDescribedClassTemplate(D2);
4447
4448 D2->setAccess(D->getAccess());
4449 D2->setLexicalDeclContext(LexicalDC);
4450 LexicalDC->addDeclInternal(D2);
4451
4452 if (FromTemplated->isCompleteDefinition() &&
4453 !ToTemplated->isCompleteDefinition()) {
4454 // FIXME: Import definition!
4455 }
4456
4457 return D2;
4458}
4459
4460Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
4461 ClassTemplateSpecializationDecl *D) {
4462 // If this record has a definition in the translation unit we're coming from,
4463 // but this particular declaration is not that definition, import the
4464 // definition and map to that.
4465 TagDecl *Definition = D->getDefinition();
4466 if (Definition && Definition != D) {
4467 Decl *ImportedDef = Importer.Import(Definition);
4468 if (!ImportedDef)
4469 return nullptr;
4470
4471 return Importer.MapImported(D, ImportedDef);
4472 }
4473
4474 auto *ClassTemplate =
4475 cast_or_null<ClassTemplateDecl>(Importer.Import(
4476 D->getSpecializedTemplate()));
4477 if (!ClassTemplate)
4478 return nullptr;
4479
4480 // Import the context of this declaration.
4481 DeclContext *DC = ClassTemplate->getDeclContext();
4482 if (!DC)
4483 return nullptr;
4484
4485 DeclContext *LexicalDC = DC;
4486 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4487 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4488 if (!LexicalDC)
4489 return nullptr;
4490 }
4491
4492 // Import the location of this declaration.
4493 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4494 SourceLocation IdLoc = Importer.Import(D->getLocation());
4495
4496 // Import template arguments.
4497 SmallVector<TemplateArgument, 2> TemplateArgs;
4498 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4499 D->getTemplateArgs().size(),
4500 TemplateArgs))
4501 return nullptr;
4502
4503 // Try to find an existing specialization with these template arguments.
4504 void *InsertPos = nullptr;
4505 ClassTemplateSpecializationDecl *D2
4506 = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
4507 if (D2) {
4508 // We already have a class template specialization with these template
4509 // arguments.
4510
4511 // FIXME: Check for specialization vs. instantiation errors.
4512
4513 if (RecordDecl *FoundDef = D2->getDefinition()) {
4514 if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
4515 // The record types structurally match, or the "from" translation
4516 // unit only had a forward declaration anyway; call it the same
4517 // function.
4518 return Importer.MapImported(D, FoundDef);
4519 }
4520 }
4521 } else {
4522 // Create a new specialization.
4523 if (auto *PartialSpec =
4524 dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
4525 // Import TemplateArgumentListInfo
4526 TemplateArgumentListInfo ToTAInfo;
4527 const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
4528 if (ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
4529 return nullptr;
4530
4531 QualType CanonInjType = Importer.Import(
4532 PartialSpec->getInjectedSpecializationType());
4533 if (CanonInjType.isNull())
4534 return nullptr;
4535 CanonInjType = CanonInjType.getCanonicalType();
4536
4537 TemplateParameterList *ToTPList = ImportTemplateParameterList(
4538 PartialSpec->getTemplateParameters());
4539 if (!ToTPList && PartialSpec->getTemplateParameters())
4540 return nullptr;
4541
4542 if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
4543 D2, D, Importer.getToContext(), D->getTagKind(), DC, StartLoc,
4544 IdLoc, ToTPList, ClassTemplate,
4545 llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()),
4546 ToTAInfo, CanonInjType, nullptr))
4547 return D2;
4548
4549 } else {
4550 if (GetImportedOrCreateDecl(
4551 D2, D, Importer.getToContext(), D->getTagKind(), DC, StartLoc,
4552 IdLoc, ClassTemplate, TemplateArgs, /*PrevDecl=*/nullptr))
4553 return D2;
4554 }
4555
4556 D2->setSpecializationKind(D->getSpecializationKind());
4557
4558 // Add this specialization to the class template.
4559 ClassTemplate->AddSpecialization(D2, InsertPos);
4560
4561 // Import the qualifier, if any.
4562 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4563
4564 if (auto *TSI = D->getTypeAsWritten()) {
4565 TypeSourceInfo *TInfo = Importer.Import(TSI);
4566 if (!TInfo)
4567 return nullptr;
4568 D2->setTypeAsWritten(TInfo);
4569 D2->setTemplateKeywordLoc(Importer.Import(D->getTemplateKeywordLoc()));
4570 D2->setExternLoc(Importer.Import(D->getExternLoc()));
4571 }
4572
4573 SourceLocation POI = Importer.Import(D->getPointOfInstantiation());
4574 if (POI.isValid())
4575 D2->setPointOfInstantiation(POI);
4576 else if (D->getPointOfInstantiation().isValid())
4577 return nullptr;
4578
4579 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
4580
4581 // Set the context of this specialization/instantiation.
4582 D2->setLexicalDeclContext(LexicalDC);
4583
4584 // Add to the DC only if it was an explicit specialization/instantiation.
4585 if (D2->isExplicitInstantiationOrSpecialization()) {
4586 LexicalDC->addDeclInternal(D2);
4587 }
4588 }
4589 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
4590 return nullptr;
4591
4592 return D2;
4593}
4594
4595Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
4596 // If this variable has a definition in the translation unit we're coming
4597 // from,
4598 // but this particular declaration is not that definition, import the
4599 // definition and map to that.
4600 auto *Definition =
4601 cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
4602 if (Definition && Definition != D->getTemplatedDecl()) {
4603 Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
4604 if (!ImportedDef)
4605 return nullptr;
4606
4607 return Importer.MapImported(D, ImportedDef);
4608 }
4609
4610 // Import the major distinguishing characteristics of this variable template.
4611 DeclContext *DC, *LexicalDC;
4612 DeclarationName Name;
4613 SourceLocation Loc;
4614 NamedDecl *ToD;
4615 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4616 return nullptr;
4617 if (ToD)
4618 return ToD;
4619
4620 // We may already have a template of the same name; try to find and match it.
4621 assert(!DC->isFunctionOrMethod() &&(static_cast <bool> (!DC->isFunctionOrMethod() &&
"Variable templates cannot be declared at function scope") ?
void (0) : __assert_fail ("!DC->isFunctionOrMethod() && \"Variable templates cannot be declared at function scope\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 4622, __extension__ __PRETTY_FUNCTION__))
4622 "Variable templates cannot be declared at function scope")(static_cast <bool> (!DC->isFunctionOrMethod() &&
"Variable templates cannot be declared at function scope") ?
void (0) : __assert_fail ("!DC->isFunctionOrMethod() && \"Variable templates cannot be declared at function scope\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 4622, __extension__ __PRETTY_FUNCTION__))
;
4623 SmallVector<NamedDecl *, 4> ConflictingDecls;
4624 SmallVector<NamedDecl *, 2> FoundDecls;
4625 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4626 for (auto *FoundDecl : FoundDecls) {
4627 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4628 continue;
4629
4630 Decl *Found = FoundDecl;
4631 if (auto *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
4632 if (IsStructuralMatch(D, FoundTemplate)) {
4633 // The variable templates structurally match; call it the same template.
4634 Importer.MapImported(D->getTemplatedDecl(),
4635 FoundTemplate->getTemplatedDecl());
4636 return Importer.MapImported(D, FoundTemplate);
4637 }
4638 }
4639
4640 ConflictingDecls.push_back(FoundDecl);
4641 }
4642
4643 if (!ConflictingDecls.empty()) {
4644 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4645 ConflictingDecls.data(),
4646 ConflictingDecls.size());
4647 }
4648
4649 if (!Name)
4650 return nullptr;
4651
4652 VarDecl *DTemplated = D->getTemplatedDecl();
4653
4654 // Import the type.
4655 QualType T = Importer.Import(DTemplated->getType());
4656 if (T.isNull())
4657 return nullptr;
4658
4659 // Create the declaration that is being templated.
4660 auto *ToTemplated = dyn_cast_or_null<VarDecl>(Importer.Import(DTemplated));
4661 if (!ToTemplated)
4662 return nullptr;
4663
4664 // Create the variable template declaration itself.
4665 TemplateParameterList *TemplateParams =
4666 ImportTemplateParameterList(D->getTemplateParameters());
4667 if (!TemplateParams)
4668 return nullptr;
4669
4670 VarTemplateDecl *ToVarTD;
4671 if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
4672 Name, TemplateParams, ToTemplated))
4673 return ToVarTD;
4674
4675 ToTemplated->setDescribedVarTemplate(ToVarTD);
4676
4677 ToVarTD->setAccess(D->getAccess());
4678 ToVarTD->setLexicalDeclContext(LexicalDC);
4679 LexicalDC->addDeclInternal(ToVarTD);
4680
4681 if (DTemplated->isThisDeclarationADefinition() &&
4682 !ToTemplated->isThisDeclarationADefinition()) {
4683 // FIXME: Import definition!
4684 }
4685
4686 return ToVarTD;
4687}
4688
4689Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
4690 VarTemplateSpecializationDecl *D) {
4691 // If this record has a definition in the translation unit we're coming from,
4692 // but this particular declaration is not that definition, import the
4693 // definition and map to that.
4694 VarDecl *Definition = D->getDefinition();
4695 if (Definition && Definition != D) {
4696 Decl *ImportedDef = Importer.Import(Definition);
4697 if (!ImportedDef)
4698 return nullptr;
4699
4700 return Importer.MapImported(D, ImportedDef);
4701 }
4702
4703 auto *VarTemplate = cast_or_null<VarTemplateDecl>(
4704 Importer.Import(D->getSpecializedTemplate()));
4705 if (!VarTemplate)
4706 return nullptr;
4707
4708 // Import the context of this declaration.
4709 DeclContext *DC = VarTemplate->getDeclContext();
4710 if (!DC)
4711 return nullptr;
4712
4713 DeclContext *LexicalDC = DC;
4714 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4715 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4716 if (!LexicalDC)
4717 return nullptr;
4718 }
4719
4720 // Import the location of this declaration.
4721 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4722 SourceLocation IdLoc = Importer.Import(D->getLocation());
4723
4724 // Import template arguments.
4725 SmallVector<TemplateArgument, 2> TemplateArgs;
4726 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4727 D->getTemplateArgs().size(), TemplateArgs))
4728 return nullptr;
4729
4730 // Try to find an existing specialization with these template arguments.
4731 void *InsertPos = nullptr;
4732 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
4733 TemplateArgs, InsertPos);
4734 if (D2) {
4735 // We already have a variable template specialization with these template
4736 // arguments.
4737
4738 // FIXME: Check for specialization vs. instantiation errors.
4739
4740 if (VarDecl *FoundDef = D2->getDefinition()) {
4741 if (!D->isThisDeclarationADefinition() ||
4742 IsStructuralMatch(D, FoundDef)) {
4743 // The record types structurally match, or the "from" translation
4744 // unit only had a forward declaration anyway; call it the same
4745 // variable.
4746 return Importer.MapImported(D, FoundDef);
4747 }
4748 }
4749 } else {
4750 // Import the type.
4751 QualType T = Importer.Import(D->getType());
4752 if (T.isNull())
4753 return nullptr;
4754
4755 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4756 if (D->getTypeSourceInfo() && !TInfo)
4757 return nullptr;
4758
4759 TemplateArgumentListInfo ToTAInfo;
4760 if (ImportTemplateArgumentListInfo(D->getTemplateArgsInfo(), ToTAInfo))
4761 return nullptr;
4762
4763 using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
4764 // Create a new specialization.
4765 if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
4766 // Import TemplateArgumentListInfo
4767 TemplateArgumentListInfo ArgInfos;
4768 const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
4769 // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
4770 if (ImportTemplateArgumentListInfo(*FromTAArgsAsWritten, ArgInfos))
4771 return nullptr;
4772
4773 TemplateParameterList *ToTPList = ImportTemplateParameterList(
4774 FromPartial->getTemplateParameters());
4775 if (!ToTPList)
4776 return nullptr;
4777
4778 PartVarSpecDecl *ToPartial;
4779 if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
4780 StartLoc, IdLoc, ToTPList, VarTemplate, T,
4781 TInfo, D->getStorageClass(), TemplateArgs,
4782 ArgInfos))
4783 return ToPartial;
4784
4785 auto *FromInst = FromPartial->getInstantiatedFromMember();
4786 auto *ToInst = cast_or_null<PartVarSpecDecl>(Importer.Import(FromInst));
4787 if (FromInst && !ToInst)
4788 return nullptr;
4789
4790 ToPartial->setInstantiatedFromMember(ToInst);
4791 if (FromPartial->isMemberSpecialization())
4792 ToPartial->setMemberSpecialization();
4793
4794 D2 = ToPartial;
4795 } else { // Full specialization
4796 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, StartLoc,
4797 IdLoc, VarTemplate, T, TInfo,
4798 D->getStorageClass(), TemplateArgs))
4799 return D2;
4800 }
4801
4802 SourceLocation POI = D->getPointOfInstantiation();
4803 if (POI.isValid())
4804 D2->setPointOfInstantiation(Importer.Import(POI));
4805
4806 D2->setSpecializationKind(D->getSpecializationKind());
4807 D2->setTemplateArgsInfo(ToTAInfo);
4808
4809 // Add this specialization to the class template.
4810 VarTemplate->AddSpecialization(D2, InsertPos);
4811
4812 // Import the qualifier, if any.
4813 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4814
4815 if (D->isConstexpr())
4816 D2->setConstexpr(true);
4817
4818 // Add the specialization to this context.
4819 D2->setLexicalDeclContext(LexicalDC);
4820 LexicalDC->addDeclInternal(D2);
4821
4822 D2->setAccess(D->getAccess());
4823 }
4824
4825 // NOTE: isThisDeclarationADefinition() can return DeclarationOnly even if
4826 // declaration has initializer. Should this be fixed in the AST?.. Anyway,
4827 // we have to check the declaration for initializer - otherwise, it won't be
4828 // imported.
4829 if ((D->isThisDeclarationADefinition() || D->hasInit()) &&
4830 ImportDefinition(D, D2))
4831 return nullptr;
4832
4833 return D2;
4834}
4835
4836Decl *ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
4837 DeclContext *DC, *LexicalDC;
4838 DeclarationName Name;
4839 SourceLocation Loc;
4840 NamedDecl *ToD;
4841
4842 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4843 return nullptr;
4844
4845 if (ToD)
4846 return ToD;
4847
4848 // Try to find a function in our own ("to") context with the same name, same
4849 // type, and in the same context as the function we're importing.
4850 if (!LexicalDC->isFunctionOrMethod()) {
4851 unsigned IDNS = Decl::IDNS_Ordinary;
4852 SmallVector<NamedDecl *, 2> FoundDecls;
4853 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4854 for (auto *FoundDecl : FoundDecls) {
4855 if (!FoundDecl->isInIdentifierNamespace(IDNS))
4856 continue;
4857
4858 if (auto *FoundFunction = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
4859 if (FoundFunction->hasExternalFormalLinkage() &&
4860 D->hasExternalFormalLinkage()) {
4861 if (IsStructuralMatch(D, FoundFunction)) {
4862 Importer.MapImported(D, FoundFunction);
4863 // FIXME: Actually try to merge the body and other attributes.
4864 return FoundFunction;
4865 }
4866 }
4867 }
4868 }
4869 }
4870
4871 TemplateParameterList *Params =
4872 ImportTemplateParameterList(D->getTemplateParameters());
4873 if (!Params)
4874 return nullptr;
4875
4876 auto *TemplatedFD =
4877 cast_or_null<FunctionDecl>(Importer.Import(D->getTemplatedDecl()));
4878 if (!TemplatedFD)
4879 return nullptr;
4880
4881 FunctionTemplateDecl *ToFunc;
4882 if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
4883 Params, TemplatedFD))
4884 return ToFunc;
4885
4886 TemplatedFD->setDescribedFunctionTemplate(ToFunc);
4887 ToFunc->setAccess(D->getAccess());
4888 ToFunc->setLexicalDeclContext(LexicalDC);
4889
4890 LexicalDC->addDeclInternal(ToFunc);
4891 return ToFunc;
4892}
4893
4894//----------------------------------------------------------------------------
4895// Import Statements
4896//----------------------------------------------------------------------------
4897
4898DeclGroupRef ASTNodeImporter::ImportDeclGroup(DeclGroupRef DG) {
4899 if (DG.isNull())
4900 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
4901 size_t NumDecls = DG.end() - DG.begin();
4902 SmallVector<Decl *, 1> ToDecls(NumDecls);
4903 auto &_Importer = this->Importer;
4904 std::transform(DG.begin(), DG.end(), ToDecls.begin(),
4905 [&_Importer](Decl *D) -> Decl * {
4906 return _Importer.Import(D);
4907 });
4908 return DeclGroupRef::Create(Importer.getToContext(),
4909 ToDecls.begin(),
4910 NumDecls);
4911}
4912
4913Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
4914 Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
4915 << S->getStmtClassName();
4916 return nullptr;
4917}
4918
4919Stmt *ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
4920 SmallVector<IdentifierInfo *, 4> Names;
4921 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
4922 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
4923 // ToII is nullptr when no symbolic name is given for output operand
4924 // see ParseStmtAsm::ParseAsmOperandsOpt
4925 if (!ToII && S->getOutputIdentifier(I))
4926 return nullptr;
4927 Names.push_back(ToII);
4928 }
4929 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
4930 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
4931 // ToII is nullptr when no symbolic name is given for input operand
4932 // see ParseStmtAsm::ParseAsmOperandsOpt
4933 if (!ToII && S->getInputIdentifier(I))
4934 return nullptr;
4935 Names.push_back(ToII);
4936 }
4937
4938 SmallVector<StringLiteral *, 4> Clobbers;
4939 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
4940 auto *Clobber = cast_or_null<StringLiteral>(
4941 Importer.Import(S->getClobberStringLiteral(I)));
4942 if (!Clobber)
4943 return nullptr;
4944 Clobbers.push_back(Clobber);
4945 }
4946
4947 SmallVector<StringLiteral *, 4> Constraints;
4948 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
4949 auto *Output = cast_or_null<StringLiteral>(
4950 Importer.Import(S->getOutputConstraintLiteral(I)));
4951 if (!Output)
4952 return nullptr;
4953 Constraints.push_back(Output);
4954 }
4955
4956 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
4957 auto *Input = cast_or_null<StringLiteral>(
4958 Importer.Import(S->getInputConstraintLiteral(I)));
4959 if (!Input)
4960 return nullptr;
4961 Constraints.push_back(Input);
4962 }
4963
4964 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs());
4965 if (ImportContainerChecked(S->outputs(), Exprs))
4966 return nullptr;
4967
4968 if (ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
4969 return nullptr;
4970
4971 auto *AsmStr = cast_or_null<StringLiteral>(
4972 Importer.Import(S->getAsmString()));
4973 if (!AsmStr)
4974 return nullptr;
4975
4976 return new (Importer.getToContext()) GCCAsmStmt(
4977 Importer.getToContext(),
4978 Importer.Import(S->getAsmLoc()),
4979 S->isSimple(),
4980 S->isVolatile(),
4981 S->getNumOutputs(),
4982 S->getNumInputs(),
4983 Names.data(),
4984 Constraints.data(),
4985 Exprs.data(),
4986 AsmStr,
4987 S->getNumClobbers(),
4988 Clobbers.data(),
4989 Importer.Import(S->getRParenLoc()));
4990}
4991
4992Stmt *ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
4993 DeclGroupRef ToDG = ImportDeclGroup(S->getDeclGroup());
4994 for (auto *ToD : ToDG) {
4995 if (!ToD)
4996 return nullptr;
4997 }
4998 SourceLocation ToStartLoc = Importer.Import(S->getStartLoc());
4999 SourceLocation ToEndLoc = Importer.Import(S->getEndLoc());
5000 return new (Importer.getToContext()) DeclStmt(ToDG, ToStartLoc, ToEndLoc);
5001}
5002
5003Stmt *ASTNodeImporter::VisitNullStmt(NullStmt *S) {
5004 SourceLocation ToSemiLoc = Importer.Import(S->getSemiLoc());
5005 return new (Importer.getToContext()) NullStmt(ToSemiLoc,
5006 S->hasLeadingEmptyMacro());
5007}
5008
5009Stmt *ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
5010 SmallVector<Stmt *, 8> ToStmts(S->size());
5011
5012 if (ImportContainerChecked(S->body(), ToStmts))
5013 return nullptr;
5014
5015 SourceLocation ToLBraceLoc = Importer.Import(S->getLBracLoc());
5016 SourceLocation ToRBraceLoc = Importer.Import(S->getRBracLoc());
5017 return CompoundStmt::Create(Importer.getToContext(), ToStmts, ToLBraceLoc,
5018 ToRBraceLoc);
5019}
5020
5021Stmt *ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
5022 Expr *ToLHS = Importer.Import(S->getLHS());
5023 if (!ToLHS)
5024 return nullptr;
5025 Expr *ToRHS = Importer.Import(S->getRHS());
5026 if (!ToRHS && S->getRHS())
5027 return nullptr;
5028 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5029 if (!ToSubStmt && S->getSubStmt())
5030 return nullptr;
5031 SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
5032 SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
5033 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
5034 auto *ToStmt = new (Importer.getToContext())
5035 CaseStmt(ToLHS, ToRHS, ToCaseLoc, ToEllipsisLoc, ToColonLoc);
5036 ToStmt->setSubStmt(ToSubStmt);
5037 return ToStmt;
5038}
5039
5040Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
5041 SourceLocation ToDefaultLoc = Importer.Import(S->getDefaultLoc());
5042 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
5043 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5044 if (!ToSubStmt && S->getSubStmt())
5045 return nullptr;
5046 return new (Importer.getToContext()) DefaultStmt(ToDefaultLoc, ToColonLoc,
5047 ToSubStmt);
5048}
5049
5050Stmt *ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
5051 SourceLocation ToIdentLoc = Importer.Import(S->getIdentLoc());
5052 auto *ToLabelDecl = cast_or_null<LabelDecl>(Importer.Import(S->getDecl()));
5053 if (!ToLabelDecl && S->getDecl())
5054 return nullptr;
5055 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5056 if (!ToSubStmt && S->getSubStmt())
5057 return nullptr;
5058 return new (Importer.getToContext()) LabelStmt(ToIdentLoc, ToLabelDecl,
5059 ToSubStmt);
5060}
5061
5062Stmt *ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
5063 SourceLocation ToAttrLoc = Importer.Import(S->getAttrLoc());
5064 ArrayRef<const Attr*> FromAttrs(S->getAttrs());
5065 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
5066 if (ImportContainerChecked(FromAttrs, ToAttrs))
5067 return nullptr;
5068 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5069 if (!ToSubStmt && S->getSubStmt())
5070 return nullptr;
5071 return AttributedStmt::Create(Importer.getToContext(), ToAttrLoc,
5072 ToAttrs, ToSubStmt);
5073}
5074
5075Stmt *ASTNodeImporter::VisitIfStmt(IfStmt *S) {
5076 SourceLocation ToIfLoc = Importer.Import(S->getIfLoc());
5077 Stmt *ToInit = Importer.Import(S->getInit());
5078 if (!ToInit && S->getInit())
5079 return nullptr;
5080 VarDecl *ToConditionVariable = nullptr;
5081 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5082 ToConditionVariable =
5083 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5084 if (!ToConditionVariable)
5085 return nullptr;
5086 }
5087 Expr *ToCondition = Importer.Import(S->getCond());
5088 if (!ToCondition && S->getCond())
5089 return nullptr;
5090 Stmt *ToThenStmt = Importer.Import(S->getThen());
5091 if (!ToThenStmt && S->getThen())
5092 return nullptr;
5093 SourceLocation ToElseLoc = Importer.Import(S->getElseLoc());
5094 Stmt *ToElseStmt = Importer.Import(S->getElse());
5095 if (!ToElseStmt && S->getElse())
5096 return nullptr;
5097 return new (Importer.getToContext()) IfStmt(Importer.getToContext(),
5098 ToIfLoc, S->isConstexpr(),
5099 ToInit,
5100 ToConditionVariable,
5101 ToCondition, ToThenStmt,
5102 ToElseLoc, ToElseStmt);
5103}
5104
5105Stmt *ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
5106 Stmt *ToInit = Importer.Import(S->getInit());
5107 if (!ToInit && S->getInit())
5108 return nullptr;
5109 VarDecl *ToConditionVariable = nullptr;
5110 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5111 ToConditionVariable =
5112 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5113 if (!ToConditionVariable)
5114 return nullptr;
5115 }
5116 Expr *ToCondition = Importer.Import(S->getCond());
5117 if (!ToCondition && S->getCond())
5118 return nullptr;
5119 auto *ToStmt = new (Importer.getToContext()) SwitchStmt(
5120 Importer.getToContext(), ToInit,
5121 ToConditionVariable, ToCondition);
5122 Stmt *ToBody = Importer.Import(S->getBody());
5123 if (!ToBody && S->getBody())
5124 return nullptr;
5125 ToStmt->setBody(ToBody);
5126 ToStmt->setSwitchLoc(Importer.Import(S->getSwitchLoc()));
5127 // Now we have to re-chain the cases.
5128 SwitchCase *LastChainedSwitchCase = nullptr;
5129 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
5130 SC = SC->getNextSwitchCase()) {
5131 auto *ToSC = dyn_cast_or_null<SwitchCase>(Importer.Import(SC));
5132 if (!ToSC)
5133 return nullptr;
5134 if (LastChainedSwitchCase)
5135 LastChainedSwitchCase->setNextSwitchCase(ToSC);
5136 else
5137 ToStmt->setSwitchCaseList(ToSC);
5138 LastChainedSwitchCase = ToSC;
5139 }
5140 return ToStmt;
5141}
5142
5143Stmt *ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
5144 VarDecl *ToConditionVariable = nullptr;
5145 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5146 ToConditionVariable =
5147 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5148 if (!ToConditionVariable)
5149 return nullptr;
5150 }
5151 Expr *ToCondition = Importer.Import(S->getCond());
5152 if (!ToCondition && S->getCond())
5153 return nullptr;
5154 Stmt *ToBody = Importer.Import(S->getBody());
5155 if (!ToBody && S->getBody())
5156 return nullptr;
5157 SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
5158 return new (Importer.getToContext()) WhileStmt(Importer.getToContext(),
5159 ToConditionVariable,
5160 ToCondition, ToBody,
5161 ToWhileLoc);
5162}
5163
5164Stmt *ASTNodeImporter::VisitDoStmt(DoStmt *S) {
5165 Stmt *ToBody = Importer.Import(S->getBody());
5166 if (!ToBody && S->getBody())
5167 return nullptr;
5168 Expr *ToCondition = Importer.Import(S->getCond());
5169 if (!ToCondition && S->getCond())
5170 return nullptr;
5171 SourceLocation ToDoLoc = Importer.Import(S->getDoLoc());
5172 SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
5173 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5174 return new (Importer.getToContext()) DoStmt(ToBody, ToCondition,
5175 ToDoLoc, ToWhileLoc,
5176 ToRParenLoc);
5177}
5178
5179Stmt *ASTNodeImporter::VisitForStmt(ForStmt *S) {
5180 Stmt *ToInit = Importer.Import(S->getInit());
5181 if (!ToInit && S->getInit())
5182 return nullptr;
5183 Expr *ToCondition = Importer.Import(S->getCond());
5184 if (!ToCondition && S->getCond())
5185 return nullptr;
5186 VarDecl *ToConditionVariable = nullptr;
5187 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5188 ToConditionVariable =
5189 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5190 if (!ToConditionVariable)
5191 return nullptr;
5192 }
5193 Expr *ToInc = Importer.Import(S->getInc());
5194 if (!ToInc && S->getInc())
5195 return nullptr;
5196 Stmt *ToBody = Importer.Import(S->getBody());
5197 if (!ToBody && S->getBody())
5198 return nullptr;
5199 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5200 SourceLocation ToLParenLoc = Importer.Import(S->getLParenLoc());
5201 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5202 return new (Importer.getToContext()) ForStmt(Importer.getToContext(),
5203 ToInit, ToCondition,
5204 ToConditionVariable,
5205 ToInc, ToBody,
5206 ToForLoc, ToLParenLoc,
5207 ToRParenLoc);
5208}
5209
5210Stmt *ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
5211 LabelDecl *ToLabel = nullptr;
5212 if (LabelDecl *FromLabel = S->getLabel()) {
5213 ToLabel = dyn_cast_or_null<LabelDecl>(Importer.Import(FromLabel));
5214 if (!ToLabel)
5215 return nullptr;
5216 }
5217 SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
5218 SourceLocation ToLabelLoc = Importer.Import(S->getLabelLoc());
5219 return new (Importer.getToContext()) GotoStmt(ToLabel,
5220 ToGotoLoc, ToLabelLoc);
5221}
5222
5223Stmt *ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
5224 SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
5225 SourceLocation ToStarLoc = Importer.Import(S->getStarLoc());
5226 Expr *ToTarget = Importer.Import(S->getTarget());
5227 if (!ToTarget && S->getTarget())
5228 return nullptr;
5229 return new (Importer.getToContext()) IndirectGotoStmt(ToGotoLoc, ToStarLoc,
5230 ToTarget);
5231}
5232
5233Stmt *ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
5234 SourceLocation ToContinueLoc = Importer.Import(S->getContinueLoc());
5235 return new (Importer.getToContext()) ContinueStmt(ToContinueLoc);
5236}
5237
5238Stmt *ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
5239 SourceLocation ToBreakLoc = Importer.Import(S->getBreakLoc());
5240 return new (Importer.getToContext()) BreakStmt(ToBreakLoc);
5241}
5242
5243Stmt *ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
5244 SourceLocation ToRetLoc = Importer.Import(S->getReturnLoc());
5245 Expr *ToRetExpr = Importer.Import(S->getRetValue());
5246 if (!ToRetExpr && S->getRetValue())
5247 return nullptr;
5248 auto *NRVOCandidate = const_cast<VarDecl *>(S->getNRVOCandidate());
5249 auto *ToNRVOCandidate = cast_or_null<VarDecl>(Importer.Import(NRVOCandidate));
5250 if (!ToNRVOCandidate && NRVOCandidate)
5251 return nullptr;
5252 return new (Importer.getToContext()) ReturnStmt(ToRetLoc, ToRetExpr,
5253 ToNRVOCandidate);
5254}
5255
5256Stmt *ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
5257 SourceLocation ToCatchLoc = Importer.Import(S->getCatchLoc());
5258 VarDecl *ToExceptionDecl = nullptr;
5259 if (VarDecl *FromExceptionDecl = S->getExceptionDecl()) {
5260 ToExceptionDecl =
5261 dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
5262 if (!ToExceptionDecl)
5263 return nullptr;
5264 }
5265 Stmt *ToHandlerBlock = Importer.Import(S->getHandlerBlock());
5266 if (!ToHandlerBlock && S->getHandlerBlock())
5267 return nullptr;
5268 return new (Importer.getToContext()) CXXCatchStmt(ToCatchLoc,
5269 ToExceptionDecl,
5270 ToHandlerBlock);
5271}
5272
5273Stmt *ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
5274 SourceLocation ToTryLoc = Importer.Import(S->getTryLoc());
5275 Stmt *ToTryBlock = Importer.Import(S->getTryBlock());
5276 if (!ToTryBlock && S->getTryBlock())
5277 return nullptr;
5278 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
5279 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
5280 CXXCatchStmt *FromHandler = S->getHandler(HI);
5281 if (Stmt *ToHandler = Importer.Import(FromHandler))
5282 ToHandlers[HI] = ToHandler;
5283 else
5284 return nullptr;
5285 }
5286 return CXXTryStmt::Create(Importer.getToContext(), ToTryLoc, ToTryBlock,
5287 ToHandlers);
5288}
5289
5290Stmt *ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
5291 auto *ToRange =
5292 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getRangeStmt()));
5293 if (!ToRange && S->getRangeStmt())
5294 return nullptr;
5295 auto *ToBegin =
5296 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getBeginStmt()));
5297 if (!ToBegin && S->getBeginStmt())
5298 return nullptr;
5299 auto *ToEnd =
5300 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getEndStmt()));
5301 if (!ToEnd && S->getEndStmt())
5302 return nullptr;
5303 Expr *ToCond = Importer.Import(S->getCond());
5304 if (!ToCond && S->getCond())
5305 return nullptr;
5306 Expr *ToInc = Importer.Import(S->getInc());
5307 if (!ToInc && S->getInc())
5308 return nullptr;
5309 auto *ToLoopVar =
5310 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getLoopVarStmt()));
5311 if (!ToLoopVar && S->getLoopVarStmt())
5312 return nullptr;
5313 Stmt *ToBody = Importer.Import(S->getBody());
5314 if (!ToBody && S->getBody())
5315 return nullptr;
5316 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5317 SourceLocation ToCoawaitLoc = Importer.Import(S->getCoawaitLoc());
5318 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
5319 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5320 return new (Importer.getToContext()) CXXForRangeStmt(ToRange, ToBegin, ToEnd,
5321 ToCond, ToInc,
5322 ToLoopVar, ToBody,
5323 ToForLoc, ToCoawaitLoc,
5324 ToColonLoc, ToRParenLoc);
5325}
5326
5327Stmt *ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
5328 Stmt *ToElem = Importer.Import(S->getElement());
5329 if (!ToElem && S->getElement())
5330 return nullptr;
5331 Expr *ToCollect = Importer.Import(S->getCollection());
5332 if (!ToCollect && S->getCollection())
5333 return nullptr;
5334 Stmt *ToBody = Importer.Import(S->getBody());
5335 if (!ToBody && S->getBody())
5336 return nullptr;
5337 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5338 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5339 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElem,
5340 ToCollect,
5341 ToBody, ToForLoc,
5342 ToRParenLoc);
5343}
5344
5345Stmt *ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
5346 SourceLocation ToAtCatchLoc = Importer.Import(S->getAtCatchLoc());
5347 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5348 VarDecl *ToExceptionDecl = nullptr;
5349 if (VarDecl *FromExceptionDecl = S->getCatchParamDecl()) {
5350 ToExceptionDecl =
5351 dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
5352 if (!ToExceptionDecl)
5353 return nullptr;
5354 }
5355 Stmt *ToBody = Importer.Import(S->getCatchBody());
5356 if (!ToBody && S->getCatchBody())
5357 return nullptr;
5358 return new (Importer.getToContext()) ObjCAtCatchStmt(ToAtCatchLoc,
5359 ToRParenLoc,
5360 ToExceptionDecl,
5361 ToBody);
5362}
5363
5364Stmt *ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
5365 SourceLocation ToAtFinallyLoc = Importer.Import(S->getAtFinallyLoc());
5366 Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyBody());
5367 if (!ToAtFinallyStmt && S->getFinallyBody())
5368 return nullptr;
5369 return new (Importer.getToContext()) ObjCAtFinallyStmt(ToAtFinallyLoc,
5370 ToAtFinallyStmt);
5371}
5372
5373Stmt *ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
5374 SourceLocation ToAtTryLoc = Importer.Import(S->getAtTryLoc());
5375 Stmt *ToAtTryStmt = Importer.Import(S->getTryBody());
5376 if (!ToAtTryStmt && S->getTryBody())
5377 return nullptr;
5378 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
5379 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
5380 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
5381 if (Stmt *ToCatchStmt = Importer.Import(FromCatchStmt))
5382 ToCatchStmts[CI] = ToCatchStmt;
5383 else
5384 return nullptr;
5385 }
5386 Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyStmt());
5387 if (!ToAtFinallyStmt && S->getFinallyStmt())
5388 return nullptr;
5389 return ObjCAtTryStmt::Create(Importer.getToContext(),
5390 ToAtTryLoc, ToAtTryStmt,
5391 ToCatchStmts.begin(), ToCatchStmts.size(),
5392 ToAtFinallyStmt);
5393}
5394
5395Stmt *ASTNodeImporter::VisitObjCAtSynchronizedStmt
5396 (ObjCAtSynchronizedStmt *S) {
5397 SourceLocation ToAtSynchronizedLoc =
5398 Importer.Import(S->getAtSynchronizedLoc());
5399 Expr *ToSynchExpr = Importer.Import(S->getSynchExpr());
5400 if (!ToSynchExpr && S->getSynchExpr())
5401 return nullptr;
5402 Stmt *ToSynchBody = Importer.Import(S->getSynchBody());
5403 if (!ToSynchBody && S->getSynchBody())
5404 return nullptr;
5405 return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
5406 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
5407}
5408
5409Stmt *ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
5410 SourceLocation ToAtThrowLoc = Importer.Import(S->getThrowLoc());
5411 Expr *ToThrow = Importer.Import(S->getThrowExpr());
5412 if (!ToThrow && S->getThrowExpr())
5413 return nullptr;
5414 return new (Importer.getToContext()) ObjCAtThrowStmt(ToAtThrowLoc, ToThrow);
5415}
5416
5417Stmt *ASTNodeImporter::VisitObjCAutoreleasePoolStmt
5418 (ObjCAutoreleasePoolStmt *S) {
5419 SourceLocation ToAtLoc = Importer.Import(S->getAtLoc());
5420 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5421 if (!ToSubStmt && S->getSubStmt())
5422 return nullptr;
5423 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(ToAtLoc,
5424 ToSubStmt);
5425}
5426
5427//----------------------------------------------------------------------------
5428// Import Expressions
5429//----------------------------------------------------------------------------
5430Expr *ASTNodeImporter::VisitExpr(Expr *E) {
5431 Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
5432 << E->getStmtClassName();
5433 return nullptr;
5434}
5435
5436Expr *ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) {
5437 QualType T = Importer.Import(E->getType());
5438 if (T.isNull())
5439 return nullptr;
5440
5441 Expr *SubExpr = Importer.Import(E->getSubExpr());
5442 if (!SubExpr && E->getSubExpr())
5443 return nullptr;
5444
5445 TypeSourceInfo *TInfo = Importer.Import(E->getWrittenTypeInfo());
5446 if (!TInfo)
5447 return nullptr;
5448
5449 return new (Importer.getToContext()) VAArgExpr(
5450 Importer.Import(E->getBuiltinLoc()), SubExpr, TInfo,
5451 Importer.Import(E->getRParenLoc()), T, E->isMicrosoftABI());
5452}
5453
5454Expr *ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) {
5455 QualType T = Importer.Import(E->getType());
5456 if (T.isNull())
5457 return nullptr;
5458
5459 return new (Importer.getToContext()) GNUNullExpr(
5460 T, Importer.Import(E->getLocStart()));
5461}
5462
5463Expr *ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) {
5464 QualType T = Importer.Import(E->getType());
5465 if (T.isNull())
5466 return nullptr;
5467
5468 auto *SL = cast_or_null<StringLiteral>(Importer.Import(E->getFunctionName()));
5469 if (!SL && E->getFunctionName())
5470 return nullptr;
5471
5472 return new (Importer.getToContext()) PredefinedExpr(
5473 Importer.Import(E->getLocStart()), T, E->getIdentType(), SL);
5474}
5475
5476Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
5477 auto *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
5478 if (!ToD)
5479 return nullptr;
5480
5481 NamedDecl *FoundD = nullptr;
5482 if (E->getDecl() != E->getFoundDecl()) {
5483 FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
5484 if (!FoundD)
5485 return nullptr;
5486 }
5487
5488 QualType T = Importer.Import(E->getType());
5489 if (T.isNull())
5490 return nullptr;
5491
5492 TemplateArgumentListInfo ToTAInfo;
5493 TemplateArgumentListInfo *ResInfo = nullptr;
5494 if (E->hasExplicitTemplateArgs()) {
5495 if (ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo))
5496 return nullptr;
5497 ResInfo = &ToTAInfo;
5498 }
5499
5500 DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(),
5501 Importer.Import(E->getQualifierLoc()),
5502 Importer.Import(E->getTemplateKeywordLoc()),
5503 ToD,
5504 E->refersToEnclosingVariableOrCapture(),
5505 Importer.Import(E->getLocation()),
5506 T, E->getValueKind(),
5507 FoundD, ResInfo);
5508 if (E->hadMultipleCandidates())
5509 DRE->setHadMultipleCandidates(true);
5510 return DRE;
5511}
5512
5513Expr *ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
5514 QualType T = Importer.Import(E->getType());
5515 if (T.isNull())
5516 return nullptr;
5517
5518 return new (Importer.getToContext()) ImplicitValueInitExpr(T);
5519}
5520
5521ASTNodeImporter::Designator
5522ASTNodeImporter::ImportDesignator(const Designator &D) {
5523 if (D.isFieldDesignator()) {
5524 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
5525 // Caller checks for import error
5526 return Designator(ToFieldName, Importer.Import(D.getDotLoc()),
5527 Importer.Import(D.getFieldLoc()));
5528 }
5529 if (D.isArrayDesignator())
5530 return Designator(D.getFirstExprIndex(),
5531 Importer.Import(D.getLBracketLoc()),
5532 Importer.Import(D.getRBracketLoc()));
5533
5534 assert(D.isArrayRangeDesignator())(static_cast <bool> (D.isArrayRangeDesignator()) ? void
(0) : __assert_fail ("D.isArrayRangeDesignator()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 5534, __extension__ __PRETTY_FUNCTION__))
;
5535 return Designator(D.getFirstExprIndex(),
5536 Importer.Import(D.getLBracketLoc()),
5537 Importer.Import(D.getEllipsisLoc()),
5538 Importer.Import(D.getRBracketLoc()));
5539}
5540
5541
5542Expr *ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *DIE) {
5543 auto *Init = cast_or_null<Expr>(Importer.Import(DIE->getInit()));
5544 if (!Init)
5545 return nullptr;
5546
5547 SmallVector<Expr *, 4> IndexExprs(DIE->getNumSubExprs() - 1);
5548 // List elements from the second, the first is Init itself
5549 for (unsigned I = 1, E = DIE->getNumSubExprs(); I < E; I++) {
5550 if (auto *Arg = cast_or_null<Expr>(Importer.Import(DIE->getSubExpr(I))))
5551 IndexExprs[I - 1] = Arg;
5552 else
5553 return nullptr;
5554 }
5555
5556 SmallVector<Designator, 4> Designators(DIE->size());
5557 llvm::transform(DIE->designators(), Designators.begin(),
5558 [this](const Designator &D) -> Designator {
5559 return ImportDesignator(D);
5560 });
5561
5562 for (const auto &D : DIE->designators())
5563 if (D.isFieldDesignator() && !D.getFieldName())
5564 return nullptr;
5565
5566 return DesignatedInitExpr::Create(
5567 Importer.getToContext(), Designators,
5568 IndexExprs, Importer.Import(DIE->getEqualOrColonLoc()),
5569 DIE->usesGNUSyntax(), Init);
5570}
5571
5572Expr *ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
5573 QualType T = Importer.Import(E->getType());
5574 if (T.isNull())
5575 return nullptr;
5576
5577 return new (Importer.getToContext())
5578 CXXNullPtrLiteralExpr(T, Importer.Import(E->getLocation()));
5579}
5580
5581Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
5582 QualType T = Importer.Import(E->getType());
5583 if (T.isNull())
5584 return nullptr;
5585
5586 return IntegerLiteral::Create(Importer.getToContext(),
5587 E->getValue(), T,
5588 Importer.Import(E->getLocation()));
5589}
5590
5591Expr *ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) {
5592 QualType T = Importer.Import(E->getType());
5593 if (T.isNull())
5594 return nullptr;
5595
5596 return FloatingLiteral::Create(Importer.getToContext(),
5597 E->getValue(), E->isExact(), T,
5598 Importer.Import(E->getLocation()));
5599}
5600
5601Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
5602 QualType T = Importer.Import(E->getType());
5603 if (T.isNull())
5604 return nullptr;
5605
5606 return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
5607 E->getKind(), T,
5608 Importer.Import(E->getLocation()));
5609}
5610
5611Expr *ASTNodeImporter::VisitStringLiteral(StringLiteral *E) {
5612 QualType T = Importer.Import(E->getType());
5613 if (T.isNull())
5614 return nullptr;
5615
5616 SmallVector<SourceLocation, 4> Locations(E->getNumConcatenated());
5617 ImportArray(E->tokloc_begin(), E->tokloc_end(), Locations.begin());
5618
5619 return StringLiteral::Create(Importer.getToContext(), E->getBytes(),
5620 E->getKind(), E->isPascal(), T,
5621 Locations.data(), Locations.size());
5622}
5623
5624Expr *ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
5625 QualType T = Importer.Import(E->getType());
5626 if (T.isNull())
5627 return nullptr;
5628
5629 TypeSourceInfo *TInfo = Importer.Import(E->getTypeSourceInfo());
5630 if (!TInfo)
5631 return nullptr;
5632
5633 Expr *Init = Importer.Import(E->getInitializer());
5634 if (!Init)
5635 return nullptr;
5636
5637 return new (Importer.getToContext()) CompoundLiteralExpr(
5638 Importer.Import(E->getLParenLoc()), TInfo, T, E->getValueKind(),
5639 Init, E->isFileScope());
5640}
5641
5642Expr *ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
5643 QualType T = Importer.Import(E->getType());
5644 if (T.isNull())
5645 return nullptr;
5646
5647 SmallVector<Expr *, 6> Exprs(E->getNumSubExprs());
5648 if (ImportArrayChecked(
5649 E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(),
5650 Exprs.begin()))
5651 return nullptr;
5652
5653 return new (Importer.getToContext()) AtomicExpr(
5654 Importer.Import(E->getBuiltinLoc()), Exprs, T, E->getOp(),
5655 Importer.Import(E->getRParenLoc()));
5656}
5657
5658Expr *ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) {
5659 QualType T = Importer.Import(E->getType());
5660 if (T.isNull())
5661 return nullptr;
5662
5663 auto *ToLabel = cast_or_null<LabelDecl>(Importer.Import(E->getLabel()));
5664 if (!ToLabel)
5665 return nullptr;
5666
5667 return new (Importer.getToContext()) AddrLabelExpr(
5668 Importer.Import(E->getAmpAmpLoc()), Importer.Import(E->getLabelLoc()),
5669 ToLabel, T);
5670}
5671
5672Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
5673 Expr *SubExpr = Importer.Import(E->getSubExpr());
5674 if (!SubExpr)
5675 return nullptr;
5676
5677 return new (Importer.getToContext())
5678 ParenExpr(Importer.Import(E->getLParen()),
5679 Importer.Import(E->getRParen()),
5680 SubExpr);
5681}
5682
5683Expr *ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) {
5684 SmallVector<Expr *, 4> Exprs(E->getNumExprs());
5685 if (ImportContainerChecked(E->exprs(), Exprs))
5686 return nullptr;
5687
5688 return new (Importer.getToContext()) ParenListExpr(
5689 Importer.getToContext(), Importer.Import(E->getLParenLoc()),
5690 Exprs, Importer.Import(E->getLParenLoc()));
5691}
5692
5693Expr *ASTNodeImporter::VisitStmtExpr(StmtExpr *E) {
5694 QualType T = Importer.Import(E->getType());
5695 if (T.isNull())
5696 return nullptr;
5697
5698 auto *ToSubStmt = cast_or_null<CompoundStmt>(
5699 Importer.Import(E->getSubStmt()));
5700 if (!ToSubStmt && E->getSubStmt())
5701 return nullptr;
5702
5703 return new (Importer.getToContext()) StmtExpr(ToSubStmt, T,
5704 Importer.Import(E->getLParenLoc()), Importer.Import(E->getRParenLoc()));
5705}
5706
5707Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
5708 QualType T = Importer.Import(E->getType());
5709 if (T.isNull())
5710 return nullptr;
5711
5712 Expr *SubExpr = Importer.Import(E->getSubExpr());
5713 if (!SubExpr)
5714 return nullptr;
5715
5716 return new (Importer.getToContext()) UnaryOperator(
5717 SubExpr, E->getOpcode(), T, E->getValueKind(), E->getObjectKind(),
5718 Importer.Import(E->getOperatorLoc()), E->canOverflow());
5719}
5720
5721Expr *
5722ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) {
5723 QualType ResultType = Importer.Import(E->getType());
5724
5725 if (E->isArgumentType()) {
5726 TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
5727 if (!TInfo)
5728 return nullptr;
5729
5730 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5731 TInfo, ResultType,
5732 Importer.Import(E->getOperatorLoc()),
5733 Importer.Import(E->getRParenLoc()));
5734 }
5735
5736 Expr *SubExpr = Importer.Import(E->getArgumentExpr());
5737 if (!SubExpr)
5738 return nullptr;
5739
5740 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5741 SubExpr, ResultType,
5742 Importer.Import(E->getOperatorLoc()),
5743 Importer.Import(E->getRParenLoc()));
5744}
5745
5746Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
5747 QualType T = Importer.Import(E->getType());
5748 if (T.isNull())
5749 return nullptr;
5750
5751 Expr *LHS = Importer.Import(E->getLHS());
5752 if (!LHS)
5753 return nullptr;
5754
5755 Expr *RHS = Importer.Import(E->getRHS());
5756 if (!RHS)
5757 return nullptr;
5758
5759 return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
5760 T, E->getValueKind(),
5761 E->getObjectKind(),
5762 Importer.Import(E->getOperatorLoc()),
5763 E->getFPFeatures());
5764}
5765
5766Expr *ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) {
5767 QualType T = Importer.Import(E->getType());
5768 if (T.isNull())
5769 return nullptr;
5770
5771 Expr *ToLHS = Importer.Import(E->getLHS());
5772 if (!ToLHS)
5773 return nullptr;
5774
5775 Expr *ToRHS = Importer.Import(E->getRHS());
5776 if (!ToRHS)
5777 return nullptr;
5778
5779 Expr *ToCond = Importer.Import(E->getCond());
5780 if (!ToCond)
5781 return nullptr;
5782
5783 return new (Importer.getToContext()) ConditionalOperator(
5784 ToCond, Importer.Import(E->getQuestionLoc()),
5785 ToLHS, Importer.Import(E->getColonLoc()),
5786 ToRHS, T, E->getValueKind(), E->getObjectKind());
5787}
5788
5789Expr *ASTNodeImporter::VisitBinaryConditionalOperator(
5790 BinaryConditionalOperator *E) {
5791 QualType T = Importer.Import(E->getType());
5792 if (T.isNull())
5793 return nullptr;
5794
5795 Expr *Common = Importer.Import(E->getCommon());
5796 if (!Common)
5797 return nullptr;
5798
5799 Expr *Cond = Importer.Import(E->getCond());
5800 if (!Cond)
5801 return nullptr;
5802
5803 auto *OpaqueValue = cast_or_null<OpaqueValueExpr>(
5804 Importer.Import(E->getOpaqueValue()));
5805 if (!OpaqueValue)
5806 return nullptr;
5807
5808 Expr *TrueExpr = Importer.Import(E->getTrueExpr());
5809 if (!TrueExpr)
5810 return nullptr;
5811
5812 Expr *FalseExpr = Importer.Import(E->getFalseExpr());
5813 if (!FalseExpr)
5814 return nullptr;
5815
5816 return new (Importer.getToContext()) BinaryConditionalOperator(
5817 Common, OpaqueValue, Cond, TrueExpr, FalseExpr,
5818 Importer.Import(E->getQuestionLoc()), Importer.Import(E->getColonLoc()),
5819 T, E->getValueKind(), E->getObjectKind());
5820}
5821
5822Expr *ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
5823 QualType T = Importer.Import(E->getType());
5824 if (T.isNull())
5825 return nullptr;
5826
5827 TypeSourceInfo *ToQueried = Importer.Import(E->getQueriedTypeSourceInfo());
5828 if (!ToQueried)
5829 return nullptr;
5830
5831 Expr *Dim = Importer.Import(E->getDimensionExpression());
5832 if (!Dim && E->getDimensionExpression())
5833 return nullptr;
5834
5835 return new (Importer.getToContext()) ArrayTypeTraitExpr(
5836 Importer.Import(E->getLocStart()), E->getTrait(), ToQueried,
5837 E->getValue(), Dim, Importer.Import(E->getLocEnd()), T);
5838}
5839
5840Expr *ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
5841 QualType T = Importer.Import(E->getType());
5842 if (T.isNull())
5843 return nullptr;
5844
5845 Expr *ToQueried = Importer.Import(E->getQueriedExpression());
5846 if (!ToQueried)
5847 return nullptr;
5848
5849 return new (Importer.getToContext()) ExpressionTraitExpr(
5850 Importer.Import(E->getLocStart()), E->getTrait(), ToQueried,
5851 E->getValue(), Importer.Import(E->getLocEnd()), T);
5852}
5853
5854Expr *ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
5855 QualType T = Importer.Import(E->getType());
5856 if (T.isNull())
5857 return nullptr;
5858
5859 Expr *SourceExpr = Importer.Import(E->getSourceExpr());
5860 if (!SourceExpr && E->getSourceExpr())
5861 return nullptr;
5862
5863 return new (Importer.getToContext()) OpaqueValueExpr(
5864 Importer.Import(E->getLocation()), T, E->getValueKind(),
5865 E->getObjectKind(), SourceExpr);
5866}
5867
5868Expr *ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
5869 QualType T = Importer.Import(E->getType());
5870 if (T.isNull())
5871 return nullptr;
5872
5873 Expr *ToLHS = Importer.Import(E->getLHS());
5874 if (!ToLHS)
5875 return nullptr;
5876
5877 Expr *ToRHS = Importer.Import(E->getRHS());
5878 if (!ToRHS)
5879 return nullptr;
5880
5881 return new (Importer.getToContext()) ArraySubscriptExpr(
5882 ToLHS, ToRHS, T, E->getValueKind(), E->getObjectKind(),
5883 Importer.Import(E->getRBracketLoc()));
5884}
5885
5886Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
5887 QualType T = Importer.Import(E->getType());
5888 if (T.isNull())
5889 return nullptr;
5890
5891 QualType CompLHSType = Importer.Import(E->getComputationLHSType());
5892 if (CompLHSType.isNull())
5893 return nullptr;
5894
5895 QualType CompResultType = Importer.Import(E->getComputationResultType());
5896 if (CompResultType.isNull())
5897 return nullptr;
5898
5899 Expr *LHS = Importer.Import(E->getLHS());
5900 if (!LHS)
5901 return nullptr;
5902
5903 Expr *RHS = Importer.Import(E->getRHS());
5904 if (!RHS)
5905 return nullptr;
5906
5907 return new (Importer.getToContext())
5908 CompoundAssignOperator(LHS, RHS, E->getOpcode(),
5909 T, E->getValueKind(),
5910 E->getObjectKind(),
5911 CompLHSType, CompResultType,
5912 Importer.Import(E->getOperatorLoc()),
5913 E->getFPFeatures());
5914}
5915
5916bool ASTNodeImporter::ImportCastPath(CastExpr *CE, CXXCastPath &Path) {
5917 for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) {
5918 if (CXXBaseSpecifier *Spec = Importer.Import(*I))
5919 Path.push_back(Spec);
5920 else
5921 return true;
5922 }
5923 return false;
5924}
5925
5926Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
5927 QualType T = Importer.Import(E->getType());
5928 if (T.isNull())
5929 return nullptr;
5930
5931 Expr *SubExpr = Importer.Import(E->getSubExpr());
5932 if (!SubExpr)
5933 return nullptr;
5934
5935 CXXCastPath BasePath;
5936 if (ImportCastPath(E, BasePath))
5937 return nullptr;
5938
5939 return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
5940 SubExpr, &BasePath, E->getValueKind());
5941}
5942
5943Expr *ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) {
5944 QualType T = Importer.Import(E->getType());
5945 if (T.isNull())
5946 return nullptr;
5947
5948 Expr *SubExpr = Importer.Import(E->getSubExpr());
5949 if (!SubExpr)
5950 return nullptr;
5951
5952 TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
5953 if (!TInfo && E->getTypeInfoAsWritten())
5954 return nullptr;
5955
5956 CXXCastPath BasePath;
5957 if (ImportCastPath(E, BasePath))
5958 return nullptr;
5959
5960 switch (E->getStmtClass()) {
5961 case Stmt::CStyleCastExprClass: {
5962 auto *CCE = cast<CStyleCastExpr>(E);
5963 return CStyleCastExpr::Create(Importer.getToContext(), T,
5964 E->getValueKind(), E->getCastKind(),
5965 SubExpr, &BasePath, TInfo,
5966 Importer.Import(CCE->getLParenLoc()),
5967 Importer.Import(CCE->getRParenLoc()));
5968 }
5969
5970 case Stmt::CXXFunctionalCastExprClass: {
5971 auto *FCE = cast<CXXFunctionalCastExpr>(E);
5972 return CXXFunctionalCastExpr::Create(Importer.getToContext(), T,
5973 E->getValueKind(), TInfo,
5974 E->getCastKind(), SubExpr, &BasePath,
5975 Importer.Import(FCE->getLParenLoc()),
5976 Importer.Import(FCE->getRParenLoc()));
5977 }
5978
5979 case Stmt::ObjCBridgedCastExprClass: {
5980 auto *OCE = cast<ObjCBridgedCastExpr>(E);
5981 return new (Importer.getToContext()) ObjCBridgedCastExpr(
5982 Importer.Import(OCE->getLParenLoc()), OCE->getBridgeKind(),
5983 E->getCastKind(), Importer.Import(OCE->getBridgeKeywordLoc()),
5984 TInfo, SubExpr);
5985 }
5986 default:
5987 break; // just fall through
5988 }
5989
5990 auto *Named = cast<CXXNamedCastExpr>(E);
5991 SourceLocation ExprLoc = Importer.Import(Named->getOperatorLoc()),
5992 RParenLoc = Importer.Import(Named->getRParenLoc());
5993 SourceRange Brackets = Importer.Import(Named->getAngleBrackets());
5994
5995 switch (E->getStmtClass()) {
5996 case Stmt::CXXStaticCastExprClass:
5997 return CXXStaticCastExpr::Create(Importer.getToContext(), T,
5998 E->getValueKind(), E->getCastKind(),
5999 SubExpr, &BasePath, TInfo,
6000 ExprLoc, RParenLoc, Brackets);
6001
6002 case Stmt::CXXDynamicCastExprClass:
6003 return CXXDynamicCastExpr::Create(Importer.getToContext(), T,
6004 E->getValueKind(), E->getCastKind(),
6005 SubExpr, &BasePath, TInfo,
6006 ExprLoc, RParenLoc, Brackets);
6007
6008 case Stmt::CXXReinterpretCastExprClass:
6009 return CXXReinterpretCastExpr::Create(Importer.getToContext(), T,
6010 E->getValueKind(), E->getCastKind(),
6011 SubExpr, &BasePath, TInfo,
6012 ExprLoc, RParenLoc, Brackets);
6013
6014 case Stmt::CXXConstCastExprClass:
6015 return CXXConstCastExpr::Create(Importer.getToContext(), T,
6016 E->getValueKind(), SubExpr, TInfo, ExprLoc,
6017 RParenLoc, Brackets);
6018 default:
6019 llvm_unreachable("Cast expression of unsupported type!")::llvm::llvm_unreachable_internal("Cast expression of unsupported type!"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 6019)
;
6020 return nullptr;
6021 }
6022}
6023
6024Expr *ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *OE) {
6025 QualType T = Importer.Import(OE->getType());
6026 if (T.isNull())
6027 return nullptr;
6028
6029 SmallVector<OffsetOfNode, 4> Nodes;
6030 for (int I = 0, E = OE->getNumComponents(); I < E; ++I) {
6031 const OffsetOfNode &Node = OE->getComponent(I);
6032
6033 switch (Node.getKind()) {
6034 case OffsetOfNode::Array:
6035 Nodes.push_back(OffsetOfNode(Importer.Import(Node.getLocStart()),
6036 Node.getArrayExprIndex(),
6037 Importer.Import(Node.getLocEnd())));
6038 break;
6039
6040 case OffsetOfNode::Base: {
6041 CXXBaseSpecifier *BS = Importer.Import(Node.getBase());
6042 if (!BS && Node.getBase())
6043 return nullptr;
6044 Nodes.push_back(OffsetOfNode(BS));
6045 break;
6046 }
6047 case OffsetOfNode::Field: {
6048 auto *FD = cast_or_null<FieldDecl>(Importer.Import(Node.getField()));
6049 if (!FD)
6050 return nullptr;
6051 Nodes.push_back(OffsetOfNode(Importer.Import(Node.getLocStart()), FD,
6052 Importer.Import(Node.getLocEnd())));
6053 break;
6054 }
6055 case OffsetOfNode::Identifier: {
6056 IdentifierInfo *ToII = Importer.Import(Node.getFieldName());
6057 if (!ToII)
6058 return nullptr;
6059 Nodes.push_back(OffsetOfNode(Importer.Import(Node.getLocStart()), ToII,
6060 Importer.Import(Node.getLocEnd())));
6061 break;
6062 }
6063 }
6064 }
6065
6066 SmallVector<Expr *, 4> Exprs(OE->getNumExpressions());
6067 for (int I = 0, E = OE->getNumExpressions(); I < E; ++I) {
6068 Expr *ToIndexExpr = Importer.Import(OE->getIndexExpr(I));
6069 if (!ToIndexExpr)
6070 return nullptr;
6071 Exprs[I] = ToIndexExpr;
6072 }
6073
6074 TypeSourceInfo *TInfo = Importer.Import(OE->getTypeSourceInfo());
6075 if (!TInfo && OE->getTypeSourceInfo())
6076 return nullptr;
6077
6078 return OffsetOfExpr::Create(Importer.getToContext(), T,
6079 Importer.Import(OE->getOperatorLoc()),
6080 TInfo, Nodes, Exprs,
6081 Importer.Import(OE->getRParenLoc()));
6082}
6083
6084Expr *ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
6085 QualType T = Importer.Import(E->getType());
6086 if (T.isNull())
6087 return nullptr;
6088
6089 Expr *Operand = Importer.Import(E->getOperand());
6090 if (!Operand)
6091 return nullptr;
6092
6093 CanThrowResult CanThrow;
6094 if (E->isValueDependent())
6095 CanThrow = CT_Dependent;
6096 else
6097 CanThrow = E->getValue() ? CT_Can : CT_Cannot;
6098
6099 return new (Importer.getToContext()) CXXNoexceptExpr(
6100 T, Operand, CanThrow,
6101 Importer.Import(E->getLocStart()), Importer.Import(E->getLocEnd()));
6102}
6103
6104Expr *ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) {
6105 QualType T = Importer.Import(E->getType());
6106 if (T.isNull())
6107 return nullptr;
6108
6109 Expr *SubExpr = Importer.Import(E->getSubExpr());
6110 if (!SubExpr && E->getSubExpr())
6111 return nullptr;
6112
6113 return new (Importer.getToContext()) CXXThrowExpr(
6114 SubExpr, T, Importer.Import(E->getThrowLoc()),
6115 E->isThrownVariableInScope());
6116}
6117
6118Expr *ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
6119 auto *Param = cast_or_null<ParmVarDecl>(Importer.Import(E->getParam()));
6120 if (!Param)
6121 return nullptr;
6122
6123 return CXXDefaultArgExpr::Create(
6124 Importer.getToContext(), Importer.Import(E->getUsedLocation()), Param);
6125}
6126
6127Expr *ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
6128 QualType T = Importer.Import(E->getType());
6129 if (T.isNull())
6130 return nullptr;
6131
6132 TypeSourceInfo *TypeInfo = Importer.Import(E->getTypeSourceInfo());
6133 if (!TypeInfo)
6134 return nullptr;
6135
6136 return new (Importer.getToContext()) CXXScalarValueInitExpr(
6137 T, TypeInfo, Importer.Import(E->getRParenLoc()));
6138}
6139
6140Expr *ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
6141 Expr *SubExpr = Importer.Import(E->getSubExpr());
6142 if (!SubExpr)
6143 return nullptr;
6144
6145 auto *Dtor = cast_or_null<CXXDestructorDecl>(
6146 Importer.Import(const_cast<CXXDestructorDecl *>(
6147 E->getTemporary()->getDestructor())));
6148 if (!Dtor)
6149 return nullptr;
6150
6151 ASTContext &ToCtx = Importer.getToContext();
6152 CXXTemporary *Temp = CXXTemporary::Create(ToCtx, Dtor);
6153 return CXXBindTemporaryExpr::Create(ToCtx, Temp, SubExpr);
6154}
6155
6156Expr *ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *CE) {
6157 QualType T = Importer.Import(CE->getType());
6158 if (T.isNull())
6159 return nullptr;
6160
6161 TypeSourceInfo *TInfo = Importer.Import(CE->getTypeSourceInfo());
6162 if (!TInfo)
6163 return nullptr;
6164
6165 SmallVector<Expr *, 8> Args(CE->getNumArgs());
6166 if (ImportContainerChecked(CE->arguments(), Args))
6167 return nullptr;
6168
6169 auto *Ctor = cast_or_null<CXXConstructorDecl>(
6170 Importer.Import(CE->getConstructor()));
6171 if (!Ctor)
6172 return nullptr;
6173
6174 return new (Importer.getToContext()) CXXTemporaryObjectExpr(
6175 Importer.getToContext(), Ctor, T, TInfo, Args,
6176 Importer.Import(CE->getParenOrBraceRange()), CE->hadMultipleCandidates(),
6177 CE->isListInitialization(), CE->isStdInitListInitialization(),
6178 CE->requiresZeroInitialization());
6179}
6180
6181Expr *
6182ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
6183 QualType T = Importer.Import(E->getType());
6184 if (T.isNull())
6185 return nullptr;
6186
6187 Expr *TempE = Importer.Import(E->GetTemporaryExpr());
6188 if (!TempE)
6189 return nullptr;
6190
6191 auto *ExtendedBy = cast_or_null<ValueDecl>(
6192 Importer.Import(const_cast<ValueDecl *>(E->getExtendingDecl())));
6193 if (!ExtendedBy && E->getExtendingDecl())
6194 return nullptr;
6195
6196 auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr(
6197 T, TempE, E->isBoundToLvalueReference());
6198
6199 // FIXME: Should ManglingNumber get numbers associated with 'to' context?
6200 ToMTE->setExtendingDecl(ExtendedBy, E->getManglingNumber());
6201 return ToMTE;
6202}
6203
6204Expr *ASTNodeImporter::VisitPackExpansionExpr(PackExpansionExpr *E) {
6205 QualType T = Importer.Import(E->getType());
6206 if (T.isNull())
6207 return nullptr;
6208
6209 Expr *Pattern = Importer.Import(E->getPattern());
6210 if (!Pattern)
6211 return nullptr;
6212
6213 return new (Importer.getToContext()) PackExpansionExpr(
6214 T, Pattern, Importer.Import(E->getEllipsisLoc()),
6215 E->getNumExpansions());
6216}
6217
6218Expr *ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
6219 auto *Pack = cast_or_null<NamedDecl>(Importer.Import(E->getPack()));
6220 if (!Pack)
6221 return nullptr;
6222
6223 Optional<unsigned> Length;
6224
6225 if (!E->isValueDependent())
6226 Length = E->getPackLength();
6227
6228 SmallVector<TemplateArgument, 8> PartialArguments;
6229 if (E->isPartiallySubstituted()) {
6230 if (ImportTemplateArguments(E->getPartialArguments().data(),
6231 E->getPartialArguments().size(),
6232 PartialArguments))
6233 return nullptr;
6234 }
6235
6236 return SizeOfPackExpr::Create(
6237 Importer.getToContext(), Importer.Import(E->getOperatorLoc()), Pack,
6238 Importer.Import(E->getPackLoc()), Importer.Import(E->getRParenLoc()),
6239 Length, PartialArguments);
6240}
6241
6242Expr *ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *CE) {
6243 QualType T = Importer.Import(CE->getType());
6244 if (T.isNull())
6245 return nullptr;
6246
6247 SmallVector<Expr *, 4> PlacementArgs(CE->getNumPlacementArgs());
6248 if (ImportContainerChecked(CE->placement_arguments(), PlacementArgs))
6249 return nullptr;
6250
6251 auto *OperatorNewDecl = cast_or_null<FunctionDecl>(
6252 Importer.Import(CE->getOperatorNew()));
6253 if (!OperatorNewDecl && CE->getOperatorNew())
6254 return nullptr;
6255
6256 auto *OperatorDeleteDecl = cast_or_null<FunctionDecl>(
6257 Importer.Import(CE->getOperatorDelete()));
6258 if (!OperatorDeleteDecl && CE->getOperatorDelete())
6259 return nullptr;
6260
6261 Expr *ToInit = Importer.Import(CE->getInitializer());
6262 if (!ToInit && CE->getInitializer())
6263 return nullptr;
6264
6265 TypeSourceInfo *TInfo = Importer.Import(CE->getAllocatedTypeSourceInfo());
6266 if (!TInfo)
6267 return nullptr;
6268
6269 Expr *ToArrSize = Importer.Import(CE->getArraySize());
6270 if (!ToArrSize && CE->getArraySize())
6271 return nullptr;
6272
6273 return new (Importer.getToContext()) CXXNewExpr(
6274 Importer.getToContext(),
6275 CE->isGlobalNew(),
6276 OperatorNewDecl, OperatorDeleteDecl,
6277 CE->passAlignment(),
6278 CE->doesUsualArrayDeleteWantSize(),
6279 PlacementArgs,
6280 Importer.Import(CE->getTypeIdParens()),
6281 ToArrSize, CE->getInitializationStyle(), ToInit, T, TInfo,
6282 Importer.Import(CE->getSourceRange()),
6283 Importer.Import(CE->getDirectInitRange()));
6284}
6285
6286Expr *ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
6287 QualType T = Importer.Import(E->getType());
6288 if (T.isNull())
6289 return nullptr;
6290
6291 auto *OperatorDeleteDecl = cast_or_null<FunctionDecl>(
6292 Importer.Import(E->getOperatorDelete()));
6293 if (!OperatorDeleteDecl && E->getOperatorDelete())
6294 return nullptr;
6295
6296 Expr *ToArg = Importer.Import(E->getArgument());
6297 if (!ToArg && E->getArgument())
6298 return nullptr;
6299
6300 return new (Importer.getToContext()) CXXDeleteExpr(
6301 T, E->isGlobalDelete(),
6302 E->isArrayForm(),
6303 E->isArrayFormAsWritten(),
6304 E->doesUsualArrayDeleteWantSize(),
6305 OperatorDeleteDecl,
6306 ToArg,
6307 Importer.Import(E->getLocStart()));
6308}
6309
6310Expr *ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
6311 QualType T = Importer.Import(E->getType());
6312 if (T.isNull())
6313 return nullptr;
6314
6315 auto *ToCCD =
6316 dyn_cast_or_null<CXXConstructorDecl>(Importer.Import(E->getConstructor()));
6317 if (!ToCCD)
6318 return nullptr;
6319
6320 SmallVector<Expr *, 6> ToArgs(E->getNumArgs());
6321 if (ImportContainerChecked(E->arguments(), ToArgs))
6322 return nullptr;
6323
6324 return CXXConstructExpr::Create(Importer.getToContext(), T,
6325 Importer.Import(E->getLocation()),
6326 ToCCD, E->isElidable(),
6327 ToArgs, E->hadMultipleCandidates(),
6328 E->isListInitialization(),
6329 E->isStdInitListInitialization(),
6330 E->requiresZeroInitialization(),
6331 E->getConstructionKind(),
6332 Importer.Import(E->getParenOrBraceRange()));
6333}
6334
6335Expr *ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *EWC) {
6336 Expr *SubExpr = Importer.Import(EWC->getSubExpr());
6337 if (!SubExpr && EWC->getSubExpr())
6338 return nullptr;
6339
6340 SmallVector<ExprWithCleanups::CleanupObject, 8> Objs(EWC->getNumObjects());
6341 for (unsigned I = 0, E = EWC->getNumObjects(); I < E; I++)
6342 if (ExprWithCleanups::CleanupObject Obj =
6343 cast_or_null<BlockDecl>(Importer.Import(EWC->getObject(I))))
6344 Objs[I] = Obj;
6345 else
6346 return nullptr;
6347
6348 return ExprWithCleanups::Create(Importer.getToContext(),
6349 SubExpr, EWC->cleanupsHaveSideEffects(),
6350 Objs);
6351}
6352
6353Expr *ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
6354 QualType T = Importer.Import(E->getType());
6355 if (T.isNull())
6356 return nullptr;
6357
6358 Expr *ToFn = Importer.Import(E->getCallee());
6359 if (!ToFn)
6360 return nullptr;
6361
6362 SmallVector<Expr *, 4> ToArgs(E->getNumArgs());
6363 if (ImportContainerChecked(E->arguments(), ToArgs))
6364 return nullptr;
6365
6366 return new (Importer.getToContext()) CXXMemberCallExpr(
6367 Importer.getToContext(), ToFn, ToArgs, T, E->getValueKind(),
6368 Importer.Import(E->getRParenLoc()));
6369}
6370
6371Expr *ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) {
6372 QualType T = Importer.Import(E->getType());
6373 if (T.isNull())
6374 return nullptr;
6375
6376 return new (Importer.getToContext())
6377 CXXThisExpr(Importer.Import(E->getLocation()), T, E->isImplicit());
6378}
6379
6380Expr *ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
6381 QualType T = Importer.Import(E->getType());
6382 if (T.isNull())
6383 return nullptr;
6384
6385 return new (Importer.getToContext())
6386 CXXBoolLiteralExpr(E->getValue(), T, Importer.Import(E->getLocation()));
6387}
6388
6389
6390Expr *ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
6391 QualType T = Importer.Import(E->getType());
6392 if (T.isNull())
6393 return nullptr;
6394
6395 Expr *ToBase = Importer.Import(E->getBase());
6396 if (!ToBase && E->getBase())
6397 return nullptr;
6398
6399 auto *ToMember = dyn_cast<ValueDecl>(Importer.Import(E->getMemberDecl()));
6400 if (!ToMember && E->getMemberDecl())
6401 return nullptr;
6402
6403 auto *ToDecl =
6404 dyn_cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl().getDecl()));
6405 if (!ToDecl && E->getFoundDecl().getDecl())
6406 return nullptr;
6407
6408 DeclAccessPair ToFoundDecl =
6409 DeclAccessPair::make(ToDecl, E->getFoundDecl().getAccess());
6410
6411 DeclarationNameInfo ToMemberNameInfo(
6412 Importer.Import(E->getMemberNameInfo().getName()),
6413 Importer.Import(E->getMemberNameInfo().getLoc()));
6414
6415 if (E->hasExplicitTemplateArgs()) {
6416 return nullptr; // FIXME: handle template arguments
6417 }
6418
6419 return MemberExpr::Create(Importer.getToContext(), ToBase,
6420 E->isArrow(),
6421 Importer.Import(E->getOperatorLoc()),
6422 Importer.Import(E->getQualifierLoc()),
6423 Importer.Import(E->getTemplateKeywordLoc()),
6424 ToMember, ToFoundDecl, ToMemberNameInfo,
6425 nullptr, T, E->getValueKind(),
6426 E->getObjectKind());
6427}
6428
6429Expr *ASTNodeImporter::VisitCXXPseudoDestructorExpr(
6430 CXXPseudoDestructorExpr *E) {
6431 Expr *BaseE = Importer.Import(E->getBase());
6432 if (!BaseE)
6433 return nullptr;
6434
6435 TypeSourceInfo *ScopeInfo = Importer.Import(E->getScopeTypeInfo());
6436 if (!ScopeInfo && E->getScopeTypeInfo())
6437 return nullptr;
6438
6439 PseudoDestructorTypeStorage Storage;
6440 if (IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) {
6441 IdentifierInfo *ToII = Importer.Import(FromII);
6442 if (!ToII)
6443 return nullptr;
6444 Storage = PseudoDestructorTypeStorage(
6445 ToII, Importer.Import(E->getDestroyedTypeLoc()));
6446 } else {
6447 TypeSourceInfo *TI = Importer.Import(E->getDestroyedTypeInfo());
6448 if (!TI)
6449 return nullptr;
6450 Storage = PseudoDestructorTypeStorage(TI);
6451 }
6452
6453 return new (Importer.getToContext()) CXXPseudoDestructorExpr(
6454 Importer.getToContext(), BaseE, E->isArrow(),
6455 Importer.Import(E->getOperatorLoc()),
6456 Importer.Import(E->getQualifierLoc()),
6457 ScopeInfo, Importer.Import(E->getColonColonLoc()),
6458 Importer.Import(E->getTildeLoc()), Storage);
6459}
6460
6461Expr *ASTNodeImporter::VisitCXXDependentScopeMemberExpr(
6462 CXXDependentScopeMemberExpr *E) {
6463 Expr *Base = nullptr;
6464 if (!E->isImplicitAccess()) {
6465 Base = Importer.Import(E->getBase());
6466 if (!Base)
6467 return nullptr;
6468 }
6469
6470 QualType BaseType = Importer.Import(E->getBaseType());
6471 if (BaseType.isNull())
6472 return nullptr;
6473
6474 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
6475 if (E->hasExplicitTemplateArgs()) {
6476 if (ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
6477 E->template_arguments(), ToTAInfo))
6478 return nullptr;
6479 ResInfo = &ToTAInfo;
6480 }
6481
6482 DeclarationName Name = Importer.Import(E->getMember());
6483 if (!E->getMember().isEmpty() && Name.isEmpty())
6484 return nullptr;
6485
6486 DeclarationNameInfo MemberNameInfo(Name, Importer.Import(E->getMemberLoc()));
6487 // Import additional name location/type info.
6488 ImportDeclarationNameLoc(E->getMemberNameInfo(), MemberNameInfo);
6489 auto ToFQ = Importer.Import(E->getFirstQualifierFoundInScope());
6490 if (!ToFQ && E->getFirstQualifierFoundInScope())
6491 return nullptr;
6492
6493 return CXXDependentScopeMemberExpr::Create(
6494 Importer.getToContext(), Base, BaseType, E->isArrow(),
6495 Importer.Import(E->getOperatorLoc()),
6496 Importer.Import(E->getQualifierLoc()),
6497 Importer.Import(E->getTemplateKeywordLoc()),
6498 cast_or_null<NamedDecl>(ToFQ), MemberNameInfo, ResInfo);
6499}
6500
6501Expr *
6502ASTNodeImporter::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
6503 DeclarationName Name = Importer.Import(E->getDeclName());
6504 if (!E->getDeclName().isEmpty() && Name.isEmpty())
6505 return nullptr;
6506
6507 DeclarationNameInfo NameInfo(Name, Importer.Import(E->getExprLoc()));
6508 ImportDeclarationNameLoc(E->getNameInfo(), NameInfo);
6509
6510 TemplateArgumentListInfo ToTAInfo(Importer.Import(E->getLAngleLoc()),
6511 Importer.Import(E->getRAngleLoc()));
6512 TemplateArgumentListInfo *ResInfo = nullptr;
6513 if (E->hasExplicitTemplateArgs()) {
6514 if (ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo))
6515 return nullptr;
6516 ResInfo = &ToTAInfo;
6517 }
6518
6519 return DependentScopeDeclRefExpr::Create(
6520 Importer.getToContext(), Importer.Import(E->getQualifierLoc()),
6521 Importer.Import(E->getTemplateKeywordLoc()), NameInfo, ResInfo);
6522}
6523
6524Expr *ASTNodeImporter::VisitCXXUnresolvedConstructExpr(
6525 CXXUnresolvedConstructExpr *CE) {
6526 unsigned NumArgs = CE->arg_size();
6527
6528 SmallVector<Expr *, 8> ToArgs(NumArgs);
6529 if (ImportArrayChecked(CE->arg_begin(), CE->arg_end(), ToArgs.begin()))
6530 return nullptr;
6531
6532 return CXXUnresolvedConstructExpr::Create(
6533 Importer.getToContext(), Importer.Import(CE->getTypeSourceInfo()),
6534 Importer.Import(CE->getLParenLoc()), llvm::makeArrayRef(ToArgs),
6535 Importer.Import(CE->getRParenLoc()));
6536}
6537
6538Expr *ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
6539 auto *NamingClass =
6540 cast_or_null<CXXRecordDecl>(Importer.Import(E->getNamingClass()));
6541 if (E->getNamingClass() && !NamingClass)
6542 return nullptr;
6543
6544 DeclarationName Name = Importer.Import(E->getName());
6545 if (E->getName() && !Name)
6546 return nullptr;
6547
6548 DeclarationNameInfo NameInfo(Name, Importer.Import(E->getNameLoc()));
6549 // Import additional name location/type info.
6550 ImportDeclarationNameLoc(E->getNameInfo(), NameInfo);
6551
6552 UnresolvedSet<8> ToDecls;
6553 for (auto *D : E->decls()) {
6554 if (auto *To = cast_or_null<NamedDecl>(Importer.Import(D)))
6555 ToDecls.addDecl(To);
6556 else
6557 return nullptr;
6558 }
6559
6560 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
6561 if (E->hasExplicitTemplateArgs()) {
6562 if (ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
6563 E->template_arguments(), ToTAInfo))
6564 return nullptr;
6565 ResInfo = &ToTAInfo;
6566 }
6567
6568 if (ResInfo || E->getTemplateKeywordLoc().isValid())
6569 return UnresolvedLookupExpr::Create(
6570 Importer.getToContext(), NamingClass,
6571 Importer.Import(E->getQualifierLoc()),
6572 Importer.Import(E->getTemplateKeywordLoc()), NameInfo, E->requiresADL(),
6573 ResInfo, ToDecls.begin(), ToDecls.end());
6574
6575 return UnresolvedLookupExpr::Create(
6576 Importer.getToContext(), NamingClass,
6577 Importer.Import(E->getQualifierLoc()), NameInfo, E->requiresADL(),
6578 E->isOverloaded(), ToDecls.begin(), ToDecls.end());
6579}
6580
6581Expr *ASTNodeImporter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
6582 DeclarationName Name = Importer.Import(E->getName());
6583 if (!E->getName().isEmpty() && Name.isEmpty())
6584 return nullptr;
6585 DeclarationNameInfo NameInfo(Name, Importer.Import(E->getNameLoc()));
6586 // Import additional name location/type info.
6587 ImportDeclarationNameLoc(E->getNameInfo(), NameInfo);
6588
6589 QualType BaseType = Importer.Import(E->getType());
6590 if (!E->getType().isNull() && BaseType.isNull())
6591 return nullptr;
6592
6593 UnresolvedSet<8> ToDecls;
6594 for (Decl *D : E->decls()) {
6595 if (NamedDecl *To = cast_or_null<NamedDecl>(Importer.Import(D)))
6596 ToDecls.addDecl(To);
6597 else
6598 return nullptr;
6599 }
6600
6601 TemplateArgumentListInfo ToTAInfo;
6602 TemplateArgumentListInfo *ResInfo = nullptr;
6603 if (E->hasExplicitTemplateArgs()) {
6604 if (ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo))
6605 return nullptr;
6606 ResInfo = &ToTAInfo;
6607 }
6608
6609 Expr *BaseE = E->isImplicitAccess() ? nullptr : Importer.Import(E->getBase());
6610 if (!BaseE && !E->isImplicitAccess() && E->getBase()) {
6611 return nullptr;
6612 }
6613
6614 return UnresolvedMemberExpr::Create(
6615 Importer.getToContext(), E->hasUnresolvedUsing(), BaseE, BaseType,
6616 E->isArrow(), Importer.Import(E->getOperatorLoc()),
6617 Importer.Import(E->getQualifierLoc()),
6618 Importer.Import(E->getTemplateKeywordLoc()), NameInfo, ResInfo,
6619 ToDecls.begin(), ToDecls.end());
6620}
6621
6622Expr *ASTNodeImporter::VisitCallExpr(CallExpr *E) {
6623 QualType T = Importer.Import(E->getType());
6624 if (T.isNull())
6625 return nullptr;
6626
6627 Expr *ToCallee = Importer.Import(E->getCallee());
6628 if (!ToCallee && E->getCallee())
6629 return nullptr;
6630
6631 unsigned NumArgs = E->getNumArgs();
6632 SmallVector<Expr *, 2> ToArgs(NumArgs);
6633 if (ImportContainerChecked(E->arguments(), ToArgs))
6634 return nullptr;
6635
6636 auto **ToArgs_Copied = new (Importer.getToContext()) Expr*[NumArgs];
6637
6638 for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai)
6639 ToArgs_Copied[ai] = ToArgs[ai];
6640
6641 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6642 return new (Importer.getToContext()) CXXOperatorCallExpr(
6643 Importer.getToContext(), OCE->getOperator(), ToCallee, ToArgs, T,
6644 OCE->getValueKind(), Importer.Import(OCE->getRParenLoc()),
6645 OCE->getFPFeatures());
6646 }
6647
6648 return new (Importer.getToContext())
6649 CallExpr(Importer.getToContext(), ToCallee,
6650 llvm::makeArrayRef(ToArgs_Copied, NumArgs), T, E->getValueKind(),
6651 Importer.Import(E->getRParenLoc()));
6652}
6653
6654Optional<LambdaCapture>
6655ASTNodeImporter::ImportLambdaCapture(const LambdaCapture &From) {
6656 VarDecl *Var = nullptr;
6657 if (From.capturesVariable()) {
6658 Var = cast_or_null<VarDecl>(Importer.Import(From.getCapturedVar()));
6659 if (!Var)
6660 return None;
6661 }
6662
6663 return LambdaCapture(Importer.Import(From.getLocation()), From.isImplicit(),
6664 From.getCaptureKind(), Var,
6665 From.isPackExpansion()
6666 ? Importer.Import(From.getEllipsisLoc())
6667 : SourceLocation());
6668}
6669
6670Expr *ASTNodeImporter::VisitLambdaExpr(LambdaExpr *LE) {
6671 CXXRecordDecl *FromClass = LE->getLambdaClass();
6672 auto *ToClass = dyn_cast_or_null<CXXRecordDecl>(Importer.Import(FromClass));
6673 if (!ToClass)
6674 return nullptr;
6675
6676 // NOTE: lambda classes are created with BeingDefined flag set up.
6677 // It means that ImportDefinition doesn't work for them and we should fill it
6678 // manually.
6679 if (ToClass->isBeingDefined()) {
6680 for (auto FromField : FromClass->fields()) {
6681 auto *ToField = cast_or_null<FieldDecl>(Importer.Import(FromField));
6682 if (!ToField)
6683 return nullptr;
6684 }
6685 }
6686
6687 auto *ToCallOp = dyn_cast_or_null<CXXMethodDecl>(
6688 Importer.Import(LE->getCallOperator()));
6689 if (!ToCallOp)
6690 return nullptr;
6691
6692 ToClass->completeDefinition();
6693
6694 unsigned NumCaptures = LE->capture_size();
6695 SmallVector<LambdaCapture, 8> Captures;
6696 Captures.reserve(NumCaptures);
6697 for (const auto &FromCapture : LE->captures()) {
6698 if (auto ToCapture = ImportLambdaCapture(FromCapture))
6699 Captures.push_back(*ToCapture);
6700 else
6701 return nullptr;
6702 }
6703
6704 SmallVector<Expr *, 8> InitCaptures(NumCaptures);
6705 if (ImportContainerChecked(LE->capture_inits(), InitCaptures))
6706 return nullptr;
6707
6708 return LambdaExpr::Create(Importer.getToContext(), ToClass,
6709 Importer.Import(LE->getIntroducerRange()),
6710 LE->getCaptureDefault(),
6711 Importer.Import(LE->getCaptureDefaultLoc()),
6712 Captures,
6713 LE->hasExplicitParameters(),
6714 LE->hasExplicitResultType(),
6715 InitCaptures,
6716 Importer.Import(LE->getLocEnd()),
6717 LE->containsUnexpandedParameterPack());
6718}
6719
6720Expr *ASTNodeImporter::VisitInitListExpr(InitListExpr *ILE) {
6721 QualType T = Importer.Import(ILE->getType());
6722 if (T.isNull())
6723 return nullptr;
6724
6725 SmallVector<Expr *, 4> Exprs(ILE->getNumInits());
6726 if (ImportContainerChecked(ILE->inits(), Exprs))
6727 return nullptr;
6728
6729 ASTContext &ToCtx = Importer.getToContext();
6730 InitListExpr *To = new (ToCtx) InitListExpr(
6731 ToCtx, Importer.Import(ILE->getLBraceLoc()),
6732 Exprs, Importer.Import(ILE->getLBraceLoc()));
6733 To->setType(T);
6734
6735 if (ILE->hasArrayFiller()) {
6736 Expr *Filler = Importer.Import(ILE->getArrayFiller());
6737 if (!Filler)
6738 return nullptr;
6739 To->setArrayFiller(Filler);
6740 }
6741
6742 if (FieldDecl *FromFD = ILE->getInitializedFieldInUnion()) {
6743 auto *ToFD = cast_or_null<FieldDecl>(Importer.Import(FromFD));
6744 if (!ToFD)
6745 return nullptr;
6746 To->setInitializedFieldInUnion(ToFD);
6747 }
6748
6749 if (InitListExpr *SyntForm = ILE->getSyntacticForm()) {
6750 auto *ToSyntForm = cast_or_null<InitListExpr>(Importer.Import(SyntForm));
6751 if (!ToSyntForm)
6752 return nullptr;
6753 To->setSyntacticForm(ToSyntForm);
6754 }
6755
6756 To->sawArrayRangeDesignator(ILE->hadArrayRangeDesignator());
6757 To->setValueDependent(ILE->isValueDependent());
6758 To->setInstantiationDependent(ILE->isInstantiationDependent());
6759
6760 return To;
6761}
6762
6763Expr *ASTNodeImporter::VisitCXXStdInitializerListExpr(
6764 CXXStdInitializerListExpr *E) {
6765 QualType T = Importer.Import(E->getType());
6766 if (T.isNull())
6767 return nullptr;
6768
6769 Expr *SE = Importer.Import(E->getSubExpr());
6770 if (!SE)
6771 return nullptr;
6772
6773 return new (Importer.getToContext()) CXXStdInitializerListExpr(T, SE);
6774}
6775
6776Expr *ASTNodeImporter::VisitCXXInheritedCtorInitExpr(
6777 CXXInheritedCtorInitExpr *E) {
6778 QualType T = Importer.Import(E->getType());
6779 if (T.isNull())
6780 return nullptr;
6781
6782 auto *Ctor = cast_or_null<CXXConstructorDecl>(Importer.Import(
6783 E->getConstructor()));
6784 if (!Ctor)
6785 return nullptr;
6786
6787 return new (Importer.getToContext()) CXXInheritedCtorInitExpr(
6788 Importer.Import(E->getLocation()), T, Ctor,
6789 E->constructsVBase(), E->inheritedFromVBase());
6790}
6791
6792Expr *ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) {
6793 QualType ToType = Importer.Import(E->getType());
6794 if (ToType.isNull())
1
Taking false branch
6795 return nullptr;
6796
6797 Expr *ToCommon = Importer.Import(E->getCommonExpr());
6798 if (!ToCommon && E->getCommonExpr())
2
Assuming 'ToCommon' is non-null
6799 return nullptr;
6800
6801 Expr *ToSubExpr = Importer.Import(E->getSubExpr());
3
Calling 'ASTImporter::Import'
15
Returning from 'ASTImporter::Import'
16
'ToSubExpr' initialized here
6802 if (!ToSubExpr && E->getSubExpr())
17
Assuming 'ToSubExpr' is null
18
Assuming the condition is false
19
Taking false branch
6803 return nullptr;
6804
6805 return new (Importer.getToContext())
6806 ArrayInitLoopExpr(ToType, ToCommon, ToSubExpr);
20
Passing null pointer value via 3rd parameter 'ElementInit'
21
Calling constructor for 'ArrayInitLoopExpr'
6807}
6808
6809Expr *ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
6810 QualType ToType = Importer.Import(E->getType());
6811 if (ToType.isNull())
6812 return nullptr;
6813 return new (Importer.getToContext()) ArrayInitIndexExpr(ToType);
6814}
6815
6816Expr *ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
6817 auto *ToField = dyn_cast_or_null<FieldDecl>(Importer.Import(DIE->getField()));
6818 if (!ToField && DIE->getField())
6819 return nullptr;
6820
6821 return CXXDefaultInitExpr::Create(
6822 Importer.getToContext(), Importer.Import(DIE->getLocStart()), ToField);
6823}
6824
6825Expr *ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
6826 QualType ToType = Importer.Import(E->getType());
6827 if (ToType.isNull() && !E->getType().isNull())
6828 return nullptr;
6829 ExprValueKind VK = E->getValueKind();
6830 CastKind CK = E->getCastKind();
6831 Expr *ToOp = Importer.Import(E->getSubExpr());
6832 if (!ToOp && E->getSubExpr())
6833 return nullptr;
6834 CXXCastPath BasePath;
6835 if (ImportCastPath(E, BasePath))
6836 return nullptr;
6837 TypeSourceInfo *ToWritten = Importer.Import(E->getTypeInfoAsWritten());
6838 SourceLocation ToOperatorLoc = Importer.Import(E->getOperatorLoc());
6839 SourceLocation ToRParenLoc = Importer.Import(E->getRParenLoc());
6840 SourceRange ToAngleBrackets = Importer.Import(E->getAngleBrackets());
6841
6842 if (isa<CXXStaticCastExpr>(E)) {
6843 return CXXStaticCastExpr::Create(
6844 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6845 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6846 } else if (isa<CXXDynamicCastExpr>(E)) {
6847 return CXXDynamicCastExpr::Create(
6848 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6849 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6850 } else if (isa<CXXReinterpretCastExpr>(E)) {
6851 return CXXReinterpretCastExpr::Create(
6852 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6853 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6854 } else {
6855 return nullptr;
6856 }
6857}
6858
6859Expr *ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr(
6860 SubstNonTypeTemplateParmExpr *E) {
6861 QualType T = Importer.Import(E->getType());
6862 if (T.isNull())
6863 return nullptr;
6864
6865 auto *Param = cast_or_null<NonTypeTemplateParmDecl>(
6866 Importer.Import(E->getParameter()));
6867 if (!Param)
6868 return nullptr;
6869
6870 Expr *Replacement = Importer.Import(E->getReplacement());
6871 if (!Replacement)
6872 return nullptr;
6873
6874 return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr(
6875 T, E->getValueKind(), Importer.Import(E->getExprLoc()), Param,
6876 Replacement);
6877}
6878
6879Expr *ASTNodeImporter::VisitTypeTraitExpr(TypeTraitExpr *E) {
6880 QualType ToType = Importer.Import(E->getType());
6881 if (ToType.isNull())
6882 return nullptr;
6883
6884 SmallVector<TypeSourceInfo *, 4> ToArgs(E->getNumArgs());
6885 if (ImportContainerChecked(E->getArgs(), ToArgs))
6886 return nullptr;
6887
6888 // According to Sema::BuildTypeTrait(), if E is value-dependent,
6889 // Value is always false.
6890 bool ToValue = false;
6891 if (!E->isValueDependent())
6892 ToValue = E->getValue();
6893
6894 return TypeTraitExpr::Create(
6895 Importer.getToContext(), ToType, Importer.Import(E->getLocStart()),
6896 E->getTrait(), ToArgs, Importer.Import(E->getLocEnd()), ToValue);
6897}
6898
6899Expr *ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
6900 QualType ToType = Importer.Import(E->getType());
6901 if (ToType.isNull())
6902 return nullptr;
6903
6904 if (E->isTypeOperand()) {
6905 TypeSourceInfo *TSI = Importer.Import(E->getTypeOperandSourceInfo());
6906 if (!TSI)
6907 return nullptr;
6908
6909 return new (Importer.getToContext())
6910 CXXTypeidExpr(ToType, TSI, Importer.Import(E->getSourceRange()));
6911 }
6912
6913 Expr *Op = Importer.Import(E->getExprOperand());
6914 if (!Op)
6915 return nullptr;
6916
6917 return new (Importer.getToContext())
6918 CXXTypeidExpr(ToType, Op, Importer.Import(E->getSourceRange()));
6919}
6920
6921void ASTNodeImporter::ImportOverrides(CXXMethodDecl *ToMethod,
6922 CXXMethodDecl *FromMethod) {
6923 for (auto *FromOverriddenMethod : FromMethod->overridden_methods())
6924 ToMethod->addOverriddenMethod(
6925 cast<CXXMethodDecl>(Importer.Import(const_cast<CXXMethodDecl*>(
6926 FromOverriddenMethod))));
6927}
6928
6929ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
6930 ASTContext &FromContext, FileManager &FromFileManager,
6931 bool MinimalImport)
6932 : ToContext(ToContext), FromContext(FromContext),
6933 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
6934 Minimal(MinimalImport) {
6935 ImportedDecls[FromContext.getTranslationUnitDecl()]
6936 = ToContext.getTranslationUnitDecl();
6937}
6938
6939ASTImporter::~ASTImporter() = default;
6940
6941QualType ASTImporter::Import(QualType FromT) {
6942 if (FromT.isNull())
6943 return {};
6944
6945 const Type *fromTy = FromT.getTypePtr();
6946
6947 // Check whether we've already imported this type.
6948 llvm::DenseMap<const Type *, const Type *>::iterator Pos
6949 = ImportedTypes.find(fromTy);
6950 if (Pos != ImportedTypes.end())
6951 return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
6952
6953 // Import the type
6954 ASTNodeImporter Importer(*this);
6955 QualType ToT = Importer.Visit(fromTy);
6956 if (ToT.isNull())
6957 return ToT;
6958
6959 // Record the imported type.
6960 ImportedTypes[fromTy] = ToT.getTypePtr();
6961
6962 return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
6963}
6964
6965TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
6966 if (!FromTSI)
6967 return FromTSI;
6968
6969 // FIXME: For now we just create a "trivial" type source info based
6970 // on the type and a single location. Implement a real version of this.
6971 QualType T = Import(FromTSI->getType());
6972 if (T.isNull())
6973 return nullptr;
6974
6975 return ToContext.getTrivialTypeSourceInfo(T,
6976 Import(FromTSI->getTypeLoc().getLocStart()));
6977}
6978
6979Attr *ASTImporter::Import(const Attr *FromAttr) {
6980 Attr *ToAttr = FromAttr->clone(ToContext);
6981 ToAttr->setRange(Import(FromAttr->getRange()));
6982 return ToAttr;
6983}
6984
6985Decl *ASTImporter::GetAlreadyImportedOrNull(Decl *FromD) {
6986 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
6987 if (Pos != ImportedDecls.end()) {
6988 Decl *ToD = Pos->second;
6989 // FIXME: move this call to ImportDeclParts().
6990 ASTNodeImporter(*this).ImportDefinitionIfNeeded(FromD, ToD);
6991 return ToD;
6992 } else {
6993 return nullptr;
6994 }
6995}
6996
6997Decl *ASTImporter::Import(Decl *FromD) {
6998 if (!FromD)
6999 return nullptr;
7000
7001 ASTNodeImporter Importer(*this);
7002
7003 // Check whether we've already imported this declaration.
7004 Decl *ToD = GetAlreadyImportedOrNull(FromD);
7005 if (ToD) {
7006 // If FromD has some updated flags after last import, apply it
7007 updateFlags(FromD, ToD);
7008 return ToD;
7009 }
7010
7011 // Import the type.
7012 ToD = Importer.Visit(FromD);
7013 if (!ToD)
7014 return nullptr;
7015
7016 // Notify subclasses.
7017 Imported(FromD, ToD);
7018
7019 return ToD;
7020}
7021
7022DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
7023 if (!FromDC)
7024 return FromDC;
7025
7026 auto *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
7027 if (!ToDC)
7028 return nullptr;
7029
7030 // When we're using a record/enum/Objective-C class/protocol as a context, we
7031 // need it to have a definition.
7032 if (auto *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
7033 auto *FromRecord = cast<RecordDecl>(FromDC);
7034 if (ToRecord->isCompleteDefinition()) {
7035 // Do nothing.
7036 } else if (FromRecord->isCompleteDefinition()) {
7037 ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
7038 ASTNodeImporter::IDK_Basic);
7039 } else {
7040 CompleteDecl(ToRecord);
7041 }
7042 } else if (auto *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
7043 auto *FromEnum = cast<EnumDecl>(FromDC);
7044 if (ToEnum->isCompleteDefinition()) {
7045 // Do nothing.
7046 } else if (FromEnum->isCompleteDefinition()) {
7047 ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
7048 ASTNodeImporter::IDK_Basic);
7049 } else {
7050 CompleteDecl(ToEnum);
7051 }
7052 } else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
7053 auto *FromClass = cast<ObjCInterfaceDecl>(FromDC);
7054 if (ToClass->getDefinition()) {
7055 // Do nothing.
7056 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
7057 ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
7058 ASTNodeImporter::IDK_Basic);
7059 } else {
7060 CompleteDecl(ToClass);
7061 }
7062 } else if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
7063 auto *FromProto = cast<ObjCProtocolDecl>(FromDC);
7064 if (ToProto->getDefinition()) {
7065 // Do nothing.
7066 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
7067 ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
7068 ASTNodeImporter::IDK_Basic);
7069 } else {
7070 CompleteDecl(ToProto);
7071 }
7072 }
7073
7074 return ToDC;
7075}
7076
7077Expr *ASTImporter::Import(Expr *FromE) {
7078 if (!FromE)
4
Assuming 'FromE' is non-null
5
Taking false branch
7079 return nullptr;
7080
7081 return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
6
Calling 'cast_or_null<clang::Expr, clang::Stmt>'
14
Returning from 'cast_or_null<clang::Expr, clang::Stmt>'
7082}
7083
7084Stmt *ASTImporter::Import(Stmt *FromS) {
7085 if (!FromS)
7086 return nullptr;
7087
7088 // Check whether we've already imported this declaration.
7089 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
7090 if (Pos != ImportedStmts.end())
7091 return Pos->second;
7092
7093 // Import the type
7094 ASTNodeImporter Importer(*this);
7095 Stmt *ToS = Importer.Visit(FromS);
7096 if (!ToS)
7097 return nullptr;
7098
7099 // Record the imported declaration.
7100 ImportedStmts[FromS] = ToS;
7101 return ToS;
7102}
7103
7104NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
7105 if (!FromNNS)
7106 return nullptr;
7107
7108 NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
7109
7110 switch (FromNNS->getKind()) {
7111 case NestedNameSpecifier::Identifier:
7112 if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
7113 return NestedNameSpecifier::Create(ToContext, prefix, II);
7114 }
7115 return nullptr;
7116
7117 case NestedNameSpecifier::Namespace:
7118 if (auto *NS =
7119 cast_or_null<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
7120 return NestedNameSpecifier::Create(ToContext, prefix, NS);
7121 }
7122 return nullptr;
7123
7124 case NestedNameSpecifier::NamespaceAlias:
7125 if (auto *NSAD =
7126 cast_or_null<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
7127 return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
7128 }
7129 return nullptr;
7130
7131 case NestedNameSpecifier::Global:
7132 return NestedNameSpecifier::GlobalSpecifier(ToContext);
7133
7134 case NestedNameSpecifier::Super:
7135 if (auto *RD =
7136 cast_or_null<CXXRecordDecl>(Import(FromNNS->getAsRecordDecl()))) {
7137 return NestedNameSpecifier::SuperSpecifier(ToContext, RD);
7138 }
7139 return nullptr;
7140
7141 case NestedNameSpecifier::TypeSpec:
7142 case NestedNameSpecifier::TypeSpecWithTemplate: {
7143 QualType T = Import(QualType(FromNNS->getAsType(), 0u));
7144 if (!T.isNull()) {
7145 bool bTemplate = FromNNS->getKind() ==
7146 NestedNameSpecifier::TypeSpecWithTemplate;
7147 return NestedNameSpecifier::Create(ToContext, prefix,
7148 bTemplate, T.getTypePtr());
7149 }
7150 }
7151 return nullptr;
7152 }
7153
7154 llvm_unreachable("Invalid nested name specifier kind")::llvm::llvm_unreachable_internal("Invalid nested name specifier kind"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 7154)
;
7155}
7156
7157NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
7158 // Copied from NestedNameSpecifier mostly.
7159 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
7160 NestedNameSpecifierLoc NNS = FromNNS;
7161
7162 // Push each of the nested-name-specifiers's onto a stack for
7163 // serialization in reverse order.
7164 while (NNS) {
7165 NestedNames.push_back(NNS);
7166 NNS = NNS.getPrefix();
7167 }
7168
7169 NestedNameSpecifierLocBuilder Builder;
7170
7171 while (!NestedNames.empty()) {
7172 NNS = NestedNames.pop_back_val();
7173 NestedNameSpecifier *Spec = Import(NNS.getNestedNameSpecifier());
7174 if (!Spec)
7175 return NestedNameSpecifierLoc();
7176
7177 NestedNameSpecifier::SpecifierKind Kind = Spec->getKind();
7178 switch (Kind) {
7179 case NestedNameSpecifier::Identifier:
7180 Builder.Extend(getToContext(),
7181 Spec->getAsIdentifier(),
7182 Import(NNS.getLocalBeginLoc()),
7183 Import(NNS.getLocalEndLoc()));
7184 break;
7185
7186 case NestedNameSpecifier::Namespace:
7187 Builder.Extend(getToContext(),
7188 Spec->getAsNamespace(),
7189 Import(NNS.getLocalBeginLoc()),
7190 Import(NNS.getLocalEndLoc()));
7191 break;
7192
7193 case NestedNameSpecifier::NamespaceAlias:
7194 Builder.Extend(getToContext(),
7195 Spec->getAsNamespaceAlias(),
7196 Import(NNS.getLocalBeginLoc()),
7197 Import(NNS.getLocalEndLoc()));
7198 break;
7199
7200 case NestedNameSpecifier::TypeSpec:
7201 case NestedNameSpecifier::TypeSpecWithTemplate: {
7202 TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo(
7203 QualType(Spec->getAsType(), 0));
7204 Builder.Extend(getToContext(),
7205 Import(NNS.getLocalBeginLoc()),
7206 TSI->getTypeLoc(),
7207 Import(NNS.getLocalEndLoc()));
7208 break;
7209 }
7210
7211 case NestedNameSpecifier::Global:
7212 Builder.MakeGlobal(getToContext(), Import(NNS.getLocalBeginLoc()));
7213 break;
7214
7215 case NestedNameSpecifier::Super: {
7216 SourceRange ToRange = Import(NNS.getSourceRange());
7217 Builder.MakeSuper(getToContext(),
7218 Spec->getAsRecordDecl(),
7219 ToRange.getBegin(),
7220 ToRange.getEnd());
7221 }
7222 }
7223 }
7224
7225 return Builder.getWithLocInContext(getToContext());
7226}
7227
7228TemplateName ASTImporter::Import(TemplateName From) {
7229 switch (From.getKind()) {
7230 case TemplateName::Template:
7231 if (auto *ToTemplate =
7232 cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
7233 return TemplateName(ToTemplate);
7234
7235 return {};
7236
7237 case TemplateName::OverloadedTemplate: {
7238 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
7239 UnresolvedSet<2> ToTemplates;
7240 for (auto *I : *FromStorage) {
7241 if (auto *To = cast_or_null<NamedDecl>(Import(I)))
7242 ToTemplates.addDecl(To);
7243 else
7244 return {};
7245 }
7246 return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
7247 ToTemplates.end());
7248 }
7249
7250 case TemplateName::QualifiedTemplate: {
7251 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
7252 NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
7253 if (!Qualifier)
7254 return {};
7255
7256 if (auto *ToTemplate =
7257 cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
7258 return ToContext.getQualifiedTemplateName(Qualifier,
7259 QTN->hasTemplateKeyword(),
7260 ToTemplate);
7261
7262 return {};
7263 }
7264
7265 case TemplateName::DependentTemplate: {
7266 DependentTemplateName *DTN = From.getAsDependentTemplateName();
7267 NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
7268 if (!Qualifier)
7269 return {};
7270
7271 if (DTN->isIdentifier()) {
7272 return ToContext.getDependentTemplateName(Qualifier,
7273 Import(DTN->getIdentifier()));
7274 }
7275
7276 return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
7277 }
7278
7279 case TemplateName::SubstTemplateTemplateParm: {
7280 SubstTemplateTemplateParmStorage *subst
7281 = From.getAsSubstTemplateTemplateParm();
7282 auto *param =
7283 cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
7284 if (!param)
7285 return {};
7286
7287 TemplateName replacement = Import(subst->getReplacement());
7288 if (replacement.isNull())
7289 return {};
7290
7291 return ToContext.getSubstTemplateTemplateParm(param, replacement);
7292 }
7293
7294 case TemplateName::SubstTemplateTemplateParmPack: {
7295 SubstTemplateTemplateParmPackStorage *SubstPack
7296 = From.getAsSubstTemplateTemplateParmPack();
7297 auto *Param =
7298 cast_or_null<TemplateTemplateParmDecl>(
7299 Import(SubstPack->getParameterPack()));
7300 if (!Param)
7301 return {};
7302
7303 ASTNodeImporter Importer(*this);
7304 TemplateArgument ArgPack
7305 = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
7306 if (ArgPack.isNull())
7307 return {};
7308
7309 return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
7310 }
7311 }
7312
7313 llvm_unreachable("Invalid template name kind")::llvm::llvm_unreachable_internal("Invalid template name kind"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 7313)
;
7314}
7315
7316SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
7317 if (FromLoc.isInvalid())
7318 return {};
7319
7320 SourceManager &FromSM = FromContext.getSourceManager();
7321
7322 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
7323 FileID ToFileID = Import(Decomposed.first);
7324 if (ToFileID.isInvalid())
7325 return {};
7326 SourceManager &ToSM = ToContext.getSourceManager();
7327 return ToSM.getComposedLoc(ToFileID, Decomposed.second);
7328}
7329
7330SourceRange ASTImporter::Import(SourceRange FromRange) {
7331 return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
7332}
7333
7334FileID ASTImporter::Import(FileID FromID) {
7335 llvm::DenseMap<FileID, FileID>::iterator Pos = ImportedFileIDs.find(FromID);
7336 if (Pos != ImportedFileIDs.end())
7337 return Pos->second;
7338
7339 SourceManager &FromSM = FromContext.getSourceManager();
7340 SourceManager &ToSM = ToContext.getSourceManager();
7341 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
7342
7343 // Map the FromID to the "to" source manager.
7344 FileID ToID;
7345 if (FromSLoc.isExpansion()) {
7346 const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion();
7347 SourceLocation ToSpLoc = Import(FromEx.getSpellingLoc());
7348 SourceLocation ToExLocS = Import(FromEx.getExpansionLocStart());
7349 unsigned TokenLen = FromSM.getFileIDSize(FromID);
7350 SourceLocation MLoc;
7351 if (FromEx.isMacroArgExpansion()) {
7352 MLoc = ToSM.createMacroArgExpansionLoc(ToSpLoc, ToExLocS, TokenLen);
7353 } else {
7354 SourceLocation ToExLocE = Import(FromEx.getExpansionLocEnd());
7355 MLoc = ToSM.createExpansionLoc(ToSpLoc, ToExLocS, ToExLocE, TokenLen,
7356 FromEx.isExpansionTokenRange());
7357 }
7358 ToID = ToSM.getFileID(MLoc);
7359 } else {
7360 // Include location of this file.
7361 SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
7362
7363 const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
7364 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
7365 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
7366 // disk again
7367 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
7368 // than mmap the files several times.
7369 const FileEntry *Entry =
7370 ToFileManager.getFile(Cache->OrigEntry->getName());
7371 if (!Entry)
7372 return {};
7373 ToID = ToSM.createFileID(Entry, ToIncludeLoc,
7374 FromSLoc.getFile().getFileCharacteristic());
7375 } else {
7376 // FIXME: We want to re-use the existing MemoryBuffer!
7377 const llvm::MemoryBuffer *FromBuf =
7378 Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
7379 std::unique_ptr<llvm::MemoryBuffer> ToBuf =
7380 llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
7381 FromBuf->getBufferIdentifier());
7382 ToID = ToSM.createFileID(std::move(ToBuf),
7383 FromSLoc.getFile().getFileCharacteristic());
7384 }
7385 }
7386
7387 ImportedFileIDs[FromID] = ToID;
7388 return ToID;
7389}
7390
7391CXXCtorInitializer *ASTImporter::Import(CXXCtorInitializer *From) {
7392 Expr *ToExpr = Import(From->getInit());
7393 if (!ToExpr && From->getInit())
7394 return nullptr;
7395
7396 if (From->isBaseInitializer()) {
7397 TypeSourceInfo *ToTInfo = Import(From->getTypeSourceInfo());
7398 if (!ToTInfo && From->getTypeSourceInfo())
7399 return nullptr;
7400
7401 return new (ToContext) CXXCtorInitializer(
7402 ToContext, ToTInfo, From->isBaseVirtual(), Import(From->getLParenLoc()),
7403 ToExpr, Import(From->getRParenLoc()),
7404 From->isPackExpansion() ? Import(From->getEllipsisLoc())
7405 : SourceLocation());
7406 } else if (From->isMemberInitializer()) {
7407 auto *ToField = cast_or_null<FieldDecl>(Import(From->getMember()));
7408 if (!ToField && From->getMember())
7409 return nullptr;
7410
7411 return new (ToContext) CXXCtorInitializer(
7412 ToContext, ToField, Import(From->getMemberLocation()),
7413 Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()));
7414 } else if (From->isIndirectMemberInitializer()) {
7415 auto *ToIField = cast_or_null<IndirectFieldDecl>(
7416 Import(From->getIndirectMember()));
7417 if (!ToIField && From->getIndirectMember())
7418 return nullptr;
7419
7420 return new (ToContext) CXXCtorInitializer(
7421 ToContext, ToIField, Import(From->getMemberLocation()),
7422 Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()));
7423 } else if (From->isDelegatingInitializer()) {
7424 TypeSourceInfo *ToTInfo = Import(From->getTypeSourceInfo());
7425 if (!ToTInfo && From->getTypeSourceInfo())
7426 return nullptr;
7427
7428 return new (ToContext)
7429 CXXCtorInitializer(ToContext, ToTInfo, Import(From->getLParenLoc()),
7430 ToExpr, Import(From->getRParenLoc()));
7431 } else {
7432 return nullptr;
7433 }
7434}
7435
7436CXXBaseSpecifier *ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) {
7437 auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec);
7438 if (Pos != ImportedCXXBaseSpecifiers.end())
7439 return Pos->second;
7440
7441 CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier(
7442 Import(BaseSpec->getSourceRange()),
7443 BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(),
7444 BaseSpec->getAccessSpecifierAsWritten(),
7445 Import(BaseSpec->getTypeSourceInfo()),
7446 Import(BaseSpec->getEllipsisLoc()));
7447 ImportedCXXBaseSpecifiers[BaseSpec] = Imported;
7448 return Imported;
7449}
7450
7451void ASTImporter::ImportDefinition(Decl *From) {
7452 Decl *To = Import(From);
7453 if (!To)
7454 return;
7455
7456 if (auto *FromDC = cast<DeclContext>(From)) {
7457 ASTNodeImporter Importer(*this);
7458
7459 if (auto *ToRecord = dyn_cast<RecordDecl>(To)) {
7460 if (!ToRecord->getDefinition()) {
7461 Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,
7462 ASTNodeImporter::IDK_Everything);
7463 return;
7464 }
7465 }
7466
7467 if (auto *ToEnum = dyn_cast<EnumDecl>(To)) {
7468 if (!ToEnum->getDefinition()) {
7469 Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum,
7470 ASTNodeImporter::IDK_Everything);
7471 return;
7472 }
7473 }
7474
7475 if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
7476 if (!ToIFace->getDefinition()) {
7477 Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
7478 ASTNodeImporter::IDK_Everything);
7479 return;
7480 }
7481 }
7482
7483 if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
7484 if (!ToProto->getDefinition()) {
7485 Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
7486 ASTNodeImporter::IDK_Everything);
7487 return;
7488 }
7489 }
7490
7491 Importer.ImportDeclContext(FromDC, true);
7492 }
7493}
7494
7495DeclarationName ASTImporter::Import(DeclarationName FromName) {
7496 if (!FromName)
7497 return {};
7498
7499 switch (FromName.getNameKind()) {
7500 case DeclarationName::Identifier:
7501 return Import(FromName.getAsIdentifierInfo());
7502
7503 case DeclarationName::ObjCZeroArgSelector:
7504 case DeclarationName::ObjCOneArgSelector:
7505 case DeclarationName::ObjCMultiArgSelector:
7506 return Import(FromName.getObjCSelector());
7507
7508 case DeclarationName::CXXConstructorName: {
7509 QualType T = Import(FromName.getCXXNameType());
7510 if (T.isNull())
7511 return {};
7512
7513 return ToContext.DeclarationNames.getCXXConstructorName(
7514 ToContext.getCanonicalType(T));
7515 }
7516
7517 case DeclarationName::CXXDestructorName: {
7518 QualType T = Import(FromName.getCXXNameType());
7519 if (T.isNull())
7520 return {};
7521
7522 return ToContext.DeclarationNames.getCXXDestructorName(
7523 ToContext.getCanonicalType(T));
7524 }
7525
7526 case DeclarationName::CXXDeductionGuideName: {
7527 auto *Template = cast_or_null<TemplateDecl>(
7528 Import(FromName.getCXXDeductionGuideTemplate()));
7529 if (!Template)
7530 return {};
7531 return ToContext.DeclarationNames.getCXXDeductionGuideName(Template);
7532 }
7533
7534 case DeclarationName::CXXConversionFunctionName: {
7535 QualType T = Import(FromName.getCXXNameType());
7536 if (T.isNull())
7537 return {};
7538
7539 return ToContext.DeclarationNames.getCXXConversionFunctionName(
7540 ToContext.getCanonicalType(T));
7541 }
7542
7543 case DeclarationName::CXXOperatorName:
7544 return ToContext.DeclarationNames.getCXXOperatorName(
7545 FromName.getCXXOverloadedOperator());
7546
7547 case DeclarationName::CXXLiteralOperatorName:
7548 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
7549 Import(FromName.getCXXLiteralIdentifier()));
7550
7551 case DeclarationName::CXXUsingDirective:
7552 // FIXME: STATICS!
7553 return DeclarationName::getUsingDirectiveName();
7554 }
7555
7556 llvm_unreachable("Invalid DeclarationName Kind!")::llvm::llvm_unreachable_internal("Invalid DeclarationName Kind!"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 7556)
;
7557}
7558
7559IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
7560 if (!FromId)
7561 return nullptr;
7562
7563 IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName());
7564
7565 if (!ToId->getBuiltinID() && FromId->getBuiltinID())
7566 ToId->setBuiltinID(FromId->getBuiltinID());
7567
7568 return ToId;
7569}
7570
7571Selector ASTImporter::Import(Selector FromSel) {
7572 if (FromSel.isNull())
7573 return {};
7574
7575 SmallVector<IdentifierInfo *, 4> Idents;
7576 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
7577 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
7578 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
7579 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
7580}
7581
7582DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
7583 DeclContext *DC,
7584 unsigned IDNS,
7585 NamedDecl **Decls,
7586 unsigned NumDecls) {
7587 return Name;
7588}
7589
7590DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
7591 if (LastDiagFromFrom)
7592 ToContext.getDiagnostics().notePriorDiagnosticFrom(
7593 FromContext.getDiagnostics());
7594 LastDiagFromFrom = false;
7595 return ToContext.getDiagnostics().Report(Loc, DiagID);
7596}
7597
7598DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
7599 if (!LastDiagFromFrom)
7600 FromContext.getDiagnostics().notePriorDiagnosticFrom(
7601 ToContext.getDiagnostics());
7602 LastDiagFromFrom = true;
7603 return FromContext.getDiagnostics().Report(Loc, DiagID);
7604}
7605
7606void ASTImporter::CompleteDecl (Decl *D) {
7607 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
7608 if (!ID->getDefinition())
7609 ID->startDefinition();
7610 }
7611 else if (auto *PD = dyn_cast<ObjCProtocolDecl>(D)) {
7612 if (!PD->getDefinition())
7613 PD->startDefinition();
7614 }
7615 else if (auto *TD = dyn_cast<TagDecl>(D)) {
7616 if (!TD->getDefinition() && !TD->isBeingDefined()) {
7617 TD->startDefinition();
7618 TD->setCompleteDefinition(true);
7619 }
7620 }
7621 else {
7622 assert(0 && "CompleteDecl called on a Decl that can't be completed")(static_cast <bool> (0 && "CompleteDecl called on a Decl that can't be completed"
) ? void (0) : __assert_fail ("0 && \"CompleteDecl called on a Decl that can't be completed\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 7622, __extension__ __PRETTY_FUNCTION__))
;
7623 }
7624}
7625
7626Decl *ASTImporter::MapImported(Decl *From, Decl *To) {
7627 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(From);
7628 assert((Pos == ImportedDecls.end() || Pos->second == To) &&(static_cast <bool> ((Pos == ImportedDecls.end() || Pos
->second == To) && "Try to import an already imported Decl"
) ? void (0) : __assert_fail ("(Pos == ImportedDecls.end() || Pos->second == To) && \"Try to import an already imported Decl\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 7629, __extension__ __PRETTY_FUNCTION__))
7629 "Try to import an already imported Decl")(static_cast <bool> ((Pos == ImportedDecls.end() || Pos
->second == To) && "Try to import an already imported Decl"
) ? void (0) : __assert_fail ("(Pos == ImportedDecls.end() || Pos->second == To) && \"Try to import an already imported Decl\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/AST/ASTImporter.cpp"
, 7629, __extension__ __PRETTY_FUNCTION__))
;
7630 if (Pos != ImportedDecls.end())
7631 return Pos->second;
7632 ImportedDecls[From] = To;
7633 return To;
7634}
7635
7636bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
7637 bool Complain) {
7638 llvm::DenseMap<const Type *, const Type *>::iterator Pos
7639 = ImportedTypes.find(From.getTypePtr());
7640 if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
7641 return true;
7642
7643 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
7644 getStructuralEquivalenceKind(*this), false,
7645 Complain);
7646 return Ctx.IsEquivalent(From, To);
7647}

/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
11// and dyn_cast_or_null<X>() templates.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_CASTING_H
16#define LLVM_SUPPORT_CASTING_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/type_traits.h"
20#include <cassert>
21#include <memory>
22#include <type_traits>
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// isa<x> Support Templates
28//===----------------------------------------------------------------------===//
29
30// Define a template that can be specialized by smart pointers to reflect the
31// fact that they are automatically dereferenced, and are not involved with the
32// template selection process... the default implementation is a noop.
33//
34template<typename From> struct simplify_type {
35 using SimpleType = From; // The real type this represents...
36
37 // An accessor to get the real value...
38 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
39};
40
41template<typename From> struct simplify_type<const From> {
42 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
43 using SimpleType =
44 typename add_const_past_pointer<NonConstSimpleType>::type;
45 using RetType =
46 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
47
48 static RetType getSimplifiedValue(const From& Val) {
49 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
50 }
51};
52
53// The core of the implementation of isa<X> is here; To and From should be
54// the names of classes. This template can be specialized to customize the
55// implementation of isa<> without rewriting it from scratch.
56template <typename To, typename From, typename Enabler = void>
57struct isa_impl {
58 static inline bool doit(const From &Val) {
59 return To::classof(&Val);
60 }
61};
62
63/// Always allow upcasts, and perform no dynamic check for them.
64template <typename To, typename From>
65struct isa_impl<
66 To, From, typename std::enable_if<std::is_base_of<To, From>::value>::type> {
67 static inline bool doit(const From &) { return true; }
68};
69
70template <typename To, typename From> struct isa_impl_cl {
71 static inline bool doit(const From &Val) {
72 return isa_impl<To, From>::doit(Val);
73 }
74};
75
76template <typename To, typename From> struct isa_impl_cl<To, const From> {
77 static inline bool doit(const From &Val) {
78 return isa_impl<To, From>::doit(Val);
79 }
80};
81
82template <typename To, typename From>
83struct isa_impl_cl<To, const std::unique_ptr<From>> {
84 static inline bool doit(const std::unique_ptr<From> &Val) {
85 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Support/Casting.h"
, 85, __extension__ __PRETTY_FUNCTION__))
;
86 return isa_impl_cl<To, From>::doit(*Val);
87 }
88};
89
90template <typename To, typename From> struct isa_impl_cl<To, From*> {
91 static inline bool doit(const From *Val) {
92 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Support/Casting.h"
, 92, __extension__ __PRETTY_FUNCTION__))
;
93 return isa_impl<To, From>::doit(*Val);
94 }
95};
96
97template <typename To, typename From> struct isa_impl_cl<To, From*const> {
98 static inline bool doit(const From *Val) {
99 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Support/Casting.h"
, 99, __extension__ __PRETTY_FUNCTION__))
;
100 return isa_impl<To, From>::doit(*Val);
101 }
102};
103
104template <typename To, typename From> struct isa_impl_cl<To, const From*> {
105 static inline bool doit(const From *Val) {
106 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Support/Casting.h"
, 106, __extension__ __PRETTY_FUNCTION__))
;
107 return isa_impl<To, From>::doit(*Val);
108 }
109};
110
111template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
112 static inline bool doit(const From *Val) {
113 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Support/Casting.h"
, 113, __extension__ __PRETTY_FUNCTION__))
;
114 return isa_impl<To, From>::doit(*Val);
115 }
116};
117
118template<typename To, typename From, typename SimpleFrom>
119struct isa_impl_wrap {
120 // When From != SimplifiedType, we can simplify the type some more by using
121 // the simplify_type template.
122 static bool doit(const From &Val) {
123 return isa_impl_wrap<To, SimpleFrom,
124 typename simplify_type<SimpleFrom>::SimpleType>::doit(
125 simplify_type<const From>::getSimplifiedValue(Val));
126 }
127};
128
129template<typename To, typename FromTy>
130struct isa_impl_wrap<To, FromTy, FromTy> {
131 // When From == SimpleType, we are as simple as we are going to get.
132 static bool doit(const FromTy &Val) {
133 return isa_impl_cl<To,FromTy>::doit(Val);
134 }
135};
136
137// isa<X> - Return true if the parameter to the template is an instance of the
138// template type argument. Used like this:
139//
140// if (isa<Type>(myVal)) { ... }
141//
142template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
143 return isa_impl_wrap<X, const Y,
144 typename simplify_type<const Y>::SimpleType>::doit(Val);
145}
146
147//===----------------------------------------------------------------------===//
148// cast<x> Support Templates
149//===----------------------------------------------------------------------===//
150
151template<class To, class From> struct cast_retty;
152
153// Calculate what type the 'cast' function should return, based on a requested
154// type of To and a source type of From.
155template<class To, class From> struct cast_retty_impl {
156 using ret_type = To &; // Normal case, return Ty&
157};
158template<class To, class From> struct cast_retty_impl<To, const From> {
159 using ret_type = const To &; // Normal case, return Ty&
160};
161
162template<class To, class From> struct cast_retty_impl<To, From*> {
163 using ret_type = To *; // Pointer arg case, return Ty*
164};
165
166template<class To, class From> struct cast_retty_impl<To, const From*> {
167 using ret_type = const To *; // Constant pointer arg case, return const Ty*
168};
169
170template<class To, class From> struct cast_retty_impl<To, const From*const> {
171 using ret_type = const To *; // Constant pointer arg case, return const Ty*
172};
173
174template <class To, class From>
175struct cast_retty_impl<To, std::unique_ptr<From>> {
176private:
177 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
178 using ResultType = typename std::remove_pointer<PointerType>::type;
179
180public:
181 using ret_type = std::unique_ptr<ResultType>;
182};
183
184template<class To, class From, class SimpleFrom>
185struct cast_retty_wrap {
186 // When the simplified type and the from type are not the same, use the type
187 // simplifier to reduce the type, then reuse cast_retty_impl to get the
188 // resultant type.
189 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
190};
191
192template<class To, class FromTy>
193struct cast_retty_wrap<To, FromTy, FromTy> {
194 // When the simplified type is equal to the from type, use it directly.
195 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
196};
197
198template<class To, class From>
199struct cast_retty {
200 using ret_type = typename cast_retty_wrap<
201 To, From, typename simplify_type<From>::SimpleType>::ret_type;
202};
203
204// Ensure the non-simple values are converted using the simplify_type template
205// that may be specialized by smart pointers...
206//
207template<class To, class From, class SimpleFrom> struct cast_convert_val {
208 // This is not a simple type, use the template to simplify it...
209 static typename cast_retty<To, From>::ret_type doit(From &Val) {
210 return cast_convert_val<To, SimpleFrom,
211 typename simplify_type<SimpleFrom>::SimpleType>::doit(
212 simplify_type<From>::getSimplifiedValue(Val));
213 }
214};
215
216template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
217 // This _is_ a simple type, just cast it.
218 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
219 typename cast_retty<To, FromTy>::ret_type Res2
220 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
221 return Res2;
222 }
223};
224
225template <class X> struct is_simple_type {
226 static const bool value =
227 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
228};
229
230// cast<X> - Return the argument parameter cast to the specified type. This
231// casting operator asserts that the type is correct, so it does not return null
232// on failure. It does not allow a null argument (use cast_or_null for that).
233// It is typically used like this:
234//
235// cast<Instruction>(myVal)->getParent()
236//
237template <class X, class Y>
238inline typename std::enable_if<!is_simple_type<Y>::value,
239 typename cast_retty<X, const Y>::ret_type>::type
240cast(const Y &Val) {
241 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Support/Casting.h"
, 241, __extension__ __PRETTY_FUNCTION__))
;
242 return cast_convert_val<
243 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
244}
245
246template <class X, class Y>
247inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
248 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Support/Casting.h"
, 248, __extension__ __PRETTY_FUNCTION__))
;
249 return cast_convert_val<X, Y,
250 typename simplify_type<Y>::SimpleType>::doit(Val);
251}
252
253template <class X, class Y>
254inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Support/Casting.h"
, 255, __extension__ __PRETTY_FUNCTION__))
;
10
Within the expansion of the macro 'assert':
a
Assuming the condition is true
256 return cast_convert_val<X, Y*,
11
Calling 'cast_convert_val::doit'
12
Returning from 'cast_convert_val::doit'
257 typename simplify_type<Y*>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
262cast(std::unique_ptr<Y> &&Val) {
263 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val.get()) &&
"cast<Ty>() argument of incompatible type!") ? void (0
) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Support/Casting.h"
, 263, __extension__ __PRETTY_FUNCTION__))
;
264 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
265 return ret_type(
266 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
267 Val.release()));
268}
269
270// cast_or_null<X> - Functionally identical to cast, except that a null value is
271// accepted.
272//
273template <class X, class Y>
274LLVM_NODISCARD[[clang::warn_unused_result]] inline
275 typename std::enable_if<!is_simple_type<Y>::value,
276 typename cast_retty<X, const Y>::ret_type>::type
277 cast_or_null(const Y &Val) {
278 if (!Val)
279 return nullptr;
280 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Support/Casting.h"
, 280, __extension__ __PRETTY_FUNCTION__))
;
281 return cast<X>(Val);
282}
283
284template <class X, class Y>
285LLVM_NODISCARD[[clang::warn_unused_result]] inline
286 typename std::enable_if<!is_simple_type<Y>::value,
287 typename cast_retty<X, Y>::ret_type>::type
288 cast_or_null(Y &Val) {
289 if (!Val)
290 return nullptr;
291 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Support/Casting.h"
, 291, __extension__ __PRETTY_FUNCTION__))
;
292 return cast<X>(Val);
293}
294
295template <class X, class Y>
296LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
297cast_or_null(Y *Val) {
298 if (!Val) return nullptr;
7
Taking false branch
299 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Support/Casting.h"
, 299, __extension__ __PRETTY_FUNCTION__))
;
8
Within the expansion of the macro 'assert':
300 return cast<X>(Val);
9
Calling 'cast<clang::Expr, clang::Stmt>'
13
Returning from 'cast<clang::Expr, clang::Stmt>'
301}
302
303template <class X, class Y>
304inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
305cast_or_null(std::unique_ptr<Y> &&Val) {
306 if (!Val)
307 return nullptr;
308 return cast<X>(std::move(Val));
309}
310
311// dyn_cast<X> - Return the argument parameter cast to the specified type. This
312// casting operator returns null if the argument is of the wrong type, so it can
313// be used to test for a type as well as cast if successful. This should be
314// used in the context of an if statement like this:
315//
316// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
317//
318
319template <class X, class Y>
320LLVM_NODISCARD[[clang::warn_unused_result]] inline
321 typename std::enable_if<!is_simple_type<Y>::value,
322 typename cast_retty<X, const Y>::ret_type>::type
323 dyn_cast(const Y &Val) {
324 return isa<X>(Val) ? cast<X>(Val) : nullptr;
325}
326
327template <class X, class Y>
328LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
329 return isa<X>(Val) ? cast<X>(Val) : nullptr;
330}
331
332template <class X, class Y>
333LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
334 return isa<X>(Val) ? cast<X>(Val) : nullptr;
335}
336
337// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
338// value is accepted.
339//
340template <class X, class Y>
341LLVM_NODISCARD[[clang::warn_unused_result]] inline
342 typename std::enable_if<!is_simple_type<Y>::value,
343 typename cast_retty<X, const Y>::ret_type>::type
344 dyn_cast_or_null(const Y &Val) {
345 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
346}
347
348template <class X, class Y>
349LLVM_NODISCARD[[clang::warn_unused_result]] inline
350 typename std::enable_if<!is_simple_type<Y>::value,
351 typename cast_retty<X, Y>::ret_type>::type
352 dyn_cast_or_null(Y &Val) {
353 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
354}
355
356template <class X, class Y>
357LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
358dyn_cast_or_null(Y *Val) {
359 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
360}
361
362// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
363// taking ownership of the input pointer iff isa<X>(Val) is true. If the
364// cast is successful, From refers to nullptr on exit and the casted value
365// is returned. If the cast is unsuccessful, the function returns nullptr
366// and From is unchanged.
367template <class X, class Y>
368LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
369 -> decltype(cast<X>(Val)) {
370 if (!isa<X>(Val))
371 return nullptr;
372 return cast<X>(std::move(Val));
373}
374
375template <class X, class Y>
376LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val)
377 -> decltype(cast<X>(Val)) {
378 return unique_dyn_cast<X, Y>(Val);
379}
380
381// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
382// a null value is accepted.
383template <class X, class Y>
384LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
385 -> decltype(cast<X>(Val)) {
386 if (!Val)
387 return nullptr;
388 return unique_dyn_cast<X, Y>(Val);
389}
390
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val)
393 -> decltype(cast<X>(Val)) {
394 return unique_dyn_cast_or_null<X, Y>(Val);
395}
396
397} // end namespace llvm
398
399#endif // LLVM_SUPPORT_CASTING_H

/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h

1//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Expr interface and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_EXPR_H
15#define LLVM_CLANG_AST_EXPR_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/ASTVector.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclAccessPair.h"
21#include "clang/AST/OperationKinds.h"
22#include "clang/AST/Stmt.h"
23#include "clang/AST/TemplateBase.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/CharInfo.h"
26#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/SyncScope.h"
28#include "clang/Basic/TypeTraits.h"
29#include "llvm/ADT/APFloat.h"
30#include "llvm/ADT/APSInt.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/Support/AtomicOrdering.h"
34#include "llvm/Support/Compiler.h"
35
36namespace clang {
37 class APValue;
38 class ASTContext;
39 class BlockDecl;
40 class CXXBaseSpecifier;
41 class CXXMemberCallExpr;
42 class CXXOperatorCallExpr;
43 class CastExpr;
44 class Decl;
45 class IdentifierInfo;
46 class MaterializeTemporaryExpr;
47 class NamedDecl;
48 class ObjCPropertyRefExpr;
49 class OpaqueValueExpr;
50 class ParmVarDecl;
51 class StringLiteral;
52 class TargetInfo;
53 class ValueDecl;
54
55/// A simple array of base specifiers.
56typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
57
58/// An adjustment to be made to the temporary created when emitting a
59/// reference binding, which accesses a particular subobject of that temporary.
60struct SubobjectAdjustment {
61 enum {
62 DerivedToBaseAdjustment,
63 FieldAdjustment,
64 MemberPointerAdjustment
65 } Kind;
66
67 struct DTB {
68 const CastExpr *BasePath;
69 const CXXRecordDecl *DerivedClass;
70 };
71
72 struct P {
73 const MemberPointerType *MPT;
74 Expr *RHS;
75 };
76
77 union {
78 struct DTB DerivedToBase;
79 FieldDecl *Field;
80 struct P Ptr;
81 };
82
83 SubobjectAdjustment(const CastExpr *BasePath,
84 const CXXRecordDecl *DerivedClass)
85 : Kind(DerivedToBaseAdjustment) {
86 DerivedToBase.BasePath = BasePath;
87 DerivedToBase.DerivedClass = DerivedClass;
88 }
89
90 SubobjectAdjustment(FieldDecl *Field)
91 : Kind(FieldAdjustment) {
92 this->Field = Field;
93 }
94
95 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
96 : Kind(MemberPointerAdjustment) {
97 this->Ptr.MPT = MPT;
98 this->Ptr.RHS = RHS;
99 }
100};
101
102/// Expr - This represents one expression. Note that Expr's are subclasses of
103/// Stmt. This allows an expression to be transparently used any place a Stmt
104/// is required.
105///
106class Expr : public Stmt {
107 QualType TR;
108
109protected:
110 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
111 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
112 : Stmt(SC)
113 {
114 ExprBits.TypeDependent = TD;
115 ExprBits.ValueDependent = VD;
116 ExprBits.InstantiationDependent = ID;
117 ExprBits.ValueKind = VK;
118 ExprBits.ObjectKind = OK;
119 assert(ExprBits.ObjectKind == OK && "truncated kind")(static_cast <bool> (ExprBits.ObjectKind == OK &&
"truncated kind") ? void (0) : __assert_fail ("ExprBits.ObjectKind == OK && \"truncated kind\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 119, __extension__ __PRETTY_FUNCTION__))
;
120 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
121 setType(T);
122 }
123
124 /// Construct an empty expression.
125 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
126
127public:
128 QualType getType() const { return TR; }
129 void setType(QualType t) {
130 // In C++, the type of an expression is always adjusted so that it
131 // will not have reference type (C++ [expr]p6). Use
132 // QualType::getNonReferenceType() to retrieve the non-reference
133 // type. Additionally, inspect Expr::isLvalue to determine whether
134 // an expression that is adjusted in this manner should be
135 // considered an lvalue.
136 assert((t.isNull() || !t->isReferenceType()) &&(static_cast <bool> ((t.isNull() || !t->isReferenceType
()) && "Expressions can't have reference type") ? void
(0) : __assert_fail ("(t.isNull() || !t->isReferenceType()) && \"Expressions can't have reference type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 137, __extension__ __PRETTY_FUNCTION__))
137 "Expressions can't have reference type")(static_cast <bool> ((t.isNull() || !t->isReferenceType
()) && "Expressions can't have reference type") ? void
(0) : __assert_fail ("(t.isNull() || !t->isReferenceType()) && \"Expressions can't have reference type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 137, __extension__ __PRETTY_FUNCTION__))
;
138
139 TR = t;
140 }
141
142 /// isValueDependent - Determines whether this expression is
143 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
144 /// array bound of "Chars" in the following example is
145 /// value-dependent.
146 /// @code
147 /// template<int Size, char (&Chars)[Size]> struct meta_string;
148 /// @endcode
149 bool isValueDependent() const { return ExprBits.ValueDependent; }
150
151 /// Set whether this expression is value-dependent or not.
152 void setValueDependent(bool VD) {
153 ExprBits.ValueDependent = VD;
154 }
155
156 /// isTypeDependent - Determines whether this expression is
157 /// type-dependent (C++ [temp.dep.expr]), which means that its type
158 /// could change from one template instantiation to the next. For
159 /// example, the expressions "x" and "x + y" are type-dependent in
160 /// the following code, but "y" is not type-dependent:
161 /// @code
162 /// template<typename T>
163 /// void add(T x, int y) {
164 /// x + y;
165 /// }
166 /// @endcode
167 bool isTypeDependent() const { return ExprBits.TypeDependent; }
168
169 /// Set whether this expression is type-dependent or not.
170 void setTypeDependent(bool TD) {
171 ExprBits.TypeDependent = TD;
172 }
173
174 /// Whether this expression is instantiation-dependent, meaning that
175 /// it depends in some way on a template parameter, even if neither its type
176 /// nor (constant) value can change due to the template instantiation.
177 ///
178 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
179 /// instantiation-dependent (since it involves a template parameter \c T), but
180 /// is neither type- nor value-dependent, since the type of the inner
181 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
182 /// \c sizeof is known.
183 ///
184 /// \code
185 /// template<typename T>
186 /// void f(T x, T y) {
187 /// sizeof(sizeof(T() + T());
188 /// }
189 /// \endcode
190 ///
191 bool isInstantiationDependent() const {
192 return ExprBits.InstantiationDependent;
193 }
194
195 /// Set whether this expression is instantiation-dependent or not.
196 void setInstantiationDependent(bool ID) {
197 ExprBits.InstantiationDependent = ID;
198 }
199
200 /// Whether this expression contains an unexpanded parameter
201 /// pack (for C++11 variadic templates).
202 ///
203 /// Given the following function template:
204 ///
205 /// \code
206 /// template<typename F, typename ...Types>
207 /// void forward(const F &f, Types &&...args) {
208 /// f(static_cast<Types&&>(args)...);
209 /// }
210 /// \endcode
211 ///
212 /// The expressions \c args and \c static_cast<Types&&>(args) both
213 /// contain parameter packs.
214 bool containsUnexpandedParameterPack() const {
215 return ExprBits.ContainsUnexpandedParameterPack;
216 }
217
218 /// Set the bit that describes whether this expression
219 /// contains an unexpanded parameter pack.
220 void setContainsUnexpandedParameterPack(bool PP = true) {
221 ExprBits.ContainsUnexpandedParameterPack = PP;
222 }
223
224 /// getExprLoc - Return the preferred location for the arrow when diagnosing
225 /// a problem with a generic expression.
226 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__));
227
228 /// isUnusedResultAWarning - Return true if this immediate expression should
229 /// be warned about if the result is unused. If so, fill in expr, location,
230 /// and ranges with expr to warn on and source locations/ranges appropriate
231 /// for a warning.
232 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
233 SourceRange &R1, SourceRange &R2,
234 ASTContext &Ctx) const;
235
236 /// isLValue - True if this expression is an "l-value" according to
237 /// the rules of the current language. C and C++ give somewhat
238 /// different rules for this concept, but in general, the result of
239 /// an l-value expression identifies a specific object whereas the
240 /// result of an r-value expression is a value detached from any
241 /// specific storage.
242 ///
243 /// C++11 divides the concept of "r-value" into pure r-values
244 /// ("pr-values") and so-called expiring values ("x-values"), which
245 /// identify specific objects that can be safely cannibalized for
246 /// their resources. This is an unfortunate abuse of terminology on
247 /// the part of the C++ committee. In Clang, when we say "r-value",
248 /// we generally mean a pr-value.
249 bool isLValue() const { return getValueKind() == VK_LValue; }
250 bool isRValue() const { return getValueKind() == VK_RValue; }
251 bool isXValue() const { return getValueKind() == VK_XValue; }
252 bool isGLValue() const { return getValueKind() != VK_RValue; }
253
254 enum LValueClassification {
255 LV_Valid,
256 LV_NotObjectType,
257 LV_IncompleteVoidType,
258 LV_DuplicateVectorComponents,
259 LV_InvalidExpression,
260 LV_InvalidMessageExpression,
261 LV_MemberFunction,
262 LV_SubObjCPropertySetting,
263 LV_ClassTemporary,
264 LV_ArrayTemporary
265 };
266 /// Reasons why an expression might not be an l-value.
267 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
268
269 enum isModifiableLvalueResult {
270 MLV_Valid,
271 MLV_NotObjectType,
272 MLV_IncompleteVoidType,
273 MLV_DuplicateVectorComponents,
274 MLV_InvalidExpression,
275 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
276 MLV_IncompleteType,
277 MLV_ConstQualified,
278 MLV_ConstQualifiedField,
279 MLV_ConstAddrSpace,
280 MLV_ArrayType,
281 MLV_NoSetterProperty,
282 MLV_MemberFunction,
283 MLV_SubObjCPropertySetting,
284 MLV_InvalidMessageExpression,
285 MLV_ClassTemporary,
286 MLV_ArrayTemporary
287 };
288 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
289 /// does not have an incomplete type, does not have a const-qualified type,
290 /// and if it is a structure or union, does not have any member (including,
291 /// recursively, any member or element of all contained aggregates or unions)
292 /// with a const-qualified type.
293 ///
294 /// \param Loc [in,out] - A source location which *may* be filled
295 /// in with the location of the expression making this a
296 /// non-modifiable lvalue, if specified.
297 isModifiableLvalueResult
298 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
299
300 /// The return type of classify(). Represents the C++11 expression
301 /// taxonomy.
302 class Classification {
303 public:
304 /// The various classification results. Most of these mean prvalue.
305 enum Kinds {
306 CL_LValue,
307 CL_XValue,
308 CL_Function, // Functions cannot be lvalues in C.
309 CL_Void, // Void cannot be an lvalue in C.
310 CL_AddressableVoid, // Void expression whose address can be taken in C.
311 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
312 CL_MemberFunction, // An expression referring to a member function
313 CL_SubObjCPropertySetting,
314 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
315 CL_ArrayTemporary, // A temporary of array type.
316 CL_ObjCMessageRValue, // ObjC message is an rvalue
317 CL_PRValue // A prvalue for any other reason, of any other type
318 };
319 /// The results of modification testing.
320 enum ModifiableType {
321 CM_Untested, // testModifiable was false.
322 CM_Modifiable,
323 CM_RValue, // Not modifiable because it's an rvalue
324 CM_Function, // Not modifiable because it's a function; C++ only
325 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
326 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
327 CM_ConstQualified,
328 CM_ConstQualifiedField,
329 CM_ConstAddrSpace,
330 CM_ArrayType,
331 CM_IncompleteType
332 };
333
334 private:
335 friend class Expr;
336
337 unsigned short Kind;
338 unsigned short Modifiable;
339
340 explicit Classification(Kinds k, ModifiableType m)
341 : Kind(k), Modifiable(m)
342 {}
343
344 public:
345 Classification() {}
346
347 Kinds getKind() const { return static_cast<Kinds>(Kind); }
348 ModifiableType getModifiable() const {
349 assert(Modifiable != CM_Untested && "Did not test for modifiability.")(static_cast <bool> (Modifiable != CM_Untested &&
"Did not test for modifiability.") ? void (0) : __assert_fail
("Modifiable != CM_Untested && \"Did not test for modifiability.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 349, __extension__ __PRETTY_FUNCTION__))
;
350 return static_cast<ModifiableType>(Modifiable);
351 }
352 bool isLValue() const { return Kind == CL_LValue; }
353 bool isXValue() const { return Kind == CL_XValue; }
354 bool isGLValue() const { return Kind <= CL_XValue; }
355 bool isPRValue() const { return Kind >= CL_Function; }
356 bool isRValue() const { return Kind >= CL_XValue; }
357 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
358
359 /// Create a simple, modifiably lvalue
360 static Classification makeSimpleLValue() {
361 return Classification(CL_LValue, CM_Modifiable);
362 }
363
364 };
365 /// Classify - Classify this expression according to the C++11
366 /// expression taxonomy.
367 ///
368 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
369 /// old lvalue vs rvalue. This function determines the type of expression this
370 /// is. There are three expression types:
371 /// - lvalues are classical lvalues as in C++03.
372 /// - prvalues are equivalent to rvalues in C++03.
373 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
374 /// function returning an rvalue reference.
375 /// lvalues and xvalues are collectively referred to as glvalues, while
376 /// prvalues and xvalues together form rvalues.
377 Classification Classify(ASTContext &Ctx) const {
378 return ClassifyImpl(Ctx, nullptr);
379 }
380
381 /// ClassifyModifiable - Classify this expression according to the
382 /// C++11 expression taxonomy, and see if it is valid on the left side
383 /// of an assignment.
384 ///
385 /// This function extends classify in that it also tests whether the
386 /// expression is modifiable (C99 6.3.2.1p1).
387 /// \param Loc A source location that might be filled with a relevant location
388 /// if the expression is not modifiable.
389 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
390 return ClassifyImpl(Ctx, &Loc);
391 }
392
393 /// getValueKindForType - Given a formal return or parameter type,
394 /// give its value kind.
395 static ExprValueKind getValueKindForType(QualType T) {
396 if (const ReferenceType *RT = T->getAs<ReferenceType>())
397 return (isa<LValueReferenceType>(RT)
398 ? VK_LValue
399 : (RT->getPointeeType()->isFunctionType()
400 ? VK_LValue : VK_XValue));
401 return VK_RValue;
402 }
403
404 /// getValueKind - The value kind that this expression produces.
405 ExprValueKind getValueKind() const {
406 return static_cast<ExprValueKind>(ExprBits.ValueKind);
407 }
408
409 /// getObjectKind - The object kind that this expression produces.
410 /// Object kinds are meaningful only for expressions that yield an
411 /// l-value or x-value.
412 ExprObjectKind getObjectKind() const {
413 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
414 }
415
416 bool isOrdinaryOrBitFieldObject() const {
417 ExprObjectKind OK = getObjectKind();
418 return (OK == OK_Ordinary || OK == OK_BitField);
419 }
420
421 /// setValueKind - Set the value kind produced by this expression.
422 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
423
424 /// setObjectKind - Set the object kind produced by this expression.
425 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
426
427private:
428 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
429
430public:
431
432 /// Returns true if this expression is a gl-value that
433 /// potentially refers to a bit-field.
434 ///
435 /// In C++, whether a gl-value refers to a bitfield is essentially
436 /// an aspect of the value-kind type system.
437 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
438
439 /// If this expression refers to a bit-field, retrieve the
440 /// declaration of that bit-field.
441 ///
442 /// Note that this returns a non-null pointer in subtly different
443 /// places than refersToBitField returns true. In particular, this can
444 /// return a non-null pointer even for r-values loaded from
445 /// bit-fields, but it will return null for a conditional bit-field.
446 FieldDecl *getSourceBitField();
447
448 const FieldDecl *getSourceBitField() const {
449 return const_cast<Expr*>(this)->getSourceBitField();
450 }
451
452 Decl *getReferencedDeclOfCallee();
453 const Decl *getReferencedDeclOfCallee() const {
454 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
455 }
456
457 /// If this expression is an l-value for an Objective C
458 /// property, find the underlying property reference expression.
459 const ObjCPropertyRefExpr *getObjCProperty() const;
460
461 /// Check if this expression is the ObjC 'self' implicit parameter.
462 bool isObjCSelfExpr() const;
463
464 /// Returns whether this expression refers to a vector element.
465 bool refersToVectorElement() const;
466
467 /// Returns whether this expression refers to a global register
468 /// variable.
469 bool refersToGlobalRegisterVar() const;
470
471 /// Returns whether this expression has a placeholder type.
472 bool hasPlaceholderType() const {
473 return getType()->isPlaceholderType();
474 }
475
476 /// Returns whether this expression has a specific placeholder type.
477 bool hasPlaceholderType(BuiltinType::Kind K) const {
478 assert(BuiltinType::isPlaceholderTypeKind(K))(static_cast <bool> (BuiltinType::isPlaceholderTypeKind
(K)) ? void (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind(K)"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 478, __extension__ __PRETTY_FUNCTION__))
;
479 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
480 return BT->getKind() == K;
481 return false;
482 }
483
484 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
485 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
486 /// but also int expressions which are produced by things like comparisons in
487 /// C.
488 bool isKnownToHaveBooleanValue() const;
489
490 /// isIntegerConstantExpr - Return true if this expression is a valid integer
491 /// constant expression, and, if so, return its value in Result. If not a
492 /// valid i-c-e, return false and fill in Loc (if specified) with the location
493 /// of the invalid expression.
494 ///
495 /// Note: This does not perform the implicit conversions required by C++11
496 /// [expr.const]p5.
497 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
498 SourceLocation *Loc = nullptr,
499 bool isEvaluated = true) const;
500 bool isIntegerConstantExpr(const ASTContext &Ctx,
501 SourceLocation *Loc = nullptr) const;
502
503 /// isCXX98IntegralConstantExpr - Return true if this expression is an
504 /// integral constant expression in C++98. Can only be used in C++.
505 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
506
507 /// isCXX11ConstantExpr - Return true if this expression is a constant
508 /// expression in C++11. Can only be used in C++.
509 ///
510 /// Note: This does not perform the implicit conversions required by C++11
511 /// [expr.const]p5.
512 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
513 SourceLocation *Loc = nullptr) const;
514
515 /// isPotentialConstantExpr - Return true if this function's definition
516 /// might be usable in a constant expression in C++11, if it were marked
517 /// constexpr. Return false if the function can never produce a constant
518 /// expression, along with diagnostics describing why not.
519 static bool isPotentialConstantExpr(const FunctionDecl *FD,
520 SmallVectorImpl<
521 PartialDiagnosticAt> &Diags);
522
523 /// isPotentialConstantExprUnevaluted - Return true if this expression might
524 /// be usable in a constant expression in C++11 in an unevaluated context, if
525 /// it were in function FD marked constexpr. Return false if the function can
526 /// never produce a constant expression, along with diagnostics describing
527 /// why not.
528 static bool isPotentialConstantExprUnevaluated(Expr *E,
529 const FunctionDecl *FD,
530 SmallVectorImpl<
531 PartialDiagnosticAt> &Diags);
532
533 /// isConstantInitializer - Returns true if this expression can be emitted to
534 /// IR as a constant, and thus can be used as a constant initializer in C.
535 /// If this expression is not constant and Culprit is non-null,
536 /// it is used to store the address of first non constant expr.
537 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
538 const Expr **Culprit = nullptr) const;
539
540 /// EvalStatus is a struct with detailed info about an evaluation in progress.
541 struct EvalStatus {
542 /// Whether the evaluated expression has side effects.
543 /// For example, (f() && 0) can be folded, but it still has side effects.
544 bool HasSideEffects;
545
546 /// Whether the evaluation hit undefined behavior.
547 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
548 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
549 bool HasUndefinedBehavior;
550
551 /// Diag - If this is non-null, it will be filled in with a stack of notes
552 /// indicating why evaluation failed (or why it failed to produce a constant
553 /// expression).
554 /// If the expression is unfoldable, the notes will indicate why it's not
555 /// foldable. If the expression is foldable, but not a constant expression,
556 /// the notes will describes why it isn't a constant expression. If the
557 /// expression *is* a constant expression, no notes will be produced.
558 SmallVectorImpl<PartialDiagnosticAt> *Diag;
559
560 EvalStatus()
561 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
562
563 // hasSideEffects - Return true if the evaluated expression has
564 // side effects.
565 bool hasSideEffects() const {
566 return HasSideEffects;
567 }
568 };
569
570 /// EvalResult is a struct with detailed info about an evaluated expression.
571 struct EvalResult : EvalStatus {
572 /// Val - This is the value the expression can be folded to.
573 APValue Val;
574
575 // isGlobalLValue - Return true if the evaluated lvalue expression
576 // is global.
577 bool isGlobalLValue() const;
578 };
579
580 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
581 /// an rvalue using any crazy technique (that has nothing to do with language
582 /// standards) that we want to, even if the expression has side-effects. If
583 /// this function returns true, it returns the folded constant in Result. If
584 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
585 /// applied.
586 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
587
588 /// EvaluateAsBooleanCondition - Return true if this is a constant
589 /// which we can fold and convert to a boolean condition using
590 /// any crazy technique that we want to, even if the expression has
591 /// side-effects.
592 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
593
594 enum SideEffectsKind {
595 SE_NoSideEffects, ///< Strictly evaluate the expression.
596 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
597 ///< arbitrary unmodeled side effects.
598 SE_AllowSideEffects ///< Allow any unmodeled side effect.
599 };
600
601 /// EvaluateAsInt - Return true if this is a constant which we can fold and
602 /// convert to an integer, using any crazy technique that we want to.
603 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
604 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
605
606 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
607 /// convert to a floating point value, using any crazy technique that we
608 /// want to.
609 bool
610 EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
611 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
612
613 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
614 /// constant folded without side-effects, but discard the result.
615 bool isEvaluatable(const ASTContext &Ctx,
616 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
617
618 /// HasSideEffects - This routine returns true for all those expressions
619 /// which have any effect other than producing a value. Example is a function
620 /// call, volatile variable read, or throwing an exception. If
621 /// IncludePossibleEffects is false, this call treats certain expressions with
622 /// potential side effects (such as function call-like expressions,
623 /// instantiation-dependent expressions, or invocations from a macro) as not
624 /// having side effects.
625 bool HasSideEffects(const ASTContext &Ctx,
626 bool IncludePossibleEffects = true) const;
627
628 /// Determine whether this expression involves a call to any function
629 /// that is not trivial.
630 bool hasNonTrivialCall(const ASTContext &Ctx) const;
631
632 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
633 /// integer. This must be called on an expression that constant folds to an
634 /// integer.
635 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
636 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
637
638 void EvaluateForOverflow(const ASTContext &Ctx) const;
639
640 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
641 /// lvalue with link time known address, with no side-effects.
642 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
643
644 /// EvaluateAsInitializer - Evaluate an expression as if it were the
645 /// initializer of the given declaration. Returns true if the initializer
646 /// can be folded to a constant, and produces any relevant notes. In C++11,
647 /// notes will be produced if the expression is not a constant expression.
648 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
649 const VarDecl *VD,
650 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
651
652 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
653 /// of a call to the given function with the given arguments, inside an
654 /// unevaluated context. Returns true if the expression could be folded to a
655 /// constant.
656 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
657 const FunctionDecl *Callee,
658 ArrayRef<const Expr*> Args,
659 const Expr *This = nullptr) const;
660
661 /// Indicates how the constant expression will be used.
662 enum ConstExprUsage { EvaluateForCodeGen, EvaluateForMangling };
663
664 /// Evaluate an expression that is required to be a constant expression.
665 bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
666 const ASTContext &Ctx) const;
667
668 /// If the current Expr is a pointer, this will try to statically
669 /// determine the number of bytes available where the pointer is pointing.
670 /// Returns true if all of the above holds and we were able to figure out the
671 /// size, false otherwise.
672 ///
673 /// \param Type - How to evaluate the size of the Expr, as defined by the
674 /// "type" parameter of __builtin_object_size
675 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
676 unsigned Type) const;
677
678 /// Enumeration used to describe the kind of Null pointer constant
679 /// returned from \c isNullPointerConstant().
680 enum NullPointerConstantKind {
681 /// Expression is not a Null pointer constant.
682 NPCK_NotNull = 0,
683
684 /// Expression is a Null pointer constant built from a zero integer
685 /// expression that is not a simple, possibly parenthesized, zero literal.
686 /// C++ Core Issue 903 will classify these expressions as "not pointers"
687 /// once it is adopted.
688 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
689 NPCK_ZeroExpression,
690
691 /// Expression is a Null pointer constant built from a literal zero.
692 NPCK_ZeroLiteral,
693
694 /// Expression is a C++11 nullptr.
695 NPCK_CXX11_nullptr,
696
697 /// Expression is a GNU-style __null constant.
698 NPCK_GNUNull
699 };
700
701 /// Enumeration used to describe how \c isNullPointerConstant()
702 /// should cope with value-dependent expressions.
703 enum NullPointerConstantValueDependence {
704 /// Specifies that the expression should never be value-dependent.
705 NPC_NeverValueDependent = 0,
706
707 /// Specifies that a value-dependent expression of integral or
708 /// dependent type should be considered a null pointer constant.
709 NPC_ValueDependentIsNull,
710
711 /// Specifies that a value-dependent expression should be considered
712 /// to never be a null pointer constant.
713 NPC_ValueDependentIsNotNull
714 };
715
716 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
717 /// a Null pointer constant. The return value can further distinguish the
718 /// kind of NULL pointer constant that was detected.
719 NullPointerConstantKind isNullPointerConstant(
720 ASTContext &Ctx,
721 NullPointerConstantValueDependence NPC) const;
722
723 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
724 /// write barrier.
725 bool isOBJCGCCandidate(ASTContext &Ctx) const;
726
727 /// Returns true if this expression is a bound member function.
728 bool isBoundMemberFunction(ASTContext &Ctx) const;
729
730 /// Given an expression of bound-member type, find the type
731 /// of the member. Returns null if this is an *overloaded* bound
732 /// member expression.
733 static QualType findBoundMemberType(const Expr *expr);
734
735 /// IgnoreImpCasts - Skip past any implicit casts which might
736 /// surround this expression. Only skips ImplicitCastExprs.
737 Expr *IgnoreImpCasts() LLVM_READONLY__attribute__((__pure__));
738
739 /// IgnoreImplicit - Skip past any implicit AST nodes which might
740 /// surround this expression.
741 Expr *IgnoreImplicit() LLVM_READONLY__attribute__((__pure__)) {
742 return cast<Expr>(Stmt::IgnoreImplicit());
743 }
744
745 const Expr *IgnoreImplicit() const LLVM_READONLY__attribute__((__pure__)) {
746 return const_cast<Expr*>(this)->IgnoreImplicit();
747 }
748
749 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
750 /// its subexpression. If that subexpression is also a ParenExpr,
751 /// then this method recursively returns its subexpression, and so forth.
752 /// Otherwise, the method returns the current Expr.
753 Expr *IgnoreParens() LLVM_READONLY__attribute__((__pure__));
754
755 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
756 /// or CastExprs, returning their operand.
757 Expr *IgnoreParenCasts() LLVM_READONLY__attribute__((__pure__));
758
759 /// Ignore casts. Strip off any CastExprs, returning their operand.
760 Expr *IgnoreCasts() LLVM_READONLY__attribute__((__pure__));
761
762 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
763 /// any ParenExpr or ImplicitCastExprs, returning their operand.
764 Expr *IgnoreParenImpCasts() LLVM_READONLY__attribute__((__pure__));
765
766 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
767 /// call to a conversion operator, return the argument.
768 Expr *IgnoreConversionOperator() LLVM_READONLY__attribute__((__pure__));
769
770 const Expr *IgnoreConversionOperator() const LLVM_READONLY__attribute__((__pure__)) {
771 return const_cast<Expr*>(this)->IgnoreConversionOperator();
772 }
773
774 const Expr *IgnoreParenImpCasts() const LLVM_READONLY__attribute__((__pure__)) {
775 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
776 }
777
778 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
779 /// CastExprs that represent lvalue casts, returning their operand.
780 Expr *IgnoreParenLValueCasts() LLVM_READONLY__attribute__((__pure__));
781
782 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY__attribute__((__pure__)) {
783 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
784 }
785
786 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
787 /// value (including ptr->int casts of the same size). Strip off any
788 /// ParenExpr or CastExprs, returning their operand.
789 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY__attribute__((__pure__));
790
791 /// Ignore parentheses and derived-to-base casts.
792 Expr *ignoreParenBaseCasts() LLVM_READONLY__attribute__((__pure__));
793
794 const Expr *ignoreParenBaseCasts() const LLVM_READONLY__attribute__((__pure__)) {
795 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
796 }
797
798 /// Determine whether this expression is a default function argument.
799 ///
800 /// Default arguments are implicitly generated in the abstract syntax tree
801 /// by semantic analysis for function calls, object constructions, etc. in
802 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
803 /// this routine also looks through any implicit casts to determine whether
804 /// the expression is a default argument.
805 bool isDefaultArgument() const;
806
807 /// Determine whether the result of this expression is a
808 /// temporary object of the given class type.
809 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
810
811 /// Whether this expression is an implicit reference to 'this' in C++.
812 bool isImplicitCXXThis() const;
813
814 const Expr *IgnoreImpCasts() const LLVM_READONLY__attribute__((__pure__)) {
815 return const_cast<Expr*>(this)->IgnoreImpCasts();
816 }
817 const Expr *IgnoreParens() const LLVM_READONLY__attribute__((__pure__)) {
818 return const_cast<Expr*>(this)->IgnoreParens();
819 }
820 const Expr *IgnoreParenCasts() const LLVM_READONLY__attribute__((__pure__)) {
821 return const_cast<Expr*>(this)->IgnoreParenCasts();
822 }
823 /// Strip off casts, but keep parentheses.
824 const Expr *IgnoreCasts() const LLVM_READONLY__attribute__((__pure__)) {
825 return const_cast<Expr*>(this)->IgnoreCasts();
826 }
827
828 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY__attribute__((__pure__)) {
829 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
830 }
831
832 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
833
834 /// For an expression of class type or pointer to class type,
835 /// return the most derived class decl the expression is known to refer to.
836 ///
837 /// If this expression is a cast, this method looks through it to find the
838 /// most derived decl that can be inferred from the expression.
839 /// This is valid because derived-to-base conversions have undefined
840 /// behavior if the object isn't dynamically of the derived type.
841 const CXXRecordDecl *getBestDynamicClassType() const;
842
843 /// Get the inner expression that determines the best dynamic class.
844 /// If this is a prvalue, we guarantee that it is of the most-derived type
845 /// for the object itself.
846 const Expr *getBestDynamicClassTypeExpr() const;
847
848 /// Walk outwards from an expression we want to bind a reference to and
849 /// find the expression whose lifetime needs to be extended. Record
850 /// the LHSs of comma expressions and adjustments needed along the path.
851 const Expr *skipRValueSubobjectAdjustments(
852 SmallVectorImpl<const Expr *> &CommaLHS,
853 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
854 const Expr *skipRValueSubobjectAdjustments() const {
855 SmallVector<const Expr *, 8> CommaLHSs;
856 SmallVector<SubobjectAdjustment, 8> Adjustments;
857 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
858 }
859
860 static bool classof(const Stmt *T) {
861 return T->getStmtClass() >= firstExprConstant &&
862 T->getStmtClass() <= lastExprConstant;
863 }
864};
865
866//===----------------------------------------------------------------------===//
867// Primary Expressions.
868//===----------------------------------------------------------------------===//
869
870/// OpaqueValueExpr - An expression referring to an opaque object of a
871/// fixed type and value class. These don't correspond to concrete
872/// syntax; instead they're used to express operations (usually copy
873/// operations) on values whose source is generally obvious from
874/// context.
875class OpaqueValueExpr : public Expr {
876 friend class ASTStmtReader;
877 Expr *SourceExpr;
878 SourceLocation Loc;
879
880public:
881 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
882 ExprObjectKind OK = OK_Ordinary,
883 Expr *SourceExpr = nullptr)
884 : Expr(OpaqueValueExprClass, T, VK, OK,
885 T->isDependentType() ||
886 (SourceExpr && SourceExpr->isTypeDependent()),
887 T->isDependentType() ||
888 (SourceExpr && SourceExpr->isValueDependent()),
889 T->isInstantiationDependentType() ||
890 (SourceExpr && SourceExpr->isInstantiationDependent()),
891 false),
892 SourceExpr(SourceExpr), Loc(Loc) {
893 setIsUnique(false);
894 }
895
896 /// Given an expression which invokes a copy constructor --- i.e. a
897 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
898 /// find the OpaqueValueExpr that's the source of the construction.
899 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
900
901 explicit OpaqueValueExpr(EmptyShell Empty)
902 : Expr(OpaqueValueExprClass, Empty) { }
903
904 /// Retrieve the location of this expression.
905 SourceLocation getLocation() const { return Loc; }
906
907 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
908 return SourceExpr ? SourceExpr->getLocStart() : Loc;
909 }
910 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
911 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
912 }
913 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
914 if (SourceExpr) return SourceExpr->getExprLoc();
915 return Loc;
916 }
917
918 child_range children() {
919 return child_range(child_iterator(), child_iterator());
920 }
921
922 const_child_range children() const {
923 return const_child_range(const_child_iterator(), const_child_iterator());
924 }
925
926 /// The source expression of an opaque value expression is the
927 /// expression which originally generated the value. This is
928 /// provided as a convenience for analyses that don't wish to
929 /// precisely model the execution behavior of the program.
930 ///
931 /// The source expression is typically set when building the
932 /// expression which binds the opaque value expression in the first
933 /// place.
934 Expr *getSourceExpr() const { return SourceExpr; }
935
936 void setIsUnique(bool V) {
937 assert((!V || SourceExpr) &&(static_cast <bool> ((!V || SourceExpr) && "unique OVEs are expected to have source expressions"
) ? void (0) : __assert_fail ("(!V || SourceExpr) && \"unique OVEs are expected to have source expressions\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 938, __extension__ __PRETTY_FUNCTION__))
938 "unique OVEs are expected to have source expressions")(static_cast <bool> ((!V || SourceExpr) && "unique OVEs are expected to have source expressions"
) ? void (0) : __assert_fail ("(!V || SourceExpr) && \"unique OVEs are expected to have source expressions\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 938, __extension__ __PRETTY_FUNCTION__))
;
939 OpaqueValueExprBits.IsUnique = V;
940 }
941
942 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
943
944 static bool classof(const Stmt *T) {
945 return T->getStmtClass() == OpaqueValueExprClass;
946 }
947};
948
949/// A reference to a declared variable, function, enum, etc.
950/// [C99 6.5.1p2]
951///
952/// This encodes all the information about how a declaration is referenced
953/// within an expression.
954///
955/// There are several optional constructs attached to DeclRefExprs only when
956/// they apply in order to conserve memory. These are laid out past the end of
957/// the object, and flags in the DeclRefExprBitfield track whether they exist:
958///
959/// DeclRefExprBits.HasQualifier:
960/// Specifies when this declaration reference expression has a C++
961/// nested-name-specifier.
962/// DeclRefExprBits.HasFoundDecl:
963/// Specifies when this declaration reference expression has a record of
964/// a NamedDecl (different from the referenced ValueDecl) which was found
965/// during name lookup and/or overload resolution.
966/// DeclRefExprBits.HasTemplateKWAndArgsInfo:
967/// Specifies when this declaration reference expression has an explicit
968/// C++ template keyword and/or template argument list.
969/// DeclRefExprBits.RefersToEnclosingVariableOrCapture
970/// Specifies when this declaration reference expression (validly)
971/// refers to an enclosed local or a captured variable.
972class DeclRefExpr final
973 : public Expr,
974 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
975 NamedDecl *, ASTTemplateKWAndArgsInfo,
976 TemplateArgumentLoc> {
977 /// The declaration that we are referencing.
978 ValueDecl *D;
979
980 /// The location of the declaration name itself.
981 SourceLocation Loc;
982
983 /// Provides source/type location info for the declaration name
984 /// embedded in D.
985 DeclarationNameLoc DNLoc;
986
987 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
988 return hasQualifier() ? 1 : 0;
989 }
990
991 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
992 return hasFoundDecl() ? 1 : 0;
993 }
994
995 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
996 return hasTemplateKWAndArgsInfo() ? 1 : 0;
997 }
998
999 /// Test whether there is a distinct FoundDecl attached to the end of
1000 /// this DRE.
1001 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1002
1003 DeclRefExpr(const ASTContext &Ctx,
1004 NestedNameSpecifierLoc QualifierLoc,
1005 SourceLocation TemplateKWLoc,
1006 ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
1007 const DeclarationNameInfo &NameInfo,
1008 NamedDecl *FoundD,
1009 const TemplateArgumentListInfo *TemplateArgs,
1010 QualType T, ExprValueKind VK);
1011
1012 /// Construct an empty declaration reference expression.
1013 explicit DeclRefExpr(EmptyShell Empty)
1014 : Expr(DeclRefExprClass, Empty) { }
1015
1016 /// Computes the type- and value-dependence flags for this
1017 /// declaration reference expression.
1018 void computeDependence(const ASTContext &C);
1019
1020public:
1021 DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
1022 ExprValueKind VK, SourceLocation L,
1023 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
1024 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
1025 D(D), Loc(L), DNLoc(LocInfo) {
1026 DeclRefExprBits.HasQualifier = 0;
1027 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
1028 DeclRefExprBits.HasFoundDecl = 0;
1029 DeclRefExprBits.HadMultipleCandidates = 0;
1030 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
1031 RefersToEnclosingVariableOrCapture;
1032 computeDependence(D->getASTContext());
1033 }
1034
1035 static DeclRefExpr *
1036 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1037 SourceLocation TemplateKWLoc, ValueDecl *D,
1038 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1039 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1040 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1041
1042 static DeclRefExpr *
1043 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1044 SourceLocation TemplateKWLoc, ValueDecl *D,
1045 bool RefersToEnclosingVariableOrCapture,
1046 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1047 NamedDecl *FoundD = nullptr,
1048 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1049
1050 /// Construct an empty declaration reference expression.
1051 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
1052 bool HasQualifier,
1053 bool HasFoundDecl,
1054 bool HasTemplateKWAndArgsInfo,
1055 unsigned NumTemplateArgs);
1056
1057 ValueDecl *getDecl() { return D; }
1058 const ValueDecl *getDecl() const { return D; }
1059 void setDecl(ValueDecl *NewD) { D = NewD; }
1060
1061 DeclarationNameInfo getNameInfo() const {
1062 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
1063 }
1064
1065 SourceLocation getLocation() const { return Loc; }
1066 void setLocation(SourceLocation L) { Loc = L; }
1067 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__));
1068 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__));
1069
1070 /// Determine whether this declaration reference was preceded by a
1071 /// C++ nested-name-specifier, e.g., \c N::foo.
1072 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1073
1074 /// If the name was qualified, retrieves the nested-name-specifier
1075 /// that precedes the name, with source-location information.
1076 NestedNameSpecifierLoc getQualifierLoc() const {
1077 if (!hasQualifier())
1078 return NestedNameSpecifierLoc();
1079 return *getTrailingObjects<NestedNameSpecifierLoc>();
1080 }
1081
1082 /// If the name was qualified, retrieves the nested-name-specifier
1083 /// that precedes the name. Otherwise, returns NULL.
1084 NestedNameSpecifier *getQualifier() const {
1085 return getQualifierLoc().getNestedNameSpecifier();
1086 }
1087
1088 /// Get the NamedDecl through which this reference occurred.
1089 ///
1090 /// This Decl may be different from the ValueDecl actually referred to in the
1091 /// presence of using declarations, etc. It always returns non-NULL, and may
1092 /// simple return the ValueDecl when appropriate.
1093
1094 NamedDecl *getFoundDecl() {
1095 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1096 }
1097
1098 /// Get the NamedDecl through which this reference occurred.
1099 /// See non-const variant.
1100 const NamedDecl *getFoundDecl() const {
1101 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1102 }
1103
1104 bool hasTemplateKWAndArgsInfo() const {
1105 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1106 }
1107
1108 /// Retrieve the location of the template keyword preceding
1109 /// this name, if any.
1110 SourceLocation getTemplateKeywordLoc() const {
1111 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1112 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1113 }
1114
1115 /// Retrieve the location of the left angle bracket starting the
1116 /// explicit template argument list following the name, if any.
1117 SourceLocation getLAngleLoc() const {
1118 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1119 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1120 }
1121
1122 /// Retrieve the location of the right angle bracket ending the
1123 /// explicit template argument list following the name, if any.
1124 SourceLocation getRAngleLoc() const {
1125 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1126 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1127 }
1128
1129 /// Determines whether the name in this declaration reference
1130 /// was preceded by the template keyword.
1131 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1132
1133 /// Determines whether this declaration reference was followed by an
1134 /// explicit template argument list.
1135 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1136
1137 /// Copies the template arguments (if present) into the given
1138 /// structure.
1139 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1140 if (hasExplicitTemplateArgs())
1141 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1142 getTrailingObjects<TemplateArgumentLoc>(), List);
1143 }
1144
1145 /// Retrieve the template arguments provided as part of this
1146 /// template-id.
1147 const TemplateArgumentLoc *getTemplateArgs() const {
1148 if (!hasExplicitTemplateArgs())
1149 return nullptr;
1150
1151 return getTrailingObjects<TemplateArgumentLoc>();
1152 }
1153
1154 /// Retrieve the number of template arguments provided as part of this
1155 /// template-id.
1156 unsigned getNumTemplateArgs() const {
1157 if (!hasExplicitTemplateArgs())
1158 return 0;
1159
1160 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1161 }
1162
1163 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1164 return {getTemplateArgs(), getNumTemplateArgs()};
1165 }
1166
1167 /// Returns true if this expression refers to a function that
1168 /// was resolved from an overloaded set having size greater than 1.
1169 bool hadMultipleCandidates() const {
1170 return DeclRefExprBits.HadMultipleCandidates;
1171 }
1172 /// Sets the flag telling whether this expression refers to
1173 /// a function that was resolved from an overloaded set having size
1174 /// greater than 1.
1175 void setHadMultipleCandidates(bool V = true) {
1176 DeclRefExprBits.HadMultipleCandidates = V;
1177 }
1178
1179 /// Does this DeclRefExpr refer to an enclosing local or a captured
1180 /// variable?
1181 bool refersToEnclosingVariableOrCapture() const {
1182 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1183 }
1184
1185 static bool classof(const Stmt *T) {
1186 return T->getStmtClass() == DeclRefExprClass;
1187 }
1188
1189 // Iterators
1190 child_range children() {
1191 return child_range(child_iterator(), child_iterator());
1192 }
1193
1194 const_child_range children() const {
1195 return const_child_range(const_child_iterator(), const_child_iterator());
1196 }
1197
1198 friend TrailingObjects;
1199 friend class ASTStmtReader;
1200 friend class ASTStmtWriter;
1201};
1202
1203/// [C99 6.4.2.2] - A predefined identifier such as __func__.
1204class PredefinedExpr : public Expr {
1205public:
1206 enum IdentType {
1207 Func,
1208 Function,
1209 LFunction, // Same as Function, but as wide string.
1210 FuncDName,
1211 FuncSig,
1212 LFuncSig, // Same as FuncSig, but as as wide string
1213 PrettyFunction,
1214 /// The same as PrettyFunction, except that the
1215 /// 'virtual' keyword is omitted for virtual member functions.
1216 PrettyFunctionNoVirtual
1217 };
1218
1219private:
1220 SourceLocation Loc;
1221 IdentType Type;
1222 Stmt *FnName;
1223
1224public:
1225 PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
1226 StringLiteral *SL);
1227
1228 /// Construct an empty predefined expression.
1229 explicit PredefinedExpr(EmptyShell Empty)
1230 : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
1231
1232 IdentType getIdentType() const { return Type; }
1233
1234 SourceLocation getLocation() const { return Loc; }
1235 void setLocation(SourceLocation L) { Loc = L; }
1236
1237 StringLiteral *getFunctionName();
1238 const StringLiteral *getFunctionName() const {
1239 return const_cast<PredefinedExpr *>(this)->getFunctionName();
1240 }
1241
1242 static StringRef getIdentTypeName(IdentType IT);
1243 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1244
1245 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1246 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1247
1248 static bool classof(const Stmt *T) {
1249 return T->getStmtClass() == PredefinedExprClass;
1250 }
1251
1252 // Iterators
1253 child_range children() { return child_range(&FnName, &FnName + 1); }
1254 const_child_range children() const {
1255 return const_child_range(&FnName, &FnName + 1);
1256 }
1257
1258 friend class ASTStmtReader;
1259};
1260
1261/// Used by IntegerLiteral/FloatingLiteral to store the numeric without
1262/// leaking memory.
1263///
1264/// For large floats/integers, APFloat/APInt will allocate memory from the heap
1265/// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1266/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1267/// the APFloat/APInt values will never get freed. APNumericStorage uses
1268/// ASTContext's allocator for memory allocation.
1269class APNumericStorage {
1270 union {
1271 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1272 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1273 };
1274 unsigned BitWidth;
1275
1276 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1277
1278 APNumericStorage(const APNumericStorage &) = delete;
1279 void operator=(const APNumericStorage &) = delete;
1280
1281protected:
1282 APNumericStorage() : VAL(0), BitWidth(0) { }
1283
1284 llvm::APInt getIntValue() const {
1285 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1286 if (NumWords > 1)
1287 return llvm::APInt(BitWidth, NumWords, pVal);
1288 else
1289 return llvm::APInt(BitWidth, VAL);
1290 }
1291 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1292};
1293
1294class APIntStorage : private APNumericStorage {
1295public:
1296 llvm::APInt getValue() const { return getIntValue(); }
1297 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1298 setIntValue(C, Val);
1299 }
1300};
1301
1302class APFloatStorage : private APNumericStorage {
1303public:
1304 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1305 return llvm::APFloat(Semantics, getIntValue());
1306 }
1307 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1308 setIntValue(C, Val.bitcastToAPInt());
1309 }
1310};
1311
1312class IntegerLiteral : public Expr, public APIntStorage {
1313 SourceLocation Loc;
1314
1315 /// Construct an empty integer literal.
1316 explicit IntegerLiteral(EmptyShell Empty)
1317 : Expr(IntegerLiteralClass, Empty) { }
1318
1319public:
1320 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1321 // or UnsignedLongLongTy
1322 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1323 SourceLocation l);
1324
1325 /// Returns a new integer literal with value 'V' and type 'type'.
1326 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1327 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1328 /// \param V - the value that the returned integer literal contains.
1329 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1330 QualType type, SourceLocation l);
1331 /// Returns a new empty integer literal.
1332 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1333
1334 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1335 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1336
1337 /// Retrieve the location of the literal.
1338 SourceLocation getLocation() const { return Loc; }
1339
1340 void setLocation(SourceLocation Location) { Loc = Location; }
1341
1342 static bool classof(const Stmt *T) {
1343 return T->getStmtClass() == IntegerLiteralClass;
1344 }
1345
1346 // Iterators
1347 child_range children() {
1348 return child_range(child_iterator(), child_iterator());
1349 }
1350 const_child_range children() const {
1351 return const_child_range(const_child_iterator(), const_child_iterator());
1352 }
1353};
1354
1355class FixedPointLiteral : public Expr, public APIntStorage {
1356 SourceLocation Loc;
1357 unsigned Scale;
1358
1359 /// \brief Construct an empty integer literal.
1360 explicit FixedPointLiteral(EmptyShell Empty)
1361 : Expr(FixedPointLiteralClass, Empty) {}
1362
1363 public:
1364 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1365 SourceLocation l, unsigned Scale);
1366
1367 // Store the int as is without any bit shifting.
1368 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1369 const llvm::APInt &V,
1370 QualType type, SourceLocation l,
1371 unsigned Scale);
1372
1373 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1374 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1375
1376 /// \brief Retrieve the location of the literal.
1377 SourceLocation getLocation() const { return Loc; }
1378
1379 void setLocation(SourceLocation Location) { Loc = Location; }
1380
1381 static bool classof(const Stmt *T) {
1382 return T->getStmtClass() == FixedPointLiteralClass;
1383 }
1384
1385 std::string getValueAsString(unsigned Radix) const;
1386
1387 // Iterators
1388 child_range children() {
1389 return child_range(child_iterator(), child_iterator());
1390 }
1391 const_child_range children() const {
1392 return const_child_range(const_child_iterator(), const_child_iterator());
1393 }
1394};
1395
1396class CharacterLiteral : public Expr {
1397public:
1398 enum CharacterKind {
1399 Ascii,
1400 Wide,
1401 UTF8,
1402 UTF16,
1403 UTF32
1404 };
1405
1406private:
1407 unsigned Value;
1408 SourceLocation Loc;
1409public:
1410 // type should be IntTy
1411 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1412 SourceLocation l)
1413 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1414 false, false),
1415 Value(value), Loc(l) {
1416 CharacterLiteralBits.Kind = kind;
1417 }
1418
1419 /// Construct an empty character literal.
1420 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1421
1422 SourceLocation getLocation() const { return Loc; }
1423 CharacterKind getKind() const {
1424 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1425 }
1426
1427 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1428 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1429
1430 unsigned getValue() const { return Value; }
1431
1432 void setLocation(SourceLocation Location) { Loc = Location; }
1433 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1434 void setValue(unsigned Val) { Value = Val; }
1435
1436 static bool classof(const Stmt *T) {
1437 return T->getStmtClass() == CharacterLiteralClass;
1438 }
1439
1440 // Iterators
1441 child_range children() {
1442 return child_range(child_iterator(), child_iterator());
1443 }
1444 const_child_range children() const {
1445 return const_child_range(const_child_iterator(), const_child_iterator());
1446 }
1447};
1448
1449class FloatingLiteral : public Expr, private APFloatStorage {
1450 SourceLocation Loc;
1451
1452 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1453 QualType Type, SourceLocation L);
1454
1455 /// Construct an empty floating-point literal.
1456 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1457
1458public:
1459 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1460 bool isexact, QualType Type, SourceLocation L);
1461 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1462
1463 llvm::APFloat getValue() const {
1464 return APFloatStorage::getValue(getSemantics());
1465 }
1466 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1467 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics")(static_cast <bool> (&getSemantics() == &Val.getSemantics
() && "Inconsistent semantics") ? void (0) : __assert_fail
("&getSemantics() == &Val.getSemantics() && \"Inconsistent semantics\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 1467, __extension__ __PRETTY_FUNCTION__))
;
1468 APFloatStorage::setValue(C, Val);
1469 }
1470
1471 /// Get a raw enumeration value representing the floating-point semantics of
1472 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1473 APFloatSemantics getRawSemantics() const {
1474 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1475 }
1476
1477 /// Set the raw enumeration value representing the floating-point semantics of
1478 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1479 void setRawSemantics(APFloatSemantics Sem) {
1480 FloatingLiteralBits.Semantics = Sem;
1481 }
1482
1483 /// Return the APFloat semantics this literal uses.
1484 const llvm::fltSemantics &getSemantics() const;
1485
1486 /// Set the APFloat semantics this literal uses.
1487 void setSemantics(const llvm::fltSemantics &Sem);
1488
1489 bool isExact() const { return FloatingLiteralBits.IsExact; }
1490 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1491
1492 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1493 /// double. Note that this may cause loss of precision, but is useful for
1494 /// debugging dumps, etc.
1495 double getValueAsApproximateDouble() const;
1496
1497 SourceLocation getLocation() const { return Loc; }
1498 void setLocation(SourceLocation L) { Loc = L; }
1499
1500 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1501 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1502
1503 static bool classof(const Stmt *T) {
1504 return T->getStmtClass() == FloatingLiteralClass;
1505 }
1506
1507 // Iterators
1508 child_range children() {
1509 return child_range(child_iterator(), child_iterator());
1510 }
1511 const_child_range children() const {
1512 return const_child_range(const_child_iterator(), const_child_iterator());
1513 }
1514};
1515
1516/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1517/// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1518/// IntegerLiteral classes. Instances of this class always have a Complex type
1519/// whose element type matches the subexpression.
1520///
1521class ImaginaryLiteral : public Expr {
1522 Stmt *Val;
1523public:
1524 ImaginaryLiteral(Expr *val, QualType Ty)
1525 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1526 false, false),
1527 Val(val) {}
1528
1529 /// Build an empty imaginary literal.
1530 explicit ImaginaryLiteral(EmptyShell Empty)
1531 : Expr(ImaginaryLiteralClass, Empty) { }
1532
1533 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1534 Expr *getSubExpr() { return cast<Expr>(Val); }
1535 void setSubExpr(Expr *E) { Val = E; }
1536
1537 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return Val->getLocStart(); }
1538 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return Val->getLocEnd(); }
1539
1540 static bool classof(const Stmt *T) {
1541 return T->getStmtClass() == ImaginaryLiteralClass;
1542 }
1543
1544 // Iterators
1545 child_range children() { return child_range(&Val, &Val+1); }
1546 const_child_range children() const {
1547 return const_child_range(&Val, &Val + 1);
1548 }
1549};
1550
1551/// StringLiteral - This represents a string literal expression, e.g. "foo"
1552/// or L"bar" (wide strings). The actual string is returned by getBytes()
1553/// is NOT null-terminated, and the length of the string is determined by
1554/// calling getByteLength(). The C type for a string is always a
1555/// ConstantArrayType. In C++, the char type is const qualified, in C it is
1556/// not.
1557///
1558/// Note that strings in C can be formed by concatenation of multiple string
1559/// literal pptokens in translation phase #6. This keeps track of the locations
1560/// of each of these pieces.
1561///
1562/// Strings in C can also be truncated and extended by assigning into arrays,
1563/// e.g. with constructs like:
1564/// char X[2] = "foobar";
1565/// In this case, getByteLength() will return 6, but the string literal will
1566/// have type "char[2]".
1567class StringLiteral : public Expr {
1568public:
1569 enum StringKind {
1570 Ascii,
1571 Wide,
1572 UTF8,
1573 UTF16,
1574 UTF32
1575 };
1576
1577private:
1578 friend class ASTStmtReader;
1579
1580 union {
1581 const char *asChar;
1582 const uint16_t *asUInt16;
1583 const uint32_t *asUInt32;
1584 } StrData;
1585 unsigned Length;
1586 unsigned CharByteWidth : 4;
1587 unsigned Kind : 3;
1588 unsigned IsPascal : 1;
1589 unsigned NumConcatenated;
1590 SourceLocation TokLocs[1];
1591
1592 StringLiteral(QualType Ty) :
1593 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1594 false) {}
1595
1596 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1597
1598public:
1599 /// This is the "fully general" constructor that allows representation of
1600 /// strings formed from multiple concatenated tokens.
1601 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1602 StringKind Kind, bool Pascal, QualType Ty,
1603 const SourceLocation *Loc, unsigned NumStrs);
1604
1605 /// Simple constructor for string literals made from one token.
1606 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1607 StringKind Kind, bool Pascal, QualType Ty,
1608 SourceLocation Loc) {
1609 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1610 }
1611
1612 /// Construct an empty string literal.
1613 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1614
1615 StringRef getString() const {
1616 assert(CharByteWidth==1(static_cast <bool> (CharByteWidth==1 && "This function is used in places that assume strings use char"
) ? void (0) : __assert_fail ("CharByteWidth==1 && \"This function is used in places that assume strings use char\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 1617, __extension__ __PRETTY_FUNCTION__))
1617 && "This function is used in places that assume strings use char")(static_cast <bool> (CharByteWidth==1 && "This function is used in places that assume strings use char"
) ? void (0) : __assert_fail ("CharByteWidth==1 && \"This function is used in places that assume strings use char\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 1617, __extension__ __PRETTY_FUNCTION__))
;
1618 return StringRef(StrData.asChar, getByteLength());
1619 }
1620
1621 /// Allow access to clients that need the byte representation, such as
1622 /// ASTWriterStmt::VisitStringLiteral().
1623 StringRef getBytes() const {
1624 // FIXME: StringRef may not be the right type to use as a result for this.
1625 if (CharByteWidth == 1)
1626 return StringRef(StrData.asChar, getByteLength());
1627 if (CharByteWidth == 4)
1628 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1629 getByteLength());
1630 assert(CharByteWidth == 2 && "unsupported CharByteWidth")(static_cast <bool> (CharByteWidth == 2 && "unsupported CharByteWidth"
) ? void (0) : __assert_fail ("CharByteWidth == 2 && \"unsupported CharByteWidth\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 1630, __extension__ __PRETTY_FUNCTION__))
;
1631 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1632 getByteLength());
1633 }
1634
1635 void outputString(raw_ostream &OS) const;
1636
1637 uint32_t getCodeUnit(size_t i) const {
1638 assert(i < Length && "out of bounds access")(static_cast <bool> (i < Length && "out of bounds access"
) ? void (0) : __assert_fail ("i < Length && \"out of bounds access\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 1638, __extension__ __PRETTY_FUNCTION__))
;
1639 if (CharByteWidth == 1)
1640 return static_cast<unsigned char>(StrData.asChar[i]);
1641 if (CharByteWidth == 4)
1642 return StrData.asUInt32[i];
1643 assert(CharByteWidth == 2 && "unsupported CharByteWidth")(static_cast <bool> (CharByteWidth == 2 && "unsupported CharByteWidth"
) ? void (0) : __assert_fail ("CharByteWidth == 2 && \"unsupported CharByteWidth\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 1643, __extension__ __PRETTY_FUNCTION__))
;
1644 return StrData.asUInt16[i];
1645 }
1646
1647 unsigned getByteLength() const { return CharByteWidth*Length; }
1648 unsigned getLength() const { return Length; }
1649 unsigned getCharByteWidth() const { return CharByteWidth; }
1650
1651 /// Sets the string data to the given string data.
1652 void setString(const ASTContext &C, StringRef Str,
1653 StringKind Kind, bool IsPascal);
1654
1655 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1656
1657
1658 bool isAscii() const { return Kind == Ascii; }
1659 bool isWide() const { return Kind == Wide; }
1660 bool isUTF8() const { return Kind == UTF8; }
1661 bool isUTF16() const { return Kind == UTF16; }
1662 bool isUTF32() const { return Kind == UTF32; }
1663 bool isPascal() const { return IsPascal; }
1664
1665 bool containsNonAscii() const {
1666 StringRef Str = getString();
1667 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1668 if (!isASCII(Str[i]))
1669 return true;
1670 return false;
1671 }
1672
1673 bool containsNonAsciiOrNull() const {
1674 StringRef Str = getString();
1675 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1676 if (!isASCII(Str[i]) || !Str[i])
1677 return true;
1678 return false;
1679 }
1680
1681 /// getNumConcatenated - Get the number of string literal tokens that were
1682 /// concatenated in translation phase #6 to form this string literal.
1683 unsigned getNumConcatenated() const { return NumConcatenated; }
1684
1685 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1686 assert(TokNum < NumConcatenated && "Invalid tok number")(static_cast <bool> (TokNum < NumConcatenated &&
"Invalid tok number") ? void (0) : __assert_fail ("TokNum < NumConcatenated && \"Invalid tok number\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 1686, __extension__ __PRETTY_FUNCTION__))
;
1687 return TokLocs[TokNum];
1688 }
1689 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1690 assert(TokNum < NumConcatenated && "Invalid tok number")(static_cast <bool> (TokNum < NumConcatenated &&
"Invalid tok number") ? void (0) : __assert_fail ("TokNum < NumConcatenated && \"Invalid tok number\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 1690, __extension__ __PRETTY_FUNCTION__))
;
1691 TokLocs[TokNum] = L;
1692 }
1693
1694 /// getLocationOfByte - Return a source location that points to the specified
1695 /// byte of this string literal.
1696 ///
1697 /// Strings are amazingly complex. They can be formed from multiple tokens
1698 /// and can have escape sequences in them in addition to the usual trigraph
1699 /// and escaped newline business. This routine handles this complexity.
1700 ///
1701 SourceLocation
1702 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1703 const LangOptions &Features, const TargetInfo &Target,
1704 unsigned *StartToken = nullptr,
1705 unsigned *StartTokenByteOffset = nullptr) const;
1706
1707 typedef const SourceLocation *tokloc_iterator;
1708 tokloc_iterator tokloc_begin() const { return TokLocs; }
1709 tokloc_iterator tokloc_end() const { return TokLocs + NumConcatenated; }
1710
1711 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return TokLocs[0]; }
1712 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
1713 return TokLocs[NumConcatenated - 1];
1714 }
1715
1716 static bool classof(const Stmt *T) {
1717 return T->getStmtClass() == StringLiteralClass;
1718 }
1719
1720 // Iterators
1721 child_range children() {
1722 return child_range(child_iterator(), child_iterator());
1723 }
1724 const_child_range children() const {
1725 return const_child_range(const_child_iterator(), const_child_iterator());
1726 }
1727};
1728
1729/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1730/// AST node is only formed if full location information is requested.
1731class ParenExpr : public Expr {
1732 SourceLocation L, R;
1733 Stmt *Val;
1734public:
1735 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1736 : Expr(ParenExprClass, val->getType(),
1737 val->getValueKind(), val->getObjectKind(),
1738 val->isTypeDependent(), val->isValueDependent(),
1739 val->isInstantiationDependent(),
1740 val->containsUnexpandedParameterPack()),
1741 L(l), R(r), Val(val) {}
1742
1743 /// Construct an empty parenthesized expression.
1744 explicit ParenExpr(EmptyShell Empty)
1745 : Expr(ParenExprClass, Empty) { }
1746
1747 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1748 Expr *getSubExpr() { return cast<Expr>(Val); }
1749 void setSubExpr(Expr *E) { Val = E; }
1750
1751 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return L; }
1752 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return R; }
1753
1754 /// Get the location of the left parentheses '('.
1755 SourceLocation getLParen() const { return L; }
1756 void setLParen(SourceLocation Loc) { L = Loc; }
1757
1758 /// Get the location of the right parentheses ')'.
1759 SourceLocation getRParen() const { return R; }
1760 void setRParen(SourceLocation Loc) { R = Loc; }
1761
1762 static bool classof(const Stmt *T) {
1763 return T->getStmtClass() == ParenExprClass;
1764 }
1765
1766 // Iterators
1767 child_range children() { return child_range(&Val, &Val+1); }
1768 const_child_range children() const {
1769 return const_child_range(&Val, &Val + 1);
1770 }
1771};
1772
1773/// UnaryOperator - This represents the unary-expression's (except sizeof and
1774/// alignof), the postinc/postdec operators from postfix-expression, and various
1775/// extensions.
1776///
1777/// Notes on various nodes:
1778///
1779/// Real/Imag - These return the real/imag part of a complex operand. If
1780/// applied to a non-complex value, the former returns its operand and the
1781/// later returns zero in the type of the operand.
1782///
1783class UnaryOperator : public Expr {
1784public:
1785 typedef UnaryOperatorKind Opcode;
1786
1787private:
1788 unsigned Opc : 5;
1789 unsigned CanOverflow : 1;
1790 SourceLocation Loc;
1791 Stmt *Val;
1792public:
1793 UnaryOperator(Expr *input, Opcode opc, QualType type, ExprValueKind VK,
1794 ExprObjectKind OK, SourceLocation l, bool CanOverflow)
1795 : Expr(UnaryOperatorClass, type, VK, OK,
1796 input->isTypeDependent() || type->isDependentType(),
1797 input->isValueDependent(),
1798 (input->isInstantiationDependent() ||
1799 type->isInstantiationDependentType()),
1800 input->containsUnexpandedParameterPack()),
1801 Opc(opc), CanOverflow(CanOverflow), Loc(l), Val(input) {}
1802
1803 /// Build an empty unary operator.
1804 explicit UnaryOperator(EmptyShell Empty)
1805 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1806
1807 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1808 void setOpcode(Opcode O) { Opc = O; }
1809
1810 Expr *getSubExpr() const { return cast<Expr>(Val); }
1811 void setSubExpr(Expr *E) { Val = E; }
1812
1813 /// getOperatorLoc - Return the location of the operator.
1814 SourceLocation getOperatorLoc() const { return Loc; }
1815 void setOperatorLoc(SourceLocation L) { Loc = L; }
1816
1817 /// Returns true if the unary operator can cause an overflow. For instance,
1818 /// signed int i = INT_MAX; i++;
1819 /// signed char c = CHAR_MAX; c++;
1820 /// Due to integer promotions, c++ is promoted to an int before the postfix
1821 /// increment, and the result is an int that cannot overflow. However, i++
1822 /// can overflow.
1823 bool canOverflow() const { return CanOverflow; }
1824 void setCanOverflow(bool C) { CanOverflow = C; }
1825
1826 /// isPostfix - Return true if this is a postfix operation, like x++.
1827 static bool isPostfix(Opcode Op) {
1828 return Op == UO_PostInc || Op == UO_PostDec;
1829 }
1830
1831 /// isPrefix - Return true if this is a prefix operation, like --x.
1832 static bool isPrefix(Opcode Op) {
1833 return Op == UO_PreInc || Op == UO_PreDec;
1834 }
1835
1836 bool isPrefix() const { return isPrefix(getOpcode()); }
1837 bool isPostfix() const { return isPostfix(getOpcode()); }
1838
1839 static bool isIncrementOp(Opcode Op) {
1840 return Op == UO_PreInc || Op == UO_PostInc;
1841 }
1842 bool isIncrementOp() const {
1843 return isIncrementOp(getOpcode());
1844 }
1845
1846 static bool isDecrementOp(Opcode Op) {
1847 return Op == UO_PreDec || Op == UO_PostDec;
1848 }
1849 bool isDecrementOp() const {
1850 return isDecrementOp(getOpcode());
1851 }
1852
1853 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1854 bool isIncrementDecrementOp() const {
1855 return isIncrementDecrementOp(getOpcode());
1856 }
1857
1858 static bool isArithmeticOp(Opcode Op) {
1859 return Op >= UO_Plus && Op <= UO_LNot;
1860 }
1861 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1862
1863 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1864 /// corresponds to, e.g. "sizeof" or "[pre]++"
1865 static StringRef getOpcodeStr(Opcode Op);
1866
1867 /// Retrieve the unary opcode that corresponds to the given
1868 /// overloaded operator.
1869 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1870
1871 /// Retrieve the overloaded operator kind that corresponds to
1872 /// the given unary opcode.
1873 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1874
1875 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
1876 return isPostfix() ? Val->getLocStart() : Loc;
1877 }
1878 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
1879 return isPostfix() ? Loc : Val->getLocEnd();
1880 }
1881 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1882
1883 static bool classof(const Stmt *T) {
1884 return T->getStmtClass() == UnaryOperatorClass;
1885 }
1886
1887 // Iterators
1888 child_range children() { return child_range(&Val, &Val+1); }
1889 const_child_range children() const {
1890 return const_child_range(&Val, &Val + 1);
1891 }
1892};
1893
1894/// Helper class for OffsetOfExpr.
1895
1896// __builtin_offsetof(type, identifier(.identifier|[expr])*)
1897class OffsetOfNode {
1898public:
1899 /// The kind of offsetof node we have.
1900 enum Kind {
1901 /// An index into an array.
1902 Array = 0x00,
1903 /// A field.
1904 Field = 0x01,
1905 /// A field in a dependent type, known only by its name.
1906 Identifier = 0x02,
1907 /// An implicit indirection through a C++ base class, when the
1908 /// field found is in a base class.
1909 Base = 0x03
1910 };
1911
1912private:
1913 enum { MaskBits = 2, Mask = 0x03 };
1914
1915 /// The source range that covers this part of the designator.
1916 SourceRange Range;
1917
1918 /// The data describing the designator, which comes in three
1919 /// different forms, depending on the lower two bits.
1920 /// - An unsigned index into the array of Expr*'s stored after this node
1921 /// in memory, for [constant-expression] designators.
1922 /// - A FieldDecl*, for references to a known field.
1923 /// - An IdentifierInfo*, for references to a field with a given name
1924 /// when the class type is dependent.
1925 /// - A CXXBaseSpecifier*, for references that look at a field in a
1926 /// base class.
1927 uintptr_t Data;
1928
1929public:
1930 /// Create an offsetof node that refers to an array element.
1931 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1932 SourceLocation RBracketLoc)
1933 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
1934
1935 /// Create an offsetof node that refers to a field.
1936 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
1937 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1938 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
1939
1940 /// Create an offsetof node that refers to an identifier.
1941 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1942 SourceLocation NameLoc)
1943 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1944 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
1945
1946 /// Create an offsetof node that refers into a C++ base class.
1947 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1948 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1949
1950 /// Determine what kind of offsetof node this is.
1951 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
1952
1953 /// For an array element node, returns the index into the array
1954 /// of expressions.
1955 unsigned getArrayExprIndex() const {
1956 assert(getKind() == Array)(static_cast <bool> (getKind() == Array) ? void (0) : __assert_fail
("getKind() == Array", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 1956, __extension__ __PRETTY_FUNCTION__))
;
1957 return Data >> 2;
1958 }
1959
1960 /// For a field offsetof node, returns the field.
1961 FieldDecl *getField() const {
1962 assert(getKind() == Field)(static_cast <bool> (getKind() == Field) ? void (0) : __assert_fail
("getKind() == Field", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 1962, __extension__ __PRETTY_FUNCTION__))
;
1963 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1964 }
1965
1966 /// For a field or identifier offsetof node, returns the name of
1967 /// the field.
1968 IdentifierInfo *getFieldName() const;
1969
1970 /// For a base class node, returns the base specifier.
1971 CXXBaseSpecifier *getBase() const {
1972 assert(getKind() == Base)(static_cast <bool> (getKind() == Base) ? void (0) : __assert_fail
("getKind() == Base", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 1972, __extension__ __PRETTY_FUNCTION__))
;
1973 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1974 }
1975
1976 /// Retrieve the source range that covers this offsetof node.
1977 ///
1978 /// For an array element node, the source range contains the locations of
1979 /// the square brackets. For a field or identifier node, the source range
1980 /// contains the location of the period (if there is one) and the
1981 /// identifier.
1982 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
1983 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
1984 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
1985};
1986
1987/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1988/// offsetof(record-type, member-designator). For example, given:
1989/// @code
1990/// struct S {
1991/// float f;
1992/// double d;
1993/// };
1994/// struct T {
1995/// int i;
1996/// struct S s[10];
1997/// };
1998/// @endcode
1999/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2000
2001class OffsetOfExpr final
2002 : public Expr,
2003 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2004 SourceLocation OperatorLoc, RParenLoc;
2005 // Base type;
2006 TypeSourceInfo *TSInfo;
2007 // Number of sub-components (i.e. instances of OffsetOfNode).
2008 unsigned NumComps;
2009 // Number of sub-expressions (i.e. array subscript expressions).
2010 unsigned NumExprs;
2011
2012 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2013 return NumComps;
2014 }
2015
2016 OffsetOfExpr(const ASTContext &C, QualType type,
2017 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2018 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2019 SourceLocation RParenLoc);
2020
2021 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2022 : Expr(OffsetOfExprClass, EmptyShell()),
2023 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2024
2025public:
2026
2027 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2028 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2029 ArrayRef<OffsetOfNode> comps,
2030 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2031
2032 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2033 unsigned NumComps, unsigned NumExprs);
2034
2035 /// getOperatorLoc - Return the location of the operator.
2036 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2037 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2038
2039 /// Return the location of the right parentheses.
2040 SourceLocation getRParenLoc() const { return RParenLoc; }
2041 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2042
2043 TypeSourceInfo *getTypeSourceInfo() const {
2044 return TSInfo;
2045 }
2046 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2047 TSInfo = tsi;
2048 }
2049
2050 const OffsetOfNode &getComponent(unsigned Idx) const {
2051 assert(Idx < NumComps && "Subscript out of range")(static_cast <bool> (Idx < NumComps && "Subscript out of range"
) ? void (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2051, __extension__ __PRETTY_FUNCTION__))
;
2052 return getTrailingObjects<OffsetOfNode>()[Idx];
2053 }
2054
2055 void setComponent(unsigned Idx, OffsetOfNode ON) {
2056 assert(Idx < NumComps && "Subscript out of range")(static_cast <bool> (Idx < NumComps && "Subscript out of range"
) ? void (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2056, __extension__ __PRETTY_FUNCTION__))
;
2057 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2058 }
2059
2060 unsigned getNumComponents() const {
2061 return NumComps;
2062 }
2063
2064 Expr* getIndexExpr(unsigned Idx) {
2065 assert(Idx < NumExprs && "Subscript out of range")(static_cast <bool> (Idx < NumExprs && "Subscript out of range"
) ? void (0) : __assert_fail ("Idx < NumExprs && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2065, __extension__ __PRETTY_FUNCTION__))
;
2066 return getTrailingObjects<Expr *>()[Idx];
2067 }
2068
2069 const Expr *getIndexExpr(unsigned Idx) const {
2070 assert(Idx < NumExprs && "Subscript out of range")(static_cast <bool> (Idx < NumExprs && "Subscript out of range"
) ? void (0) : __assert_fail ("Idx < NumExprs && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2070, __extension__ __PRETTY_FUNCTION__))
;
2071 return getTrailingObjects<Expr *>()[Idx];
2072 }
2073
2074 void setIndexExpr(unsigned Idx, Expr* E) {
2075 assert(Idx < NumComps && "Subscript out of range")(static_cast <bool> (Idx < NumComps && "Subscript out of range"
) ? void (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2075, __extension__ __PRETTY_FUNCTION__))
;
2076 getTrailingObjects<Expr *>()[Idx] = E;
2077 }
2078
2079 unsigned getNumExpressions() const {
2080 return NumExprs;
2081 }
2082
2083 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return OperatorLoc; }
2084 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
2085
2086 static bool classof(const Stmt *T) {
2087 return T->getStmtClass() == OffsetOfExprClass;
2088 }
2089
2090 // Iterators
2091 child_range children() {
2092 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2093 return child_range(begin, begin + NumExprs);
2094 }
2095 const_child_range children() const {
2096 Stmt *const *begin =
2097 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2098 return const_child_range(begin, begin + NumExprs);
2099 }
2100 friend TrailingObjects;
2101};
2102
2103/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2104/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2105/// vec_step (OpenCL 1.1 6.11.12).
2106class UnaryExprOrTypeTraitExpr : public Expr {
2107 union {
2108 TypeSourceInfo *Ty;
2109 Stmt *Ex;
2110 } Argument;
2111 SourceLocation OpLoc, RParenLoc;
2112
2113public:
2114 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2115 QualType resultType, SourceLocation op,
2116 SourceLocation rp) :
2117 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2118 false, // Never type-dependent (C++ [temp.dep.expr]p3).
2119 // Value-dependent if the argument is type-dependent.
2120 TInfo->getType()->isDependentType(),
2121 TInfo->getType()->isInstantiationDependentType(),
2122 TInfo->getType()->containsUnexpandedParameterPack()),
2123 OpLoc(op), RParenLoc(rp) {
2124 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2125 UnaryExprOrTypeTraitExprBits.IsType = true;
2126 Argument.Ty = TInfo;
2127 }
2128
2129 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2130 QualType resultType, SourceLocation op,
2131 SourceLocation rp);
2132
2133 /// Construct an empty sizeof/alignof expression.
2134 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2135 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2136
2137 UnaryExprOrTypeTrait getKind() const {
2138 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2139 }
2140 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2141
2142 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2143 QualType getArgumentType() const {
2144 return getArgumentTypeInfo()->getType();
2145 }
2146 TypeSourceInfo *getArgumentTypeInfo() const {
2147 assert(isArgumentType() && "calling getArgumentType() when arg is expr")(static_cast <bool> (isArgumentType() && "calling getArgumentType() when arg is expr"
) ? void (0) : __assert_fail ("isArgumentType() && \"calling getArgumentType() when arg is expr\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2147, __extension__ __PRETTY_FUNCTION__))
;
2148 return Argument.Ty;
2149 }
2150 Expr *getArgumentExpr() {
2151 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type")(static_cast <bool> (!isArgumentType() && "calling getArgumentExpr() when arg is type"
) ? void (0) : __assert_fail ("!isArgumentType() && \"calling getArgumentExpr() when arg is type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2151, __extension__ __PRETTY_FUNCTION__))
;
2152 return static_cast<Expr*>(Argument.Ex);
2153 }
2154 const Expr *getArgumentExpr() const {
2155 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2156 }
2157
2158 void setArgument(Expr *E) {
2159 Argument.Ex = E;
2160 UnaryExprOrTypeTraitExprBits.IsType = false;
2161 }
2162 void setArgument(TypeSourceInfo *TInfo) {
2163 Argument.Ty = TInfo;
2164 UnaryExprOrTypeTraitExprBits.IsType = true;
2165 }
2166
2167 /// Gets the argument type, or the type of the argument expression, whichever
2168 /// is appropriate.
2169 QualType getTypeOfArgument() const {
2170 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2171 }
2172
2173 SourceLocation getOperatorLoc() const { return OpLoc; }
2174 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2175
2176 SourceLocation getRParenLoc() const { return RParenLoc; }
2177 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2178
2179 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return OpLoc; }
2180 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
2181
2182 static bool classof(const Stmt *T) {
2183 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2184 }
2185
2186 // Iterators
2187 child_range children();
2188 const_child_range children() const;
2189};
2190
2191//===----------------------------------------------------------------------===//
2192// Postfix Operators.
2193//===----------------------------------------------------------------------===//
2194
2195/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2196class ArraySubscriptExpr : public Expr {
2197 enum { LHS, RHS, END_EXPR=2 };
2198 Stmt* SubExprs[END_EXPR];
2199 SourceLocation RBracketLoc;
2200public:
2201 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2202 ExprValueKind VK, ExprObjectKind OK,
2203 SourceLocation rbracketloc)
2204 : Expr(ArraySubscriptExprClass, t, VK, OK,
2205 lhs->isTypeDependent() || rhs->isTypeDependent(),
2206 lhs->isValueDependent() || rhs->isValueDependent(),
2207 (lhs->isInstantiationDependent() ||
2208 rhs->isInstantiationDependent()),
2209 (lhs->containsUnexpandedParameterPack() ||
2210 rhs->containsUnexpandedParameterPack())),
2211 RBracketLoc(rbracketloc) {
2212 SubExprs[LHS] = lhs;
2213 SubExprs[RHS] = rhs;
2214 }
2215
2216 /// Create an empty array subscript expression.
2217 explicit ArraySubscriptExpr(EmptyShell Shell)
2218 : Expr(ArraySubscriptExprClass, Shell) { }
2219
2220 /// An array access can be written A[4] or 4[A] (both are equivalent).
2221 /// - getBase() and getIdx() always present the normalized view: A[4].
2222 /// In this case getBase() returns "A" and getIdx() returns "4".
2223 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2224 /// 4[A] getLHS() returns "4".
2225 /// Note: Because vector element access is also written A[4] we must
2226 /// predicate the format conversion in getBase and getIdx only on the
2227 /// the type of the RHS, as it is possible for the LHS to be a vector of
2228 /// integer type
2229 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2230 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2231 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2232
2233 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2234 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2235 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2236
2237 Expr *getBase() {
2238 return getRHS()->getType()->isIntegerType() ? getLHS() : getRHS();
2239 }
2240
2241 const Expr *getBase() const {
2242 return getRHS()->getType()->isIntegerType() ? getLHS() : getRHS();
2243 }
2244
2245 Expr *getIdx() {
2246 return getRHS()->getType()->isIntegerType() ? getRHS() : getLHS();
2247 }
2248
2249 const Expr *getIdx() const {
2250 return getRHS()->getType()->isIntegerType() ? getRHS() : getLHS();
2251 }
2252
2253 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
2254 return getLHS()->getLocStart();
2255 }
2256 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return RBracketLoc; }
2257
2258 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2259 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2260
2261 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
2262 return getBase()->getExprLoc();
2263 }
2264
2265 static bool classof(const Stmt *T) {
2266 return T->getStmtClass() == ArraySubscriptExprClass;
2267 }
2268
2269 // Iterators
2270 child_range children() {
2271 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2272 }
2273 const_child_range children() const {
2274 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2275 }
2276};
2277
2278/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2279/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2280/// while its subclasses may represent alternative syntax that (semantically)
2281/// results in a function call. For example, CXXOperatorCallExpr is
2282/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2283/// "str1 + str2" to resolve to a function call.
2284class CallExpr : public Expr {
2285 enum { FN=0, PREARGS_START=1 };
2286 Stmt **SubExprs;
2287 unsigned NumArgs;
2288 SourceLocation RParenLoc;
2289
2290 void updateDependenciesFromArg(Expr *Arg);
2291
2292protected:
2293 // These versions of the constructor are for derived classes.
2294 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
2295 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
2296 ExprValueKind VK, SourceLocation rparenloc);
2297 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef<Expr *> args,
2298 QualType t, ExprValueKind VK, SourceLocation rparenloc);
2299 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2300 EmptyShell Empty);
2301
2302 Stmt *getPreArg(unsigned i) {
2303 assert(i < getNumPreArgs() && "Prearg access out of range!")(static_cast <bool> (i < getNumPreArgs() && "Prearg access out of range!"
) ? void (0) : __assert_fail ("i < getNumPreArgs() && \"Prearg access out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2303, __extension__ __PRETTY_FUNCTION__))
;
2304 return SubExprs[PREARGS_START+i];
2305 }
2306 const Stmt *getPreArg(unsigned i) const {
2307 assert(i < getNumPreArgs() && "Prearg access out of range!")(static_cast <bool> (i < getNumPreArgs() && "Prearg access out of range!"
) ? void (0) : __assert_fail ("i < getNumPreArgs() && \"Prearg access out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2307, __extension__ __PRETTY_FUNCTION__))
;
2308 return SubExprs[PREARGS_START+i];
2309 }
2310 void setPreArg(unsigned i, Stmt *PreArg) {
2311 assert(i < getNumPreArgs() && "Prearg access out of range!")(static_cast <bool> (i < getNumPreArgs() && "Prearg access out of range!"
) ? void (0) : __assert_fail ("i < getNumPreArgs() && \"Prearg access out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2311, __extension__ __PRETTY_FUNCTION__))
;
2312 SubExprs[PREARGS_START+i] = PreArg;
2313 }
2314
2315 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2316
2317public:
2318 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2319 ExprValueKind VK, SourceLocation rparenloc);
2320
2321 /// Build an empty call expression.
2322 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2323
2324 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2325 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2326 void setCallee(Expr *F) { SubExprs[FN] = F; }
2327
2328 Decl *getCalleeDecl();
2329 const Decl *getCalleeDecl() const {
2330 return const_cast<CallExpr*>(this)->getCalleeDecl();
2331 }
2332
2333 /// If the callee is a FunctionDecl, return it. Otherwise return 0.
2334 FunctionDecl *getDirectCallee();
2335 const FunctionDecl *getDirectCallee() const {
2336 return const_cast<CallExpr*>(this)->getDirectCallee();
2337 }
2338
2339 /// getNumArgs - Return the number of actual arguments to this call.
2340 ///
2341 unsigned getNumArgs() const { return NumArgs; }
2342
2343 /// Retrieve the call arguments.
2344 Expr **getArgs() {
2345 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2346 }
2347 const Expr *const *getArgs() const {
2348 return reinterpret_cast<Expr **>(SubExprs + getNumPreArgs() +
2349 PREARGS_START);
2350 }
2351
2352 /// getArg - Return the specified argument.
2353 Expr *getArg(unsigned Arg) {
2354 assert(Arg < NumArgs && "Arg access out of range!")(static_cast <bool> (Arg < NumArgs && "Arg access out of range!"
) ? void (0) : __assert_fail ("Arg < NumArgs && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2354, __extension__ __PRETTY_FUNCTION__))
;
2355 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2356 }
2357 const Expr *getArg(unsigned Arg) const {
2358 assert(Arg < NumArgs && "Arg access out of range!")(static_cast <bool> (Arg < NumArgs && "Arg access out of range!"
) ? void (0) : __assert_fail ("Arg < NumArgs && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2358, __extension__ __PRETTY_FUNCTION__))
;
2359 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2360 }
2361
2362 /// setArg - Set the specified argument.
2363 void setArg(unsigned Arg, Expr *ArgExpr) {
2364 assert(Arg < NumArgs && "Arg access out of range!")(static_cast <bool> (Arg < NumArgs && "Arg access out of range!"
) ? void (0) : __assert_fail ("Arg < NumArgs && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2364, __extension__ __PRETTY_FUNCTION__))
;
2365 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2366 }
2367
2368 /// setNumArgs - This changes the number of arguments present in this call.
2369 /// Any orphaned expressions are deleted by this, and any new operands are set
2370 /// to null.
2371 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2372
2373 typedef ExprIterator arg_iterator;
2374 typedef ConstExprIterator const_arg_iterator;
2375 typedef llvm::iterator_range<arg_iterator> arg_range;
2376 typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2377
2378 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2379 arg_const_range arguments() const {
2380 return arg_const_range(arg_begin(), arg_end());
2381 }
2382
2383 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2384 arg_iterator arg_end() {
2385 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2386 }
2387 const_arg_iterator arg_begin() const {
2388 return SubExprs+PREARGS_START+getNumPreArgs();
2389 }
2390 const_arg_iterator arg_end() const {
2391 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2392 }
2393
2394 /// This method provides fast access to all the subexpressions of
2395 /// a CallExpr without going through the slower virtual child_iterator
2396 /// interface. This provides efficient reverse iteration of the
2397 /// subexpressions. This is currently used for CFG construction.
2398 ArrayRef<Stmt*> getRawSubExprs() {
2399 return llvm::makeArrayRef(SubExprs,
2400 getNumPreArgs() + PREARGS_START + getNumArgs());
2401 }
2402
2403 /// getNumCommas - Return the number of commas that must have been present in
2404 /// this function call.
2405 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2406
2407 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2408 /// of the callee. If not, return 0.
2409 unsigned getBuiltinCallee() const;
2410
2411 /// Returns \c true if this is a call to a builtin which does not
2412 /// evaluate side-effects within its arguments.
2413 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2414
2415 /// getCallReturnType - Get the return type of the call expr. This is not
2416 /// always the type of the expr itself, if the return type is a reference
2417 /// type.
2418 QualType getCallReturnType(const ASTContext &Ctx) const;
2419
2420 SourceLocation getRParenLoc() const { return RParenLoc; }
2421 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2422
2423 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__));
2424 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__));
2425
2426 /// Return true if this is a call to __assume() or __builtin_assume() with
2427 /// a non-value-dependent constant parameter evaluating as false.
2428 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
2429
2430 bool isCallToStdMove() const {
2431 const FunctionDecl* FD = getDirectCallee();
2432 return getNumArgs() == 1 && FD && FD->isInStdNamespace() &&
2433 FD->getIdentifier() && FD->getIdentifier()->isStr("move");
2434 }
2435
2436 static bool classof(const Stmt *T) {
2437 return T->getStmtClass() >= firstCallExprConstant &&
2438 T->getStmtClass() <= lastCallExprConstant;
2439 }
2440
2441 // Iterators
2442 child_range children() {
2443 return child_range(&SubExprs[0],
2444 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2445 }
2446
2447 const_child_range children() const {
2448 return const_child_range(&SubExprs[0], &SubExprs[0] + NumArgs +
2449 getNumPreArgs() + PREARGS_START);
2450 }
2451};
2452
2453/// Extra data stored in some MemberExpr objects.
2454struct MemberExprNameQualifier {
2455 /// The nested-name-specifier that qualifies the name, including
2456 /// source-location information.
2457 NestedNameSpecifierLoc QualifierLoc;
2458
2459 /// The DeclAccessPair through which the MemberDecl was found due to
2460 /// name qualifiers.
2461 DeclAccessPair FoundDecl;
2462};
2463
2464/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2465///
2466class MemberExpr final
2467 : public Expr,
2468 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2469 ASTTemplateKWAndArgsInfo,
2470 TemplateArgumentLoc> {
2471 /// Base - the expression for the base pointer or structure references. In
2472 /// X.F, this is "X".
2473 Stmt *Base;
2474
2475 /// MemberDecl - This is the decl being referenced by the field/member name.
2476 /// In X.F, this is the decl referenced by F.
2477 ValueDecl *MemberDecl;
2478
2479 /// MemberDNLoc - Provides source/type location info for the
2480 /// declaration name embedded in MemberDecl.
2481 DeclarationNameLoc MemberDNLoc;
2482
2483 /// MemberLoc - This is the location of the member name.
2484 SourceLocation MemberLoc;
2485
2486 /// This is the location of the -> or . in the expression.
2487 SourceLocation OperatorLoc;
2488
2489 /// IsArrow - True if this is "X->F", false if this is "X.F".
2490 bool IsArrow : 1;
2491
2492 /// True if this member expression used a nested-name-specifier to
2493 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2494 /// declaration. When true, a MemberExprNameQualifier
2495 /// structure is allocated immediately after the MemberExpr.
2496 bool HasQualifierOrFoundDecl : 1;
2497
2498 /// True if this member expression specified a template keyword
2499 /// and/or a template argument list explicitly, e.g., x->f<int>,
2500 /// x->template f, x->template f<int>.
2501 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2502 /// TemplateArguments (if any) are present.
2503 bool HasTemplateKWAndArgsInfo : 1;
2504
2505 /// True if this member expression refers to a method that
2506 /// was resolved from an overloaded set having size greater than 1.
2507 bool HadMultipleCandidates : 1;
2508
2509 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2510 return HasQualifierOrFoundDecl ? 1 : 0;
2511 }
2512
2513 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2514 return HasTemplateKWAndArgsInfo ? 1 : 0;
2515 }
2516
2517public:
2518 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2519 ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2520 QualType ty, ExprValueKind VK, ExprObjectKind OK)
2521 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2522 base->isValueDependent(), base->isInstantiationDependent(),
2523 base->containsUnexpandedParameterPack()),
2524 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2525 MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2526 IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2527 HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2528 assert(memberdecl->getDeclName() == NameInfo.getName())(static_cast <bool> (memberdecl->getDeclName() == NameInfo
.getName()) ? void (0) : __assert_fail ("memberdecl->getDeclName() == NameInfo.getName()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2528, __extension__ __PRETTY_FUNCTION__))
;
2529 }
2530
2531 // NOTE: this constructor should be used only when it is known that
2532 // the member name can not provide additional syntactic info
2533 // (i.e., source locations for C++ operator names or type source info
2534 // for constructors, destructors and conversion operators).
2535 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2536 ValueDecl *memberdecl, SourceLocation l, QualType ty,
2537 ExprValueKind VK, ExprObjectKind OK)
2538 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2539 base->isValueDependent(), base->isInstantiationDependent(),
2540 base->containsUnexpandedParameterPack()),
2541 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2542 OperatorLoc(operatorloc), IsArrow(isarrow),
2543 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2544 HadMultipleCandidates(false) {}
2545
2546 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2547 SourceLocation OperatorLoc,
2548 NestedNameSpecifierLoc QualifierLoc,
2549 SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2550 DeclAccessPair founddecl,
2551 DeclarationNameInfo MemberNameInfo,
2552 const TemplateArgumentListInfo *targs, QualType ty,
2553 ExprValueKind VK, ExprObjectKind OK);
2554
2555 void setBase(Expr *E) { Base = E; }
2556 Expr *getBase() const { return cast<Expr>(Base); }
2557
2558 /// Retrieve the member declaration to which this expression refers.
2559 ///
2560 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
2561 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
2562 ValueDecl *getMemberDecl() const { return MemberDecl; }
2563 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2564
2565 /// Retrieves the declaration found by lookup.
2566 DeclAccessPair getFoundDecl() const {
2567 if (!HasQualifierOrFoundDecl)
2568 return DeclAccessPair::make(getMemberDecl(),
2569 getMemberDecl()->getAccess());
2570 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2571 }
2572
2573 /// Determines whether this member expression actually had
2574 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2575 /// x->Base::foo.
2576 bool hasQualifier() const { return getQualifier() != nullptr; }
2577
2578 /// If the member name was qualified, retrieves the
2579 /// nested-name-specifier that precedes the member name, with source-location
2580 /// information.
2581 NestedNameSpecifierLoc getQualifierLoc() const {
2582 if (!HasQualifierOrFoundDecl)
2583 return NestedNameSpecifierLoc();
2584
2585 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2586 }
2587
2588 /// If the member name was qualified, retrieves the
2589 /// nested-name-specifier that precedes the member name. Otherwise, returns
2590 /// NULL.
2591 NestedNameSpecifier *getQualifier() const {
2592 return getQualifierLoc().getNestedNameSpecifier();
2593 }
2594
2595 /// Retrieve the location of the template keyword preceding
2596 /// the member name, if any.
2597 SourceLocation getTemplateKeywordLoc() const {
2598 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2599 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2600 }
2601
2602 /// Retrieve the location of the left angle bracket starting the
2603 /// explicit template argument list following the member name, if any.
2604 SourceLocation getLAngleLoc() const {
2605 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2606 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2607 }
2608
2609 /// Retrieve the location of the right angle bracket ending the
2610 /// explicit template argument list following the member name, if any.
2611 SourceLocation getRAngleLoc() const {
2612 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2613 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2614 }
2615
2616 /// Determines whether the member name was preceded by the template keyword.
2617 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2618
2619 /// Determines whether the member name was followed by an
2620 /// explicit template argument list.
2621 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2622
2623 /// Copies the template arguments (if present) into the given
2624 /// structure.
2625 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2626 if (hasExplicitTemplateArgs())
2627 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2628 getTrailingObjects<TemplateArgumentLoc>(), List);
2629 }
2630
2631 /// Retrieve the template arguments provided as part of this
2632 /// template-id.
2633 const TemplateArgumentLoc *getTemplateArgs() const {
2634 if (!hasExplicitTemplateArgs())
2635 return nullptr;
2636
2637 return getTrailingObjects<TemplateArgumentLoc>();
2638 }
2639
2640 /// Retrieve the number of template arguments provided as part of this
2641 /// template-id.
2642 unsigned getNumTemplateArgs() const {
2643 if (!hasExplicitTemplateArgs())
2644 return 0;
2645
2646 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2647 }
2648
2649 ArrayRef<TemplateArgumentLoc> template_arguments() const {
2650 return {getTemplateArgs(), getNumTemplateArgs()};
2651 }
2652
2653 /// Retrieve the member declaration name info.
2654 DeclarationNameInfo getMemberNameInfo() const {
2655 return DeclarationNameInfo(MemberDecl->getDeclName(),
2656 MemberLoc, MemberDNLoc);
2657 }
2658
2659 SourceLocation getOperatorLoc() const LLVM_READONLY__attribute__((__pure__)) { return OperatorLoc; }
2660
2661 bool isArrow() const { return IsArrow; }
2662 void setArrow(bool A) { IsArrow = A; }
2663
2664 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2665 /// location of 'F'.
2666 SourceLocation getMemberLoc() const { return MemberLoc; }
2667 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2668
2669 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__));
2670 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__));
2671
2672 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { return MemberLoc; }
2673
2674 /// Determine whether the base of this explicit is implicit.
2675 bool isImplicitAccess() const {
2676 return getBase() && getBase()->isImplicitCXXThis();
2677 }
2678
2679 /// Returns true if this member expression refers to a method that
2680 /// was resolved from an overloaded set having size greater than 1.
2681 bool hadMultipleCandidates() const {
2682 return HadMultipleCandidates;
2683 }
2684 /// Sets the flag telling whether this expression refers to
2685 /// a method that was resolved from an overloaded set having size
2686 /// greater than 1.
2687 void setHadMultipleCandidates(bool V = true) {
2688 HadMultipleCandidates = V;
2689 }
2690
2691 /// Returns true if virtual dispatch is performed.
2692 /// If the member access is fully qualified, (i.e. X::f()), virtual
2693 /// dispatching is not performed. In -fapple-kext mode qualified
2694 /// calls to virtual method will still go through the vtable.
2695 bool performsVirtualDispatch(const LangOptions &LO) const {
2696 return LO.AppleKext || !hasQualifier();
2697 }
2698
2699 static bool classof(const Stmt *T) {
2700 return T->getStmtClass() == MemberExprClass;
2701 }
2702
2703 // Iterators
2704 child_range children() { return child_range(&Base, &Base+1); }
2705 const_child_range children() const {
2706 return const_child_range(&Base, &Base + 1);
2707 }
2708
2709 friend TrailingObjects;
2710 friend class ASTReader;
2711 friend class ASTStmtWriter;
2712};
2713
2714/// CompoundLiteralExpr - [C99 6.5.2.5]
2715///
2716class CompoundLiteralExpr : public Expr {
2717 /// LParenLoc - If non-null, this is the location of the left paren in a
2718 /// compound literal like "(int){4}". This can be null if this is a
2719 /// synthesized compound expression.
2720 SourceLocation LParenLoc;
2721
2722 /// The type as written. This can be an incomplete array type, in
2723 /// which case the actual expression type will be different.
2724 /// The int part of the pair stores whether this expr is file scope.
2725 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2726 Stmt *Init;
2727public:
2728 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2729 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2730 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2731 tinfo->getType()->isDependentType(),
2732 init->isValueDependent(),
2733 (init->isInstantiationDependent() ||
2734 tinfo->getType()->isInstantiationDependentType()),
2735 init->containsUnexpandedParameterPack()),
2736 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2737
2738 /// Construct an empty compound literal.
2739 explicit CompoundLiteralExpr(EmptyShell Empty)
2740 : Expr(CompoundLiteralExprClass, Empty) { }
2741
2742 const Expr *getInitializer() const { return cast<Expr>(Init); }
2743 Expr *getInitializer() { return cast<Expr>(Init); }
2744 void setInitializer(Expr *E) { Init = E; }
2745
2746 bool isFileScope() const { return TInfoAndScope.getInt(); }
2747 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2748
2749 SourceLocation getLParenLoc() const { return LParenLoc; }
2750 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2751
2752 TypeSourceInfo *getTypeSourceInfo() const {
2753 return TInfoAndScope.getPointer();
2754 }
2755 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2756 TInfoAndScope.setPointer(tinfo);
2757 }
2758
2759 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
2760 // FIXME: Init should never be null.
2761 if (!Init)
2762 return SourceLocation();
2763 if (LParenLoc.isInvalid())
2764 return Init->getLocStart();
2765 return LParenLoc;
2766 }
2767 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
2768 // FIXME: Init should never be null.
2769 if (!Init)
2770 return SourceLocation();
2771 return Init->getLocEnd();
2772 }
2773
2774 static bool classof(const Stmt *T) {
2775 return T->getStmtClass() == CompoundLiteralExprClass;
2776 }
2777
2778 // Iterators
2779 child_range children() { return child_range(&Init, &Init+1); }
2780 const_child_range children() const {
2781 return const_child_range(&Init, &Init + 1);
2782 }
2783};
2784
2785/// CastExpr - Base class for type casts, including both implicit
2786/// casts (ImplicitCastExpr) and explicit casts that have some
2787/// representation in the source code (ExplicitCastExpr's derived
2788/// classes).
2789class CastExpr : public Expr {
2790private:
2791 Stmt *Op;
2792
2793 bool CastConsistency() const;
2794
2795 const CXXBaseSpecifier * const *path_buffer() const {
2796 return const_cast<CastExpr*>(this)->path_buffer();
2797 }
2798 CXXBaseSpecifier **path_buffer();
2799
2800 void setBasePathSize(unsigned basePathSize) {
2801 CastExprBits.BasePathSize = basePathSize;
2802 assert(CastExprBits.BasePathSize == basePathSize &&(static_cast <bool> (CastExprBits.BasePathSize == basePathSize
&& "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!"
) ? void (0) : __assert_fail ("CastExprBits.BasePathSize == basePathSize && \"basePathSize doesn't fit in bits of CastExprBits.BasePathSize!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2803, __extension__ __PRETTY_FUNCTION__))
2803 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!")(static_cast <bool> (CastExprBits.BasePathSize == basePathSize
&& "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!"
) ? void (0) : __assert_fail ("CastExprBits.BasePathSize == basePathSize && \"basePathSize doesn't fit in bits of CastExprBits.BasePathSize!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2803, __extension__ __PRETTY_FUNCTION__))
;
2804 }
2805
2806protected:
2807 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2808 Expr *op, unsigned BasePathSize)
2809 : Expr(SC, ty, VK, OK_Ordinary,
2810 // Cast expressions are type-dependent if the type is
2811 // dependent (C++ [temp.dep.expr]p3).
2812 ty->isDependentType(),
2813 // Cast expressions are value-dependent if the type is
2814 // dependent or if the subexpression is value-dependent.
2815 ty->isDependentType() || (op && op->isValueDependent()),
2816 (ty->isInstantiationDependentType() ||
2817 (op && op->isInstantiationDependent())),
2818 // An implicit cast expression doesn't (lexically) contain an
2819 // unexpanded pack, even if its target type does.
2820 ((SC != ImplicitCastExprClass &&
2821 ty->containsUnexpandedParameterPack()) ||
2822 (op && op->containsUnexpandedParameterPack()))),
2823 Op(op) {
2824 CastExprBits.Kind = kind;
2825 CastExprBits.PartOfExplicitCast = false;
2826 setBasePathSize(BasePathSize);
2827 assert(CastConsistency())(static_cast <bool> (CastConsistency()) ? void (0) : __assert_fail
("CastConsistency()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2827, __extension__ __PRETTY_FUNCTION__))
;
2828 }
2829
2830 /// Construct an empty cast.
2831 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2832 : Expr(SC, Empty) {
2833 CastExprBits.PartOfExplicitCast = false;
2834 setBasePathSize(BasePathSize);
2835 }
2836
2837public:
2838 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2839 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2840
2841 static const char *getCastKindName(CastKind CK);
2842 const char *getCastKindName() const { return getCastKindName(getCastKind()); }
2843
2844 Expr *getSubExpr() { return cast<Expr>(Op); }
2845 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2846 void setSubExpr(Expr *E) { Op = E; }
2847
2848 /// Retrieve the cast subexpression as it was written in the source
2849 /// code, looking through any implicit casts or other intermediate nodes
2850 /// introduced by semantic analysis.
2851 Expr *getSubExprAsWritten();
2852 const Expr *getSubExprAsWritten() const {
2853 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2854 }
2855
2856 /// If this cast applies a user-defined conversion, retrieve the conversion
2857 /// function that it invokes.
2858 NamedDecl *getConversionFunction() const;
2859
2860 typedef CXXBaseSpecifier **path_iterator;
2861 typedef const CXXBaseSpecifier * const *path_const_iterator;
2862 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2863 unsigned path_size() const { return CastExprBits.BasePathSize; }
2864 path_iterator path_begin() { return path_buffer(); }
2865 path_iterator path_end() { return path_buffer() + path_size(); }
2866 path_const_iterator path_begin() const { return path_buffer(); }
2867 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2868
2869 const FieldDecl *getTargetUnionField() const {
2870 assert(getCastKind() == CK_ToUnion)(static_cast <bool> (getCastKind() == CK_ToUnion) ? void
(0) : __assert_fail ("getCastKind() == CK_ToUnion", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 2870, __extension__ __PRETTY_FUNCTION__))
;
2871 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
2872 }
2873
2874 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
2875 QualType opType);
2876 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
2877 QualType opType);
2878
2879 static bool classof(const Stmt *T) {
2880 return T->getStmtClass() >= firstCastExprConstant &&
2881 T->getStmtClass() <= lastCastExprConstant;
2882 }
2883
2884 // Iterators
2885 child_range children() { return child_range(&Op, &Op+1); }
2886 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
2887};
2888
2889/// ImplicitCastExpr - Allows us to explicitly represent implicit type
2890/// conversions, which have no direct representation in the original
2891/// source code. For example: converting T[]->T*, void f()->void
2892/// (*f)(), float->double, short->int, etc.
2893///
2894/// In C, implicit casts always produce rvalues. However, in C++, an
2895/// implicit cast whose result is being bound to a reference will be
2896/// an lvalue or xvalue. For example:
2897///
2898/// @code
2899/// class Base { };
2900/// class Derived : public Base { };
2901/// Derived &&ref();
2902/// void f(Derived d) {
2903/// Base& b = d; // initializer is an ImplicitCastExpr
2904/// // to an lvalue of type Base
2905/// Base&& r = ref(); // initializer is an ImplicitCastExpr
2906/// // to an xvalue of type Base
2907/// }
2908/// @endcode
2909class ImplicitCastExpr final
2910 : public CastExpr,
2911 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
2912private:
2913 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2914 unsigned BasePathLength, ExprValueKind VK)
2915 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2916 }
2917
2918 /// Construct an empty implicit cast.
2919 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2920 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2921
2922public:
2923 enum OnStack_t { OnStack };
2924 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2925 ExprValueKind VK)
2926 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2927 }
2928
2929 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
2930 void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
2931 CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
2932 }
2933
2934 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2935 CastKind Kind, Expr *Operand,
2936 const CXXCastPath *BasePath,
2937 ExprValueKind Cat);
2938
2939 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2940 unsigned PathSize);
2941
2942 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
2943 return getSubExpr()->getLocStart();
2944 }
2945 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
2946 return getSubExpr()->getLocEnd();
2947 }
2948
2949 static bool classof(const Stmt *T) {
2950 return T->getStmtClass() == ImplicitCastExprClass;
2951 }
2952
2953 friend TrailingObjects;
2954 friend class CastExpr;
2955};
2956
2957inline Expr *Expr::IgnoreImpCasts() {
2958 Expr *e = this;
2959 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2960 e = ice->getSubExpr();
2961 return e;
2962}
2963
2964/// ExplicitCastExpr - An explicit cast written in the source
2965/// code.
2966///
2967/// This class is effectively an abstract class, because it provides
2968/// the basic representation of an explicitly-written cast without
2969/// specifying which kind of cast (C cast, functional cast, static
2970/// cast, etc.) was written; specific derived classes represent the
2971/// particular style of cast and its location information.
2972///
2973/// Unlike implicit casts, explicit cast nodes have two different
2974/// types: the type that was written into the source code, and the
2975/// actual type of the expression as determined by semantic
2976/// analysis. These types may differ slightly. For example, in C++ one
2977/// can cast to a reference type, which indicates that the resulting
2978/// expression will be an lvalue or xvalue. The reference type, however,
2979/// will not be used as the type of the expression.
2980class ExplicitCastExpr : public CastExpr {
2981 /// TInfo - Source type info for the (written) type
2982 /// this expression is casting to.
2983 TypeSourceInfo *TInfo;
2984
2985protected:
2986 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2987 CastKind kind, Expr *op, unsigned PathSize,
2988 TypeSourceInfo *writtenTy)
2989 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2990
2991 /// Construct an empty explicit cast.
2992 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2993 : CastExpr(SC, Shell, PathSize) { }
2994
2995public:
2996 /// getTypeInfoAsWritten - Returns the type source info for the type
2997 /// that this expression is casting to.
2998 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2999 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3000
3001 /// getTypeAsWritten - Returns the type that this expression is
3002 /// casting to, as written in the source code.
3003 QualType getTypeAsWritten() const { return TInfo->getType(); }
3004
3005 static bool classof(const Stmt *T) {
3006 return T->getStmtClass() >= firstExplicitCastExprConstant &&
3007 T->getStmtClass() <= lastExplicitCastExprConstant;
3008 }
3009};
3010
3011/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3012/// cast in C++ (C++ [expr.cast]), which uses the syntax
3013/// (Type)expr. For example: @c (int)f.
3014class CStyleCastExpr final
3015 : public ExplicitCastExpr,
3016 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
3017 SourceLocation LPLoc; // the location of the left paren
3018 SourceLocation RPLoc; // the location of the right paren
3019
3020 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3021 unsigned PathSize, TypeSourceInfo *writtenTy,
3022 SourceLocation l, SourceLocation r)
3023 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3024 writtenTy), LPLoc(l), RPLoc(r) {}
3025
3026 /// Construct an empty C-style explicit cast.
3027 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
3028 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
3029
3030public:
3031 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
3032 ExprValueKind VK, CastKind K,
3033 Expr *Op, const CXXCastPath *BasePath,
3034 TypeSourceInfo *WrittenTy, SourceLocation L,
3035 SourceLocation R);
3036
3037 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3038 unsigned PathSize);
3039
3040 SourceLocation getLParenLoc() const { return LPLoc; }
3041 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3042
3043 SourceLocation getRParenLoc() const { return RPLoc; }
3044 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3045
3046 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LPLoc; }
3047 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
3048 return getSubExpr()->getLocEnd();
3049 }
3050
3051 static bool classof(const Stmt *T) {
3052 return T->getStmtClass() == CStyleCastExprClass;
3053 }
3054
3055 friend TrailingObjects;
3056 friend class CastExpr;
3057};
3058
3059/// A builtin binary operation expression such as "x + y" or "x <= y".
3060///
3061/// This expression node kind describes a builtin binary operation,
3062/// such as "x + y" for integer values "x" and "y". The operands will
3063/// already have been converted to appropriate types (e.g., by
3064/// performing promotions or conversions).
3065///
3066/// In C++, where operators may be overloaded, a different kind of
3067/// expression node (CXXOperatorCallExpr) is used to express the
3068/// invocation of an overloaded operator with operator syntax. Within
3069/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3070/// used to store an expression "x + y" depends on the subexpressions
3071/// for x and y. If neither x or y is type-dependent, and the "+"
3072/// operator resolves to a built-in operation, BinaryOperator will be
3073/// used to express the computation (x and y may still be
3074/// value-dependent). If either x or y is type-dependent, or if the
3075/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3076/// be used to express the computation.
3077class BinaryOperator : public Expr {
3078public:
3079 typedef BinaryOperatorKind Opcode;
3080
3081private:
3082 unsigned Opc : 6;
3083
3084 // This is only meaningful for operations on floating point types and 0
3085 // otherwise.
3086 unsigned FPFeatures : 2;
3087 SourceLocation OpLoc;
3088
3089 enum { LHS, RHS, END_EXPR };
3090 Stmt* SubExprs[END_EXPR];
3091public:
3092
3093 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3094 ExprValueKind VK, ExprObjectKind OK,
3095 SourceLocation opLoc, FPOptions FPFeatures)
3096 : Expr(BinaryOperatorClass, ResTy, VK, OK,
3097 lhs->isTypeDependent() || rhs->isTypeDependent(),
3098 lhs->isValueDependent() || rhs->isValueDependent(),
3099 (lhs->isInstantiationDependent() ||
3100 rhs->isInstantiationDependent()),
3101 (lhs->containsUnexpandedParameterPack() ||
3102 rhs->containsUnexpandedParameterPack())),
3103 Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3104 SubExprs[LHS] = lhs;
3105 SubExprs[RHS] = rhs;
3106 assert(!isCompoundAssignmentOp() &&(static_cast <bool> (!isCompoundAssignmentOp() &&
"Use CompoundAssignOperator for compound assignments") ? void
(0) : __assert_fail ("!isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 3107, __extension__ __PRETTY_FUNCTION__))
3107 "Use CompoundAssignOperator for compound assignments")(static_cast <bool> (!isCompoundAssignmentOp() &&
"Use CompoundAssignOperator for compound assignments") ? void
(0) : __assert_fail ("!isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 3107, __extension__ __PRETTY_FUNCTION__))
;
3108 }
3109
3110 /// Construct an empty binary operator.
3111 explicit BinaryOperator(EmptyShell Empty)
3112 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
3113
3114 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { return OpLoc; }
3115 SourceLocation getOperatorLoc() const { return OpLoc; }
3116 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
3117
3118 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
3119 void setOpcode(Opcode O) { Opc = O; }
3120
3121 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3122 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3123 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3124 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3125
3126 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
3127 return getLHS()->getLocStart();
3128 }
3129 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
3130 return getRHS()->getLocEnd();
3131 }
3132
3133 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3134 /// corresponds to, e.g. "<<=".
3135 static StringRef getOpcodeStr(Opcode Op);
3136
3137 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3138
3139 /// Retrieve the binary opcode that corresponds to the given
3140 /// overloaded operator.
3141 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3142
3143 /// Retrieve the overloaded operator kind that corresponds to
3144 /// the given binary opcode.
3145 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3146
3147 /// predicates to categorize the respective opcodes.
3148 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
3149 static bool isMultiplicativeOp(Opcode Opc) {
3150 return Opc >= BO_Mul && Opc <= BO_Rem;
3151 }
3152 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
3153 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3154 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3155 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3156 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3157
3158 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3159 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3160
3161 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3162 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3163
3164 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3165 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3166
3167 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
3168 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3169
3170 static Opcode negateComparisonOp(Opcode Opc) {
3171 switch (Opc) {
3172 default:
3173 llvm_unreachable("Not a comparison operator.")::llvm::llvm_unreachable_internal("Not a comparison operator."
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 3173)
;
3174 case BO_LT: return BO_GE;
3175 case BO_GT: return BO_LE;
3176 case BO_LE: return BO_GT;
3177 case BO_GE: return BO_LT;
3178 case BO_EQ: return BO_NE;
3179 case BO_NE: return BO_EQ;
3180 }
3181 }
3182
3183 static Opcode reverseComparisonOp(Opcode Opc) {
3184 switch (Opc) {
3185 default:
3186 llvm_unreachable("Not a comparison operator.")::llvm::llvm_unreachable_internal("Not a comparison operator."
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 3186)
;
3187 case BO_LT: return BO_GT;
3188 case BO_GT: return BO_LT;
3189 case BO_LE: return BO_GE;
3190 case BO_GE: return BO_LE;
3191 case BO_EQ:
3192 case BO_NE:
3193 return Opc;
3194 }
3195 }
3196
3197 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3198 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3199
3200 static bool isAssignmentOp(Opcode Opc) {
3201 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3202 }
3203 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3204
3205 static bool isCompoundAssignmentOp(Opcode Opc) {
3206 return Opc > BO_Assign && Opc <= BO_OrAssign;
3207 }
3208 bool isCompoundAssignmentOp() const {
3209 return isCompoundAssignmentOp(getOpcode());
3210 }
3211 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3212 assert(isCompoundAssignmentOp(Opc))(static_cast <bool> (isCompoundAssignmentOp(Opc)) ? void
(0) : __assert_fail ("isCompoundAssignmentOp(Opc)", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 3212, __extension__ __PRETTY_FUNCTION__))
;
3213 if (Opc >= BO_AndAssign)
3214 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3215 else
3216 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3217 }
3218
3219 static bool isShiftAssignOp(Opcode Opc) {
3220 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3221 }
3222 bool isShiftAssignOp() const {
3223 return isShiftAssignOp(getOpcode());
3224 }
3225
3226 // Return true if a binary operator using the specified opcode and operands
3227 // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3228 // integer to a pointer.
3229 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3230 Expr *LHS, Expr *RHS);
3231
3232 static bool classof(const Stmt *S) {
3233 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3234 S->getStmtClass() <= lastBinaryOperatorConstant;
3235 }
3236
3237 // Iterators
3238 child_range children() {
3239 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3240 }
3241 const_child_range children() const {
3242 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3243 }
3244
3245 // Set the FP contractability status of this operator. Only meaningful for
3246 // operations on floating point types.
3247 void setFPFeatures(FPOptions F) { FPFeatures = F.getInt(); }
3248
3249 FPOptions getFPFeatures() const { return FPOptions(FPFeatures); }
3250
3251 // Get the FP contractability status of this operator. Only meaningful for
3252 // operations on floating point types.
3253 bool isFPContractableWithinStatement() const {
3254 return FPOptions(FPFeatures).allowFPContractWithinStatement();
3255 }
3256
3257protected:
3258 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3259 ExprValueKind VK, ExprObjectKind OK,
3260 SourceLocation opLoc, FPOptions FPFeatures, bool dead2)
3261 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3262 lhs->isTypeDependent() || rhs->isTypeDependent(),
3263 lhs->isValueDependent() || rhs->isValueDependent(),
3264 (lhs->isInstantiationDependent() ||
3265 rhs->isInstantiationDependent()),
3266 (lhs->containsUnexpandedParameterPack() ||
3267 rhs->containsUnexpandedParameterPack())),
3268 Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3269 SubExprs[LHS] = lhs;
3270 SubExprs[RHS] = rhs;
3271 }
3272
3273 BinaryOperator(StmtClass SC, EmptyShell Empty)
3274 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3275};
3276
3277/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3278/// track of the type the operation is performed in. Due to the semantics of
3279/// these operators, the operands are promoted, the arithmetic performed, an
3280/// implicit conversion back to the result type done, then the assignment takes
3281/// place. This captures the intermediate type which the computation is done
3282/// in.
3283class CompoundAssignOperator : public BinaryOperator {
3284 QualType ComputationLHSType;
3285 QualType ComputationResultType;
3286public:
3287 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3288 ExprValueKind VK, ExprObjectKind OK,
3289 QualType CompLHSType, QualType CompResultType,
3290 SourceLocation OpLoc, FPOptions FPFeatures)
3291 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
3292 true),
3293 ComputationLHSType(CompLHSType),
3294 ComputationResultType(CompResultType) {
3295 assert(isCompoundAssignmentOp() &&(static_cast <bool> (isCompoundAssignmentOp() &&
"Only should be used for compound assignments") ? void (0) :
__assert_fail ("isCompoundAssignmentOp() && \"Only should be used for compound assignments\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 3296, __extension__ __PRETTY_FUNCTION__))
3296 "Only should be used for compound assignments")(static_cast <bool> (isCompoundAssignmentOp() &&
"Only should be used for compound assignments") ? void (0) :
__assert_fail ("isCompoundAssignmentOp() && \"Only should be used for compound assignments\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 3296, __extension__ __PRETTY_FUNCTION__))
;
3297 }
3298
3299 /// Build an empty compound assignment operator expression.
3300 explicit CompoundAssignOperator(EmptyShell Empty)
3301 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3302
3303 // The two computation types are the type the LHS is converted
3304 // to for the computation and the type of the result; the two are
3305 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3306 QualType getComputationLHSType() const { return ComputationLHSType; }
3307 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3308
3309 QualType getComputationResultType() const { return ComputationResultType; }
3310 void setComputationResultType(QualType T) { ComputationResultType = T; }
3311
3312 static bool classof(const Stmt *S) {
3313 return S->getStmtClass() == CompoundAssignOperatorClass;
3314 }
3315};
3316
3317/// AbstractConditionalOperator - An abstract base class for
3318/// ConditionalOperator and BinaryConditionalOperator.
3319class AbstractConditionalOperator : public Expr {
3320 SourceLocation QuestionLoc, ColonLoc;
3321 friend class ASTStmtReader;
3322
3323protected:
3324 AbstractConditionalOperator(StmtClass SC, QualType T,
3325 ExprValueKind VK, ExprObjectKind OK,
3326 bool TD, bool VD, bool ID,
3327 bool ContainsUnexpandedParameterPack,
3328 SourceLocation qloc,
3329 SourceLocation cloc)
3330 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3331 QuestionLoc(qloc), ColonLoc(cloc) {}
3332
3333 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3334 : Expr(SC, Empty) { }
3335
3336public:
3337 // getCond - Return the expression representing the condition for
3338 // the ?: operator.
3339 Expr *getCond() const;
3340
3341 // getTrueExpr - Return the subexpression representing the value of
3342 // the expression if the condition evaluates to true.
3343 Expr *getTrueExpr() const;
3344
3345 // getFalseExpr - Return the subexpression representing the value of
3346 // the expression if the condition evaluates to false. This is
3347 // the same as getRHS.
3348 Expr *getFalseExpr() const;
3349
3350 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3351 SourceLocation getColonLoc() const { return ColonLoc; }
3352
3353 static bool classof(const Stmt *T) {
3354 return T->getStmtClass() == ConditionalOperatorClass ||
3355 T->getStmtClass() == BinaryConditionalOperatorClass;
3356 }
3357};
3358
3359/// ConditionalOperator - The ?: ternary operator. The GNU "missing
3360/// middle" extension is a BinaryConditionalOperator.
3361class ConditionalOperator : public AbstractConditionalOperator {
3362 enum { COND, LHS, RHS, END_EXPR };
3363 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3364
3365 friend class ASTStmtReader;
3366public:
3367 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3368 SourceLocation CLoc, Expr *rhs,
3369 QualType t, ExprValueKind VK, ExprObjectKind OK)
3370 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3371 // FIXME: the type of the conditional operator doesn't
3372 // depend on the type of the conditional, but the standard
3373 // seems to imply that it could. File a bug!
3374 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3375 (cond->isValueDependent() || lhs->isValueDependent() ||
3376 rhs->isValueDependent()),
3377 (cond->isInstantiationDependent() ||
3378 lhs->isInstantiationDependent() ||
3379 rhs->isInstantiationDependent()),
3380 (cond->containsUnexpandedParameterPack() ||
3381 lhs->containsUnexpandedParameterPack() ||
3382 rhs->containsUnexpandedParameterPack()),
3383 QLoc, CLoc) {
3384 SubExprs[COND] = cond;
3385 SubExprs[LHS] = lhs;
3386 SubExprs[RHS] = rhs;
3387 }
3388
3389 /// Build an empty conditional operator.
3390 explicit ConditionalOperator(EmptyShell Empty)
3391 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3392
3393 // getCond - Return the expression representing the condition for
3394 // the ?: operator.
3395 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3396
3397 // getTrueExpr - Return the subexpression representing the value of
3398 // the expression if the condition evaluates to true.
3399 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3400
3401 // getFalseExpr - Return the subexpression representing the value of
3402 // the expression if the condition evaluates to false. This is
3403 // the same as getRHS.
3404 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3405
3406 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3407 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3408
3409 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
3410 return getCond()->getLocStart();
3411 }
3412 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
3413 return getRHS()->getLocEnd();
3414 }
3415
3416 static bool classof(const Stmt *T) {
3417 return T->getStmtClass() == ConditionalOperatorClass;
3418 }
3419
3420 // Iterators
3421 child_range children() {
3422 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3423 }
3424 const_child_range children() const {
3425 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3426 }
3427};
3428
3429/// BinaryConditionalOperator - The GNU extension to the conditional
3430/// operator which allows the middle operand to be omitted.
3431///
3432/// This is a different expression kind on the assumption that almost
3433/// every client ends up needing to know that these are different.
3434class BinaryConditionalOperator : public AbstractConditionalOperator {
3435 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3436
3437 /// - the common condition/left-hand-side expression, which will be
3438 /// evaluated as the opaque value
3439 /// - the condition, expressed in terms of the opaque value
3440 /// - the left-hand-side, expressed in terms of the opaque value
3441 /// - the right-hand-side
3442 Stmt *SubExprs[NUM_SUBEXPRS];
3443 OpaqueValueExpr *OpaqueValue;
3444
3445 friend class ASTStmtReader;
3446public:
3447 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3448 Expr *cond, Expr *lhs, Expr *rhs,
3449 SourceLocation qloc, SourceLocation cloc,
3450 QualType t, ExprValueKind VK, ExprObjectKind OK)
3451 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3452 (common->isTypeDependent() || rhs->isTypeDependent()),
3453 (common->isValueDependent() || rhs->isValueDependent()),
3454 (common->isInstantiationDependent() ||
3455 rhs->isInstantiationDependent()),
3456 (common->containsUnexpandedParameterPack() ||
3457 rhs->containsUnexpandedParameterPack()),
3458 qloc, cloc),
3459 OpaqueValue(opaqueValue) {
3460 SubExprs[COMMON] = common;
3461 SubExprs[COND] = cond;
3462 SubExprs[LHS] = lhs;
3463 SubExprs[RHS] = rhs;
3464 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value")(static_cast <bool> (OpaqueValue->getSourceExpr() ==
common && "Wrong opaque value") ? void (0) : __assert_fail
("OpaqueValue->getSourceExpr() == common && \"Wrong opaque value\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 3464, __extension__ __PRETTY_FUNCTION__))
;
3465 }
3466
3467 /// Build an empty conditional operator.
3468 explicit BinaryConditionalOperator(EmptyShell Empty)
3469 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3470
3471 /// getCommon - Return the common expression, written to the
3472 /// left of the condition. The opaque value will be bound to the
3473 /// result of this expression.
3474 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3475
3476 /// getOpaqueValue - Return the opaque value placeholder.
3477 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3478
3479 /// getCond - Return the condition expression; this is defined
3480 /// in terms of the opaque value.
3481 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3482
3483 /// getTrueExpr - Return the subexpression which will be
3484 /// evaluated if the condition evaluates to true; this is defined
3485 /// in terms of the opaque value.
3486 Expr *getTrueExpr() const {
3487 return cast<Expr>(SubExprs[LHS]);
3488 }
3489
3490 /// getFalseExpr - Return the subexpression which will be
3491 /// evaluated if the condnition evaluates to false; this is
3492 /// defined in terms of the opaque value.
3493 Expr *getFalseExpr() const {
3494 return cast<Expr>(SubExprs[RHS]);
3495 }
3496
3497 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
3498 return getCommon()->getLocStart();
3499 }
3500 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
3501 return getFalseExpr()->getLocEnd();
3502 }
3503
3504 static bool classof(const Stmt *T) {
3505 return T->getStmtClass() == BinaryConditionalOperatorClass;
3506 }
3507
3508 // Iterators
3509 child_range children() {
3510 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3511 }
3512 const_child_range children() const {
3513 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3514 }
3515};
3516
3517inline Expr *AbstractConditionalOperator::getCond() const {
3518 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3519 return co->getCond();
3520 return cast<BinaryConditionalOperator>(this)->getCond();
3521}
3522
3523inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3524 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3525 return co->getTrueExpr();
3526 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3527}
3528
3529inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3530 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3531 return co->getFalseExpr();
3532 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3533}
3534
3535/// AddrLabelExpr - The GNU address of label extension, representing &&label.
3536class AddrLabelExpr : public Expr {
3537 SourceLocation AmpAmpLoc, LabelLoc;
3538 LabelDecl *Label;
3539public:
3540 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3541 QualType t)
3542 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3543 false),
3544 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3545
3546 /// Build an empty address of a label expression.
3547 explicit AddrLabelExpr(EmptyShell Empty)
3548 : Expr(AddrLabelExprClass, Empty) { }
3549
3550 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3551 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3552 SourceLocation getLabelLoc() const { return LabelLoc; }
3553 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3554
3555 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return AmpAmpLoc; }
3556 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return LabelLoc; }
3557
3558 LabelDecl *getLabel() const { return Label; }
3559 void setLabel(LabelDecl *L) { Label = L; }
3560
3561 static bool classof(const Stmt *T) {
3562 return T->getStmtClass() == AddrLabelExprClass;
3563 }
3564
3565 // Iterators
3566 child_range children() {
3567 return child_range(child_iterator(), child_iterator());
3568 }
3569 const_child_range children() const {
3570 return const_child_range(const_child_iterator(), const_child_iterator());
3571 }
3572};
3573
3574/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3575/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3576/// takes the value of the last subexpression.
3577///
3578/// A StmtExpr is always an r-value; values "returned" out of a
3579/// StmtExpr will be copied.
3580class StmtExpr : public Expr {
3581 Stmt *SubStmt;
3582 SourceLocation LParenLoc, RParenLoc;
3583public:
3584 // FIXME: Does type-dependence need to be computed differently?
3585 // FIXME: Do we need to compute instantiation instantiation-dependence for
3586 // statements? (ugh!)
3587 StmtExpr(CompoundStmt *substmt, QualType T,
3588 SourceLocation lp, SourceLocation rp) :
3589 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3590 T->isDependentType(), false, false, false),
3591 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3592
3593 /// Build an empty statement expression.
3594 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3595
3596 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3597 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3598 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3599
3600 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LParenLoc; }
3601 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
3602
3603 SourceLocation getLParenLoc() const { return LParenLoc; }
3604 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3605 SourceLocation getRParenLoc() const { return RParenLoc; }
3606 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3607
3608 static bool classof(const Stmt *T) {
3609 return T->getStmtClass() == StmtExprClass;
3610 }
3611
3612 // Iterators
3613 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3614 const_child_range children() const {
3615 return const_child_range(&SubStmt, &SubStmt + 1);
3616 }
3617};
3618
3619/// ShuffleVectorExpr - clang-specific builtin-in function
3620/// __builtin_shufflevector.
3621/// This AST node represents a operator that does a constant
3622/// shuffle, similar to LLVM's shufflevector instruction. It takes
3623/// two vectors and a variable number of constant indices,
3624/// and returns the appropriately shuffled vector.
3625class ShuffleVectorExpr : public Expr {
3626 SourceLocation BuiltinLoc, RParenLoc;
3627
3628 // SubExprs - the list of values passed to the __builtin_shufflevector
3629 // function. The first two are vectors, and the rest are constant
3630 // indices. The number of values in this list is always
3631 // 2+the number of indices in the vector type.
3632 Stmt **SubExprs;
3633 unsigned NumExprs;
3634
3635public:
3636 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3637 SourceLocation BLoc, SourceLocation RP);
3638
3639 /// Build an empty vector-shuffle expression.
3640 explicit ShuffleVectorExpr(EmptyShell Empty)
3641 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3642
3643 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3644 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3645
3646 SourceLocation getRParenLoc() const { return RParenLoc; }
3647 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3648
3649 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
3650 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
3651
3652 static bool classof(const Stmt *T) {
3653 return T->getStmtClass() == ShuffleVectorExprClass;
3654 }
3655
3656 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3657 /// constant expression, the actual arguments passed in, and the function
3658 /// pointers.
3659 unsigned getNumSubExprs() const { return NumExprs; }
3660
3661 /// Retrieve the array of expressions.
3662 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3663
3664 /// getExpr - Return the Expr at the specified index.
3665 Expr *getExpr(unsigned Index) {
3666 assert((Index < NumExprs) && "Arg access out of range!")(static_cast <bool> ((Index < NumExprs) && "Arg access out of range!"
) ? void (0) : __assert_fail ("(Index < NumExprs) && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 3666, __extension__ __PRETTY_FUNCTION__))
;
3667 return cast<Expr>(SubExprs[Index]);
3668 }
3669 const Expr *getExpr(unsigned Index) const {
3670 assert((Index < NumExprs) && "Arg access out of range!")(static_cast <bool> ((Index < NumExprs) && "Arg access out of range!"
) ? void (0) : __assert_fail ("(Index < NumExprs) && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 3670, __extension__ __PRETTY_FUNCTION__))
;
3671 return cast<Expr>(SubExprs[Index]);
3672 }
3673
3674 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3675
3676 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3677 assert((N < NumExprs - 2) && "Shuffle idx out of range!")(static_cast <bool> ((N < NumExprs - 2) && "Shuffle idx out of range!"
) ? void (0) : __assert_fail ("(N < NumExprs - 2) && \"Shuffle idx out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 3677, __extension__ __PRETTY_FUNCTION__))
;
3678 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3679 }
3680
3681 // Iterators
3682 child_range children() {
3683 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3684 }
3685 const_child_range children() const {
3686 return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
3687 }
3688};
3689
3690/// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3691/// This AST node provides support for converting a vector type to another
3692/// vector type of the same arity.
3693class ConvertVectorExpr : public Expr {
3694private:
3695 Stmt *SrcExpr;
3696 TypeSourceInfo *TInfo;
3697 SourceLocation BuiltinLoc, RParenLoc;
3698
3699 friend class ASTReader;
3700 friend class ASTStmtReader;
3701 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3702
3703public:
3704 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3705 ExprValueKind VK, ExprObjectKind OK,
3706 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3707 : Expr(ConvertVectorExprClass, DstType, VK, OK,
3708 DstType->isDependentType(),
3709 DstType->isDependentType() || SrcExpr->isValueDependent(),
3710 (DstType->isInstantiationDependentType() ||
3711 SrcExpr->isInstantiationDependent()),
3712 (DstType->containsUnexpandedParameterPack() ||
3713 SrcExpr->containsUnexpandedParameterPack())),
3714 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3715
3716 /// getSrcExpr - Return the Expr to be converted.
3717 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3718
3719 /// getTypeSourceInfo - Return the destination type.
3720 TypeSourceInfo *getTypeSourceInfo() const {
3721 return TInfo;
3722 }
3723 void setTypeSourceInfo(TypeSourceInfo *ti) {
3724 TInfo = ti;
3725 }
3726
3727 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
3728 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3729
3730 /// getRParenLoc - Return the location of final right parenthesis.
3731 SourceLocation getRParenLoc() const { return RParenLoc; }
3732
3733 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
3734 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
3735
3736 static bool classof(const Stmt *T) {
3737 return T->getStmtClass() == ConvertVectorExprClass;
3738 }
3739
3740 // Iterators
3741 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3742 const_child_range children() const {
3743 return const_child_range(&SrcExpr, &SrcExpr + 1);
3744 }
3745};
3746
3747/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3748/// This AST node is similar to the conditional operator (?:) in C, with
3749/// the following exceptions:
3750/// - the test expression must be a integer constant expression.
3751/// - the expression returned acts like the chosen subexpression in every
3752/// visible way: the type is the same as that of the chosen subexpression,
3753/// and all predicates (whether it's an l-value, whether it's an integer
3754/// constant expression, etc.) return the same result as for the chosen
3755/// sub-expression.
3756class ChooseExpr : public Expr {
3757 enum { COND, LHS, RHS, END_EXPR };
3758 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3759 SourceLocation BuiltinLoc, RParenLoc;
3760 bool CondIsTrue;
3761public:
3762 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3763 QualType t, ExprValueKind VK, ExprObjectKind OK,
3764 SourceLocation RP, bool condIsTrue,
3765 bool TypeDependent, bool ValueDependent)
3766 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3767 (cond->isInstantiationDependent() ||
3768 lhs->isInstantiationDependent() ||
3769 rhs->isInstantiationDependent()),
3770 (cond->containsUnexpandedParameterPack() ||
3771 lhs->containsUnexpandedParameterPack() ||
3772 rhs->containsUnexpandedParameterPack())),
3773 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3774 SubExprs[COND] = cond;
3775 SubExprs[LHS] = lhs;
3776 SubExprs[RHS] = rhs;
3777 }
3778
3779 /// Build an empty __builtin_choose_expr.
3780 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3781
3782 /// isConditionTrue - Return whether the condition is true (i.e. not
3783 /// equal to zero).
3784 bool isConditionTrue() const {
3785 assert(!isConditionDependent() &&(static_cast <bool> (!isConditionDependent() &&
"Dependent condition isn't true or false") ? void (0) : __assert_fail
("!isConditionDependent() && \"Dependent condition isn't true or false\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 3786, __extension__ __PRETTY_FUNCTION__))
3786 "Dependent condition isn't true or false")(static_cast <bool> (!isConditionDependent() &&
"Dependent condition isn't true or false") ? void (0) : __assert_fail
("!isConditionDependent() && \"Dependent condition isn't true or false\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 3786, __extension__ __PRETTY_FUNCTION__))
;
3787 return CondIsTrue;
3788 }
3789 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3790
3791 bool isConditionDependent() const {
3792 return getCond()->isTypeDependent() || getCond()->isValueDependent();
3793 }
3794
3795 /// getChosenSubExpr - Return the subexpression chosen according to the
3796 /// condition.
3797 Expr *getChosenSubExpr() const {
3798 return isConditionTrue() ? getLHS() : getRHS();
3799 }
3800
3801 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3802 void setCond(Expr *E) { SubExprs[COND] = E; }
3803 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3804 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3805 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3806 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3807
3808 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3809 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3810
3811 SourceLocation getRParenLoc() const { return RParenLoc; }
3812 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3813
3814 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
3815 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
3816
3817 static bool classof(const Stmt *T) {
3818 return T->getStmtClass() == ChooseExprClass;
3819 }
3820
3821 // Iterators
3822 child_range children() {
3823 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3824 }
3825 const_child_range children() const {
3826 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3827 }
3828};
3829
3830/// GNUNullExpr - Implements the GNU __null extension, which is a name
3831/// for a null pointer constant that has integral type (e.g., int or
3832/// long) and is the same size and alignment as a pointer. The __null
3833/// extension is typically only used by system headers, which define
3834/// NULL as __null in C++ rather than using 0 (which is an integer
3835/// that may not match the size of a pointer).
3836class GNUNullExpr : public Expr {
3837 /// TokenLoc - The location of the __null keyword.
3838 SourceLocation TokenLoc;
3839
3840public:
3841 GNUNullExpr(QualType Ty, SourceLocation Loc)
3842 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3843 false),
3844 TokenLoc(Loc) { }
3845
3846 /// Build an empty GNU __null expression.
3847 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3848
3849 /// getTokenLocation - The location of the __null token.
3850 SourceLocation getTokenLocation() const { return TokenLoc; }
3851 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3852
3853 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return TokenLoc; }
3854 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return TokenLoc; }
3855
3856 static bool classof(const Stmt *T) {
3857 return T->getStmtClass() == GNUNullExprClass;
3858 }
3859
3860 // Iterators
3861 child_range children() {
3862 return child_range(child_iterator(), child_iterator());
3863 }
3864 const_child_range children() const {
3865 return const_child_range(const_child_iterator(), const_child_iterator());
3866 }
3867};
3868
3869/// Represents a call to the builtin function \c __builtin_va_arg.
3870class VAArgExpr : public Expr {
3871 Stmt *Val;
3872 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
3873 SourceLocation BuiltinLoc, RParenLoc;
3874public:
3875 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
3876 SourceLocation RPLoc, QualType t, bool IsMS)
3877 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(),
3878 false, (TInfo->getType()->isInstantiationDependentType() ||
3879 e->isInstantiationDependent()),
3880 (TInfo->getType()->containsUnexpandedParameterPack() ||
3881 e->containsUnexpandedParameterPack())),
3882 Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {}
3883
3884 /// Create an empty __builtin_va_arg expression.
3885 explicit VAArgExpr(EmptyShell Empty)
3886 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
3887
3888 const Expr *getSubExpr() const { return cast<Expr>(Val); }
3889 Expr *getSubExpr() { return cast<Expr>(Val); }
3890 void setSubExpr(Expr *E) { Val = E; }
3891
3892 /// Returns whether this is really a Win64 ABI va_arg expression.
3893 bool isMicrosoftABI() const { return TInfo.getInt(); }
3894 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
3895
3896 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
3897 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
3898
3899 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3900 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3901
3902 SourceLocation getRParenLoc() const { return RParenLoc; }
3903 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3904
3905 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
3906 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
3907
3908 static bool classof(const Stmt *T) {
3909 return T->getStmtClass() == VAArgExprClass;
3910 }
3911
3912 // Iterators
3913 child_range children() { return child_range(&Val, &Val+1); }
3914 const_child_range children() const {
3915 return const_child_range(&Val, &Val + 1);
3916 }
3917};
3918
3919/// Describes an C or C++ initializer list.
3920///
3921/// InitListExpr describes an initializer list, which can be used to
3922/// initialize objects of different types, including
3923/// struct/class/union types, arrays, and vectors. For example:
3924///
3925/// @code
3926/// struct foo x = { 1, { 2, 3 } };
3927/// @endcode
3928///
3929/// Prior to semantic analysis, an initializer list will represent the
3930/// initializer list as written by the user, but will have the
3931/// placeholder type "void". This initializer list is called the
3932/// syntactic form of the initializer, and may contain C99 designated
3933/// initializers (represented as DesignatedInitExprs), initializations
3934/// of subobject members without explicit braces, and so on. Clients
3935/// interested in the original syntax of the initializer list should
3936/// use the syntactic form of the initializer list.
3937///
3938/// After semantic analysis, the initializer list will represent the
3939/// semantic form of the initializer, where the initializations of all
3940/// subobjects are made explicit with nested InitListExpr nodes and
3941/// C99 designators have been eliminated by placing the designated
3942/// initializations into the subobject they initialize. Additionally,
3943/// any "holes" in the initialization, where no initializer has been
3944/// specified for a particular subobject, will be replaced with
3945/// implicitly-generated ImplicitValueInitExpr expressions that
3946/// value-initialize the subobjects. Note, however, that the
3947/// initializer lists may still have fewer initializers than there are
3948/// elements to initialize within the object.
3949///
3950/// After semantic analysis has completed, given an initializer list,
3951/// method isSemanticForm() returns true if and only if this is the
3952/// semantic form of the initializer list (note: the same AST node
3953/// may at the same time be the syntactic form).
3954/// Given the semantic form of the initializer list, one can retrieve
3955/// the syntactic form of that initializer list (when different)
3956/// using method getSyntacticForm(); the method returns null if applied
3957/// to a initializer list which is already in syntactic form.
3958/// Similarly, given the syntactic form (i.e., an initializer list such
3959/// that isSemanticForm() returns false), one can retrieve the semantic
3960/// form using method getSemanticForm().
3961/// Since many initializer lists have the same syntactic and semantic forms,
3962/// getSyntacticForm() may return NULL, indicating that the current
3963/// semantic initializer list also serves as its syntactic form.
3964class InitListExpr : public Expr {
3965 // FIXME: Eliminate this vector in favor of ASTContext allocation
3966 typedef ASTVector<Stmt *> InitExprsTy;
3967 InitExprsTy InitExprs;
3968 SourceLocation LBraceLoc, RBraceLoc;
3969
3970 /// The alternative form of the initializer list (if it exists).
3971 /// The int part of the pair stores whether this initializer list is
3972 /// in semantic form. If not null, the pointer points to:
3973 /// - the syntactic form, if this is in semantic form;
3974 /// - the semantic form, if this is in syntactic form.
3975 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3976
3977 /// Either:
3978 /// If this initializer list initializes an array with more elements than
3979 /// there are initializers in the list, specifies an expression to be used
3980 /// for value initialization of the rest of the elements.
3981 /// Or
3982 /// If this initializer list initializes a union, specifies which
3983 /// field within the union will be initialized.
3984 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3985
3986public:
3987 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3988 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3989
3990 /// Build an empty initializer list.
3991 explicit InitListExpr(EmptyShell Empty)
3992 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
3993
3994 unsigned getNumInits() const { return InitExprs.size(); }
3995
3996 /// Retrieve the set of initializers.
3997 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3998
3999 /// Retrieve the set of initializers.
4000 Expr * const *getInits() const {
4001 return reinterpret_cast<Expr * const *>(InitExprs.data());
4002 }
4003
4004 ArrayRef<Expr *> inits() {
4005 return llvm::makeArrayRef(getInits(), getNumInits());
4006 }
4007
4008 ArrayRef<Expr *> inits() const {
4009 return llvm::makeArrayRef(getInits(), getNumInits());
4010 }
4011
4012 const Expr *getInit(unsigned Init) const {
4013 assert(Init < getNumInits() && "Initializer access out of range!")(static_cast <bool> (Init < getNumInits() &&
"Initializer access out of range!") ? void (0) : __assert_fail
("Init < getNumInits() && \"Initializer access out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4013, __extension__ __PRETTY_FUNCTION__))
;
4014 return cast_or_null<Expr>(InitExprs[Init]);
4015 }
4016
4017 Expr *getInit(unsigned Init) {
4018 assert(Init < getNumInits() && "Initializer access out of range!")(static_cast <bool> (Init < getNumInits() &&
"Initializer access out of range!") ? void (0) : __assert_fail
("Init < getNumInits() && \"Initializer access out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4018, __extension__ __PRETTY_FUNCTION__))
;
4019 return cast_or_null<Expr>(InitExprs[Init]);
4020 }
4021
4022 void setInit(unsigned Init, Expr *expr) {
4023 assert(Init < getNumInits() && "Initializer access out of range!")(static_cast <bool> (Init < getNumInits() &&
"Initializer access out of range!") ? void (0) : __assert_fail
("Init < getNumInits() && \"Initializer access out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4023, __extension__ __PRETTY_FUNCTION__))
;
4024 InitExprs[Init] = expr;
4025
4026 if (expr) {
4027 ExprBits.TypeDependent |= expr->isTypeDependent();
4028 ExprBits.ValueDependent |= expr->isValueDependent();
4029 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
4030 ExprBits.ContainsUnexpandedParameterPack |=
4031 expr->containsUnexpandedParameterPack();
4032 }
4033 }
4034
4035 /// Reserve space for some number of initializers.
4036 void reserveInits(const ASTContext &C, unsigned NumInits);
4037
4038 /// Specify the number of initializers
4039 ///
4040 /// If there are more than @p NumInits initializers, the remaining
4041 /// initializers will be destroyed. If there are fewer than @p
4042 /// NumInits initializers, NULL expressions will be added for the
4043 /// unknown initializers.
4044 void resizeInits(const ASTContext &Context, unsigned NumInits);
4045
4046 /// Updates the initializer at index @p Init with the new
4047 /// expression @p expr, and returns the old expression at that
4048 /// location.
4049 ///
4050 /// When @p Init is out of range for this initializer list, the
4051 /// initializer list will be extended with NULL expressions to
4052 /// accommodate the new entry.
4053 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
4054
4055 /// If this initializer list initializes an array with more elements
4056 /// than there are initializers in the list, specifies an expression to be
4057 /// used for value initialization of the rest of the elements.
4058 Expr *getArrayFiller() {
4059 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
4060 }
4061 const Expr *getArrayFiller() const {
4062 return const_cast<InitListExpr *>(this)->getArrayFiller();
4063 }
4064 void setArrayFiller(Expr *filler);
4065
4066 /// Return true if this is an array initializer and its array "filler"
4067 /// has been set.
4068 bool hasArrayFiller() const { return getArrayFiller(); }
4069
4070 /// If this initializes a union, specifies which field in the
4071 /// union to initialize.
4072 ///
4073 /// Typically, this field is the first named field within the
4074 /// union. However, a designated initializer can specify the
4075 /// initialization of a different field within the union.
4076 FieldDecl *getInitializedFieldInUnion() {
4077 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
4078 }
4079 const FieldDecl *getInitializedFieldInUnion() const {
4080 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
4081 }
4082 void setInitializedFieldInUnion(FieldDecl *FD) {
4083 assert((FD == nullptr(static_cast <bool> ((FD == nullptr || getInitializedFieldInUnion
() == nullptr || getInitializedFieldInUnion() == FD) &&
"Only one field of a union may be initialized at a time!") ?
void (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4086, __extension__ __PRETTY_FUNCTION__))
4084 || getInitializedFieldInUnion() == nullptr(static_cast <bool> ((FD == nullptr || getInitializedFieldInUnion
() == nullptr || getInitializedFieldInUnion() == FD) &&
"Only one field of a union may be initialized at a time!") ?
void (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4086, __extension__ __PRETTY_FUNCTION__))
4085 || getInitializedFieldInUnion() == FD)(static_cast <bool> ((FD == nullptr || getInitializedFieldInUnion
() == nullptr || getInitializedFieldInUnion() == FD) &&
"Only one field of a union may be initialized at a time!") ?
void (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4086, __extension__ __PRETTY_FUNCTION__))
4086 && "Only one field of a union may be initialized at a time!")(static_cast <bool> ((FD == nullptr || getInitializedFieldInUnion
() == nullptr || getInitializedFieldInUnion() == FD) &&
"Only one field of a union may be initialized at a time!") ?
void (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4086, __extension__ __PRETTY_FUNCTION__))
;
4087 ArrayFillerOrUnionFieldInit = FD;
4088 }
4089
4090 // Explicit InitListExpr's originate from source code (and have valid source
4091 // locations). Implicit InitListExpr's are created by the semantic analyzer.
4092 bool isExplicit() const {
4093 return LBraceLoc.isValid() && RBraceLoc.isValid();
4094 }
4095
4096 // Is this an initializer for an array of characters, initialized by a string
4097 // literal or an @encode?
4098 bool isStringLiteralInit() const;
4099
4100 /// Is this a transparent initializer list (that is, an InitListExpr that is
4101 /// purely syntactic, and whose semantics are that of the sole contained
4102 /// initializer)?
4103 bool isTransparent() const;
4104
4105 /// Is this the zero initializer {0} in a language which considers it
4106 /// idiomatic?
4107 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
4108
4109 SourceLocation getLBraceLoc() const { return LBraceLoc; }
4110 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
4111 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4112 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
4113
4114 bool isSemanticForm() const { return AltForm.getInt(); }
4115 InitListExpr *getSemanticForm() const {
4116 return isSemanticForm() ? nullptr : AltForm.getPointer();
4117 }
4118 bool isSyntacticForm() const {
4119 return !AltForm.getInt() || !AltForm.getPointer();
4120 }
4121 InitListExpr *getSyntacticForm() const {
4122 return isSemanticForm() ? AltForm.getPointer() : nullptr;
4123 }
4124
4125 void setSyntacticForm(InitListExpr *Init) {
4126 AltForm.setPointer(Init);
4127 AltForm.setInt(true);
4128 Init->AltForm.setPointer(this);
4129 Init->AltForm.setInt(false);
4130 }
4131
4132 bool hadArrayRangeDesignator() const {
4133 return InitListExprBits.HadArrayRangeDesignator != 0;
4134 }
4135 void sawArrayRangeDesignator(bool ARD = true) {
4136 InitListExprBits.HadArrayRangeDesignator = ARD;
4137 }
4138
4139 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__));
4140 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__));
4141
4142 static bool classof(const Stmt *T) {
4143 return T->getStmtClass() == InitListExprClass;
4144 }
4145
4146 // Iterators
4147 child_range children() {
4148 const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
4149 return child_range(cast_away_const(CCR.begin()),
4150 cast_away_const(CCR.end()));
4151 }
4152
4153 const_child_range children() const {
4154 // FIXME: This does not include the array filler expression.
4155 if (InitExprs.empty())
4156 return const_child_range(const_child_iterator(), const_child_iterator());
4157 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
4158 }
4159
4160 typedef InitExprsTy::iterator iterator;
4161 typedef InitExprsTy::const_iterator const_iterator;
4162 typedef InitExprsTy::reverse_iterator reverse_iterator;
4163 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
4164
4165 iterator begin() { return InitExprs.begin(); }
4166 const_iterator begin() const { return InitExprs.begin(); }
4167 iterator end() { return InitExprs.end(); }
4168 const_iterator end() const { return InitExprs.end(); }
4169 reverse_iterator rbegin() { return InitExprs.rbegin(); }
4170 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
4171 reverse_iterator rend() { return InitExprs.rend(); }
4172 const_reverse_iterator rend() const { return InitExprs.rend(); }
4173
4174 friend class ASTStmtReader;
4175 friend class ASTStmtWriter;
4176};
4177
4178/// Represents a C99 designated initializer expression.
4179///
4180/// A designated initializer expression (C99 6.7.8) contains one or
4181/// more designators (which can be field designators, array
4182/// designators, or GNU array-range designators) followed by an
4183/// expression that initializes the field or element(s) that the
4184/// designators refer to. For example, given:
4185///
4186/// @code
4187/// struct point {
4188/// double x;
4189/// double y;
4190/// };
4191/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
4192/// @endcode
4193///
4194/// The InitListExpr contains three DesignatedInitExprs, the first of
4195/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
4196/// designators, one array designator for @c [2] followed by one field
4197/// designator for @c .y. The initialization expression will be 1.0.
4198class DesignatedInitExpr final
4199 : public Expr,
4200 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
4201public:
4202 /// Forward declaration of the Designator class.
4203 class Designator;
4204
4205private:
4206 /// The location of the '=' or ':' prior to the actual initializer
4207 /// expression.
4208 SourceLocation EqualOrColonLoc;
4209
4210 /// Whether this designated initializer used the GNU deprecated
4211 /// syntax rather than the C99 '=' syntax.
4212 unsigned GNUSyntax : 1;
4213
4214 /// The number of designators in this initializer expression.
4215 unsigned NumDesignators : 15;
4216
4217 /// The number of subexpressions of this initializer expression,
4218 /// which contains both the initializer and any additional
4219 /// expressions used by array and array-range designators.
4220 unsigned NumSubExprs : 16;
4221
4222 /// The designators in this designated initialization
4223 /// expression.
4224 Designator *Designators;
4225
4226 DesignatedInitExpr(const ASTContext &C, QualType Ty,
4227 llvm::ArrayRef<Designator> Designators,
4228 SourceLocation EqualOrColonLoc, bool GNUSyntax,
4229 ArrayRef<Expr *> IndexExprs, Expr *Init);
4230
4231 explicit DesignatedInitExpr(unsigned NumSubExprs)
4232 : Expr(DesignatedInitExprClass, EmptyShell()),
4233 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
4234
4235public:
4236 /// A field designator, e.g., ".x".
4237 struct FieldDesignator {
4238 /// Refers to the field that is being initialized. The low bit
4239 /// of this field determines whether this is actually a pointer
4240 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
4241 /// initially constructed, a field designator will store an
4242 /// IdentifierInfo*. After semantic analysis has resolved that
4243 /// name, the field designator will instead store a FieldDecl*.
4244 uintptr_t NameOrField;
4245
4246 /// The location of the '.' in the designated initializer.
4247 unsigned DotLoc;
4248
4249 /// The location of the field name in the designated initializer.
4250 unsigned FieldLoc;
4251 };
4252
4253 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4254 struct ArrayOrRangeDesignator {
4255 /// Location of the first index expression within the designated
4256 /// initializer expression's list of subexpressions.
4257 unsigned Index;
4258 /// The location of the '[' starting the array range designator.
4259 unsigned LBracketLoc;
4260 /// The location of the ellipsis separating the start and end
4261 /// indices. Only valid for GNU array-range designators.
4262 unsigned EllipsisLoc;
4263 /// The location of the ']' terminating the array range designator.
4264 unsigned RBracketLoc;
4265 };
4266
4267 /// Represents a single C99 designator.
4268 ///
4269 /// @todo This class is infuriatingly similar to clang::Designator,
4270 /// but minor differences (storing indices vs. storing pointers)
4271 /// keep us from reusing it. Try harder, later, to rectify these
4272 /// differences.
4273 class Designator {
4274 /// The kind of designator this describes.
4275 enum {
4276 FieldDesignator,
4277 ArrayDesignator,
4278 ArrayRangeDesignator
4279 } Kind;
4280
4281 union {
4282 /// A field designator, e.g., ".x".
4283 struct FieldDesignator Field;
4284 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4285 struct ArrayOrRangeDesignator ArrayOrRange;
4286 };
4287 friend class DesignatedInitExpr;
4288
4289 public:
4290 Designator() {}
4291
4292 /// Initializes a field designator.
4293 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4294 SourceLocation FieldLoc)
4295 : Kind(FieldDesignator) {
4296 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4297 Field.DotLoc = DotLoc.getRawEncoding();
4298 Field.FieldLoc = FieldLoc.getRawEncoding();
4299 }
4300
4301 /// Initializes an array designator.
4302 Designator(unsigned Index, SourceLocation LBracketLoc,
4303 SourceLocation RBracketLoc)
4304 : Kind(ArrayDesignator) {
4305 ArrayOrRange.Index = Index;
4306 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4307 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4308 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4309 }
4310
4311 /// Initializes a GNU array-range designator.
4312 Designator(unsigned Index, SourceLocation LBracketLoc,
4313 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4314 : Kind(ArrayRangeDesignator) {
4315 ArrayOrRange.Index = Index;
4316 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4317 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4318 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4319 }
4320
4321 bool isFieldDesignator() const { return Kind == FieldDesignator; }
4322 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4323 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4324
4325 IdentifierInfo *getFieldName() const;
4326
4327 FieldDecl *getField() const {
4328 assert(Kind == FieldDesignator && "Only valid on a field designator")(static_cast <bool> (Kind == FieldDesignator &&
"Only valid on a field designator") ? void (0) : __assert_fail
("Kind == FieldDesignator && \"Only valid on a field designator\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4328, __extension__ __PRETTY_FUNCTION__))
;
4329 if (Field.NameOrField & 0x01)
4330 return nullptr;
4331 else
4332 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4333 }
4334
4335 void setField(FieldDecl *FD) {
4336 assert(Kind == FieldDesignator && "Only valid on a field designator")(static_cast <bool> (Kind == FieldDesignator &&
"Only valid on a field designator") ? void (0) : __assert_fail
("Kind == FieldDesignator && \"Only valid on a field designator\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4336, __extension__ __PRETTY_FUNCTION__))
;
4337 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4338 }
4339
4340 SourceLocation getDotLoc() const {
4341 assert(Kind == FieldDesignator && "Only valid on a field designator")(static_cast <bool> (Kind == FieldDesignator &&
"Only valid on a field designator") ? void (0) : __assert_fail
("Kind == FieldDesignator && \"Only valid on a field designator\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4341, __extension__ __PRETTY_FUNCTION__))
;
4342 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4343 }
4344
4345 SourceLocation getFieldLoc() const {
4346 assert(Kind == FieldDesignator && "Only valid on a field designator")(static_cast <bool> (Kind == FieldDesignator &&
"Only valid on a field designator") ? void (0) : __assert_fail
("Kind == FieldDesignator && \"Only valid on a field designator\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4346, __extension__ __PRETTY_FUNCTION__))
;
4347 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4348 }
4349
4350 SourceLocation getLBracketLoc() const {
4351 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&(static_cast <bool> ((Kind == ArrayDesignator || Kind ==
ArrayRangeDesignator) && "Only valid on an array or array-range designator"
) ? void (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4352, __extension__ __PRETTY_FUNCTION__))
4352 "Only valid on an array or array-range designator")(static_cast <bool> ((Kind == ArrayDesignator || Kind ==
ArrayRangeDesignator) && "Only valid on an array or array-range designator"
) ? void (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4352, __extension__ __PRETTY_FUNCTION__))
;
4353 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4354 }
4355
4356 SourceLocation getRBracketLoc() const {
4357 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&(static_cast <bool> ((Kind == ArrayDesignator || Kind ==
ArrayRangeDesignator) && "Only valid on an array or array-range designator"
) ? void (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4358, __extension__ __PRETTY_FUNCTION__))
4358 "Only valid on an array or array-range designator")(static_cast <bool> ((Kind == ArrayDesignator || Kind ==
ArrayRangeDesignator) && "Only valid on an array or array-range designator"
) ? void (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4358, __extension__ __PRETTY_FUNCTION__))
;
4359 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4360 }
4361
4362 SourceLocation getEllipsisLoc() const {
4363 assert(Kind == ArrayRangeDesignator &&(static_cast <bool> (Kind == ArrayRangeDesignator &&
"Only valid on an array-range designator") ? void (0) : __assert_fail
("Kind == ArrayRangeDesignator && \"Only valid on an array-range designator\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4364, __extension__ __PRETTY_FUNCTION__))
4364 "Only valid on an array-range designator")(static_cast <bool> (Kind == ArrayRangeDesignator &&
"Only valid on an array-range designator") ? void (0) : __assert_fail
("Kind == ArrayRangeDesignator && \"Only valid on an array-range designator\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4364, __extension__ __PRETTY_FUNCTION__))
;
4365 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4366 }
4367
4368 unsigned getFirstExprIndex() const {
4369 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&(static_cast <bool> ((Kind == ArrayDesignator || Kind ==
ArrayRangeDesignator) && "Only valid on an array or array-range designator"
) ? void (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4370, __extension__ __PRETTY_FUNCTION__))
4370 "Only valid on an array or array-range designator")(static_cast <bool> ((Kind == ArrayDesignator || Kind ==
ArrayRangeDesignator) && "Only valid on an array or array-range designator"
) ? void (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4370, __extension__ __PRETTY_FUNCTION__))
;
4371 return ArrayOrRange.Index;
4372 }
4373
4374 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
4375 if (Kind == FieldDesignator)
4376 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4377 else
4378 return getLBracketLoc();
4379 }
4380 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
4381 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4382 }
4383 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
4384 return SourceRange(getLocStart(), getLocEnd());
4385 }
4386 };
4387
4388 static DesignatedInitExpr *Create(const ASTContext &C,
4389 llvm::ArrayRef<Designator> Designators,
4390 ArrayRef<Expr*> IndexExprs,
4391 SourceLocation EqualOrColonLoc,
4392 bool GNUSyntax, Expr *Init);
4393
4394 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4395 unsigned NumIndexExprs);
4396
4397 /// Returns the number of designators in this initializer.
4398 unsigned size() const { return NumDesignators; }
4399
4400 // Iterator access to the designators.
4401 llvm::MutableArrayRef<Designator> designators() {
4402 return {Designators, NumDesignators};
4403 }
4404
4405 llvm::ArrayRef<Designator> designators() const {
4406 return {Designators, NumDesignators};
4407 }
4408
4409 Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
4410 const Designator *getDesignator(unsigned Idx) const {
4411 return &designators()[Idx];
4412 }
4413
4414 void setDesignators(const ASTContext &C, const Designator *Desigs,
4415 unsigned NumDesigs);
4416
4417 Expr *getArrayIndex(const Designator &D) const;
4418 Expr *getArrayRangeStart(const Designator &D) const;
4419 Expr *getArrayRangeEnd(const Designator &D) const;
4420
4421 /// Retrieve the location of the '=' that precedes the
4422 /// initializer value itself, if present.
4423 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4424 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4425
4426 /// Determines whether this designated initializer used the
4427 /// deprecated GNU syntax for designated initializers.
4428 bool usesGNUSyntax() const { return GNUSyntax; }
4429 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4430
4431 /// Retrieve the initializer value.
4432 Expr *getInit() const {
4433 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4434 }
4435
4436 void setInit(Expr *init) {
4437 *child_begin() = init;
4438 }
4439
4440 /// Retrieve the total number of subexpressions in this
4441 /// designated initializer expression, including the actual
4442 /// initialized value and any expressions that occur within array
4443 /// and array-range designators.
4444 unsigned getNumSubExprs() const { return NumSubExprs; }
4445
4446 Expr *getSubExpr(unsigned Idx) const {
4447 assert(Idx < NumSubExprs && "Subscript out of range")(static_cast <bool> (Idx < NumSubExprs && "Subscript out of range"
) ? void (0) : __assert_fail ("Idx < NumSubExprs && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4447, __extension__ __PRETTY_FUNCTION__))
;
4448 return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
4449 }
4450
4451 void setSubExpr(unsigned Idx, Expr *E) {
4452 assert(Idx < NumSubExprs && "Subscript out of range")(static_cast <bool> (Idx < NumSubExprs && "Subscript out of range"
) ? void (0) : __assert_fail ("Idx < NumSubExprs && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4452, __extension__ __PRETTY_FUNCTION__))
;
4453 getTrailingObjects<Stmt *>()[Idx] = E;
4454 }
4455
4456 /// Replaces the designator at index @p Idx with the series
4457 /// of designators in [First, Last).
4458 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4459 const Designator *First, const Designator *Last);
4460
4461 SourceRange getDesignatorsSourceRange() const;
4462
4463 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__));
4464 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__));
4465
4466 static bool classof(const Stmt *T) {
4467 return T->getStmtClass() == DesignatedInitExprClass;
4468 }
4469
4470 // Iterators
4471 child_range children() {
4472 Stmt **begin = getTrailingObjects<Stmt *>();
4473 return child_range(begin, begin + NumSubExprs);
4474 }
4475 const_child_range children() const {
4476 Stmt * const *begin = getTrailingObjects<Stmt *>();
4477 return const_child_range(begin, begin + NumSubExprs);
4478 }
4479
4480 friend TrailingObjects;
4481};
4482
4483/// Represents a place-holder for an object not to be initialized by
4484/// anything.
4485///
4486/// This only makes sense when it appears as part of an updater of a
4487/// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
4488/// initializes a big object, and the NoInitExpr's mark the spots within the
4489/// big object not to be overwritten by the updater.
4490///
4491/// \see DesignatedInitUpdateExpr
4492class NoInitExpr : public Expr {
4493public:
4494 explicit NoInitExpr(QualType ty)
4495 : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary,
4496 false, false, ty->isInstantiationDependentType(), false) { }
4497
4498 explicit NoInitExpr(EmptyShell Empty)
4499 : Expr(NoInitExprClass, Empty) { }
4500
4501 static bool classof(const Stmt *T) {
4502 return T->getStmtClass() == NoInitExprClass;
4503 }
4504
4505 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
4506 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
4507
4508 // Iterators
4509 child_range children() {
4510 return child_range(child_iterator(), child_iterator());
4511 }
4512 const_child_range children() const {
4513 return const_child_range(const_child_iterator(), const_child_iterator());
4514 }
4515};
4516
4517// In cases like:
4518// struct Q { int a, b, c; };
4519// Q *getQ();
4520// void foo() {
4521// struct A { Q q; } a = { *getQ(), .q.b = 3 };
4522// }
4523//
4524// We will have an InitListExpr for a, with type A, and then a
4525// DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
4526// is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
4527//
4528class DesignatedInitUpdateExpr : public Expr {
4529 // BaseAndUpdaterExprs[0] is the base expression;
4530 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
4531 Stmt *BaseAndUpdaterExprs[2];
4532
4533public:
4534 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
4535 Expr *baseExprs, SourceLocation rBraceLoc);
4536
4537 explicit DesignatedInitUpdateExpr(EmptyShell Empty)
4538 : Expr(DesignatedInitUpdateExprClass, Empty) { }
4539
4540 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__));
4541 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__));
4542
4543 static bool classof(const Stmt *T) {
4544 return T->getStmtClass() == DesignatedInitUpdateExprClass;
4545 }
4546
4547 Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
4548 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
4549
4550 InitListExpr *getUpdater() const {
4551 return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
4552 }
4553 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
4554
4555 // Iterators
4556 // children = the base and the updater
4557 child_range children() {
4558 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
4559 }
4560 const_child_range children() const {
4561 return const_child_range(&BaseAndUpdaterExprs[0],
4562 &BaseAndUpdaterExprs[0] + 2);
4563 }
4564};
4565
4566/// Represents a loop initializing the elements of an array.
4567///
4568/// The need to initialize the elements of an array occurs in a number of
4569/// contexts:
4570///
4571/// * in the implicit copy/move constructor for a class with an array member
4572/// * when a lambda-expression captures an array by value
4573/// * when a decomposition declaration decomposes an array
4574///
4575/// There are two subexpressions: a common expression (the source array)
4576/// that is evaluated once up-front, and a per-element initializer that
4577/// runs once for each array element.
4578///
4579/// Within the per-element initializer, the common expression may be referenced
4580/// via an OpaqueValueExpr, and the current index may be obtained via an
4581/// ArrayInitIndexExpr.
4582class ArrayInitLoopExpr : public Expr {
4583 Stmt *SubExprs[2];
4584
4585 explicit ArrayInitLoopExpr(EmptyShell Empty)
4586 : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
4587
4588public:
4589 explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
4590 : Expr(ArrayInitLoopExprClass, T, VK_RValue, OK_Ordinary, false,
4591 CommonInit->isValueDependent() || ElementInit->isValueDependent(),
22
Assuming the condition is false
23
Called C++ object pointer is null
4592 T->isInstantiationDependentType(),
4593 CommonInit->containsUnexpandedParameterPack() ||
4594 ElementInit->containsUnexpandedParameterPack()),
4595 SubExprs{CommonInit, ElementInit} {}
4596
4597 /// Get the common subexpression shared by all initializations (the source
4598 /// array).
4599 OpaqueValueExpr *getCommonExpr() const {
4600 return cast<OpaqueValueExpr>(SubExprs[0]);
4601 }
4602
4603 /// Get the initializer to use for each array element.
4604 Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); }
4605
4606 llvm::APInt getArraySize() const {
4607 return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
4608 ->getSize();
4609 }
4610
4611 static bool classof(const Stmt *S) {
4612 return S->getStmtClass() == ArrayInitLoopExprClass;
4613 }
4614
4615 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
4616 return getCommonExpr()->getLocStart();
4617 }
4618 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
4619 return getCommonExpr()->getLocEnd();
4620 }
4621
4622 child_range children() {
4623 return child_range(SubExprs, SubExprs + 2);
4624 }
4625 const_child_range children() const {
4626 return const_child_range(SubExprs, SubExprs + 2);
4627 }
4628
4629 friend class ASTReader;
4630 friend class ASTStmtReader;
4631 friend class ASTStmtWriter;
4632};
4633
4634/// Represents the index of the current element of an array being
4635/// initialized by an ArrayInitLoopExpr. This can only appear within the
4636/// subexpression of an ArrayInitLoopExpr.
4637class ArrayInitIndexExpr : public Expr {
4638 explicit ArrayInitIndexExpr(EmptyShell Empty)
4639 : Expr(ArrayInitIndexExprClass, Empty) {}
4640
4641public:
4642 explicit ArrayInitIndexExpr(QualType T)
4643 : Expr(ArrayInitIndexExprClass, T, VK_RValue, OK_Ordinary,
4644 false, false, false, false) {}
4645
4646 static bool classof(const Stmt *S) {
4647 return S->getStmtClass() == ArrayInitIndexExprClass;
4648 }
4649
4650 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
4651 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
4652
4653 child_range children() {
4654 return child_range(child_iterator(), child_iterator());
4655 }
4656 const_child_range children() const {
4657 return const_child_range(const_child_iterator(), const_child_iterator());
4658 }
4659
4660 friend class ASTReader;
4661 friend class ASTStmtReader;
4662};
4663
4664/// Represents an implicitly-generated value initialization of
4665/// an object of a given type.
4666///
4667/// Implicit value initializations occur within semantic initializer
4668/// list expressions (InitListExpr) as placeholders for subobject
4669/// initializations not explicitly specified by the user.
4670///
4671/// \see InitListExpr
4672class ImplicitValueInitExpr : public Expr {
4673public:
4674 explicit ImplicitValueInitExpr(QualType ty)
4675 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4676 false, false, ty->isInstantiationDependentType(), false) { }
4677
4678 /// Construct an empty implicit value initialization.
4679 explicit ImplicitValueInitExpr(EmptyShell Empty)
4680 : Expr(ImplicitValueInitExprClass, Empty) { }
4681
4682 static bool classof(const Stmt *T) {
4683 return T->getStmtClass() == ImplicitValueInitExprClass;
4684 }
4685
4686 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
4687 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
4688
4689 // Iterators
4690 child_range children() {
4691 return child_range(child_iterator(), child_iterator());
4692 }
4693 const_child_range children() const {
4694 return const_child_range(const_child_iterator(), const_child_iterator());
4695 }
4696};
4697
4698class ParenListExpr : public Expr {
4699 Stmt **Exprs;
4700 unsigned NumExprs;
4701 SourceLocation LParenLoc, RParenLoc;
4702
4703public:
4704 ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4705 ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4706
4707 /// Build an empty paren list.
4708 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4709
4710 unsigned getNumExprs() const { return NumExprs; }
4711
4712 const Expr* getExpr(unsigned Init) const {
4713 assert(Init < getNumExprs() && "Initializer access out of range!")(static_cast <bool> (Init < getNumExprs() &&
"Initializer access out of range!") ? void (0) : __assert_fail
("Init < getNumExprs() && \"Initializer access out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4713, __extension__ __PRETTY_FUNCTION__))
;
4714 return cast_or_null<Expr>(Exprs[Init]);
4715 }
4716
4717 Expr* getExpr(unsigned Init) {
4718 assert(Init < getNumExprs() && "Initializer access out of range!")(static_cast <bool> (Init < getNumExprs() &&
"Initializer access out of range!") ? void (0) : __assert_fail
("Init < getNumExprs() && \"Initializer access out of range!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4718, __extension__ __PRETTY_FUNCTION__))
;
4719 return cast_or_null<Expr>(Exprs[Init]);
4720 }
4721
4722 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4723
4724 ArrayRef<Expr *> exprs() {
4725 return llvm::makeArrayRef(getExprs(), getNumExprs());
4726 }
4727
4728 SourceLocation getLParenLoc() const { return LParenLoc; }
4729 SourceLocation getRParenLoc() const { return RParenLoc; }
4730
4731 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LParenLoc; }
4732 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4733
4734 static bool classof(const Stmt *T) {
4735 return T->getStmtClass() == ParenListExprClass;
4736 }
4737
4738 // Iterators
4739 child_range children() {
4740 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4741 }
4742 const_child_range children() const {
4743 return const_child_range(&Exprs[0], &Exprs[0] + NumExprs);
4744 }
4745
4746 friend class ASTStmtReader;
4747 friend class ASTStmtWriter;
4748};
4749
4750/// Represents a C11 generic selection.
4751///
4752/// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4753/// expression, followed by one or more generic associations. Each generic
4754/// association specifies a type name and an expression, or "default" and an
4755/// expression (in which case it is known as a default generic association).
4756/// The type and value of the generic selection are identical to those of its
4757/// result expression, which is defined as the expression in the generic
4758/// association with a type name that is compatible with the type of the
4759/// controlling expression, or the expression in the default generic association
4760/// if no types are compatible. For example:
4761///
4762/// @code
4763/// _Generic(X, double: 1, float: 2, default: 3)
4764/// @endcode
4765///
4766/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4767/// or 3 if "hello".
4768///
4769/// As an extension, generic selections are allowed in C++, where the following
4770/// additional semantics apply:
4771///
4772/// Any generic selection whose controlling expression is type-dependent or
4773/// which names a dependent type in its association list is result-dependent,
4774/// which means that the choice of result expression is dependent.
4775/// Result-dependent generic associations are both type- and value-dependent.
4776class GenericSelectionExpr : public Expr {
4777 enum { CONTROLLING, END_EXPR };
4778 TypeSourceInfo **AssocTypes;
4779 Stmt **SubExprs;
4780 unsigned NumAssocs, ResultIndex;
4781 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4782
4783public:
4784 GenericSelectionExpr(const ASTContext &Context,
4785 SourceLocation GenericLoc, Expr *ControllingExpr,
4786 ArrayRef<TypeSourceInfo*> AssocTypes,
4787 ArrayRef<Expr*> AssocExprs,
4788 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4789 bool ContainsUnexpandedParameterPack,
4790 unsigned ResultIndex);
4791
4792 /// This constructor is used in the result-dependent case.
4793 GenericSelectionExpr(const ASTContext &Context,
4794 SourceLocation GenericLoc, Expr *ControllingExpr,
4795 ArrayRef<TypeSourceInfo*> AssocTypes,
4796 ArrayRef<Expr*> AssocExprs,
4797 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4798 bool ContainsUnexpandedParameterPack);
4799
4800 explicit GenericSelectionExpr(EmptyShell Empty)
4801 : Expr(GenericSelectionExprClass, Empty) { }
4802
4803 unsigned getNumAssocs() const { return NumAssocs; }
4804
4805 SourceLocation getGenericLoc() const { return GenericLoc; }
4806 SourceLocation getDefaultLoc() const { return DefaultLoc; }
4807 SourceLocation getRParenLoc() const { return RParenLoc; }
4808
4809 const Expr *getAssocExpr(unsigned i) const {
4810 return cast<Expr>(SubExprs[END_EXPR+i]);
4811 }
4812 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4813 ArrayRef<Expr *> getAssocExprs() const {
4814 return NumAssocs
4815 ? llvm::makeArrayRef(
4816 &reinterpret_cast<Expr **>(SubExprs)[END_EXPR], NumAssocs)
4817 : None;
4818 }
4819 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4820 return AssocTypes[i];
4821 }
4822 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4823 ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
4824 return NumAssocs ? llvm::makeArrayRef(&AssocTypes[0], NumAssocs) : None;
4825 }
4826
4827 QualType getAssocType(unsigned i) const {
4828 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4829 return TS->getType();
4830 else
4831 return QualType();
4832 }
4833
4834 const Expr *getControllingExpr() const {
4835 return cast<Expr>(SubExprs[CONTROLLING]);
4836 }
4837 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4838
4839 /// Whether this generic selection is result-dependent.
4840 bool isResultDependent() const { return ResultIndex == -1U; }
4841
4842 /// The zero-based index of the result expression's generic association in
4843 /// the generic selection's association list. Defined only if the
4844 /// generic selection is not result-dependent.
4845 unsigned getResultIndex() const {
4846 assert(!isResultDependent() && "Generic selection is result-dependent")(static_cast <bool> (!isResultDependent() && "Generic selection is result-dependent"
) ? void (0) : __assert_fail ("!isResultDependent() && \"Generic selection is result-dependent\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 4846, __extension__ __PRETTY_FUNCTION__))
;
4847 return ResultIndex;
4848 }
4849
4850 /// The generic selection's result expression. Defined only if the
4851 /// generic selection is not result-dependent.
4852 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4853 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4854
4855 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return GenericLoc; }
4856 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4857
4858 static bool classof(const Stmt *T) {
4859 return T->getStmtClass() == GenericSelectionExprClass;
4860 }
4861
4862 child_range children() {
4863 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4864 }
4865 const_child_range children() const {
4866 return const_child_range(SubExprs, SubExprs + END_EXPR + NumAssocs);
4867 }
4868 friend class ASTStmtReader;
4869};
4870
4871//===----------------------------------------------------------------------===//
4872// Clang Extensions
4873//===----------------------------------------------------------------------===//
4874
4875/// ExtVectorElementExpr - This represents access to specific elements of a
4876/// vector, and may occur on the left hand side or right hand side. For example
4877/// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4878///
4879/// Note that the base may have either vector or pointer to vector type, just
4880/// like a struct field reference.
4881///
4882class ExtVectorElementExpr : public Expr {
4883 Stmt *Base;
4884 IdentifierInfo *Accessor;
4885 SourceLocation AccessorLoc;
4886public:
4887 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4888 IdentifierInfo &accessor, SourceLocation loc)
4889 : Expr(ExtVectorElementExprClass, ty, VK,
4890 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4891 base->isTypeDependent(), base->isValueDependent(),
4892 base->isInstantiationDependent(),
4893 base->containsUnexpandedParameterPack()),
4894 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4895
4896 /// Build an empty vector element expression.
4897 explicit ExtVectorElementExpr(EmptyShell Empty)
4898 : Expr(ExtVectorElementExprClass, Empty) { }
4899
4900 const Expr *getBase() const { return cast<Expr>(Base); }
4901 Expr *getBase() { return cast<Expr>(Base); }
4902 void setBase(Expr *E) { Base = E; }
4903
4904 IdentifierInfo &getAccessor() const { return *Accessor; }
4905 void setAccessor(IdentifierInfo *II) { Accessor = II; }
4906
4907 SourceLocation getAccessorLoc() const { return AccessorLoc; }
4908 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4909
4910 /// getNumElements - Get the number of components being selected.
4911 unsigned getNumElements() const;
4912
4913 /// containsDuplicateElements - Return true if any element access is
4914 /// repeated.
4915 bool containsDuplicateElements() const;
4916
4917 /// getEncodedElementAccess - Encode the elements accessed into an llvm
4918 /// aggregate Constant of ConstantInt(s).
4919 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
4920
4921 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
4922 return getBase()->getLocStart();
4923 }
4924 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return AccessorLoc; }
4925
4926 /// isArrow - Return true if the base expression is a pointer to vector,
4927 /// return false if the base expression is a vector.
4928 bool isArrow() const;
4929
4930 static bool classof(const Stmt *T) {
4931 return T->getStmtClass() == ExtVectorElementExprClass;
4932 }
4933
4934 // Iterators
4935 child_range children() { return child_range(&Base, &Base+1); }
4936 const_child_range children() const {
4937 return const_child_range(&Base, &Base + 1);
4938 }
4939};
4940
4941/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4942/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4943class BlockExpr : public Expr {
4944protected:
4945 BlockDecl *TheBlock;
4946public:
4947 BlockExpr(BlockDecl *BD, QualType ty)
4948 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4949 ty->isDependentType(), ty->isDependentType(),
4950 ty->isInstantiationDependentType() || BD->isDependentContext(),
4951 false),
4952 TheBlock(BD) {}
4953
4954 /// Build an empty block expression.
4955 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4956
4957 const BlockDecl *getBlockDecl() const { return TheBlock; }
4958 BlockDecl *getBlockDecl() { return TheBlock; }
4959 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4960
4961 // Convenience functions for probing the underlying BlockDecl.
4962 SourceLocation getCaretLocation() const;
4963 const Stmt *getBody() const;
4964 Stmt *getBody();
4965
4966 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return getCaretLocation(); }
4967 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return getBody()->getLocEnd(); }
4968
4969 /// getFunctionType - Return the underlying function type for this block.
4970 const FunctionProtoType *getFunctionType() const;
4971
4972 static bool classof(const Stmt *T) {
4973 return T->getStmtClass() == BlockExprClass;
4974 }
4975
4976 // Iterators
4977 child_range children() {
4978 return child_range(child_iterator(), child_iterator());
4979 }
4980 const_child_range children() const {
4981 return const_child_range(const_child_iterator(), const_child_iterator());
4982 }
4983};
4984
4985/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4986/// This AST node provides support for reinterpreting a type to another
4987/// type of the same size.
4988class AsTypeExpr : public Expr {
4989private:
4990 Stmt *SrcExpr;
4991 SourceLocation BuiltinLoc, RParenLoc;
4992
4993 friend class ASTReader;
4994 friend class ASTStmtReader;
4995 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4996
4997public:
4998 AsTypeExpr(Expr* SrcExpr, QualType DstType,
4999 ExprValueKind VK, ExprObjectKind OK,
5000 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
5001 : Expr(AsTypeExprClass, DstType, VK, OK,
5002 DstType->isDependentType(),
5003 DstType->isDependentType() || SrcExpr->isValueDependent(),
5004 (DstType->isInstantiationDependentType() ||
5005 SrcExpr->isInstantiationDependent()),
5006 (DstType->containsUnexpandedParameterPack() ||
5007 SrcExpr->containsUnexpandedParameterPack())),
5008 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
5009
5010 /// getSrcExpr - Return the Expr to be converted.
5011 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
5012
5013 /// getBuiltinLoc - Return the location of the __builtin_astype token.
5014 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
5015
5016 /// getRParenLoc - Return the location of final right parenthesis.
5017 SourceLocation getRParenLoc() const { return RParenLoc; }
5018
5019 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
5020 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
5021
5022 static bool classof(const Stmt *T) {
5023 return T->getStmtClass() == AsTypeExprClass;
5024 }
5025
5026 // Iterators
5027 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
5028 const_child_range children() const {
5029 return const_child_range(&SrcExpr, &SrcExpr + 1);
5030 }
5031};
5032
5033/// PseudoObjectExpr - An expression which accesses a pseudo-object
5034/// l-value. A pseudo-object is an abstract object, accesses to which
5035/// are translated to calls. The pseudo-object expression has a
5036/// syntactic form, which shows how the expression was actually
5037/// written in the source code, and a semantic form, which is a series
5038/// of expressions to be executed in order which detail how the
5039/// operation is actually evaluated. Optionally, one of the semantic
5040/// forms may also provide a result value for the expression.
5041///
5042/// If any of the semantic-form expressions is an OpaqueValueExpr,
5043/// that OVE is required to have a source expression, and it is bound
5044/// to the result of that source expression. Such OVEs may appear
5045/// only in subsequent semantic-form expressions and as
5046/// sub-expressions of the syntactic form.
5047///
5048/// PseudoObjectExpr should be used only when an operation can be
5049/// usefully described in terms of fairly simple rewrite rules on
5050/// objects and functions that are meant to be used by end-developers.
5051/// For example, under the Itanium ABI, dynamic casts are implemented
5052/// as a call to a runtime function called __dynamic_cast; using this
5053/// class to describe that would be inappropriate because that call is
5054/// not really part of the user-visible semantics, and instead the
5055/// cast is properly reflected in the AST and IR-generation has been
5056/// taught to generate the call as necessary. In contrast, an
5057/// Objective-C property access is semantically defined to be
5058/// equivalent to a particular message send, and this is very much
5059/// part of the user model. The name of this class encourages this
5060/// modelling design.
5061class PseudoObjectExpr final
5062 : public Expr,
5063 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
5064 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
5065 // Always at least two, because the first sub-expression is the
5066 // syntactic form.
5067
5068 // PseudoObjectExprBits.ResultIndex - The index of the
5069 // sub-expression holding the result. 0 means the result is void,
5070 // which is unambiguous because it's the index of the syntactic
5071 // form. Note that this is therefore 1 higher than the value passed
5072 // in to Create, which is an index within the semantic forms.
5073 // Note also that ASTStmtWriter assumes this encoding.
5074
5075 Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
5076 const Expr * const *getSubExprsBuffer() const {
5077 return getTrailingObjects<Expr *>();
5078 }
5079
5080 PseudoObjectExpr(QualType type, ExprValueKind VK,
5081 Expr *syntactic, ArrayRef<Expr*> semantic,
5082 unsigned resultIndex);
5083
5084 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
5085
5086 unsigned getNumSubExprs() const {
5087 return PseudoObjectExprBits.NumSubExprs;
5088 }
5089
5090public:
5091 /// NoResult - A value for the result index indicating that there is
5092 /// no semantic result.
5093 enum : unsigned { NoResult = ~0U };
5094
5095 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
5096 ArrayRef<Expr*> semantic,
5097 unsigned resultIndex);
5098
5099 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
5100 unsigned numSemanticExprs);
5101
5102 /// Return the syntactic form of this expression, i.e. the
5103 /// expression it actually looks like. Likely to be expressed in
5104 /// terms of OpaqueValueExprs bound in the semantic form.
5105 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
5106 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
5107
5108 /// Return the index of the result-bearing expression into the semantics
5109 /// expressions, or PseudoObjectExpr::NoResult if there is none.
5110 unsigned getResultExprIndex() const {
5111 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
5112 return PseudoObjectExprBits.ResultIndex - 1;
5113 }
5114
5115 /// Return the result-bearing expression, or null if there is none.
5116 Expr *getResultExpr() {
5117 if (PseudoObjectExprBits.ResultIndex == 0)
5118 return nullptr;
5119 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
5120 }
5121 const Expr *getResultExpr() const {
5122 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
5123 }
5124
5125 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
5126
5127 typedef Expr * const *semantics_iterator;
5128 typedef const Expr * const *const_semantics_iterator;
5129 semantics_iterator semantics_begin() {
5130 return getSubExprsBuffer() + 1;
5131 }
5132 const_semantics_iterator semantics_begin() const {
5133 return getSubExprsBuffer() + 1;
5134 }
5135 semantics_iterator semantics_end() {
5136 return getSubExprsBuffer() + getNumSubExprs();
5137 }
5138 const_semantics_iterator semantics_end() const {
5139 return getSubExprsBuffer() + getNumSubExprs();
5140 }
5141
5142 llvm::iterator_range<semantics_iterator> semantics() {
5143 return llvm::make_range(semantics_begin(), semantics_end());
5144 }
5145 llvm::iterator_range<const_semantics_iterator> semantics() const {
5146 return llvm::make_range(semantics_begin(), semantics_end());
5147 }
5148
5149 Expr *getSemanticExpr(unsigned index) {
5150 assert(index + 1 < getNumSubExprs())(static_cast <bool> (index + 1 < getNumSubExprs()) ?
void (0) : __assert_fail ("index + 1 < getNumSubExprs()",
"/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 5150, __extension__ __PRETTY_FUNCTION__))
;
5151 return getSubExprsBuffer()[index + 1];
5152 }
5153 const Expr *getSemanticExpr(unsigned index) const {
5154 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
5155 }
5156
5157 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
5158 return getSyntacticForm()->getExprLoc();
5159 }
5160
5161 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
5162 return getSyntacticForm()->getLocStart();
5163 }
5164 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
5165 return getSyntacticForm()->getLocEnd();
5166 }
5167
5168 child_range children() {
5169 const_child_range CCR =
5170 const_cast<const PseudoObjectExpr *>(this)->children();
5171 return child_range(cast_away_const(CCR.begin()),
5172 cast_away_const(CCR.end()));
5173 }
5174 const_child_range children() const {
5175 Stmt *const *cs = const_cast<Stmt *const *>(
5176 reinterpret_cast<const Stmt *const *>(getSubExprsBuffer()));
5177 return const_child_range(cs, cs + getNumSubExprs());
5178 }
5179
5180 static bool classof(const Stmt *T) {
5181 return T->getStmtClass() == PseudoObjectExprClass;
5182 }
5183
5184 friend TrailingObjects;
5185 friend class ASTStmtReader;
5186};
5187
5188/// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
5189/// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
5190/// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>,
5191/// and corresponding __opencl_atomic_* for OpenCL 2.0.
5192/// All of these instructions take one primary pointer, at least one memory
5193/// order. The instructions for which getScopeModel returns non-null value
5194/// take one synch scope.
5195class AtomicExpr : public Expr {
5196public:
5197 enum AtomicOp {
5198#define BUILTIN(ID, TYPE, ATTRS)
5199#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
5200#include "clang/Basic/Builtins.def"
5201 // Avoid trailing comma
5202 BI_First = 0
5203 };
5204
5205private:
5206 /// Location of sub-expressions.
5207 /// The location of Scope sub-expression is NumSubExprs - 1, which is
5208 /// not fixed, therefore is not defined in enum.
5209 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
5210 Stmt *SubExprs[END_EXPR + 1];
5211 unsigned NumSubExprs;
5212 SourceLocation BuiltinLoc, RParenLoc;
5213 AtomicOp Op;
5214
5215 friend class ASTStmtReader;
5216public:
5217 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
5218 AtomicOp op, SourceLocation RP);
5219
5220 /// Determine the number of arguments the specified atomic builtin
5221 /// should have.
5222 static unsigned getNumSubExprs(AtomicOp Op);
5223
5224 /// Build an empty AtomicExpr.
5225 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
5226
5227 Expr *getPtr() const {
5228 return cast<Expr>(SubExprs[PTR]);
5229 }
5230 Expr *getOrder() const {
5231 return cast<Expr>(SubExprs[ORDER]);
5232 }
5233 Expr *getScope() const {
5234 assert(getScopeModel() && "No scope")(static_cast <bool> (getScopeModel() && "No scope"
) ? void (0) : __assert_fail ("getScopeModel() && \"No scope\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 5234, __extension__ __PRETTY_FUNCTION__))
;
5235 return cast<Expr>(SubExprs[NumSubExprs - 1]);
5236 }
5237 Expr *getVal1() const {
5238 if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init)
5239 return cast<Expr>(SubExprs[ORDER]);
5240 assert(NumSubExprs > VAL1)(static_cast <bool> (NumSubExprs > VAL1) ? void (0) :
__assert_fail ("NumSubExprs > VAL1", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 5240, __extension__ __PRETTY_FUNCTION__))
;
5241 return cast<Expr>(SubExprs[VAL1]);
5242 }
5243 Expr *getOrderFail() const {
5244 assert(NumSubExprs > ORDER_FAIL)(static_cast <bool> (NumSubExprs > ORDER_FAIL) ? void
(0) : __assert_fail ("NumSubExprs > ORDER_FAIL", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 5244, __extension__ __PRETTY_FUNCTION__))
;
5245 return cast<Expr>(SubExprs[ORDER_FAIL]);
5246 }
5247 Expr *getVal2() const {
5248 if (Op == AO__atomic_exchange)
5249 return cast<Expr>(SubExprs[ORDER_FAIL]);
5250 assert(NumSubExprs > VAL2)(static_cast <bool> (NumSubExprs > VAL2) ? void (0) :
__assert_fail ("NumSubExprs > VAL2", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 5250, __extension__ __PRETTY_FUNCTION__))
;
5251 return cast<Expr>(SubExprs[VAL2]);
5252 }
5253 Expr *getWeak() const {
5254 assert(NumSubExprs > WEAK)(static_cast <bool> (NumSubExprs > WEAK) ? void (0) :
__assert_fail ("NumSubExprs > WEAK", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 5254, __extension__ __PRETTY_FUNCTION__))
;
5255 return cast<Expr>(SubExprs[WEAK]);
5256 }
5257 QualType getValueType() const;
5258
5259 AtomicOp getOp() const { return Op; }
5260 unsigned getNumSubExprs() const { return NumSubExprs; }
5261
5262 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
5263 const Expr * const *getSubExprs() const {
5264 return reinterpret_cast<Expr * const *>(SubExprs);
5265 }
5266
5267 bool isVolatile() const {
5268 return getPtr()->getType()->getPointeeType().isVolatileQualified();
5269 }
5270
5271 bool isCmpXChg() const {
5272 return getOp() == AO__c11_atomic_compare_exchange_strong ||
5273 getOp() == AO__c11_atomic_compare_exchange_weak ||
5274 getOp() == AO__opencl_atomic_compare_exchange_strong ||
5275 getOp() == AO__opencl_atomic_compare_exchange_weak ||
5276 getOp() == AO__atomic_compare_exchange ||
5277 getOp() == AO__atomic_compare_exchange_n;
5278 }
5279
5280 bool isOpenCL() const {
5281 return getOp() >= AO__opencl_atomic_init &&
5282 getOp() <= AO__opencl_atomic_fetch_max;
5283 }
5284
5285 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
5286 SourceLocation getRParenLoc() const { return RParenLoc; }
5287
5288 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
5289 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
5290
5291 static bool classof(const Stmt *T) {
5292 return T->getStmtClass() == AtomicExprClass;
5293 }
5294
5295 // Iterators
5296 child_range children() {
5297 return child_range(SubExprs, SubExprs+NumSubExprs);
5298 }
5299 const_child_range children() const {
5300 return const_child_range(SubExprs, SubExprs + NumSubExprs);
5301 }
5302
5303 /// Get atomic scope model for the atomic op code.
5304 /// \return empty atomic scope model if the atomic op code does not have
5305 /// scope operand.
5306 static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) {
5307 auto Kind =
5308 (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max)
5309 ? AtomicScopeModelKind::OpenCL
5310 : AtomicScopeModelKind::None;
5311 return AtomicScopeModel::create(Kind);
5312 }
5313
5314 /// Get atomic scope model.
5315 /// \return empty atomic scope model if this atomic expression does not have
5316 /// scope operand.
5317 std::unique_ptr<AtomicScopeModel> getScopeModel() const {
5318 return getScopeModel(getOp());
5319 }
5320};
5321
5322/// TypoExpr - Internal placeholder for expressions where typo correction
5323/// still needs to be performed and/or an error diagnostic emitted.
5324class TypoExpr : public Expr {
5325public:
5326 TypoExpr(QualType T)
5327 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
5328 /*isTypeDependent*/ true,
5329 /*isValueDependent*/ true,
5330 /*isInstantiationDependent*/ true,
5331 /*containsUnexpandedParameterPack*/ false) {
5332 assert(T->isDependentType() && "TypoExpr given a non-dependent type")(static_cast <bool> (T->isDependentType() &&
"TypoExpr given a non-dependent type") ? void (0) : __assert_fail
("T->isDependentType() && \"TypoExpr given a non-dependent type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include/clang/AST/Expr.h"
, 5332, __extension__ __PRETTY_FUNCTION__))
;
5333 }
5334
5335 child_range children() {
5336 return child_range(child_iterator(), child_iterator());
5337 }
5338 const_child_range children() const {
5339 return const_child_range(const_child_iterator(), const_child_iterator());
5340 }
5341
5342 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5343 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5344
5345 static bool classof(const Stmt *T) {
5346 return T->getStmtClass() == TypoExprClass;
5347 }
5348
5349};
5350} // end namespace clang
5351
5352#endif // LLVM_CLANG_AST_EXPR_H